@knocklabs/client 0.14.9 → 0.14.10-canary.2
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/dist/cjs/clients/feed/feed.js.map +1 -1
- package/dist/cjs/clients/feed/store.js +1 -1
- package/dist/cjs/clients/feed/store.js.map +1 -1
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/esm/clients/feed/store.mjs +80 -32
- package/dist/esm/clients/feed/store.mjs.map +1 -1
- package/dist/types/clients/feed/feed.d.ts +4 -4
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/feed/store.d.ts +18 -1
- package/dist/types/clients/feed/store.d.ts.map +1 -1
- package/package.json +5 -6
- package/src/clients/feed/feed.ts +2 -4
- package/src/clients/feed/store.ts +75 -18
- package/CHANGELOG.md +0 -300
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\nimport type { StoreApi } from \"zustand\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":"uhBAwCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAE3BC,EAAuB,UAE7B,MAAMC,CAAK,CAgBT,YACWC,EACAC,EACTC,EACAC,E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AuB,KAAK,IAAI,EACpE,KAAK,kCAAoC,GAChC,SAAA,iBAAiB,mBAAoB,KAAK,uBAAuB,EAAA,CAGpE,6BAA8B,CAChC,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBACP,EACA,KAAK,kCAAoC,GAAA,CAGnC,UACNN,EAQA1B,EACA,CAEA,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAG9C,wBAAyB,SACzB,MAAAoC,EACJ,KAAK,eAAe,qCACpBvD,EAEIwD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtC3C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,aACf,KAAK,gBAAkB,MACtB0C,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpB1C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,gBAClB4C,EAAAD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
|
|
1
|
+
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":"uhBAsCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAE3BC,EAAuB,UAE7B,MAAMC,CAAK,CAgBT,YACWC,EACAC,EACTC,EACAC,EACA,CApBcC,EAAA,uBACAA,EAAA,oBACTA,EAAA,oCACCA,EAAA,sBACAA,EAAA,mBACAA,EAAA,oBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAJ,EACA,KAAA,OAAAC,GAIL,CAACA,GAAU,CAACI,EAAA,YAAYJ,CAAM,IAChC,KAAK,MAAM,IACT,8NACA,EACF,EAGF,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EAClC,KAAA,YAAcH,EAAuBQ,SAAO,EACjD,KAAK,cAAgBH,EACrB,KAAK,MAAQI,UAAY,EACpB,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CACpB,GAAGZ,EACH,GAAGa,uBAAqBP,CAAO,CACjC,EACA,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,EAG/D,KAAK,6BAA6B,EAElC,KAAK,sBAAsB,CAAA,CAM7B,aAAaE,EAAmC,CAC9C,KAAK,cAAgBA,EAGhB,KAAA,WAAa,KAAK,gBAAgB,EAGvC,KAAK,6BAA6B,EAGlC,KAAK,sBAAsB,CAAA,CAO7B,UAAW,OACJ,KAAA,MAAM,IAAI,mCAAmC,GAE7CO,EAAA,KAAA,gBAAA,MAAAA,EAAe,MAAM,MAE1B,KAAK,4BAA4B,EAE7B,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,MAGrB,KAAK,kBACP,KAAK,iBAAiB,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,EAA6B,CACnD,OAAQA,EAAQ,MAAO,CACrB,KAAKG,EAAgB,gBAAA,WACnB,KAAK,qBAAqBH,CAAO,EACjC,OACF,QAAS,CACyBA,EAAQ,MACxC,MAAA,CACF,CACF,CAOM,0BAA2B,CAE/B,OAAO,SAAa,KACpB,KAAK,oCAKP,KAAK,wBAA0B,KAAK,uBAAuB,KAAK,IAAI,EACpE,KAAK,kCAAoC,GAChC,SAAA,iBAAiB,mBAAoB,KAAK,uBAAuB,EAAA,CAGpE,6BAA8B,CAChC,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBACP,EACA,KAAK,kCAAoC,GAAA,CAGnC,UACNN,EAQA1B,EACA,CAEA,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAG9C,wBAAyB,SACzB,MAAAoC,EACJ,KAAK,eAAe,qCACpBvD,EAEIwD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtC3C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,aACf,KAAK,gBAAkB,MACtB0C,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpB1C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,gBAClB4C,EAAAD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
1
|
+
"use strict";var f=Object.defineProperty;var g=(s,t,e)=>t in s?f(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var l=(s,t,e)=>g(s,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("@tanstack/store"),d=require("../../networkStatus.js"),S=require("./utils.js");function m(s){const t=S.deduplicateItems(s);return S.sortItems(t)}const w={shouldSetPage:!0,shouldAppend:!1},u={items:[],metadata:{total_count:0,unread_count:0,unseen_count:0},pageInfo:{before:null,after:null,page_size:50},loading:!1,networkStatus:d.NetworkStatus.ready,setResult:()=>{},setMetadata:()=>{},setNetworkStatus:()=>{},resetStore:()=>{},setItemAttrs:()=>{}},k=()=>{const s=new p.Store(u);return s.setState(t=>({...t,networkStatus:d.NetworkStatus.ready,loading:!1,setNetworkStatus:e=>s.setState(r=>({...r,networkStatus:e,loading:e===d.NetworkStatus.loading})),setResult:({entries:e,meta:r,page_info:i},o=w)=>s.setState(a=>{const n=o.shouldAppend?m(a.items.concat(e)):e;return{...a,items:n,metadata:r,pageInfo:o.shouldSetPage?i:a.pageInfo,loading:!1,networkStatus:d.NetworkStatus.ready}}),setMetadata:e=>s.setState(r=>({...r,metadata:e})),resetStore:(e=u.metadata)=>s.setState(()=>({...u,metadata:e})),setItemAttrs:(e,r)=>{const i=e.reduce((o,a)=>({...o,[a]:r}),{});return s.setState(o=>{const a=o.items.map(n=>i[n.id]?{...n,...i[n.id]}:n);return{...o,items:a}})}})),s};class c{constructor(t){l(this,"store");this.store=t}getState(){return this.store.state}setState(t){this.store.setState(typeof t=="function"?t:()=>t)}getInitialState(){return u}subscribe(t){return this.store.subscribe(e=>t(e.currentVal))}}function I(){const s=k();return new c(s)}exports.FeedStore=c;exports.default=I;exports.initialStoreState=u;
|
|
2
2
|
//# sourceMappingURL=store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport {
|
|
1
|
+
{"version":3,"file":"store.js","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { Store } from \"@tanstack/store\";\n\nimport { NetworkStatus } from \"../../networkStatus\";\n\nimport { FeedItem, FeedMetadata, FeedResponse } from \"./interfaces\";\nimport { FeedStoreState, StoreFeedResultOptions } from \"./types\";\nimport { deduplicateItems, sortItems } from \"./utils\";\n\nfunction processItems(items: FeedItem[]) {\n const deduped = deduplicateItems(items);\n const sorted = sortItems(deduped);\n\n return sorted;\n}\n\nconst defaultSetResultOptions = {\n shouldSetPage: true,\n shouldAppend: false,\n};\n\nexport const initialStoreState: FeedStoreState = {\n items: [],\n metadata: {\n total_count: 0,\n unread_count: 0,\n unseen_count: 0,\n },\n pageInfo: {\n before: null,\n after: null,\n page_size: 50,\n },\n loading: false,\n networkStatus: NetworkStatus.ready,\n setResult: () => {},\n setMetadata: () => {},\n setNetworkStatus: () => {},\n resetStore: () => {},\n setItemAttrs: () => {},\n};\n\n/**\n * Initalize the store with tanstack store so it can be used within our\n * FeedStore class. We do this seperately so that we have the ability to\n * change which store library we use in the future if need be.\n */\nconst initalizeStore = () => {\n const store = new Store(initialStoreState);\n\n store.setState((state) => ({\n ...state,\n // The network status indicates what's happening with the request\n networkStatus: NetworkStatus.ready,\n loading: false,\n setNetworkStatus: (networkStatus: NetworkStatus) =>\n store.setState((state) => ({\n ...state,\n networkStatus,\n loading: networkStatus === NetworkStatus.loading,\n })),\n\n setResult: (\n { entries, meta, page_info }: FeedResponse,\n options: StoreFeedResultOptions = defaultSetResultOptions,\n ) =>\n store.setState((state) => {\n // We resort the list on set, so concating everything is fine (if a bit suboptimal)\n const items = options.shouldAppend\n ? processItems(state.items.concat(entries as FeedItem<GenericData>[]))\n : entries;\n\n return {\n ...state,\n items,\n metadata: meta,\n pageInfo: options.shouldSetPage ? page_info : state.pageInfo,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n }),\n\n setMetadata: (metadata: FeedMetadata) =>\n store.setState((state) => ({ ...state, metadata })),\n\n resetStore: (metadata = initialStoreState.metadata) =>\n store.setState(() => ({ ...initialStoreState, metadata })),\n\n setItemAttrs: (itemIds: Array<string>, attrs: object) => {\n // Create a map for the items to the updates to be made\n const itemUpdatesMap: { [id: string]: object } = itemIds.reduce(\n (acc, itemId) => ({ ...acc, [itemId]: attrs }),\n {},\n );\n\n return store.setState((state) => {\n const items = state.items.map((item) => {\n if (itemUpdatesMap[item.id]) {\n return { ...item, ...itemUpdatesMap[item.id] };\n }\n\n return item;\n });\n\n return { ...state, items };\n });\n },\n }));\n\n return store;\n};\n\n/**\n * The FeedStore class is a wrapper for our store solution that's\n * based on the same shape as zustand. This wrapping class allows\n * us to maintain backwards compatibility with the zustand model\n * while still allowing us to utilize tanstack store for the\n * underlying store solution.\n */\nexport class FeedStore {\n store: Store<FeedStoreState>;\n\n constructor(store: Store<FeedStoreState>) {\n this.store = store;\n }\n\n getState() {\n return this.store.state;\n }\n\n setState(\n updater: ((state: FeedStoreState) => FeedStoreState) | FeedStoreState,\n ) {\n this.store.setState(\n typeof updater === \"function\" ? updater : () => updater,\n );\n }\n\n getInitialState() {\n return initialStoreState;\n }\n\n subscribe(listener: (state: FeedStoreState) => void) {\n return this.store.subscribe((state) => listener(state.currentVal));\n }\n}\n\nexport default function createStore() {\n const store = initalizeStore();\n return new FeedStore(store);\n}\n"],"names":["processItems","items","deduped","deduplicateItems","sortItems","defaultSetResultOptions","initialStoreState","NetworkStatus","initalizeStore","store","Store","state","networkStatus","entries","meta","page_info","options","metadata","itemIds","attrs","itemUpdatesMap","acc","itemId","item","FeedStore","__publicField","updater","listener","createStore"],"mappings":"+WASA,SAASA,EAAaC,EAAmB,CACjC,MAAAC,EAAUC,mBAAiBF,CAAK,EAG/B,OAFQG,YAAUF,CAAO,CAGlC,CAEA,MAAMG,EAA0B,CAC9B,cAAe,GACf,aAAc,EAChB,EAEaC,EAAoC,CAC/C,MAAO,CAAC,EACR,SAAU,CACR,YAAa,EACb,aAAc,EACd,aAAc,CAChB,EACA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jB,CAAE,GAAGA,EAAM,GAAGH,EAAeG,EAAK,EAAE,CAAE,EAGxCA,CACR,EAEM,MAAA,CAAE,GAAGZ,EAAO,MAAAV,CAAM,CAAA,CAC1B,CAAA,CACH,EACA,EAEKQ,CACT,EASO,MAAMe,CAAU,CAGrB,YAAYf,EAA8B,CAF1CgB,EAAA,cAGE,KAAK,MAAQhB,CAAA,CAGf,UAAW,CACT,OAAO,KAAK,MAAM,KAAA,CAGpB,SACEiB,EACA,CACA,KAAK,MAAM,SACT,OAAOA,GAAY,WAAaA,EAAU,IAAMA,CAClD,CAAA,CAGF,iBAAkB,CACT,OAAApB,CAAA,CAGT,UAAUqB,EAA2C,CAC5C,OAAA,KAAK,MAAM,UAAWhB,GAAUgB,EAAShB,EAAM,UAAU,CAAC,CAAA,CAErE,CAEA,SAAwBiB,GAAc,CACpC,MAAMnB,EAAQD,EAAe,EACtB,OAAA,IAAIgB,EAAUf,CAAK,CAC5B"}
|
|
@@ -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 { nanoid } from \"nanoid\";\nimport type { StoreApi } from \"zustand\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":";;;;;;;;;;AAwCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ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AAW,MAAM;;AACtC,OAAA3C,IAAA2C,EAAO,WAAP,QAAA3C,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtB0C,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpB1C,IAAA2C,EAAO,WAAP,QAAA3C,EAAe,kBAClB4C,IAAAD,EAAO,WAAP,QAAAC,EAAe;AAAA,EAEnB;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":";;;;;;;;;;AAsCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B,KAE3BC,IAAuB;AAE7B,MAAMC,EAAK;AAAA,EAgBT,YACWC,GACAC,GACTC,GACAC,GACA;AApBc,IAAAC,EAAA;AACA,IAAAA,EAAA;AACT,IAAAA,EAAA;AACC,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,IAAC;AAC7C,IAAAA,EAAA,2CAA6C;AAG9C;AAA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
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
var c = Object.defineProperty;
|
|
2
|
+
var S = (s, t, e) => t in s ? c(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
|
|
3
|
+
var l = (s, t, e) => S(s, typeof t != "symbol" ? t + "" : t, e);
|
|
4
|
+
import { Store as f } from "@tanstack/store";
|
|
5
|
+
import { NetworkStatus as d } from "../../networkStatus.mjs";
|
|
6
|
+
import { deduplicateItems as m, sortItems as p } from "./utils.mjs";
|
|
7
|
+
function g(s) {
|
|
8
|
+
const t = m(s);
|
|
9
|
+
return p(t);
|
|
7
10
|
}
|
|
8
|
-
const
|
|
11
|
+
const I = {
|
|
9
12
|
shouldSetPage: !0,
|
|
10
13
|
shouldAppend: !1
|
|
11
|
-
},
|
|
14
|
+
}, i = {
|
|
12
15
|
items: [],
|
|
13
16
|
metadata: {
|
|
14
17
|
total_count: 0,
|
|
@@ -19,38 +22,83 @@ const p = {
|
|
|
19
22
|
before: null,
|
|
20
23
|
after: null,
|
|
21
24
|
page_size: 50
|
|
25
|
+
},
|
|
26
|
+
loading: !1,
|
|
27
|
+
networkStatus: d.ready,
|
|
28
|
+
setResult: () => {
|
|
29
|
+
},
|
|
30
|
+
setMetadata: () => {
|
|
31
|
+
},
|
|
32
|
+
setNetworkStatus: () => {
|
|
33
|
+
},
|
|
34
|
+
resetStore: () => {
|
|
35
|
+
},
|
|
36
|
+
setItemAttrs: () => {
|
|
22
37
|
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return
|
|
26
|
-
|
|
27
|
-
...d,
|
|
38
|
+
}, h = () => {
|
|
39
|
+
const s = new f(i);
|
|
40
|
+
return s.setState((t) => ({
|
|
41
|
+
...t,
|
|
28
42
|
// The network status indicates what's happening with the request
|
|
29
|
-
networkStatus:
|
|
43
|
+
networkStatus: d.ready,
|
|
30
44
|
loading: !1,
|
|
31
|
-
setNetworkStatus: (
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
setResult: ({ entries: t, meta: s, page_info: n }, a = p) => e((o) => ({
|
|
36
|
-
items: a.shouldAppend ? m(o.items.concat(t)) : t,
|
|
37
|
-
metadata: s,
|
|
38
|
-
pageInfo: a.shouldSetPage ? n : o.pageInfo,
|
|
39
|
-
loading: !1,
|
|
40
|
-
networkStatus: u.ready
|
|
45
|
+
setNetworkStatus: (e) => s.setState((r) => ({
|
|
46
|
+
...r,
|
|
47
|
+
networkStatus: e,
|
|
48
|
+
loading: e === d.loading
|
|
41
49
|
})),
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
50
|
+
setResult: ({ entries: e, meta: r, page_info: u }, o = I) => s.setState((a) => {
|
|
51
|
+
const n = o.shouldAppend ? g(a.items.concat(e)) : e;
|
|
52
|
+
return {
|
|
53
|
+
...a,
|
|
54
|
+
items: n,
|
|
55
|
+
metadata: r,
|
|
56
|
+
pageInfo: o.shouldSetPage ? u : a.pageInfo,
|
|
57
|
+
loading: !1,
|
|
58
|
+
networkStatus: d.ready
|
|
59
|
+
};
|
|
60
|
+
}),
|
|
61
|
+
setMetadata: (e) => s.setState((r) => ({ ...r, metadata: e })),
|
|
62
|
+
resetStore: (e = i.metadata) => s.setState(() => ({ ...i, metadata: e })),
|
|
63
|
+
setItemAttrs: (e, r) => {
|
|
64
|
+
const u = e.reduce(
|
|
65
|
+
(o, a) => ({ ...o, [a]: r }),
|
|
47
66
|
{}
|
|
48
67
|
);
|
|
49
|
-
return
|
|
68
|
+
return s.setState((o) => {
|
|
69
|
+
const a = o.items.map((n) => u[n.id] ? { ...n, ...u[n.id] } : n);
|
|
70
|
+
return { ...o, items: a };
|
|
71
|
+
});
|
|
50
72
|
}
|
|
51
|
-
}));
|
|
73
|
+
})), s;
|
|
74
|
+
};
|
|
75
|
+
class w {
|
|
76
|
+
constructor(t) {
|
|
77
|
+
l(this, "store");
|
|
78
|
+
this.store = t;
|
|
79
|
+
}
|
|
80
|
+
getState() {
|
|
81
|
+
return this.store.state;
|
|
82
|
+
}
|
|
83
|
+
setState(t) {
|
|
84
|
+
this.store.setState(
|
|
85
|
+
typeof t == "function" ? t : () => t
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
getInitialState() {
|
|
89
|
+
return i;
|
|
90
|
+
}
|
|
91
|
+
subscribe(t) {
|
|
92
|
+
return this.store.subscribe((e) => t(e.currentVal));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function _() {
|
|
96
|
+
const s = h();
|
|
97
|
+
return new w(s);
|
|
52
98
|
}
|
|
53
99
|
export {
|
|
54
|
-
|
|
100
|
+
w as FeedStore,
|
|
101
|
+
_ as default,
|
|
102
|
+
i as initialStoreState
|
|
55
103
|
};
|
|
56
104
|
//# sourceMappingURL=store.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.mjs","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport {
|
|
1
|
+
{"version":3,"file":"store.mjs","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { Store } from \"@tanstack/store\";\n\nimport { NetworkStatus } from \"../../networkStatus\";\n\nimport { FeedItem, FeedMetadata, FeedResponse } from \"./interfaces\";\nimport { FeedStoreState, StoreFeedResultOptions } from \"./types\";\nimport { deduplicateItems, sortItems } from \"./utils\";\n\nfunction processItems(items: FeedItem[]) {\n const deduped = deduplicateItems(items);\n const sorted = sortItems(deduped);\n\n return sorted;\n}\n\nconst defaultSetResultOptions = {\n shouldSetPage: true,\n shouldAppend: false,\n};\n\nexport const initialStoreState: FeedStoreState = {\n items: [],\n metadata: {\n total_count: 0,\n unread_count: 0,\n unseen_count: 0,\n },\n pageInfo: {\n before: null,\n after: null,\n page_size: 50,\n },\n loading: false,\n networkStatus: NetworkStatus.ready,\n setResult: () => {},\n setMetadata: () => {},\n setNetworkStatus: () => {},\n resetStore: () => {},\n setItemAttrs: () => {},\n};\n\n/**\n * Initalize the store with tanstack store so it can be used within our\n * FeedStore class. We do this seperately so that we have the ability to\n * change which store library we use in the future if need be.\n */\nconst initalizeStore = () => {\n const store = new Store(initialStoreState);\n\n store.setState((state) => ({\n ...state,\n // The network status indicates what's happening with the request\n networkStatus: NetworkStatus.ready,\n loading: false,\n setNetworkStatus: (networkStatus: NetworkStatus) =>\n store.setState((state) => ({\n ...state,\n networkStatus,\n loading: networkStatus === NetworkStatus.loading,\n })),\n\n setResult: (\n { entries, meta, page_info }: FeedResponse,\n options: StoreFeedResultOptions = defaultSetResultOptions,\n ) =>\n store.setState((state) => {\n // We resort the list on set, so concating everything is fine (if a bit suboptimal)\n const items = options.shouldAppend\n ? processItems(state.items.concat(entries as FeedItem<GenericData>[]))\n : entries;\n\n return {\n ...state,\n items,\n metadata: meta,\n pageInfo: options.shouldSetPage ? page_info : state.pageInfo,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n }),\n\n setMetadata: (metadata: FeedMetadata) =>\n store.setState((state) => ({ ...state, metadata })),\n\n resetStore: (metadata = initialStoreState.metadata) =>\n store.setState(() => ({ ...initialStoreState, metadata })),\n\n setItemAttrs: (itemIds: Array<string>, attrs: object) => {\n // Create a map for the items to the updates to be made\n const itemUpdatesMap: { [id: string]: object } = itemIds.reduce(\n (acc, itemId) => ({ ...acc, [itemId]: attrs }),\n {},\n );\n\n return store.setState((state) => {\n const items = state.items.map((item) => {\n if (itemUpdatesMap[item.id]) {\n return { ...item, ...itemUpdatesMap[item.id] };\n }\n\n return item;\n });\n\n return { ...state, items };\n });\n },\n }));\n\n return store;\n};\n\n/**\n * The FeedStore class is a wrapper for our store solution that's\n * based on the same shape as zustand. This wrapping class allows\n * us to maintain backwards compatibility with the zustand model\n * while still allowing us to utilize tanstack store for the\n * underlying store solution.\n */\nexport class FeedStore {\n store: Store<FeedStoreState>;\n\n constructor(store: Store<FeedStoreState>) {\n this.store = store;\n }\n\n getState() {\n return this.store.state;\n }\n\n setState(\n updater: ((state: FeedStoreState) => FeedStoreState) | FeedStoreState,\n ) {\n this.store.setState(\n typeof updater === \"function\" ? updater : () => updater,\n );\n }\n\n getInitialState() {\n return initialStoreState;\n }\n\n subscribe(listener: (state: FeedStoreState) => void) {\n return this.store.subscribe((state) => listener(state.currentVal));\n }\n}\n\nexport default function createStore() {\n const store = initalizeStore();\n return new FeedStore(store);\n}\n"],"names":["processItems","items","deduped","deduplicateItems","sortItems","defaultSetResultOptions","initialStoreState","NetworkStatus","initalizeStore","store","Store","state","networkStatus","entries","meta","page_info","options","metadata","itemIds","attrs","itemUpdatesMap","acc","itemId","item","FeedStore","__publicField","updater","listener","createStore"],"mappings":";;;;;;AASA,SAASA,EAAaC,GAAmB;AACjC,QAAAC,IAAUC,EAAiBF,CAAK;AAG/B,SAFQG,EAAUF,CAAO;AAGlC;AAEA,MAAMG,IAA0B;AAAA,EAC9B,eAAe;AAAA,EACf,cAAc;AAChB,GAEaC,IAAoC;AAAA,EAC/C,OAAO,CAAC;AAAA,EACR,UAAU;AAAA,IACR,aAAa;AAAA,IACb,cAAc;AAAA,IACd,cAAc;AAAA,EAChB;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,WAAW;AAAA,EACb;AAAA,EACA,SAAS;AAAA,EACT,eAAeC,EAAc;AAAA,EAC7B,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,aAAa,MAAM;AAAA,EAAC;AAAA,EACpB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,YAAY,MAAM;AAAA,EAAC;AAAA,EACnB,cAAc,MAAM;AAAA,EAAA;AACtB,GAOMC,IAAiB,MAAM;AACrB,QAAAC,IAAQ,IAAIC,EAAMJ,CAAiB;AAEnC,SAAAG,EAAA,SAAS,CAACE,OAAW;AAAA,IACzB,GAAGA;AAAA;AAAA,IAEH,eAAeJ,EAAc;AAAA,IAC7B,SAAS;AAAA,IACT,kBAAkB,CAACK,MACjBH,E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hB;AAAA,EAAA;AAAA,EAGf,WAAW;AACT,WAAO,KAAK,MAAM;AAAA,EAAA;AAAA,EAGpB,SACEiB,GACA;AACA,SAAK,MAAM;AAAA,MACT,OAAOA,KAAY,aAAaA,IAAU,MAAMA;AAAA,IAClD;AAAA,EAAA;AAAA,EAGF,kBAAkB;AACT,WAAApB;AAAA,EAAA;AAAA,EAGT,UAAUqB,GAA2C;AAC5C,WAAA,KAAK,MAAM,UAAU,CAAChB,MAAUgB,EAAShB,EAAM,UAAU,CAAC;AAAA,EAAA;AAErE;AAEA,SAAwBiB,IAAc;AACpC,QAAMnB,IAAQD,EAAe;AACtB,SAAA,IAAIgB,EAAUf,CAAK;AAC5B;"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { GenericData } from '@knocklabs/types';
|
|
2
|
-
import { StoreApi } from 'zustand';
|
|
3
2
|
import { default as Knock } from '../../knock';
|
|
4
3
|
import { FeedClientOptions, FetchFeedOptions } from './interfaces';
|
|
5
4
|
import { FeedSocketManager, SocketEventPayload } from './socket-manager';
|
|
6
|
-
import {
|
|
5
|
+
import { FeedStore } from './store';
|
|
6
|
+
import { BindableFeedEvent, FeedEventCallback, FeedItemOrItems, FeedRealTimeCallback } from './types';
|
|
7
7
|
declare class Feed {
|
|
8
8
|
readonly knock: Knock;
|
|
9
9
|
readonly feedId: string;
|
|
@@ -18,7 +18,7 @@ declare class Feed {
|
|
|
18
18
|
private hasSubscribedToRealTimeUpdates;
|
|
19
19
|
private visibilityChangeHandler;
|
|
20
20
|
private visibilityChangeListenerConnected;
|
|
21
|
-
store:
|
|
21
|
+
store: FeedStore;
|
|
22
22
|
constructor(knock: Knock, feedId: string, options: FeedClientOptions, socketManager: FeedSocketManager | undefined);
|
|
23
23
|
/**
|
|
24
24
|
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
@@ -34,7 +34,7 @@ declare class Feed {
|
|
|
34
34
|
listenForUpdates(): void;
|
|
35
35
|
on(eventName: BindableFeedEvent, callback: FeedEventCallback | FeedRealTimeCallback): void;
|
|
36
36
|
off(eventName: BindableFeedEvent, callback: FeedEventCallback | FeedRealTimeCallback): void;
|
|
37
|
-
getState(): FeedStoreState;
|
|
37
|
+
getState(): import('./types').FeedStoreState;
|
|
38
38
|
markAsSeen(itemOrItems: FeedItemOrItems): Promise<import('../messages/interfaces').Message<GenericData>[]>;
|
|
39
39
|
markAllAsSeen(): Promise<import('../..').BulkOperation>;
|
|
40
40
|
markAsUnseen(itemOrItems: FeedItemOrItems): Promise<import('../messages/interfaces').Message<GenericData>[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.d.ts","sourceRoot":"","sources":["../../../../src/clients/feed/feed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"feed.d.ts","sourceRoot":"","sources":["../../../../src/clients/feed/feed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAK/C,OAAO,KAAK,MAAM,aAAa,CAAC;AAOhC,OAAO,EACL,iBAAiB,EAIjB,gBAAgB,EAEjB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAEnB,MAAM,kBAAkB,CAAC;AAC1B,OAAoB,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EACL,iBAAiB,EAEjB,iBAAiB,EAEjB,eAAe,EAEf,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAYjB,cAAM,IAAI;IAiBN,QAAQ,CAAC,KAAK,EAAE,KAAK;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM;IAjBzB,SAAgB,cAAc,EAAE,iBAAiB,CAAC;IAClD,SAAgB,WAAW,EAAE,MAAM,CAAC;IAC7B,2BAA2B,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAa;IACzE,OAAO,CAAC,aAAa,CAAgC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oBAAoB;IAiBlC,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,iCAAiC;YAiD3B,gBAAgB;YAsBhB,oBAAoB;IA2BlC,OAAO,CAAC,qBAAqB;IAoC7B,OAAO,CAAC,oBAAoB;IAoB5B,OAAO,CAAC,4BAA4B;IAe9B,iBAAiB,CAAC,OAAO,EAAE,kBAAkB;IAYnD;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAahC,OAAO,CAAC,2BAA2B;IAUnC,OAAO,CAAC,SAAS;IAkBjB,OAAO,CAAC,sBAAsB;CA2B/B;AAED,eAAe,IAAI,CAAC"}
|
|
@@ -1,3 +1,20 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
1
2
|
import { FeedStoreState } from './types';
|
|
2
|
-
export
|
|
3
|
+
export declare const initialStoreState: FeedStoreState;
|
|
4
|
+
/**
|
|
5
|
+
* The FeedStore class is a wrapper for our store solution that's
|
|
6
|
+
* based on the same shape as zustand. This wrapping class allows
|
|
7
|
+
* us to maintain backwards compatibility with the zustand model
|
|
8
|
+
* while still allowing us to utilize tanstack store for the
|
|
9
|
+
* underlying store solution.
|
|
10
|
+
*/
|
|
11
|
+
export declare class FeedStore {
|
|
12
|
+
store: Store<FeedStoreState>;
|
|
13
|
+
constructor(store: Store<FeedStoreState>);
|
|
14
|
+
getState(): FeedStoreState;
|
|
15
|
+
setState(updater: ((state: FeedStoreState) => FeedStoreState) | FeedStoreState): void;
|
|
16
|
+
getInitialState(): FeedStoreState;
|
|
17
|
+
subscribe(listener: (state: FeedStoreState) => void): () => void;
|
|
18
|
+
}
|
|
19
|
+
export default function createStore(): FeedStore;
|
|
3
20
|
//# sourceMappingURL=store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../../src/clients/feed/store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../../src/clients/feed/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAKxC,OAAO,EAAE,cAAc,EAA0B,MAAM,SAAS,CAAC;AAejE,eAAO,MAAM,iBAAiB,EAAE,cAmB/B,CAAC;AAwEF;;;;;;GAMG;AACH,qBAAa,SAAS;IACpB,KAAK,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;gBAEjB,KAAK,EAAE,KAAK,CAAC,cAAc,CAAC;IAIxC,QAAQ;IAIR,QAAQ,CACN,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,cAAc,KAAK,cAAc,CAAC,GAAG,cAAc;IAOvE,eAAe;IAIf,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI;CAGpD;AAED,MAAM,CAAC,OAAO,UAAU,WAAW,cAGlC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@knocklabs/client",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.10-canary.2",
|
|
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",
|
|
@@ -68,8 +68,8 @@
|
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
70
|
"@babel/runtime": "^7.27.1",
|
|
71
|
-
"@knocklabs/types": "
|
|
72
|
-
"@tanstack/store": "0.
|
|
71
|
+
"@knocklabs/types": "workspace:^",
|
|
72
|
+
"@tanstack/store": "^0.7.1",
|
|
73
73
|
"@types/phoenix": "^1.6.6",
|
|
74
74
|
"axios": "^1.9.0",
|
|
75
75
|
"axios-retry": "^4.5.0",
|
|
@@ -77,7 +77,6 @@
|
|
|
77
77
|
"jwt-decode": "^4.0.0",
|
|
78
78
|
"nanoid": "^3.3.11",
|
|
79
79
|
"phoenix": "1.7.19",
|
|
80
|
-
"urlpattern-polyfill": "^10.0.0"
|
|
81
|
-
"zustand": "^4.5.6"
|
|
80
|
+
"urlpattern-polyfill": "^10.0.0"
|
|
82
81
|
}
|
|
83
|
-
}
|
|
82
|
+
}
|
package/src/clients/feed/feed.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { GenericData } from "@knocklabs/types";
|
|
2
2
|
import EventEmitter from "eventemitter2";
|
|
3
3
|
import { nanoid } from "nanoid";
|
|
4
|
-
import type { StoreApi } from "zustand";
|
|
5
4
|
|
|
6
5
|
import { isValidUuid } from "../../helpers";
|
|
7
6
|
import Knock from "../../knock";
|
|
@@ -24,7 +23,7 @@ import {
|
|
|
24
23
|
SocketEventPayload,
|
|
25
24
|
SocketEventType,
|
|
26
25
|
} from "./socket-manager";
|
|
27
|
-
import createStore from "./store";
|
|
26
|
+
import createStore, { FeedStore } from "./store";
|
|
28
27
|
import {
|
|
29
28
|
BindableFeedEvent,
|
|
30
29
|
FeedEvent,
|
|
@@ -33,7 +32,6 @@ import {
|
|
|
33
32
|
FeedItemOrItems,
|
|
34
33
|
FeedMessagesReceivedPayload,
|
|
35
34
|
FeedRealTimeCallback,
|
|
36
|
-
FeedStoreState,
|
|
37
35
|
} from "./types";
|
|
38
36
|
import { getFormattedTriggerData, mergeDateRangeParams } from "./utils";
|
|
39
37
|
|
|
@@ -60,7 +58,7 @@ class Feed {
|
|
|
60
58
|
private visibilityChangeListenerConnected: boolean = false;
|
|
61
59
|
|
|
62
60
|
// The raw store instance, used for binding in React and other environments
|
|
63
|
-
public store:
|
|
61
|
+
public store: FeedStore;
|
|
64
62
|
|
|
65
63
|
constructor(
|
|
66
64
|
readonly knock: Knock,
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { GenericData } from "@knocklabs/types";
|
|
2
|
-
import {
|
|
2
|
+
import { Store } from "@tanstack/store";
|
|
3
3
|
|
|
4
4
|
import { NetworkStatus } from "../../networkStatus";
|
|
5
5
|
|
|
6
|
-
import { FeedItem } from "./interfaces";
|
|
7
|
-
import { FeedStoreState } from "./types";
|
|
6
|
+
import { FeedItem, FeedMetadata, FeedResponse } from "./interfaces";
|
|
7
|
+
import { FeedStoreState, StoreFeedResultOptions } from "./types";
|
|
8
8
|
import { deduplicateItems, sortItems } from "./utils";
|
|
9
9
|
|
|
10
10
|
function processItems(items: FeedItem[]) {
|
|
@@ -19,7 +19,7 @@ const defaultSetResultOptions = {
|
|
|
19
19
|
shouldAppend: false,
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
-
const initialStoreState = {
|
|
22
|
+
export const initialStoreState: FeedStoreState = {
|
|
23
23
|
items: [],
|
|
24
24
|
metadata: {
|
|
25
25
|
total_count: 0,
|
|
@@ -31,33 +31,47 @@ const initialStoreState = {
|
|
|
31
31
|
after: null,
|
|
32
32
|
page_size: 50,
|
|
33
33
|
},
|
|
34
|
+
loading: false,
|
|
35
|
+
networkStatus: NetworkStatus.ready,
|
|
36
|
+
setResult: () => {},
|
|
37
|
+
setMetadata: () => {},
|
|
38
|
+
setNetworkStatus: () => {},
|
|
39
|
+
resetStore: () => {},
|
|
40
|
+
setItemAttrs: () => {},
|
|
34
41
|
};
|
|
35
42
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Initalize the store with tanstack store so it can be used within our
|
|
45
|
+
* FeedStore class. We do this seperately so that we have the ability to
|
|
46
|
+
* change which store library we use in the future if need be.
|
|
47
|
+
*/
|
|
48
|
+
const initalizeStore = () => {
|
|
49
|
+
const store = new Store(initialStoreState);
|
|
50
|
+
|
|
51
|
+
store.setState((state) => ({
|
|
52
|
+
...state,
|
|
40
53
|
// The network status indicates what's happening with the request
|
|
41
54
|
networkStatus: NetworkStatus.ready,
|
|
42
55
|
loading: false,
|
|
43
|
-
|
|
44
56
|
setNetworkStatus: (networkStatus: NetworkStatus) =>
|
|
45
|
-
|
|
57
|
+
store.setState((state) => ({
|
|
58
|
+
...state,
|
|
46
59
|
networkStatus,
|
|
47
60
|
loading: networkStatus === NetworkStatus.loading,
|
|
48
61
|
})),
|
|
49
62
|
|
|
50
63
|
setResult: (
|
|
51
|
-
{ entries, meta, page_info },
|
|
52
|
-
options = defaultSetResultOptions,
|
|
64
|
+
{ entries, meta, page_info }: FeedResponse,
|
|
65
|
+
options: StoreFeedResultOptions = defaultSetResultOptions,
|
|
53
66
|
) =>
|
|
54
|
-
|
|
67
|
+
store.setState((state) => {
|
|
55
68
|
// We resort the list on set, so concating everything is fine (if a bit suboptimal)
|
|
56
69
|
const items = options.shouldAppend
|
|
57
70
|
? processItems(state.items.concat(entries as FeedItem<GenericData>[]))
|
|
58
71
|
: entries;
|
|
59
72
|
|
|
60
73
|
return {
|
|
74
|
+
...state,
|
|
61
75
|
items,
|
|
62
76
|
metadata: meta,
|
|
63
77
|
pageInfo: options.shouldSetPage ? page_info : state.pageInfo,
|
|
@@ -66,19 +80,20 @@ export default function createStore() {
|
|
|
66
80
|
};
|
|
67
81
|
}),
|
|
68
82
|
|
|
69
|
-
setMetadata: (metadata
|
|
83
|
+
setMetadata: (metadata: FeedMetadata) =>
|
|
84
|
+
store.setState((state) => ({ ...state, metadata })),
|
|
70
85
|
|
|
71
86
|
resetStore: (metadata = initialStoreState.metadata) =>
|
|
72
|
-
|
|
87
|
+
store.setState(() => ({ ...initialStoreState, metadata })),
|
|
73
88
|
|
|
74
|
-
setItemAttrs: (itemIds
|
|
89
|
+
setItemAttrs: (itemIds: Array<string>, attrs: object) => {
|
|
75
90
|
// Create a map for the items to the updates to be made
|
|
76
91
|
const itemUpdatesMap: { [id: string]: object } = itemIds.reduce(
|
|
77
92
|
(acc, itemId) => ({ ...acc, [itemId]: attrs }),
|
|
78
93
|
{},
|
|
79
94
|
);
|
|
80
95
|
|
|
81
|
-
return
|
|
96
|
+
return store.setState((state) => {
|
|
82
97
|
const items = state.items.map((item) => {
|
|
83
98
|
if (itemUpdatesMap[item.id]) {
|
|
84
99
|
return { ...item, ...itemUpdatesMap[item.id] };
|
|
@@ -87,8 +102,50 @@ export default function createStore() {
|
|
|
87
102
|
return item;
|
|
88
103
|
});
|
|
89
104
|
|
|
90
|
-
return { items };
|
|
105
|
+
return { ...state, items };
|
|
91
106
|
});
|
|
92
107
|
},
|
|
93
108
|
}));
|
|
109
|
+
|
|
110
|
+
return store;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The FeedStore class is a wrapper for our store solution that's
|
|
115
|
+
* based on the same shape as zustand. This wrapping class allows
|
|
116
|
+
* us to maintain backwards compatibility with the zustand model
|
|
117
|
+
* while still allowing us to utilize tanstack store for the
|
|
118
|
+
* underlying store solution.
|
|
119
|
+
*/
|
|
120
|
+
export class FeedStore {
|
|
121
|
+
store: Store<FeedStoreState>;
|
|
122
|
+
|
|
123
|
+
constructor(store: Store<FeedStoreState>) {
|
|
124
|
+
this.store = store;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
getState() {
|
|
128
|
+
return this.store.state;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
setState(
|
|
132
|
+
updater: ((state: FeedStoreState) => FeedStoreState) | FeedStoreState,
|
|
133
|
+
) {
|
|
134
|
+
this.store.setState(
|
|
135
|
+
typeof updater === "function" ? updater : () => updater,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
getInitialState() {
|
|
140
|
+
return initialStoreState;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
subscribe(listener: (state: FeedStoreState) => void) {
|
|
144
|
+
return this.store.subscribe((state) => listener(state.currentVal));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export default function createStore() {
|
|
149
|
+
const store = initalizeStore();
|
|
150
|
+
return new FeedStore(store);
|
|
94
151
|
}
|
package/CHANGELOG.md
DELETED
|
@@ -1,300 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
## 0.14.9
|
|
4
|
-
|
|
5
|
-
### Patch Changes
|
|
6
|
-
|
|
7
|
-
- 4e73f12: fix: ensure this is bound to guide client instance in handleLocationChange
|
|
8
|
-
|
|
9
|
-
## 0.14.8
|
|
10
|
-
|
|
11
|
-
### Patch Changes
|
|
12
|
-
|
|
13
|
-
- 329ee05: downgrade tanstack store deps to 0.6.x to work in older TS version
|
|
14
|
-
|
|
15
|
-
## 0.14.7
|
|
16
|
-
|
|
17
|
-
### Patch Changes
|
|
18
|
-
|
|
19
|
-
- efd1005: Fix CJS builds
|
|
20
|
-
|
|
21
|
-
v0.14.6 of our client SDK did not support CJS. This version fixes CJS support.
|
|
22
|
-
|
|
23
|
-
## 0.14.6
|
|
24
|
-
|
|
25
|
-
### Patch Changes
|
|
26
|
-
|
|
27
|
-
- a5c615e: Allow multiple instances of `Feed` to listen for real-time updates to the same notification feed
|
|
28
|
-
|
|
29
|
-
Previously, using two or more instances of `Feed` with the same in-app feed channel would result in
|
|
30
|
-
only the most recently connected `Feed` receiving real-time updates. Now, all instances of `Feed`
|
|
31
|
-
configured with the same in-app channel will receive real-time updates.
|
|
32
|
-
|
|
33
|
-
## 0.14.5
|
|
34
|
-
|
|
35
|
-
### Patch Changes
|
|
36
|
-
|
|
37
|
-
- 8f00623: activation location rules support for guides
|
|
38
|
-
|
|
39
|
-
## 0.14.4
|
|
40
|
-
|
|
41
|
-
### Patch Changes
|
|
42
|
-
|
|
43
|
-
- e800896: feat: typescript fixes + quality of life improvements
|
|
44
|
-
|
|
45
|
-
## 0.14.3
|
|
46
|
-
|
|
47
|
-
### Patch Changes
|
|
48
|
-
|
|
49
|
-
- c97a1d9: Update TanStack Store
|
|
50
|
-
|
|
51
|
-
## 0.14.2
|
|
52
|
-
|
|
53
|
-
### Patch Changes
|
|
54
|
-
|
|
55
|
-
- 00439a2: fix(KNO-7843): Fix types and stringify trigger_data for feed API requests
|
|
56
|
-
|
|
57
|
-
## 0.14.1
|
|
58
|
-
|
|
59
|
-
### Patch Changes
|
|
60
|
-
|
|
61
|
-
- 4c41841: feat: accept options in the fetchNextPage method
|
|
62
|
-
|
|
63
|
-
## 0.14.0
|
|
64
|
-
|
|
65
|
-
### Minor Changes
|
|
66
|
-
|
|
67
|
-
- 711948c: feat: add guide client, hooks, provider, and components
|
|
68
|
-
|
|
69
|
-
## 0.13.1
|
|
70
|
-
|
|
71
|
-
### Patch Changes
|
|
72
|
-
|
|
73
|
-
- 187abc1: Allows the feed to accept date range options upon initialization.
|
|
74
|
-
|
|
75
|
-
## 0.13.0
|
|
76
|
-
|
|
77
|
-
### Minor Changes
|
|
78
|
-
|
|
79
|
-
- 4cd1b1e: add support for filtering by date in the feed client
|
|
80
|
-
|
|
81
|
-
## 0.12.0
|
|
82
|
-
|
|
83
|
-
### Minor Changes
|
|
84
|
-
|
|
85
|
-
- 8ba5dcb: [JS] Support React 19 in React SDKs
|
|
86
|
-
|
|
87
|
-
## 0.11.4
|
|
88
|
-
|
|
89
|
-
### Patch Changes
|
|
90
|
-
|
|
91
|
-
- 8ea25f4: fix: include missing timestamp fields on FeedItem and Message
|
|
92
|
-
|
|
93
|
-
## 0.11.3
|
|
94
|
-
|
|
95
|
-
### Patch Changes
|
|
96
|
-
|
|
97
|
-
- 4f76cd6: fix: raise when calling user methods before auth
|
|
98
|
-
|
|
99
|
-
## 0.11.2
|
|
100
|
-
|
|
101
|
-
### Patch Changes
|
|
102
|
-
|
|
103
|
-
- 2161d3f: Make id and displayName required in MsTeamsTeam and MsTeamsChannel types
|
|
104
|
-
- 2161d3f: Add `ms_teams_team_id` to MsTeamsChannelConnection type
|
|
105
|
-
- 1ba1393: add TeamsKit hooks for teams and channels
|
|
106
|
-
- b4b5c02: add getTeams and getChannels to MsTeamsClient
|
|
107
|
-
|
|
108
|
-
## 0.11.1
|
|
109
|
-
|
|
110
|
-
### Patch Changes
|
|
111
|
-
|
|
112
|
-
- b9f6712: fix: types for userId should handle undefined and null
|
|
113
|
-
|
|
114
|
-
## 0.11.0
|
|
115
|
-
|
|
116
|
-
### Minor Changes
|
|
117
|
-
|
|
118
|
-
- 013ad8d: feat: add MsTeamsAuthButton
|
|
119
|
-
|
|
120
|
-
## 0.10.17
|
|
121
|
-
|
|
122
|
-
### Patch Changes
|
|
123
|
-
|
|
124
|
-
- 26db496: fix: ensure feed can render with empty/missing userId values
|
|
125
|
-
- 988aaf9: fix: engagement_status in BulkUpdateMessagesInChannelProperties type
|
|
126
|
-
|
|
127
|
-
## 0.10.16
|
|
128
|
-
|
|
129
|
-
### Patch Changes
|
|
130
|
-
|
|
131
|
-
- bc99374: fix: bundle client package using "compat" interop
|
|
132
|
-
|
|
133
|
-
## 0.10.15
|
|
134
|
-
|
|
135
|
-
### Patch Changes
|
|
136
|
-
|
|
137
|
-
- 26166e3: fix: update preference set types
|
|
138
|
-
- Updated dependencies [26166e3]
|
|
139
|
-
- @knocklabs/types@0.1.5
|
|
140
|
-
|
|
141
|
-
## 0.10.14
|
|
142
|
-
|
|
143
|
-
### Patch Changes
|
|
144
|
-
|
|
145
|
-
- 7510909: fix: ensure axios is always imported correctly
|
|
146
|
-
|
|
147
|
-
## 0.10.13
|
|
148
|
-
|
|
149
|
-
### Patch Changes
|
|
150
|
-
|
|
151
|
-
- 1d440f7: feat: add prebuilt In App Feed Components for React Native
|
|
152
|
-
|
|
153
|
-
## 0.10.12
|
|
154
|
-
|
|
155
|
-
### Patch Changes
|
|
156
|
-
|
|
157
|
-
- 5545f9e: feat: support passing metadata for interactions
|
|
158
|
-
|
|
159
|
-
## 0.10.11
|
|
160
|
-
|
|
161
|
-
### Patch Changes
|
|
162
|
-
|
|
163
|
-
- 395f0ca: fix: check type of zustand default import and fix cjs build
|
|
164
|
-
|
|
165
|
-
## 0.10.10
|
|
166
|
-
|
|
167
|
-
### Patch Changes
|
|
168
|
-
|
|
169
|
-
- a4d520c: chore: update generic types
|
|
170
|
-
- Updated dependencies [a4d520c]
|
|
171
|
-
- @knocklabs/types@0.1.4
|
|
172
|
-
|
|
173
|
-
## 0.10.9
|
|
174
|
-
|
|
175
|
-
### Patch Changes
|
|
176
|
-
|
|
177
|
-
- d0adb14: fix: don't destroy the store, ever
|
|
178
|
-
|
|
179
|
-
## 0.10.8
|
|
180
|
-
|
|
181
|
-
### Patch Changes
|
|
182
|
-
|
|
183
|
-
- 29e3942: fix: introduce new useNotificationStore hook to prevent issues that prevent state updates
|
|
184
|
-
|
|
185
|
-
## 0.10.7
|
|
186
|
-
|
|
187
|
-
### Patch Changes
|
|
188
|
-
|
|
189
|
-
- f25b112: fix: ensure feed store reference re-renders after changes to user
|
|
190
|
-
|
|
191
|
-
## 0.10.6
|
|
192
|
-
|
|
193
|
-
### Patch Changes
|
|
194
|
-
|
|
195
|
-
- b29a47a: Add KnockExpoPushNotificationProvider to react-native sdk
|
|
196
|
-
|
|
197
|
-
## 0.10.5
|
|
198
|
-
|
|
199
|
-
### Patch Changes
|
|
200
|
-
|
|
201
|
-
- 044eb0f: fix: check if document is defined before setting up auto socket manager
|
|
202
|
-
|
|
203
|
-
## 0.10.4
|
|
204
|
-
|
|
205
|
-
### Patch Changes
|
|
206
|
-
|
|
207
|
-
- 5a7c56e: fix: avoid adding duplicate visibiliy change event listeners
|
|
208
|
-
|
|
209
|
-
## 0.10.3
|
|
210
|
-
|
|
211
|
-
### Patch Changes
|
|
212
|
-
|
|
213
|
-
- a71ce51: fix: event types to use items. and fix types
|
|
214
|
-
|
|
215
|
-
## 0.10.2
|
|
216
|
-
|
|
217
|
-
### Patch Changes
|
|
218
|
-
|
|
219
|
-
- 42ba22c: fix: improve typing for react < 18
|
|
220
|
-
|
|
221
|
-
## 0.10.1
|
|
222
|
-
|
|
223
|
-
### Patch Changes
|
|
224
|
-
|
|
225
|
-
- 3c277cb: fix: remove react-query and replace with swr for react 16+ support
|
|
226
|
-
- 567e24f: fix: clean up visibility change event listener on feed teardown
|
|
227
|
-
|
|
228
|
-
## 0.10.0
|
|
229
|
-
|
|
230
|
-
### Minor Changes
|
|
231
|
-
|
|
232
|
-
- 8bdc75b: Added a new MessageClient to access message api's independently from the Feed.
|
|
233
|
-
|
|
234
|
-
## 0.9.4
|
|
235
|
-
|
|
236
|
-
### Patch Changes
|
|
237
|
-
|
|
238
|
-
- f58371c: Added user get and identify methods
|
|
239
|
-
|
|
240
|
-
## 0.9.3
|
|
241
|
-
|
|
242
|
-
### Patch Changes
|
|
243
|
-
|
|
244
|
-
- bc69618: Add react-native to package.json files to fix a bug in our React Native SDK
|
|
245
|
-
|
|
246
|
-
## 0.9.2
|
|
247
|
-
|
|
248
|
-
### Patch Changes
|
|
249
|
-
|
|
250
|
-
- fed0f8c: add support for actions in notification feed cells
|
|
251
|
-
|
|
252
|
-
## 0.9.1
|
|
253
|
-
|
|
254
|
-
### Patch Changes
|
|
255
|
-
|
|
256
|
-
- f37d680: Update event format for client status updates
|
|
257
|
-
|
|
258
|
-
## 0.9.0
|
|
259
|
-
|
|
260
|
-
### Minor Changes
|
|
261
|
-
|
|
262
|
-
- 627e643: Add SlackKit components, hooks, client JS functions, and example apps.
|
|
263
|
-
|
|
264
|
-
## 0.8.21
|
|
265
|
-
|
|
266
|
-
### Patch Changes
|
|
267
|
-
|
|
268
|
-
- c9faba5: fix esm build issues with mjs files
|
|
269
|
-
|
|
270
|
-
## 0.8.20
|
|
271
|
-
|
|
272
|
-
### Patch Changes
|
|
273
|
-
|
|
274
|
-
- Re-releasing packages
|
|
275
|
-
|
|
276
|
-
## 0.8.19
|
|
277
|
-
|
|
278
|
-
### Patch Changes
|
|
279
|
-
|
|
280
|
-
- 7786ec5: chore: upgrade to yarn modern and update local package references
|
|
281
|
-
- 9dd0d15: feat: add onUserTokenExpiring callback option to client
|
|
282
|
-
|
|
283
|
-
## 0.8.18
|
|
284
|
-
|
|
285
|
-
### Patch Changes
|
|
286
|
-
|
|
287
|
-
- e53c200: fix: strip socket manager options from http requests
|
|
288
|
-
- d4ba1f2: chore: add shared types package
|
|
289
|
-
|
|
290
|
-
## 0.8.17
|
|
291
|
-
|
|
292
|
-
### Patch Changes
|
|
293
|
-
|
|
294
|
-
- 345ebc1: feat: add option to automatically manage open socket connections
|
|
295
|
-
|
|
296
|
-
## 0.8.16
|
|
297
|
-
|
|
298
|
-
### Patch Changes
|
|
299
|
-
|
|
300
|
-
- 7bc5e4a: fix: add @babel/runtime dependency
|