@knocklabs/client
Advanced tools
Comparing version 0.10.2 to 0.10.3
# Changelog | ||
## 0.10.3 | ||
### Patch Changes | ||
- a71ce51: fix: event types to use items. and fix types | ||
## 0.10.2 | ||
@@ -4,0 +10,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict";var S=Object.defineProperty;var k=(m,e,t)=>e in m?S(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var u=(m,e,t)=>(k(m,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("eventemitter2"),f=require("../../networkStatus.js"),_=require("./store.js"),g={archived:"exclude"},v=2e3;class y{constructor(e,t,s){u(this,"userFeedId");u(this,"channel");u(this,"broadcaster");u(this,"defaultOptions");u(this,"broadcastChannel");u(this,"disconnectTimer",null);u(this,"hasSubscribedToRealTimeUpdates",!1);u(this,"visibilityChangeHandler",()=>{});u(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=_.default(),this.broadcaster=new p({wildcard:!0,delimiter:"."}),this.defaultOptions={...g,...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{getState:e,setState:t}=this.store,{metadata:s,items:a}=e();if(this.defaultOptions.status==="unseen")t(i=>i.resetStore({...s,total_count:0,unseen_count:0}));else{t(o=>o.setMetadata({...s,unseen_count:0}));const i={seen_at:new Date().toISOString()},l=a.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const n=await this.makeBulkStatusUpdate("seen");return this.broadcaster.emit("items:all_seen",{items:a}),this.broadcastOverChannel("items:all_seen",{items:a}),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{getState:e,setState:t}=this.store,{metadata:s,items:a}=e();if(this.defaultOptions.status==="unread")t(i=>i.resetStore({...s,total_count:0,unread_count:0}));else{t(o=>o.setMetadata({...s,unread_count:0}));const i={read_at:new Date().toISOString()},l=a.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const n=await this.makeBulkStatusUpdate("read");return this.broadcaster.emit("items:all_read",{items:a}),this.broadcastOverChannel("items:all_read",{items:a}),n}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{getState:t,setState:s}=this.store,a=t(),r=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],i=n.map(l=>l.id);if(r){const l=n.filter(c=>!c.seen_at).length,o=n.filter(c=>!c.read_at).length,d={...a.metadata,total_count:a.metadata.total_count-n.length,unseen_count:a.metadata.unseen_count-l,unread_count:a.metadata.unread_count-o},h=a.items.filter(c=>!i.includes(c.id));s(c=>c.setResult({entries:h,meta:d,page_info:c.pageInfo}))}else a.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{setState:e,getState:t}=this.store,{items:s}=t(),a=this.defaultOptions.archived==="exclude";e(a?n=>n.resetStore():n=>{const i=s.map(l=>l.id);n.setItemAttrs(i,{archived_at:new Date().toISOString()})});const r=await this.makeBulkStatusUpdate("archive");return this.broadcaster.emit("items:all_archived",{items:s}),this.broadcastOverChannel("items:all_archived",{items:s}),r}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{setState:t,getState:s}=this.store,{networkStatus:a}=s();if(f.isRequestInFlight(a))return;t(d=>d.setNetworkStatus(e.__loadingType??f.NetworkStatus.loading));const r={...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:r});if(n.statusCode==="error"||!n.body)return t(d=>d.setNetworkStatus(f.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 d={shouldSetPage:!1,shouldAppend:!0};t(h=>h.setResult(i,d))}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};t(h=>h.setResult(i,d))}else t(d=>d.setResult(i));this.broadcast("messages.new",i);const l=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:l};return this.broadcast(o.event,o),{data:i,status:n.statusCode}}async fetchNextPage(){const{getState:e}=this.store,{pageInfo:t}=e();t.after&&this.fetch({after:t.after,__loadingType:f.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{getState:t,setState:s}=this.store,{items:a}=t(),r=a[0];s(n=>n.setMetadata(e)),this.fetch({before:r==null?void 0:r.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const{getState:r,setState:n}=this.store,i=Array.isArray(e)?e:[e],l=i.map(o=>o.id);if(a){const{metadata:o}=r(),d=i.filter(c=>{switch(t){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),h=t.startsWith("un")?d.length:-d.length;n(c=>c.setMetadata({...o,[a]:Math.max(0,o[a]+h)}))}n(o=>o.setItemAttrs(l,s))}async makeStatusUpdate(e,t){const s=Array.isArray(e)?e:[e],a=s.map(n=>n.id),r=await this.knock.messages.batchUpdateStatuses(a,t);return this.broadcaster.emit(`items.${t}`,{items:s}),this.broadcaster.emit(`items:${t}`,{items:s}),this.broadcastOverChannel(`items:${t}`,{items:s}),r}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(){this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeHandler)}teardownAutoSocketManager(){document.removeEventListener("visibilitychange",this.visibilityChangeHandler)}handleVisibilityChange(){var s;const e=this.defaultOptions.auto_manage_socket_connection_delay??v,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=y; | ||
"use strict";var S=Object.defineProperty;var k=(m,e,t)=>e in m?S(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var u=(m,e,t)=>(k(m,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("eventemitter2"),f=require("../../networkStatus.js"),_=require("./store.js"),g={archived:"exclude"},v=2e3;class y{constructor(e,t,a){u(this,"userFeedId");u(this,"channel");u(this,"broadcaster");u(this,"defaultOptions");u(this,"broadcastChannel");u(this,"disconnectTimer",null);u(this,"hasSubscribedToRealTimeUpdates",!1);u(this,"visibilityChangeHandler",()=>{});u(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=_.default(),this.broadcaster=new p({wildcard:!0,delimiter:"."}),this.defaultOptions={...g,...a},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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unseen")t(i=>i.resetStore({...a,total_count:0,unseen_count:0}));else{t(o=>o.setMetadata({...a,unseen_count:0}));const i={seen_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",n),s}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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unread")t(i=>i.resetStore({...a,total_count:0,unread_count:0}));else{t(o=>o.setMetadata({...a,unread_count:0}));const i={read_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",n),s}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{getState:t,setState:a}=this.store,n=t(),r=this.defaultOptions.archived==="exclude",s=Array.isArray(e)?e:[e],i=s.map(l=>l.id);if(r){const l=s.filter(c=>!c.seen_at).length,o=s.filter(c=>!c.read_at).length,d={...n.metadata,total_count:n.metadata.total_count-s.length,unseen_count:n.metadata.unseen_count-l,unread_count:n.metadata.unread_count-o},h=n.items.filter(c=>!i.includes(c.id));a(c=>c.setResult({entries:h,meta:d,page_info:c.pageInfo}))}else n.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{setState:e,getState:t}=this.store,{items:a}=t(),n=this.defaultOptions.archived==="exclude";e(n?s=>s.resetStore():s=>{const i=a.map(l=>l.id);s.setItemAttrs(i,{archived_at:new Date().toISOString()})});const r=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",a),r}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{setState:t,getState:a}=this.store,{networkStatus:n}=a();if(f.isRequestInFlight(n))return;t(d=>d.setNetworkStatus(e.__loadingType??f.NetworkStatus.loading));const r={...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},s=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(s.statusCode==="error"||!s.body)return t(d=>d.setNetworkStatus(f.NetworkStatus.error)),{status:s.statusCode,data:s.error||s.body};const i={entries:s.body.entries,meta:s.body.meta,page_info:s.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};t(h=>h.setResult(i,d))}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};t(h=>h.setResult(i,d))}else t(d=>d.setResult(i));this.broadcast("messages.new",i);const l=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:l};return this.broadcast(o.event,o),{data:i,status:s.statusCode}}async fetchNextPage(){const{getState:e}=this.store,{pageInfo:t}=e();t.after&&this.fetch({after:t.after,__loadingType:f.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{getState:t,setState:a}=this.store,{items:n}=t(),r=n[0];a(s=>s.setMetadata(e)),this.fetch({before:r==null?void 0:r.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,a,n){const{getState:r,setState:s}=this.store,i=Array.isArray(e)?e:[e],l=i.map(o=>o.id);if(n){const{metadata:o}=r(),d=i.filter(c=>{switch(t){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),h=t.startsWith("un")?d.length:-d.length;s(c=>c.setMetadata({...o,[n]:Math.max(0,o[n]+h)}))}s(o=>o.setItemAttrs(l,a))}async makeStatusUpdate(e,t){const a=Array.isArray(e)?e:[e],n=a.map(s=>s.id),r=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,a),r}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 a=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:a})}catch(a){console.warn(`Could not broadcast ${e}, got error: ${a}`)}}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(){this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityChangeHandler)}teardownAutoSocketManager(){document.removeEventListener("visibilitychange",this.visibilityChangeHandler)}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 a;const e=this.defaultOptions.auto_manage_socket_connection_delay??v,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),(a=t.socket)!=null&&a.isConnected()||this.initializeRealtimeConnection())}}exports.default=y; | ||
//# sourceMappingURL=feed.js.map |
@@ -63,2 +63,3 @@ import { StoreApi } from "zustand"; | ||
private teardownAutoSocketManager; | ||
private emitEvent; | ||
private handleVisibilityChange; | ||
@@ -65,0 +66,0 @@ } |
@@ -70,4 +70,4 @@ import { GenericData, PageInfo } from "@knocklabs/types"; | ||
} | ||
export interface FeedResponse { | ||
entries: FeedItem[]; | ||
export interface FeedResponse<T = any> { | ||
entries: FeedItem<T>[]; | ||
meta: FeedMetadata; | ||
@@ -74,0 +74,0 @@ page_info: PageInfo; |
@@ -8,3 +8,3 @@ import { PageInfo } from "@knocklabs/types"; | ||
}; | ||
export type FeedStoreState = { | ||
export interface FeedStoreState { | ||
items: FeedItem[]; | ||
@@ -20,14 +20,14 @@ pageInfo: PageInfo; | ||
resetStore: (metadata?: FeedMetadata) => void; | ||
}; | ||
export type FeedMessagesReceivedPayload = { | ||
} | ||
export interface FeedMessagesReceivedPayload { | ||
metadata: FeedMetadata; | ||
}; | ||
} | ||
export type FeedRealTimeEvent = "messages.new"; | ||
export type FeedEvent = FeedRealTimeEvent | "items.received.page" | "items.received.realtime" | "items.archived" | "items.unarchived" | "items.seen" | "items.unseen" | "items.read" | "items.unread" | "items.all_archived" | "items.all_read" | "items.all_seen"; | ||
export type BindableFeedEvent = FeedEvent | "items.received.*" | "items.*"; | ||
export type FeedEventPayload = { | ||
export interface FeedEventPayload<T = any> { | ||
event: Omit<FeedEvent, "messages.new">; | ||
items: FeedItem[]; | ||
items: FeedItem<T>[]; | ||
metadata: FeedMetadata; | ||
}; | ||
} | ||
export type FeedRealTimeCallback = (resp: FeedResponse) => void; | ||
@@ -34,0 +34,0 @@ export type FeedEventCallback = (payload: FeedEventPayload) => void; |
{ | ||
"name": "@knocklabs/client", | ||
"version": "0.10.2", | ||
"version": "0.10.3", | ||
"description": "The clientside library for interacting with Knock", | ||
@@ -5,0 +5,0 @@ "homepage": "https://github.com/knocklabs/javascript/tree/main/packages/client", |
@@ -209,6 +209,4 @@ import EventEmitter from "eventemitter2"; | ||
const result = await this.makeBulkStatusUpdate("seen"); | ||
this.emitEvent("all_seen", items); | ||
this.broadcaster.emit(`items:all_seen`, { items }); | ||
this.broadcastOverChannel(`items:all_seen`, { items }); | ||
return result; | ||
@@ -280,6 +278,4 @@ } | ||
const result = await this.makeBulkStatusUpdate("read"); | ||
this.emitEvent("all_read", items); | ||
this.broadcaster.emit(`items:all_read`, { items }); | ||
this.broadcastOverChannel(`items:all_read`, { items }); | ||
return result; | ||
@@ -421,6 +417,4 @@ } | ||
const result = await this.makeBulkStatusUpdate("archive"); | ||
this.emitEvent("all_archived", items); | ||
this.broadcaster.emit(`items:all_archived`, { items }); | ||
this.broadcastOverChannel(`items:all_archived`, { items }); | ||
return result; | ||
@@ -621,9 +615,4 @@ } | ||
// Note: we do this after the update to ensure that the server event actually completed | ||
this.broadcaster.emit(`items.${type}`, { items }); | ||
this.emitEvent(type, items); | ||
// Note: `items.type` format is being deprecated in favor over the `items:type` format, | ||
// but emit both formats to make it backward compatible for now. | ||
this.broadcaster.emit(`items:${type}`, { items }); | ||
this.broadcastOverChannel(`items:${type}`, { items }); | ||
return result; | ||
@@ -757,2 +746,20 @@ } | ||
private emitEvent( | ||
type: | ||
| MessageEngagementStatus | ||
| "all_read" | ||
| "all_seen" | ||
| "all_archived" | ||
| "unread" | ||
| "unseen" | ||
| "unarchived", | ||
items: FeedItem[], | ||
) { | ||
// Handle both `items.` and `items:` format for events for compatibility reasons | ||
this.broadcaster.emit(`items.${type}`, { items }); | ||
this.broadcaster.emit(`items:${type}`, { items }); | ||
// Internal events only need `items:` | ||
this.broadcastOverChannel(`items:${type}`, { items }); | ||
} | ||
private handleVisibilityChange() { | ||
@@ -759,0 +766,0 @@ const disconnectDelay = |
@@ -97,6 +97,6 @@ import { GenericData, PageInfo } from "@knocklabs/types"; | ||
export interface FeedResponse { | ||
entries: FeedItem[]; | ||
export interface FeedResponse<T = any> { | ||
entries: FeedItem<T>[]; | ||
meta: FeedMetadata; | ||
page_info: PageInfo; | ||
} |
@@ -12,3 +12,3 @@ import { PageInfo } from "@knocklabs/types"; | ||
export type FeedStoreState = { | ||
export interface FeedStoreState { | ||
items: FeedItem[]; | ||
@@ -24,7 +24,7 @@ pageInfo: PageInfo; | ||
resetStore: (metadata?: FeedMetadata) => void; | ||
}; | ||
} | ||
export type FeedMessagesReceivedPayload = { | ||
export interface FeedMessagesReceivedPayload { | ||
metadata: FeedMetadata; | ||
}; | ||
} | ||
@@ -56,7 +56,7 @@ /* | ||
export type FeedEventPayload = { | ||
export interface FeedEventPayload<T = any> { | ||
event: Omit<FeedEvent, "messages.new">; | ||
items: FeedItem[]; | ||
items: FeedItem<T>[]; | ||
metadata: FeedMetadata; | ||
}; | ||
} | ||
@@ -63,0 +63,0 @@ export type FeedRealTimeCallback = (resp: FeedResponse) => void; |
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
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
3523
330706