@knocklabs/client
Advanced tools
Comparing version 0.10.8 to 0.10.9
# Changelog | ||
## 0.10.9 | ||
### Patch Changes | ||
- d0adb14: fix: don't destroy the store, ever | ||
## 0.10.8 | ||
@@ -4,0 +10,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict";var f=Object.defineProperty;var p=(u,e,t)=>e in u?f(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var r=(u,e,t)=>(p(u,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},S=2e3;class y{constructor(e,t,s){r(this,"userFeedId");r(this,"channel");r(this,"broadcaster");r(this,"defaultOptions");r(this,"broadcastChannel");r(this,"disconnectTimer",null);r(this,"hasSubscribedToRealTimeUpdates",!1);r(this,"visibilityChangeHandler",()=>{});r(this,"visibilityChangeListenerConnected",!1);r(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new k({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...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),this.store.destroy()}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()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),a}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()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),a}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],a=n.map(i=>i.id);if(s){const i=n.filter(l=>!l.seen_at).length,c=n.filter(l=>!l.read_at).length,o={...t.metadata,total_count:t.metadata.total_count-n.length,unseen_count:t.metadata.unseen_count-i,unread_count:t.metadata.unread_count-c},d=t.items.filter(l=>!a.includes(l.id));t.setResult({entries:d,meta:o,page_info:t.pageInfo})}else t.setItemAttrs(a,{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 a=e.map(i=>i.id);t.setItemAttrs(a,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),n}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 n={...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},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:n});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,d)}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,d)}else s.setResult(i);this.broadcast("messages.new",i);const c=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:c};return this.broadcast(o.event,o),{data:i,status:a.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(),n=t[0];s.setMetadata(e),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,n){const a=this.store.getState(),i=Array.isArray(e)?e:[e],c=i.map(o=>o.id);if(n){const{metadata:o}=a,d=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}}),l=t.startsWith("un")?d.length:-d.length;a.setMetadata({...o,[n]:Math.max(0,o[n]+l)})}a.setItemAttrs(c,s)}async makeStatusUpdate(e,t){const s=Array.isArray(e)?e:[e],n=s.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,s),a}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){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??S,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.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=y; | ||
"use strict";var f=Object.defineProperty;var p=(u,e,t)=>e in u?f(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var r=(u,e,t)=>(p(u,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},S=2e3;class v{constructor(e,t,s){r(this,"userFeedId");r(this,"channel");r(this,"broadcaster");r(this,"defaultOptions");r(this,"broadcastChannel");r(this,"disconnectTimer",null);r(this,"hasSubscribedToRealTimeUpdates",!1);r(this,"visibilityChangeHandler",()=>{});r(this,"visibilityChangeListenerConnected",!1);r(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new k({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...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()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),a}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()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),a}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],a=n.map(i=>i.id);if(s){const i=n.filter(l=>!l.seen_at).length,c=n.filter(l=>!l.read_at).length,o={...t.metadata,total_count:t.metadata.total_count-n.length,unseen_count:t.metadata.unseen_count-i,unread_count:t.metadata.unread_count-c},d=t.items.filter(l=>!a.includes(l.id));t.setResult({entries:d,meta:o,page_info:t.pageInfo})}else t.setItemAttrs(a,{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 a=e.map(i=>i.id);t.setItemAttrs(a,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),n}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 n={...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},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:n});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,d)}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,d)}else s.setResult(i);this.broadcast("messages.new",i);const c=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:c};return this.broadcast(o.event,o),{data:i,status:a.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(),n=t[0];s.setMetadata(e),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,n){const a=this.store.getState(),i=Array.isArray(e)?e:[e],c=i.map(o=>o.id);if(n){const{metadata:o}=a,d=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}}),l=t.startsWith("un")?d.length:-d.length;a.setMetadata({...o,[n]:Math.max(0,o[n]+l)})}a.setItemAttrs(c,s)}async makeStatusUpdate(e,t){const s=Array.isArray(e)?e:[e],n=s.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,s),a}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){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??S,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.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=v; | ||
//# sourceMappingURL=feed.js.map |
{ | ||
"name": "@knocklabs/client", | ||
"version": "0.10.8", | ||
"version": "0.10.9", | ||
"description": "The clientside library for interacting with Knock", | ||
@@ -5,0 +5,0 @@ "homepage": "https://github.com/knocklabs/javascript/tree/main/packages/client", |
@@ -115,3 +115,2 @@ import EventEmitter from "eventemitter2"; | ||
this.knock.feeds.removeInstance(this); | ||
this.store.destroy(); | ||
} | ||
@@ -118,0 +117,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
329343
3508