@knocklabs/client 0.10.16 → 0.10.17
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 +7 -0
- package/dist/cjs/clients/feed/feed.js +1 -1
- package/dist/cjs/clients/feed/feed.js.map +1 -1
- package/dist/cjs/knock.js +1 -5
- package/dist/cjs/knock.js.map +1 -1
- package/dist/esm/clients/feed/feed.mjs +45 -32
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/esm/knock.mjs +32 -38
- package/dist/esm/knock.mjs.map +1 -1
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/messages/interfaces.d.ts +1 -1
- package/dist/types/clients/messages/interfaces.d.ts.map +1 -1
- package/dist/types/knock.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/clients/feed/feed.ts +25 -10
- package/src/clients/messages/interfaces.ts +9 -1
- package/src/knock.ts +0 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var f=Object.defineProperty;var p=(d,e,t)=>e in d?f(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var c=(d,e,t)=>p(d,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),k=d=>d&&typeof d=="object"&&"default"in d?d:{default:d},S=k(_),v={archived:"exclude"},y=2e3;class b{constructor(e,t,s){c(this,"userFeedId");c(this,"channel");c(this,"broadcaster");c(this,"defaultOptions");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,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new S.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...v,...s},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),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(){this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0;const e=this.knock.client().socket;e&&!e.isConnected()&&e.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}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 i={seen_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),n}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 i={read_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),n}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",a=Array.isArray(e)?e:[e],n=a.map(i=>i.id);if(s){const i=a.filter(u=>!u.seen_at).length,o=a.filter(u=>!u.read_at).length,r={...t.metadata,total_count:t.metadata.total_count-a.length,unseen_count:t.metadata.unseen_count-i,unread_count:t.metadata.unread_count-o},l=t.items.filter(u=>!n.includes(u.id));t.setResult({entries:l,meta:r,page_info:t.pageInfo})}else t.setItemAttrs(n,{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 n=e.map(i=>i.id);t.setItemAttrs(n,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(o=>o.read_at===null).map(o=>o.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const o=e.filter(l=>!a.includes(l.id)),r={...t.metadata,total_count:o.length,unread_count:0};t.setResult({entries:o,meta:r,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(m.isRequestInFlight(t))return;s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const a={...this.defaultOptions,...e,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},n=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:a});if(n.statusCode==="error"||!n.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:n.statusCode,data:n.error||n.body};const i={entries:n.body.entries,meta:n.body.meta,page_info:n.body.page_info};if(e.before){const l={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,l)}else if(e.after){const l={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,l)}else s.setResult(i);this.broadcast("messages.new",i);const o=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",r={items:i.entries,metadata:i.meta,event:o};return this.broadcast(r.event,r),{data:i,status:n.statusCode}}async fetchNextPage(){const{pageInfo:e}=this.store.getState();e.after&&this.fetch({after:e.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),a=t[0];s.setMetadata(e),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const n=this.store.getState(),i=Array.isArray(e)?e:[e],o=i.map(r=>r.id);if(a){const{metadata:r}=n,l=i.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}}),u=t.startsWith("un")?l.length:-l.length;n.setMetadata({...r,[a]:Math.max(0,r[a]+u)})}n.setItemAttrs(o,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],n=a.map(o=>o.id),i=await this.knock.messages.batchUpdateStatuses(n,t,{metadata:s});return this.emitEvent(t,a),i}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(){const{socket:e}=this.knock.client();e&&(this.channel=e.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",t=>this.onNewMessageReceived(t)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&(e.isConnected()||e.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){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;const e=this.defaultOptions.auto_manage_socket_connection_delay??y,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=t.socket)==null||a.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=b;
|
|
1
|
+
"use strict";var f=Object.defineProperty;var p=(c,t,e)=>t in c?f(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var d=(c,t,e)=>p(c,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),_=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},S=_(k),v={archived:"exclude"},y=2e3;class b{constructor(t,e,s){d(this,"userFeedId");d(this,"channel");d(this,"broadcaster");d(this,"defaultOptions");d(this,"broadcastChannel");d(this,"disconnectTimer",null);d(this,"hasSubscribedToRealTimeUpdates",!1);d(this,"visibilityChangeHandler",()=>{});d(this,"visibilityChangeListenerConnected",!1);d(this,"store");this.knock=t,this.feedId=e,this.feedId=e,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new S.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...v,...s},this.knock.log(`[Feed] Initialized a feed on channel ${e}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),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(){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}const t=this.knock.client().socket;t&&!t.isConnected()&&t.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}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 i={seen_at:new Date().toISOString()},o=e.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",e),n}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 i={read_at:new Date().toISOString()},o=e.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",e),n}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",a=Array.isArray(t)?t:[t],n=a.map(i=>i.id);if(s){const i=a.filter(u=>!u.seen_at).length,o=a.filter(u=>!u.read_at).length,r={...e.metadata,total_count:Math.max(0,e.metadata.total_count-a.length),unseen_count:Math.max(0,e.metadata.unseen_count-i),unread_count:Math.max(0,e.metadata.unread_count-o)},l=e.items.filter(u=>!n.includes(u.id));e.setResult({entries:l,meta:r,page_info:e.pageInfo})}else e.setItemAttrs(n,{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 n=t.map(i=>i.id);e.setItemAttrs(n,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",t),a}async markAllReadAsArchived(){const{items:t,...e}=this.store.getState(),a=t.filter(o=>o.read_at===null).map(o=>o.id);if(e.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const o=t.filter(l=>!a.includes(l.id)),r={...e.metadata,total_count:o.length,unread_count:0};e.setResult({entries:o,meta:r,page_info:e.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(t){return this.optimisticallyPerformStatusUpdate(t,"unarchived",{archived_at:null}),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 a={...this.defaultOptions,...t,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},n=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:a});if(n.statusCode==="error"||!n.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:n.statusCode,data:n.error||n.body};const i={entries:n.body.entries,meta:n.body.meta,page_info:n.body.page_info};if(t.before){const l={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,l)}else if(t.after){const l={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,l)}else s.setResult(i);this.broadcast("messages.new",i);const o=t.__fetchSource==="socket"?"items.received.realtime":"items.received.page",r={items:i.entries,metadata:i.meta,event:o};return this.broadcast(r.event,r),{data:i,status:n.statusCode}}async fetchNextPage(){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({after:t.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(t,e){this.broadcaster.emit(t,e)}async onNewMessageReceived({metadata:t}){this.knock.log("[Feed] Received new real-time message");const{items:e,...s}=this.store.getState(),a=e[0];s.setMetadata(t),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(t,e,s,a){const n=this.store.getState(),i=Array.isArray(t)?t:[t],o=i.map(r=>r.id);if(a){const{metadata:r}=n,l=i.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}}),u=e.startsWith("un")?l.length:-l.length;n.setMetadata({...r,[a]:Math.max(0,r[a]+u)})}n.setItemAttrs(o,s)}async makeStatusUpdate(t,e,s){const a=Array.isArray(t)?t:[t],n=a.map(o=>o.id),i=await this.knock.messages.batchUpdateStatuses(n,e,{metadata:s});return this.emitEvent(e,a),i}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(){const{socket:t}=this.knock.client();t&&(this.channel=t.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",e=>this.onNewMessageReceived(e)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(t.isConnected()||t.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(t,e){this.broadcaster.emit(`items.${t}`,{items:e}),this.broadcaster.emit(`items:${t}`,{items:e}),this.broadcastOverChannel(`items:${t}`,{items:e})}handleVisibilityChange(){var s;const t=this.defaultOptions.auto_manage_socket_connection_delay??y,e=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=e.socket)==null||a.disconnect(),this.disconnectTimer=null},t):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=e.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=b;
|
|
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 { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n\n const itemIds: string[] = normalizedItems.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = normalizedItems.filter((i) => !i.seen_at).length;\n const unreadCount = normalizedItems.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: state.metadata.total_count - normalizedItems.length,\n unseen_count: state.metadata.unseen_count - unseenCount,\n unread_count: state.metadata.unread_count - unreadCount,\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","normalizedItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAA,GAC5CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAH,EACA,KAAA,OAAAC,EAGT,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,kBACvB,KAAK,MAAQG,EAAAA,UACR,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CAAE,GA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,KAAe,QAAQ,EACpD,KAAK,QAAQ,QAEjB,CAMQ,wBAAyB,CAE7B,OAAO,SAAa,KACpB,KAAK,oCAKP,KAAK,wBAA0B,KAAK,uBAAuB,KAAK,IAAI,EACpE,KAAK,kCAAoC,GAChC,SAAA,iBAAiB,mBAAoB,KAAK,uBAAuB,EAC5E,CAEQ,2BAA4B,CAC9B,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBAAA,EAEP,KAAK,kCAAoC,GAC3C,CAEQ,UACN+B,EAQAzB,EACA,CAEA,KAAK,YAAY,KAAK,SAASyB,CAAI,GAAI,CAAE,MAAAzB,EAAO,EAChD,KAAK,YAAY,KAAK,SAASyB,CAAI,GAAI,CAAE,MAAAzB,EAAO,EAEhD,KAAK,qBAAqB,SAASyB,CAAI,GAAI,CAAE,MAAAzB,EAAO,CACtD,CAEQ,wBAAyB,OACzB,MAAAkC,EACJ,KAAK,eAAe,qCACpBhD,EAEIiD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtCC,EAAAD,EAAO,SAAP,MAAAC,EAAe,aACf,KAAK,gBAAkB,MACtBF,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpBE,EAAAD,EAAO,SAAP,MAAAC,EAAe,eAClB,KAAK,6BAA6B,EAGxC,CACF"}
|
|
1
|
+
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAA,GAC5CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAH,EACA,KAAA,OAAAC,EAGT,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,kBACvB,KAAK,MAAQG,EAAAA,UACR,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CAAE,GAAGR,EAA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
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Typically you'll see this message when you're creating a feed instance before having called
|
|
3
|
-
authenticate with a user Id and token. That means we won't know who to issue the request
|
|
4
|
-
to Knock on behalf of.
|
|
5
|
-
`),this.apiClient||(this.apiClient=this.createApiClient()),this.apiClient}authenticate(e,t,s){let r=!1;this.apiClient&&(this.userId!==e||this.userToken!==t)&&(this.log("userId or userToken changed; reinitializing connections"),this.feeds.teardownInstances(),this.teardown(),r=!0),this.userId=e,this.userToken=t,this.log(`Authenticated with userId ${e}`),this.userToken&&(s==null?void 0:s.onUserTokenExpiring)instanceof Function&&this.maybeScheduleUserTokenExpiration(s.onUserTokenExpiring,s.timeBeforeExpirationInMs),r&&(this.apiClient=this.createApiClient(),this.feeds.reinitializeInstances(),this.log("Reinitialized real-time connections"))}isAuthenticated(e=!1){return e?!!(this.userId&&this.userToken):!!this.userId}teardown(){var e;this.tokenExpirationTimer&&clearTimeout(this.tokenExpirationTimer),(e=this.apiClient)!=null&&e.socket&&this.apiClient.socket.isConnected()&&this.apiClient.socket.disconnect()}log(e){this.logLevel==="debug"&&console.log(`[Knock] ${e}`)}createApiClient(){return new d.default({apiKey:this.apiKey,host:this.host,userToken:this.userToken})}async maybeScheduleUserTokenExpiration(e,t=3e4){if(!this.userToken)return;const s=l.jwtDecode(this.userToken),r=(s.exp??0)*1e3,o=Date.now();if(r&&r>o){const u=r-t-o;this.tokenExpirationTimer=setTimeout(async()=>{const a=await e(this.userToken,s);typeof a=="string"&&this.authenticate(this.userId,a,{onUserTokenExpiring:e,timeBeforeExpirationInMs:t})},u)}}}exports.default=x;
|
|
1
|
+
"use strict";var u=Object.defineProperty;var c=(n,e,i)=>e in n?u(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var t=(n,e,i)=>c(n,typeof e!="symbol"?e+"":e,i);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("jwt-decode"),d=require("./api.js"),p=require("./clients/feed/index.js"),k=require("./clients/messages/index.js"),f=require("./clients/objects/index.js"),T=require("./clients/preferences/index.js"),g=require("./clients/slack/index.js"),w=require("./clients/users/index.js"),x="https://api.knock.app";class C{constructor(e,i={}){t(this,"host");t(this,"apiClient",null);t(this,"userId");t(this,"userToken");t(this,"logLevel");t(this,"tokenExpirationTimer",null);t(this,"feeds",new p.default(this));t(this,"objects",new f.default(this));t(this,"preferences",new T.default(this));t(this,"slack",new g.default(this));t(this,"user",new w.default(this));t(this,"messages",new k.default(this));if(this.apiKey=e,this.host=i.host||x,this.logLevel=i.logLevel,this.log("Initialized Knock instance"),this.apiKey&&this.apiKey.startsWith("sk_"))throw new Error("[Knock] You are using your secret API key on the client. Please use the public key.")}client(){return this.apiClient||(this.apiClient=this.createApiClient()),this.apiClient}authenticate(e,i,s){let r=!1;this.apiClient&&(this.userId!==e||this.userToken!==i)&&(this.log("userId or userToken changed; reinitializing connections"),this.feeds.teardownInstances(),this.teardown(),r=!0),this.userId=e,this.userToken=i,this.log(`Authenticated with userId ${e}`),this.userToken&&(s==null?void 0:s.onUserTokenExpiring)instanceof Function&&this.maybeScheduleUserTokenExpiration(s.onUserTokenExpiring,s.timeBeforeExpirationInMs),r&&(this.apiClient=this.createApiClient(),this.feeds.reinitializeInstances(),this.log("Reinitialized real-time connections"))}isAuthenticated(e=!1){return e?!!(this.userId&&this.userToken):!!this.userId}teardown(){var e;this.tokenExpirationTimer&&clearTimeout(this.tokenExpirationTimer),(e=this.apiClient)!=null&&e.socket&&this.apiClient.socket.isConnected()&&this.apiClient.socket.disconnect()}log(e){this.logLevel==="debug"&&console.log(`[Knock] ${e}`)}createApiClient(){return new d.default({apiKey:this.apiKey,host:this.host,userToken:this.userToken})}async maybeScheduleUserTokenExpiration(e,i=3e4){if(!this.userToken)return;const s=l.jwtDecode(this.userToken),r=(s.exp??0)*1e3,o=Date.now();if(r&&r>o){const h=r-i-o;this.tokenExpirationTimer=setTimeout(async()=>{const a=await e(this.userToken,s);typeof a=="string"&&this.authenticate(this.userId,a,{onUserTokenExpiring:e,timeBeforeExpirationInMs:i})},h)}}}exports.default=C;
|
|
6
2
|
//# sourceMappingURL=knock.js.map
|
package/dist/cjs/knock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knock.js","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n
|
|
1
|
+
{"version":3,"file":"knock.js","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /*\n Authenticates the current user. In non-sandbox environments\n the userToken must be specified.\n */\n authenticate(\n userId: string,\n userToken?: string,\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n return;\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string) {\n if (this.logLevel === \"debug\") {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","UserClient","MessageClient","userId","userToken","reinitializeApi","checkUserToken","_a","message","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"kjBAgBMA,EAAe,wBAErB,MAAMC,CAAM,CAcV,YACWC,EACTC,EAAwB,GACxB,CAhBKC,EAAA,aACCA,EAAA,iBAA8B,MAC/BA,EAAA,eACAA,EAAA,kBACAA,EAAA,iBACCA,EAAA,4BAA6D,MAC5DA,EAAA,aAAQ,IAAIC,UAAW,IAAI,GAC3BD,EAAA,eAAU,IAAIE,UAAa,IAAI,GAC/BF,EAAA,mBAAc,IAAIG,UAAY,IAAI,GAClCH,EAAA,aAAQ,IAAII,UAAY,IAAI,GAC5BJ,EAAA,YAAO,IAAIK,UAAW,IAAI,GAC1BL,EAAA,gBAAW,IAAIM,UAAc,IAAI,GAYxC,GATS,KAAA,OAAAR,EAGJ,KAAA,KAAOC,EAAQ,MAAQH,EAC5B,KAAK,SAAWG,EAAQ,SAExB,KAAK,IAAI,4BAA4B,EAGjC,KAAK,QAAU,KAAK,OAAO,WAAW,KAAK,EAC7C,MAAM,IAAI,MACR,qFAAA,CAGN,CAEA,QAAS,CAEH,OAAC,KAAK,YACH,KAAA,UAAY,KAAK,mBAGjB,KAAK,SACd,CAMA,aACEQ,EACAC,EACAT,EACA,CACA,IAAIU,EAAkB,GACG,KAAK,YAM3B,KAAK,SAAWF,GAAU,KAAK,YAAcC,KAE9C,KAAK,IAAI,yDAAyD,EAClE,KAAK,MAAM,oBACX,KAAK,SAAS,EACIC,EAAA,IAGpB,KAAK,OAASF,EACd,KAAK,UAAYC,EAEZ,KAAA,IAAI,6BAA6BD,CAAM,EAAE,EAE1C,KAAK,YAAaR,GAAA,YAAAA,EAAS,+BAA+B,UACvD,KAAA,iCACHA,EAAQ,oBACRA,EAAQ,wBAAA,EAORU,IACG,KAAA,UAAY,KAAK,kBACtB,KAAK,MAAM,wBACX,KAAK,IAAI,qCAAqC,EAIlD,CAMA,gBAAgBC,EAAiB,GAAO,CAC/B,OAAAA,EAAiB,CAAC,EAAE,KAAK,QAAU,KAAK,WAAa,CAAC,CAAC,KAAK,MACrE,CAGA,UAAW,OACL,KAAK,sBACP,aAAa,KAAK,oBAAoB,GAEpCC,EAAA,KAAK,YAAL,MAAAA,EAAgB,QAAU,KAAK,UAAU,OAAO,eAC7C,KAAA,UAAU,OAAO,YAE1B,CAEA,IAAIC,EAAiB,CACf,KAAK,WAAa,SACZ,QAAA,IAAI,WAAWA,CAAO,EAAE,CAEpC,CAKQ,iBAAkB,CACxB,OAAO,IAAIC,EAAAA,QAAU,CACnB,OAAQ,KAAK,OACb,KAAM,KAAK,KACX,UAAW,KAAK,SAAA,CACjB,CACH,CAEA,MAAc,iCACZC,EACAC,EAAmC,IACnC,CACI,GAAA,CAAC,KAAK,UAAW,OAEf,MAAAC,EAAUC,EAAAA,UAAU,KAAK,SAAS,EAClCC,GAAeF,EAAQ,KAAO,GAAK,IACnCG,EAAQ,KAAK,MAGf,GAAAD,GAAeA,EAAcC,EAAO,CAIhC,MAAAC,EAAaF,EAAcH,EAA2BI,EAEvD,KAAA,qBAAuB,WAAW,SAAY,CACjD,MAAME,EAAW,MAAMP,EAAW,KAAK,UAAqBE,CAAO,EAG/D,OAAOK,GAAa,UACjB,KAAA,aAAa,KAAK,OAASA,EAAU,CACxC,oBAAqBP,EACrB,yBAAAC,CAAA,CACD,GAEFK,CAAU,CACf,CACF,CACF"}
|
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
var f = Object.defineProperty;
|
|
2
2
|
var p = (u, e, t) => e in u ? f(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
3
|
-
var
|
|
4
|
-
import
|
|
5
|
-
import { isRequestInFlight as
|
|
6
|
-
import
|
|
3
|
+
var c = (u, e, t) => p(u, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import k from "eventemitter2";
|
|
5
|
+
import { isRequestInFlight as g, NetworkStatus as m } from "../../networkStatus.mjs";
|
|
6
|
+
import _ from "./store.mjs";
|
|
7
7
|
const S = {
|
|
8
8
|
archived: "exclude"
|
|
9
9
|
}, v = 2e3;
|
|
10
|
-
class
|
|
10
|
+
class U {
|
|
11
11
|
constructor(e, t, s) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
12
|
+
c(this, "userFeedId");
|
|
13
|
+
c(this, "channel");
|
|
14
|
+
c(this, "broadcaster");
|
|
15
|
+
c(this, "defaultOptions");
|
|
16
|
+
c(this, "broadcastChannel");
|
|
17
|
+
c(this, "disconnectTimer", null);
|
|
18
|
+
c(this, "hasSubscribedToRealTimeUpdates", !1);
|
|
19
|
+
c(this, "visibilityChangeHandler", () => {
|
|
20
20
|
});
|
|
21
|
-
|
|
21
|
+
c(this, "visibilityChangeListenerConnected", !1);
|
|
22
22
|
// The raw store instance, used for binding in React and other environments
|
|
23
|
-
|
|
24
|
-
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store =
|
|
23
|
+
c(this, "store");
|
|
24
|
+
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store = _(), this.broadcaster = new k({ wildcard: !0, delimiter: "." }), this.defaultOptions = { ...S, ...s }, this.knock.log(`[Feed] Initialized a feed on channel ${t}`), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
@@ -45,7 +45,12 @@ class I {
|
|
|
45
45
|
current ApiClient instance if the socket is not already connected.
|
|
46
46
|
*/
|
|
47
47
|
listenForUpdates() {
|
|
48
|
-
this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0
|
|
48
|
+
if (this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0, !this.knock.isAuthenticated()) {
|
|
49
|
+
this.knock.log(
|
|
50
|
+
"[Feed] User is not authenticated, skipping listening for updates"
|
|
51
|
+
);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
49
54
|
const e = this.knock.client().socket;
|
|
50
55
|
e && !e.isConnected() && e.connect(), this.channel && ["closed", "errored"].includes(this.channel.state) && this.channel.join();
|
|
51
56
|
}
|
|
@@ -150,14 +155,16 @@ class I {
|
|
|
150
155
|
if (s) {
|
|
151
156
|
const i = a.filter((l) => !l.seen_at).length, o = a.filter((l) => !l.read_at).length, r = {
|
|
152
157
|
...t.metadata,
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
158
|
+
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
159
|
+
// gets out of sync with the server state
|
|
160
|
+
total_count: Math.max(0, t.metadata.total_count - a.length),
|
|
161
|
+
unseen_count: Math.max(0, t.metadata.unseen_count - i),
|
|
162
|
+
unread_count: Math.max(0, t.metadata.unread_count - o)
|
|
163
|
+
}, d = t.items.filter(
|
|
157
164
|
(l) => !n.includes(l.id)
|
|
158
165
|
);
|
|
159
166
|
t.setResult({
|
|
160
|
-
entries:
|
|
167
|
+
entries: d,
|
|
161
168
|
meta: r,
|
|
162
169
|
page_info: t.pageInfo
|
|
163
170
|
});
|
|
@@ -181,7 +188,7 @@ class I {
|
|
|
181
188
|
if (t.setItemAttrs(a, {
|
|
182
189
|
archived_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
183
190
|
}), this.defaultOptions.archived === "exclude") {
|
|
184
|
-
const o = e.filter((
|
|
191
|
+
const o = e.filter((d) => !a.includes(d.id)), r = {
|
|
185
192
|
...t.metadata,
|
|
186
193
|
total_count: o.length,
|
|
187
194
|
unread_count: 0
|
|
@@ -202,8 +209,14 @@ class I {
|
|
|
202
209
|
/* Fetches the feed content, appending it to the store */
|
|
203
210
|
async fetch(e = {}) {
|
|
204
211
|
const { networkStatus: t, ...s } = this.store.getState();
|
|
205
|
-
if (
|
|
212
|
+
if (!this.knock.isAuthenticated()) {
|
|
213
|
+
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
206
214
|
return;
|
|
215
|
+
}
|
|
216
|
+
if (g(t)) {
|
|
217
|
+
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
207
220
|
s.setNetworkStatus(e.__loadingType ?? m.loading);
|
|
208
221
|
const a = {
|
|
209
222
|
...this.defaultOptions,
|
|
@@ -230,11 +243,11 @@ class I {
|
|
|
230
243
|
page_info: n.body.page_info
|
|
231
244
|
};
|
|
232
245
|
if (e.before) {
|
|
233
|
-
const
|
|
234
|
-
s.setResult(i,
|
|
246
|
+
const d = { shouldSetPage: !1, shouldAppend: !0 };
|
|
247
|
+
s.setResult(i, d);
|
|
235
248
|
} else if (e.after) {
|
|
236
|
-
const
|
|
237
|
-
s.setResult(i,
|
|
249
|
+
const d = { shouldSetPage: !0, shouldAppend: !0 };
|
|
250
|
+
s.setResult(i, d);
|
|
238
251
|
} else
|
|
239
252
|
s.setResult(i);
|
|
240
253
|
this.broadcast("messages.new", i);
|
|
@@ -269,7 +282,7 @@ class I {
|
|
|
269
282
|
optimisticallyPerformStatusUpdate(e, t, s, a) {
|
|
270
283
|
const n = this.store.getState(), i = Array.isArray(e) ? e : [e], o = i.map((r) => r.id);
|
|
271
284
|
if (a) {
|
|
272
|
-
const { metadata: r } = n,
|
|
285
|
+
const { metadata: r } = n, d = i.filter((h) => {
|
|
273
286
|
switch (t) {
|
|
274
287
|
case "seen":
|
|
275
288
|
return h.seen_at === null;
|
|
@@ -283,7 +296,7 @@ class I {
|
|
|
283
296
|
default:
|
|
284
297
|
return !0;
|
|
285
298
|
}
|
|
286
|
-
}), l = t.startsWith("un") ?
|
|
299
|
+
}), l = t.startsWith("un") ? d.length : -d.length;
|
|
287
300
|
n.setMetadata({
|
|
288
301
|
...r,
|
|
289
302
|
[a]: Math.max(0, r[a] + l)
|
|
@@ -348,7 +361,7 @@ class I {
|
|
|
348
361
|
e && (this.channel = e.channel(
|
|
349
362
|
`feeds:${this.userFeedId}`,
|
|
350
363
|
this.defaultOptions
|
|
351
|
-
), this.channel.on("new-message", (t) => this.onNewMessageReceived(t)), this.defaultOptions.auto_manage_socket_connection && this.setupAutoSocketManager(), this.hasSubscribedToRealTimeUpdates && (e.isConnected() || e.connect(), this.channel.join()));
|
|
364
|
+
), this.channel.on("new-message", (t) => this.onNewMessageReceived(t)), this.defaultOptions.auto_manage_socket_connection && this.setupAutoSocketManager(), this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated() && (e.isConnected() || e.connect(), this.channel.join()));
|
|
352
365
|
}
|
|
353
366
|
/**
|
|
354
367
|
* Listen for changes to document visibility and automatically disconnect
|
|
@@ -376,6 +389,6 @@ class I {
|
|
|
376
389
|
}
|
|
377
390
|
}
|
|
378
391
|
export {
|
|
379
|
-
|
|
392
|
+
U as default
|
|
380
393
|
};
|
|
381
394
|
//# sourceMappingURL=feed.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n\n const itemIds: string[] = normalizedItems.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = normalizedItems.filter((i) => !i.seen_at).length;\n const unreadCount = normalizedItems.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: state.metadata.total_count - normalizedItems.length,\n unseen_count: state.metadata.unseen_count - unseenCount,\n unread_count: state.metadata.unread_count - unreadCount,\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","normalizedItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":";;;;;;AAgCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B;AAEjC,MAAMC,EAAK;AAAA,EAcT,YACWC,GACAC,GACTC,GACA;AAjBM,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA,yBAAwD;AACxD,IAAAA,EAAA,wCAA0C;AAC1C,IAAAA,EAAA,iCAAsC,MAAM;AAAA,IAAA;AAC5C,IAAAA,EAAA,2CAA6C;AAG9C;AAAA,IAAAA,EAAA;AAGI,SAAA,QAAAH,GACA,KAAA,SAAAC,GAGT,KAAK,SAASA,GACT,KAAA,aAAa,KAAK,mBACvB,KAAK,QAAQG,KACR,KAAA,cAAc,IAAIC,EAAa,EAAE,UAAU,IAAM,WAAW,KAAK,GACtE,KAAK,iBAAiB,EAAE,GAAGR,GAAoB,GAAGK,EAAQ,GAE1D,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,GAG/D,KAAK,6BAA6B,GAElC,KAAK,sBAAsB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA,EAKA,eAAe;AAER,SAAA,aAAa,KAAK,mBAGvB,KAAK,6BAA6B,GAGlC,KAAK,sBAAsB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW;AACJ,SAAA,MAAM,IAAI,mCAAmC,GAE9C,KAAK,YACP,KAAK,QAAQ,SACR,KAAA,QAAQ,IAAI,aAAa,IAGhC,KAAK,0BAA0B,GAE3B,KAAK,oBACP,aAAa,KAAK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,KAAK,0BAA0B,KAAK,uBAAuB,KAAK,IAAI,GACpE,KAAK,oCAAoC,IAChC,SAAA,iBAAiB,oBAAoB,KAAK,uBAAuB;AAAA,EAC5E;AAAA,EAEQ,4BAA4B;AAC9B,IAAA,OAAO,WAAa,QAEf,SAAA;AAAA,MACP;AAAA,MACA,KAAK;AAAA,IAAA,GAEP,KAAK,oCAAoC;AAAA,EAC3C;AAAA,EAEQ,UACN+B,GAQAzB,GACA;AAEA,SAAK,YAAY,KAAK,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO,GAChD,KAAK,YAAY,KAAK,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO,GAEhD,KAAK,qBAAqB,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO;AAAA,EACtD;AAAA,EAEQ,yBAAyB;;AACzB,UAAAkC,IACJ,KAAK,eAAe,uCACpBhD,GAEIiD,IAAS,KAAK,MAAM,OAAO;AAE7B,IAAA,SAAS,oBAAoB,WAE1B,KAAA,kBAAkB,WAAW,MAAM;;AACtC,OAAAC,IAAAD,EAAO,WAAP,QAAAC,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtBF,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpBE,IAAAD,EAAO,WAAP,QAAAC,EAAe,iBAClB,KAAK,6BAA6B;AAAA,EAGxC;AACF;"}
|
|
1
|
+
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":";;;;;;AAgCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B;AAEjC,MAAMC,EAAK;AAAA,EAcT,YACWC,GACAC,GACTC,GACA;AAjBM,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA,yBAAwD;AACxD,IAAAA,EAAA,wCAA0C;AAC1C,IAAAA,EAAA,iCAAsC,MAAM;AAAA,IAAA;AAC5C,IAAAA,EAAA,2CAA6C;AAG9C;AAAA,IAAAA,EAAA;AAGI,SAAA,QAAAH,GACA,KAAA,SAAAC,GAGT,KAAK,SAASA,GACT,KAAA,aAAa,KAAK,mBACvB,KAAK,QAAQG,KACR,KAAA,cAAc,IAA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ASwB,CAAI,IAAI,EAAE,OAAAxB,GAAO,GAEhD,KAAK,qBAAqB,SAASwB,CAAI,IAAI,EAAE,OAAAxB,GAAO;AAAA,EACtD;AAAA,EAEQ,yBAAyB;;AACzB,UAAAkC,IACJ,KAAK,eAAe,uCACpBhD,GAEIiD,IAAS,KAAK,MAAM,OAAO;AAE7B,IAAA,SAAS,oBAAoB,WAE1B,KAAA,kBAAkB,WAAW,MAAM;;AACtC,OAAAC,IAAAD,EAAO,WAAP,QAAAC,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtBF,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpBE,IAAAD,EAAO,WAAP,QAAAC,EAAe,iBAClB,KAAK,6BAA6B;AAAA,EAGxC;AACF;"}
|
package/dist/esm/knock.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var l = Object.defineProperty;
|
|
2
|
-
var c = (n, e,
|
|
3
|
-
var
|
|
2
|
+
var c = (n, e, i) => e in n ? l(n, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : n[e] = i;
|
|
3
|
+
var t = (n, e, i) => c(n, typeof e != "symbol" ? e + "" : e, i);
|
|
4
4
|
import { jwtDecode as u } from "jwt-decode";
|
|
5
5
|
import p from "./api.mjs";
|
|
6
6
|
import k from "./clients/feed/index.mjs";
|
|
@@ -8,46 +8,40 @@ import f from "./clients/messages/index.mjs";
|
|
|
8
8
|
import d from "./clients/objects/index.mjs";
|
|
9
9
|
import m from "./clients/preferences/index.mjs";
|
|
10
10
|
import T from "./clients/slack/index.mjs";
|
|
11
|
-
import
|
|
11
|
+
import C from "./clients/users/index.mjs";
|
|
12
12
|
const g = "https://api.knock.app";
|
|
13
|
-
class
|
|
14
|
-
constructor(e,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (this.apiKey = e, this.host =
|
|
13
|
+
class z {
|
|
14
|
+
constructor(e, i = {}) {
|
|
15
|
+
t(this, "host");
|
|
16
|
+
t(this, "apiClient", null);
|
|
17
|
+
t(this, "userId");
|
|
18
|
+
t(this, "userToken");
|
|
19
|
+
t(this, "logLevel");
|
|
20
|
+
t(this, "tokenExpirationTimer", null);
|
|
21
|
+
t(this, "feeds", new k(this));
|
|
22
|
+
t(this, "objects", new d(this));
|
|
23
|
+
t(this, "preferences", new m(this));
|
|
24
|
+
t(this, "slack", new T(this));
|
|
25
|
+
t(this, "user", new C(this));
|
|
26
|
+
t(this, "messages", new f(this));
|
|
27
|
+
if (this.apiKey = e, this.host = i.host || g, this.logLevel = i.logLevel, this.log("Initialized Knock instance"), this.apiKey && this.apiKey.startsWith("sk_"))
|
|
28
28
|
throw new Error(
|
|
29
29
|
"[Knock] You are using your secret API key on the client. Please use the public key."
|
|
30
30
|
);
|
|
31
31
|
}
|
|
32
32
|
client() {
|
|
33
|
-
return this.
|
|
34
|
-
`[Knock] You must call authenticate(userId, userToken) first before trying to make a request.
|
|
35
|
-
Typically you'll see this message when you're creating a feed instance before having called
|
|
36
|
-
authenticate with a user Id and token. That means we won't know who to issue the request
|
|
37
|
-
to Knock on behalf of.
|
|
38
|
-
`
|
|
39
|
-
), this.apiClient || (this.apiClient = this.createApiClient()), this.apiClient;
|
|
33
|
+
return this.apiClient || (this.apiClient = this.createApiClient()), this.apiClient;
|
|
40
34
|
}
|
|
41
35
|
/*
|
|
42
36
|
Authenticates the current user. In non-sandbox environments
|
|
43
37
|
the userToken must be specified.
|
|
44
38
|
*/
|
|
45
|
-
authenticate(e,
|
|
46
|
-
let
|
|
47
|
-
this.apiClient && (this.userId !== e || this.userToken !==
|
|
39
|
+
authenticate(e, i, s) {
|
|
40
|
+
let r = !1;
|
|
41
|
+
this.apiClient && (this.userId !== e || this.userToken !== i) && (this.log("userId or userToken changed; reinitializing connections"), this.feeds.teardownInstances(), this.teardown(), r = !0), this.userId = e, this.userToken = i, this.log(`Authenticated with userId ${e}`), this.userToken && (s == null ? void 0 : s.onUserTokenExpiring) instanceof Function && this.maybeScheduleUserTokenExpiration(
|
|
48
42
|
s.onUserTokenExpiring,
|
|
49
43
|
s.timeBeforeExpirationInMs
|
|
50
|
-
),
|
|
44
|
+
), r && (this.apiClient = this.createApiClient(), this.feeds.reinitializeInstances(), this.log("Reinitialized real-time connections"));
|
|
51
45
|
}
|
|
52
46
|
/*
|
|
53
47
|
Returns whether or this Knock instance is authenticated. Passing `true` will check the presence
|
|
@@ -74,22 +68,22 @@ class v {
|
|
|
74
68
|
userToken: this.userToken
|
|
75
69
|
});
|
|
76
70
|
}
|
|
77
|
-
async maybeScheduleUserTokenExpiration(e,
|
|
71
|
+
async maybeScheduleUserTokenExpiration(e, i = 3e4) {
|
|
78
72
|
if (!this.userToken) return;
|
|
79
|
-
const s = u(this.userToken),
|
|
80
|
-
if (
|
|
81
|
-
const
|
|
73
|
+
const s = u(this.userToken), r = (s.exp ?? 0) * 1e3, o = Date.now();
|
|
74
|
+
if (r && r > o) {
|
|
75
|
+
const a = r - i - o;
|
|
82
76
|
this.tokenExpirationTimer = setTimeout(async () => {
|
|
83
|
-
const
|
|
84
|
-
typeof
|
|
77
|
+
const h = await e(this.userToken, s);
|
|
78
|
+
typeof h == "string" && this.authenticate(this.userId, h, {
|
|
85
79
|
onUserTokenExpiring: e,
|
|
86
|
-
timeBeforeExpirationInMs:
|
|
80
|
+
timeBeforeExpirationInMs: i
|
|
87
81
|
});
|
|
88
|
-
},
|
|
82
|
+
}, a);
|
|
89
83
|
}
|
|
90
84
|
}
|
|
91
85
|
}
|
|
92
86
|
export {
|
|
93
|
-
|
|
87
|
+
z as default
|
|
94
88
|
};
|
|
95
89
|
//# sourceMappingURL=knock.mjs.map
|
package/dist/esm/knock.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knock.mjs","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n
|
|
1
|
+
{"version":3,"file":"knock.mjs","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /*\n Authenticates the current user. In non-sandbox environments\n the userToken must be specified.\n */\n authenticate(\n userId: string,\n userToken?: string,\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n return;\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string) {\n if (this.logLevel === \"debug\") {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","UserClient","MessageClient","userId","userToken","reinitializeApi","checkUserToken","_a","message","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":";;;;;;;;;;;AAgBA,MAAMA,IAAe;AAErB,MAAMC,EAA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S7C,KAAK,CAAC,OAAO,GAAE,gBAAqB;;;;IAiFpC,aAAa;IAenB,OAAO,CAAC,SAAS;YAQH,oBAAoB;IAclC,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,iCAAiC;YAiD3B,gBAAgB;YAsBhB,oBAAoB;IA2BlC,OAAO,CAAC,qBAAqB;IAoC7B,OAAO,CAAC,oBAAoB;IAoB5B,OAAO,CAAC,4BAA4B;IA0BpC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,yBAAyB;IAUjC,OAAO,CAAC,SAAS;IAkBjB,OAAO,CAAC,sBAAsB;CA2B/B;AAED,eAAe,IAAI,CAAC"}
|
|
@@ -31,7 +31,7 @@ export type BulkUpdateMessagesInChannelProperties = {
|
|
|
31
31
|
status: "seen" | "read" | "archive";
|
|
32
32
|
options: {
|
|
33
33
|
user_ids?: string[];
|
|
34
|
-
engagement_status?: "seen" | "read" | "unseen" | "unread";
|
|
34
|
+
engagement_status?: "seen" | "read" | "archived" | "unseen" | "unread" | "unarchived" | "interacted" | "link_clicked";
|
|
35
35
|
archived?: "exclude" | "include" | "only";
|
|
36
36
|
has_tenant?: boolean;
|
|
37
37
|
tenants?: string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../../src/clients/messages/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,MAAM,qBAAqB,GAC7B,QAAQ,GACR,MAAM,GACN,WAAW,GACX,oBAAoB,GACpB,aAAa,GACb,UAAU,CAAC;AAEf,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB;AAED,MAAM,MAAM,uBAAuB,GAC/B,M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AM,0BAA0B,GAAG;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACnC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knock.d.ts","sourceRoot":"","sources":["../../src/knock.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,OAAO,CAAC;AAC9B,OAAO,UAAU,MAAM,gBAAgB,CAAC;AACxC,OAAO,aAAa,MAAM,oBAAoB,CAAC;AAC/C,OAAO,YAAY,MAAM,mBAAmB,CAAC;AAC7C,OAAO,WAAW,MAAM,uBAAuB,CAAC;AAChD,OAAO,WAAW,MAAM,iBAAiB,CAAC;AAC1C,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,QAAQ,EAET,MAAM,cAAc,CAAC;AAItB,cAAM,KAAK;IAeP,QAAQ,CAAC,MAAM,EAAE,MAAM;IAdlB,IAAI,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,SAAS,CAA0B;IACpC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC3B,OAAO,CAAC,oBAAoB,CAA8C;IAC1E,QAAQ,CAAC,KAAK,aAAwB;IACtC,QAAQ,CAAC,OAAO,eAA0B;IAC1C,QAAQ,CAAC,WAAW,cAAyB;IAC7C,QAAQ,CAAC,KAAK,cAAyB;IACvC,QAAQ,CAAC,IAAI,aAAwB;IACrC,QAAQ,CAAC,QAAQ,gBAA2B;gBAGjC,MAAM,EAAE,MAAM,EACvB,OAAO,GAAE,YAAiB;IAe5B,MAAM;
|
|
1
|
+
{"version":3,"file":"knock.d.ts","sourceRoot":"","sources":["../../src/knock.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,OAAO,CAAC;AAC9B,OAAO,UAAU,MAAM,gBAAgB,CAAC;AACxC,OAAO,aAAa,MAAM,oBAAoB,CAAC;AAC/C,OAAO,YAAY,MAAM,mBAAmB,CAAC;AAC7C,OAAO,WAAW,MAAM,uBAAuB,CAAC;AAChD,OAAO,WAAW,MAAM,iBAAiB,CAAC;AAC1C,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,QAAQ,EAET,MAAM,cAAc,CAAC;AAItB,cAAM,KAAK;IAeP,QAAQ,CAAC,MAAM,EAAE,MAAM;IAdlB,IAAI,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,SAAS,CAA0B;IACpC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC3B,OAAO,CAAC,oBAAoB,CAA8C;IAC1E,QAAQ,CAAC,KAAK,aAAwB;IACtC,QAAQ,CAAC,OAAO,eAA0B;IAC1C,QAAQ,CAAC,WAAW,cAAyB;IAC7C,QAAQ,CAAC,KAAK,cAAyB;IACvC,QAAQ,CAAC,IAAI,aAAwB;IACrC,QAAQ,CAAC,QAAQ,gBAA2B;gBAGjC,MAAM,EAAE,MAAM,EACvB,OAAO,GAAE,YAAiB;IAe5B,MAAM;IAaN,YAAY,CACV,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,mBAAmB;IA6C/B,eAAe,CAAC,cAAc,UAAQ;IAKtC,QAAQ;IASR,GAAG,CAAC,OAAO,EAAE,MAAM;IAMnB;;OAEG;IACH,OAAO,CAAC,eAAe;YAQT,gCAAgC;CA8B/C;AAED,eAAe,KAAK,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@knocklabs/client",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.17",
|
|
4
4
|
"description": "The clientside library for interacting with Knock",
|
|
5
5
|
"homepage": "https://github.com/knocklabs/javascript/tree/main/packages/client",
|
|
6
6
|
"author": "@knocklabs",
|
|
@@ -47,21 +47,21 @@
|
|
|
47
47
|
"prepublishOnly": "npm run build"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@babel/cli": "^7.
|
|
50
|
+
"@babel/cli": "^7.26.4",
|
|
51
51
|
"@babel/core": "^7.26.0",
|
|
52
52
|
"@babel/plugin-proposal-class-properties": "^7.16.7",
|
|
53
53
|
"@babel/plugin-proposal-object-rest-spread": "^7.16.7",
|
|
54
54
|
"@babel/plugin-transform-runtime": "^7.25.4",
|
|
55
|
-
"@babel/preset-env": "^7.
|
|
55
|
+
"@babel/preset-env": "^7.26.0",
|
|
56
56
|
"@babel/preset-typescript": "^7.16.7",
|
|
57
57
|
"@types/jsonwebtoken": "^9.0.5",
|
|
58
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
58
|
+
"@typescript-eslint/eslint-plugin": "^8.19.1",
|
|
59
59
|
"@typescript-eslint/parser": "^8.16.0",
|
|
60
60
|
"cross-env": "^7.0.3",
|
|
61
61
|
"crypto": "^1.0.1",
|
|
62
62
|
"eslint": "^8.56.0",
|
|
63
63
|
"jsonwebtoken": "^9.0.2",
|
|
64
|
-
"prettier": "^3.
|
|
64
|
+
"prettier": "^3.4.2",
|
|
65
65
|
"rimraf": "^6.0.1",
|
|
66
66
|
"rollup": "^4.27.4",
|
|
67
67
|
"typescript": "^5.6.3",
|
|
@@ -69,10 +69,10 @@
|
|
|
69
69
|
"vitest": "^2.1.4"
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
-
"@babel/runtime": "^7.
|
|
72
|
+
"@babel/runtime": "^7.26.0",
|
|
73
73
|
"@knocklabs/types": "^0.1.5",
|
|
74
74
|
"@types/phoenix": "^1.6.6",
|
|
75
|
-
"axios": "^1.7.
|
|
75
|
+
"axios": "^1.7.9",
|
|
76
76
|
"axios-retry": "^4.5.0",
|
|
77
77
|
"eventemitter2": "^6.4.5",
|
|
78
78
|
"jwt-decode": "^4.0.0",
|
package/src/clients/feed/feed.ts
CHANGED
|
@@ -124,6 +124,14 @@ class Feed {
|
|
|
124
124
|
|
|
125
125
|
this.hasSubscribedToRealTimeUpdates = true;
|
|
126
126
|
|
|
127
|
+
// If the user is not authenticated, then do nothing
|
|
128
|
+
if (!this.knock.isAuthenticated()) {
|
|
129
|
+
this.knock.log(
|
|
130
|
+
"[Feed] User is not authenticated, skipping listening for updates",
|
|
131
|
+
);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
127
135
|
const maybeSocket = this.knock.client().socket;
|
|
128
136
|
|
|
129
137
|
// Connect the socket only if we don't already have a connection
|
|
@@ -318,11 +326,9 @@ class Feed {
|
|
|
318
326
|
const shouldOptimisticallyRemoveItems =
|
|
319
327
|
this.defaultOptions.archived === "exclude";
|
|
320
328
|
|
|
321
|
-
const
|
|
322
|
-
? itemOrItems
|
|
323
|
-
: [itemOrItems];
|
|
329
|
+
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
|
|
324
330
|
|
|
325
|
-
const itemIds: string[] =
|
|
331
|
+
const itemIds: string[] = items.map((item) => item.id);
|
|
326
332
|
|
|
327
333
|
/*
|
|
328
334
|
In the code here we want to optimistically update counts and items
|
|
@@ -354,15 +360,17 @@ class Feed {
|
|
|
354
360
|
if (shouldOptimisticallyRemoveItems) {
|
|
355
361
|
// If any of the items are unseen or unread, then capture as we'll want to decrement
|
|
356
362
|
// the counts for these in the metadata we have
|
|
357
|
-
const unseenCount =
|
|
358
|
-
const unreadCount =
|
|
363
|
+
const unseenCount = items.filter((i) => !i.seen_at).length;
|
|
364
|
+
const unreadCount = items.filter((i) => !i.read_at).length;
|
|
359
365
|
|
|
360
366
|
// Build the new metadata
|
|
361
367
|
const updatedMetadata = {
|
|
362
368
|
...state.metadata,
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
369
|
+
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
370
|
+
// gets out of sync with the server state
|
|
371
|
+
total_count: Math.max(0, state.metadata.total_count - items.length),
|
|
372
|
+
unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),
|
|
373
|
+
unread_count: Math.max(0, state.metadata.unread_count - unreadCount),
|
|
366
374
|
};
|
|
367
375
|
|
|
368
376
|
// Remove the archiving entries
|
|
@@ -464,8 +472,15 @@ class Feed {
|
|
|
464
472
|
async fetch(options: FetchFeedOptions = {}) {
|
|
465
473
|
const { networkStatus, ...state } = this.store.getState();
|
|
466
474
|
|
|
475
|
+
// If the user is not authenticated, then do nothing
|
|
476
|
+
if (!this.knock.isAuthenticated()) {
|
|
477
|
+
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
|
|
467
481
|
// If there's an existing request in flight, then do nothing
|
|
468
482
|
if (isRequestInFlight(networkStatus)) {
|
|
483
|
+
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
469
484
|
return;
|
|
470
485
|
}
|
|
471
486
|
|
|
@@ -750,7 +765,7 @@ class Feed {
|
|
|
750
765
|
|
|
751
766
|
// If we're initializing but they have previously opted to listen to real-time updates
|
|
752
767
|
// then we will automatically reconnect on their behalf
|
|
753
|
-
if (this.hasSubscribedToRealTimeUpdates) {
|
|
768
|
+
if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {
|
|
754
769
|
if (!maybeSocket.isConnected()) maybeSocket.connect();
|
|
755
770
|
this.channel.join();
|
|
756
771
|
}
|
|
@@ -47,7 +47,15 @@ export type BulkUpdateMessagesInChannelProperties = {
|
|
|
47
47
|
status: "seen" | "read" | "archive";
|
|
48
48
|
options: {
|
|
49
49
|
user_ids?: string[];
|
|
50
|
-
engagement_status?:
|
|
50
|
+
engagement_status?:
|
|
51
|
+
| "seen"
|
|
52
|
+
| "read"
|
|
53
|
+
| "archived"
|
|
54
|
+
| "unseen"
|
|
55
|
+
| "unread"
|
|
56
|
+
| "unarchived"
|
|
57
|
+
| "interacted"
|
|
58
|
+
| "link_clicked";
|
|
51
59
|
archived?: "exclude" | "include" | "only";
|
|
52
60
|
has_tenant?: boolean;
|
|
53
61
|
tenants?: string[];
|
package/src/knock.ts
CHANGED
|
@@ -48,16 +48,6 @@ class Knock {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
client() {
|
|
51
|
-
if (!this.userId) {
|
|
52
|
-
console.warn(
|
|
53
|
-
`[Knock] You must call authenticate(userId, userToken) first before trying to make a request.
|
|
54
|
-
Typically you'll see this message when you're creating a feed instance before having called
|
|
55
|
-
authenticate with a user Id and token. That means we won't know who to issue the request
|
|
56
|
-
to Knock on behalf of.
|
|
57
|
-
`,
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
51
|
// Initiate a new API client if we don't have one yet
|
|
62
52
|
if (!this.apiClient) {
|
|
63
53
|
this.apiClient = this.createApiClient();
|