@dashx/react 0.5.3 → 0.6.0
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/providers/DashXProvider.d.ts +8 -1
- package/dist/cjs/providers/DashXProvider.js +1 -1
- package/dist/cjs/providers/DashXProvider.js.map +3 -3
- package/dist/esm/providers/DashXProvider.d.ts +8 -1
- package/dist/esm/providers/DashXProvider.js +1 -1
- package/dist/esm/providers/DashXProvider.js.map +3 -3
- package/package.json +2 -2
- package/src/providers/DashXProvider.tsx +43 -31
- package/CHANGELOG.md +0 -109
|
@@ -24,8 +24,15 @@ type DashXProviderProps = ClientParams & {
|
|
|
24
24
|
* Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
|
|
25
25
|
*/
|
|
26
26
|
identityToken?: string | null;
|
|
27
|
+
/**
|
|
28
|
+
* Fetches an identity token from your backend, e.g. a member token that keeps a workspace member
|
|
29
|
+
* online. The client calls it before the socket connects, before each token expires and once after
|
|
30
|
+
* the server refuses one, and reconnects the socket each time. Read through a ref, so an inline
|
|
31
|
+
* function does not recreate the client.
|
|
32
|
+
*/
|
|
33
|
+
identityTokenProvider?: () => Promise<string>;
|
|
27
34
|
};
|
|
28
|
-
declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, autocapture, maskPersonalDataProperties, customPersonalDataProperties, beforeSend, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
|
|
35
|
+
declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, autocapture, maskPersonalDataProperties, customPersonalDataProperties, beforeSend, identityTokenProvider, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
|
|
29
36
|
export declare function useWebSocket(): WebSocketContextType;
|
|
30
37
|
export default DashXProvider;
|
|
31
38
|
export { DashXContext };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var G=Object.create;var g=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var _=(t,o)=>{for(var s in o)g(t,s,{get:o[s],enumerable:!0})},I=(t,o,s,l)=>{if(o&&typeof o=="object"||typeof o=="function")for(let c of L(o))!Z.call(t,c)&&c!==s&&g(t,c,{get:()=>o[c],enumerable:!(l=H(o,c))||l.enumerable});return t};var O=(t,o,s)=>(s=t!=null?G(Y(t)):{},I(o||!t||!t.__esModule?g(s,"default",{value:t,enumerable:!0}):s,t)),V=t=>I(g({},"__esModule",{value:!0}),t);var ne={};_(ne,{DashXContext:()=>m,default:()=>te,useWebSocket:()=>ee});module.exports=V(ne);var C=require("react/jsx-runtime"),z=O(require("@dashx/browser")),e=O(require("react"));const m=(0,e.createContext)(null),B=(0,e.createContext)(null);function U({children:t,publicKey:o,baseUri:s,realtimeBaseUri:l,targetEnvironment:c,targetProduct:P,targetVersion:h,initializeWebSocketOnLoad:M=!1,webSocketQueryParams:R={},identityUid:u,identityToken:d,autocapture:b,maskPersonalDataProperties:x,customPersonalDataProperties:w,beforeSend:E,identityTokenProvider:v}){const X=(0,e.useRef)(E);X.current=E;const A=(0,e.useCallback)(r=>{let i=r;for(const f of[X.current??[]].flat()){if(!i)break;i=f(i)}return i},[]),T=(0,e.useRef)(v);T.current=v;const D=!!v,J=(0,e.useCallback)(()=>{const r=T.current;return r?r():Promise.reject(new Error("identityTokenProvider was removed"))},[]),K=JSON.stringify(w??[]),n=e.default.useMemo(()=>{const r=z.default.configure({publicKey:o,baseUri:s,realtimeBaseUri:l,targetEnvironment:c,targetProduct:P,targetVersion:h,maskPersonalDataProperties:x,customPersonalDataProperties:w,beforeSend:A,identityTokenProvider:D?J:void 0});return(u!==void 0||d!==void 0)&&r.setIdentity(u,d),r},[o,s,l,c,P,h,x,K,D]),N=JSON.stringify(R??{}),S=e.default.useMemo(()=>R??{},[N]),[q,k]=(0,e.useState)(!1),y=(0,e.useRef)(null),W=(0,e.useRef)(new Set),Q=(0,e.useCallback)(r=>(W.current.add(r),()=>{W.current.delete(r)}),[]),p=(0,e.useCallback)(r=>{if(!n){console.error("DashX client not initialized");return}if(n.isWebSocketActive)return;const i={...S,...r},f=()=>{y.current=n.webSocketManager};n.connectWebSocket({queryParams:i,onError:a=>console.error({errorEvent:a}),onClose:a=>{console.log({closeEvent:a}),f(),k(!1)},onMessage:a=>{W.current.forEach(F=>{try{F(a)}catch($){console.error("Error in WebSocket subscriber callback:",$)}})},onOpen:()=>{console.log("WebSocket connected successfully"),f(),k(!0)},onReconnect:a=>{console.log(`WebSocket reconnecting... attempt ${a}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),k(!1)}}),f()},[n,S]);(0,e.useEffect)(()=>{!n||u===void 0&&d===void 0||n.setIdentity(u,d)},[n,u,d]),(0,e.useEffect)(()=>()=>{n?.disconnectWebSocket(),y.current=null,k(!1)},[n]);const j=JSON.stringify(b??!1);return(0,e.useEffect)(()=>{if(!(!n||!b))return n.startAutocapture(b===!0?{}:b),()=>n.stopAutocapture()},[n,j]),(0,e.useEffect)(()=>{M&&p(S)},[M,p,S]),(0,C.jsx)(m.Provider,{value:n,children:(0,C.jsx)(B.Provider,{value:{isConnected:q,subscribe:Q,wsManagerRef:y,initializeWebSocket:p},children:t})})}function ee(){const t=(0,e.useContext)(B);if(!t)throw new Error("useWebSocket must be used within a DashXProvider");return t}var te=U;
|
|
2
2
|
//# sourceMappingURL=DashXProvider.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/providers/DashXProvider.tsx"],
|
|
4
|
-
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { BeforeSend, CapturedEvent, Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any>,\n /**\n * The visitor's account uid, addressed on both transports (GraphQL + WS).\n * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to\n * leave it unchanged. Pair with `identityToken` for the same identity.\n */\n identityUid?: string | null,\n /**\n * Identity token (minted with your DashX server SDK's `generateIdentityToken`,\n * or from an exchange endpoint you control). When set, the SDK uses it for both\n * GraphQL (`X-Identity-Token` header) and the WebSocket handshake \u2014 the server\n * identifies the visitor from it, which is the ownership key for InApp Chat.\n * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.\n */\n identityToken?: string | null,\n}\n\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n identityUid,\n identityToken,\n autocapture,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend,\n}: React.PropsWithChildren<DashXProviderProps>) {\n // Read through a ref so an inline `beforeSend` takes effect without recreating the client on\n // every render.\n const beforeSendRef = useRef(beforeSend);\n beforeSendRef.current = beforeSend;\n const stableBeforeSend = useCallback<BeforeSend>((event) => {\n let result: CapturedEvent | null = event;\n for (const fn of [ beforeSendRef.current ?? [] ].flat()) {\n if (!result) break;\n result = fn(result);\n }\n return result;\n }, []);\n\n const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);\n\n const dashX = React.useMemo(\n () => {\n const client = DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend: stableBeforeSend,\n });\n // Apply identity synchronously at creation so a child that starts work in\n // its own mount effect (child effects run before this provider's effects)\n // sees the token already set. Later prop changes go through the effect\n // below; identity is intentionally not a useMemo dep (we don't recreate\n // the client when it changes).\n if (identityUid !== undefined || identityToken !== undefined) {\n client.setIdentity(identityUid, identityToken);\n }\n return client;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataPropertiesKey,\n ],\n );\n\n // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of\n // the effects below, so memoize on its content to keep the reference stable \u2014\n // otherwise those effects (setIdentity / WS init) re-run on every render.\n const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});\n const stableWebSocketQueryParams = React.useMemo(\n () => webSocketQueryParams ?? {},\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [webSocketQueryParamsKey],\n );\n\n // WebSocket state\n const [isConnected, setIsConnected] = useState(false);\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());\n\n const subscribe = useCallback((callback: (message: WebsocketMessageType) => void) => {\n subscribersRef.current.add(callback);\n\n // Return unsubscribe function\n return () => {\n subscribersRef.current.delete(callback);\n };\n }, []);\n\n const initializeWebSocket = useCallback((customQueryParams?: Record<string, any>) => {\n if (!dashX) {\n console.error('DashX client not initialized');\n return;\n }\n\n // Reuse an existing manager \u2014 it owns its own throttled reconnect\n // lifecycle. Tearing it down and creating a new one on every call (e.g.\n // when a consumer re-invokes this as `isConnected` flips to false on each\n // close) resets the per-instance reconnect throttle and reconnects\n // immediately, defeating the backoff. Create one only if none exists.\n if (wsManagerRef.current) {\n return;\n }\n\n const queryParams = {\n publicKey: dashX.publicKey,\n ...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),\n // Provider-level defaults apply to every provider-owned socket \u2014 including\n // when the chat hook (or any consumer) opens the socket first by calling\n // `initializeWebSocket()` with no args. Explicit call-site params override.\n ...stableWebSocketQueryParams,\n ...customQueryParams,\n };\n\n const wsManager = dashX.createWebSocketConnection({\n queryParams,\n onError: (errorEvent: Event) => console.error({ errorEvent }),\n onClose: (closeEvent: CloseEvent) => {\n console.log({ closeEvent });\n setIsConnected(false);\n },\n onMessage: (message: WebsocketMessageType) => {\n // Notify all subscribers\n subscribersRef.current.forEach((callback) => {\n try {\n callback(message);\n } catch (error) {\n console.error('Error in WebSocket subscriber callback:', error);\n }\n });\n },\n onOpen: () => {\n console.log('WebSocket connected successfully');\n setIsConnected(true);\n },\n onReconnect: (attempt: number) => {\n console.log(`WebSocket reconnecting... attempt ${attempt}`);\n },\n onReconnectFailed: () => {\n console.error('WebSocket reconnection failed');\n setIsConnected(false);\n },\n });\n\n wsManagerRef.current = wsManager;\n wsManager.connect();\n }, [dashX, stableWebSocketQueryParams]);\n\n // Forward `identityUid` + `identityToken` into the dashX client so the same\n // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`\n // treats `undefined` as \"leave unchanged\", so setting only `identityToken`\n // won't clobber an existing account uid (and vice versa).\n const previousIdentityTokenRef = useRef(identityToken);\n useEffect(() => {\n if (!dashX || (identityUid === undefined && identityToken === undefined)) {\n return;\n }\n\n dashX.setIdentity(identityUid, identityToken);\n\n // This provider owns the socket (created via `createWebSocketConnection`,\n // not the client's internal manager that `setIdentity` reconnects), so on a\n // token change we recreate it here to put the new identity_token in the WS\n // URL. GraphQL picks up the new header on its own; tracked chat channels\n // re-subscribe on the new socket's `onOpen`.\n const tokenChanged = identityToken !== previousIdentityTokenRef.current;\n previousIdentityTokenRef.current = identityToken;\n if (tokenChanged && wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);\n\n // Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and\n // keeps one, which would leave the discarded client's listeners capturing every page view.\n const autocaptureKey = JSON.stringify(autocapture ?? false);\n useEffect(() => {\n if (!dashX || !autocapture) {\n return;\n }\n\n dashX.startAutocapture(autocapture === true ? {} : autocapture);\n return () => dashX.stopAutocapture();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ dashX, autocaptureKey ]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);\n\n return (\n <DashXContext.Provider value={dashX}>\n <WebSocketContext.Provider\n value={{\n isConnected,\n subscribe,\n wsManagerRef,\n initializeWebSocket\n }}\n >\n {children}\n </WebSocketContext.Provider>\n </DashXContext.Provider>\n );\n}\n\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (!context) {\n throw new Error('useWebSocket must be used within a DashXProvider');\n }\n return context;\n}\n\nexport default DashXProvider;\nexport { DashXContext };\n"],
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,
|
|
6
|
-
"names": ["DashXProvider_exports", "__export", "DashXContext", "DashXProvider_default", "useWebSocket", "__toCommonJS", "import_jsx_runtime", "import_browser", "import_react", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "identityUid", "identityToken", "autocapture", "maskPersonalDataProperties", "customPersonalDataProperties", "beforeSend", "beforeSendRef", "stableBeforeSend", "event", "result", "fn", "customPersonalDataPropertiesKey", "dashX", "React", "client", "DashX", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "
|
|
4
|
+
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { BeforeSend, CapturedEvent, Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any>,\n /**\n * The visitor's account uid, addressed on both transports (GraphQL + WS).\n * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to\n * leave it unchanged. Pair with `identityToken` for the same identity.\n */\n identityUid?: string | null,\n /**\n * Identity token (minted with your DashX server SDK's `generateIdentityToken`,\n * or from an exchange endpoint you control). When set, the SDK uses it for both\n * GraphQL (`X-Identity-Token` header) and the WebSocket handshake \u2014 the server\n * identifies the visitor from it, which is the ownership key for InApp Chat.\n * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.\n */\n identityToken?: string | null,\n /**\n * Fetches an identity token from your backend, e.g. a member token that keeps a workspace member\n * online. The client calls it before the socket connects, before each token expires and once after\n * the server refuses one, and reconnects the socket each time. Read through a ref, so an inline\n * function does not recreate the client.\n */\n identityTokenProvider?: () => Promise<string>,\n}\n\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n identityUid,\n identityToken,\n autocapture,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend,\n identityTokenProvider,\n}: React.PropsWithChildren<DashXProviderProps>) {\n // Read through a ref so an inline `beforeSend` takes effect without recreating the client on\n // every render.\n const beforeSendRef = useRef(beforeSend);\n beforeSendRef.current = beforeSend;\n const stableBeforeSend = useCallback<BeforeSend>((event) => {\n let result: CapturedEvent | null = event;\n for (const fn of [ beforeSendRef.current ?? [] ].flat()) {\n if (!result) break;\n result = fn(result);\n }\n return result;\n }, []);\n\n const identityTokenProviderRef = useRef(identityTokenProvider);\n identityTokenProviderRef.current = identityTokenProvider;\n const hasIdentityTokenProvider = Boolean(identityTokenProvider);\n const stableIdentityTokenProvider = useCallback(() => {\n const provider = identityTokenProviderRef.current;\n return provider ? provider() : Promise.reject(new Error('identityTokenProvider was removed'));\n }, []);\n\n const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);\n\n const dashX = React.useMemo(\n () => {\n const client = DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend: stableBeforeSend,\n identityTokenProvider: hasIdentityTokenProvider ? stableIdentityTokenProvider : undefined,\n });\n // Apply identity synchronously at creation so a child that starts work in\n // its own mount effect (child effects run before this provider's effects)\n // sees the token already set. Later prop changes go through the effect\n // below; identity is intentionally not a useMemo dep (we don't recreate\n // the client when it changes).\n if (identityUid !== undefined || identityToken !== undefined) {\n client.setIdentity(identityUid, identityToken);\n }\n return client;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataPropertiesKey,\n hasIdentityTokenProvider,\n ],\n );\n\n // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of\n // the effects below, so memoize on its content to keep the reference stable \u2014\n // otherwise those effects (setIdentity / WS init) re-run on every render.\n const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});\n const stableWebSocketQueryParams = React.useMemo(\n () => webSocketQueryParams ?? {},\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [webSocketQueryParamsKey],\n );\n\n // WebSocket state\n const [isConnected, setIsConnected] = useState(false);\n // The client replaces its manager on every reconnect for a new identity token, so read it fresh.\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());\n\n const subscribe = useCallback((callback: (message: WebsocketMessageType) => void) => {\n subscribersRef.current.add(callback);\n\n // Return unsubscribe function\n return () => {\n subscribersRef.current.delete(callback);\n };\n }, []);\n\n const initializeWebSocket = useCallback((customQueryParams?: Record<string, any>) => {\n if (!dashX) {\n console.error('DashX client not initialized');\n return;\n }\n\n // Reuse the client's socket while it is connected or retrying - it owns its own throttled\n // reconnect lifecycle, and reconnects itself for a new identity token. Starting over then (e.g.\n // when a consumer re-invokes this as `isConnected` flips to false on each close) would reset that\n // throttle. After a terminal close the client starts over with a fresh token.\n if (dashX.isWebSocketActive) {\n return;\n }\n\n // The client adds `publicKey` and `targetEnvironment` itself. Provider-level params apply to\n // every provider-owned socket, including when a hook opens it first with no args.\n const queryParams = {\n ...stableWebSocketQueryParams,\n ...customQueryParams,\n };\n\n const syncManager = () => {\n wsManagerRef.current = dashX.webSocketManager;\n };\n\n dashX.connectWebSocket({\n queryParams,\n onError: (errorEvent: Event) => console.error({ errorEvent }),\n onClose: (closeEvent: CloseEvent) => {\n console.log({ closeEvent });\n syncManager();\n setIsConnected(false);\n },\n onMessage: (message: WebsocketMessageType) => {\n subscribersRef.current.forEach((callback) => {\n try {\n callback(message);\n } catch (error) {\n console.error('Error in WebSocket subscriber callback:', error);\n }\n });\n },\n onOpen: () => {\n console.log('WebSocket connected successfully');\n syncManager();\n setIsConnected(true);\n },\n onReconnect: (attempt: number) => {\n console.log(`WebSocket reconnecting... attempt ${attempt}`);\n },\n onReconnectFailed: () => {\n console.error('WebSocket reconnection failed');\n setIsConnected(false);\n },\n });\n syncManager();\n }, [dashX, stableWebSocketQueryParams]);\n\n // Forward `identityUid` + `identityToken` into the dashX client so the same\n // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`\n // treats `undefined` as \"leave unchanged\", so setting only `identityToken`\n // won't clobber an existing account uid (and vice versa). A new token\n // reconnects the client's socket with it.\n useEffect(() => {\n if (!dashX || (identityUid === undefined && identityToken === undefined)) {\n return;\n }\n\n dashX.setIdentity(identityUid, identityToken);\n }, [ dashX, identityUid, identityToken ]);\n\n // A replaced client (new keys or environment) must not leave its socket running.\n useEffect(() => () => {\n dashX?.disconnectWebSocket();\n wsManagerRef.current = null;\n setIsConnected(false);\n }, [ dashX ]);\n\n // Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and\n // keeps one, which would leave the discarded client's listeners capturing every page view.\n const autocaptureKey = JSON.stringify(autocapture ?? false);\n useEffect(() => {\n if (!dashX || !autocapture) {\n return;\n }\n\n dashX.startAutocapture(autocapture === true ? {} : autocapture);\n return () => dashX.stopAutocapture();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ dashX, autocaptureKey ]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);\n\n return (\n <DashXContext.Provider value={dashX}>\n <WebSocketContext.Provider\n value={{\n isConnected,\n subscribe,\n wsManagerRef,\n initializeWebSocket\n }}\n >\n {children}\n </WebSocketContext.Provider>\n </DashXContext.Provider>\n );\n}\n\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (!context) {\n throw new Error('useWebSocket must be used within a DashXProvider');\n }\n return context;\n}\n\nexport default DashXProvider;\nexport { DashXContext };\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,kBAAAE,EAAA,YAAAC,GAAA,iBAAAC,KAAA,eAAAC,EAAAL,IAoP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7Cb,EAAe,EAAK,CACtB,CACF,CAAC,EACDQ,EAAY,CACd,EAAG,CAACf,EAAOK,CAA0B,CAAC,KAOtC,aAAU,IAAM,CACV,CAACL,GAAUjB,IAAgB,QAAaC,IAAkB,QAI9DgB,EAAM,YAAYjB,EAAaC,CAAa,CAC9C,EAAG,CAAEgB,EAAOjB,EAAaC,CAAc,CAAC,KAGxC,aAAU,IAAM,IAAM,CACpBgB,GAAO,oBAAoB,EAC3BQ,EAAa,QAAU,KACvBD,EAAe,EAAK,CACtB,EAAG,CAAEP,CAAM,CAAC,EAIZ,MAAMqB,EAAiB,KAAK,UAAUpC,GAAe,EAAK,EAC1D,sBAAU,IAAM,CACd,GAAI,GAACe,GAAS,CAACf,GAIf,OAAAe,EAAM,iBAAiBf,IAAgB,GAAO,CAAC,EAAIA,CAAW,EACvD,IAAMe,EAAM,gBAAgB,CAErC,EAAG,CAAEA,EAAOqB,CAAe,CAAC,KAE5B,aAAU,IAAM,CACVxC,GACF+B,EAAoBP,CAA0B,CAElD,EAAG,CAAExB,EAA2B+B,EAAqBP,CAA2B,CAAC,KAG/E,OAACxC,EAAa,SAAb,CAAsB,MAAOmC,EAC5B,mBAAC5B,EAAiB,SAAjB,CACC,MAAO,CACL,YAAAkC,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAAtC,EACH,EACF,CAEJ,CAEO,SAASP,IAAe,CAC7B,MAAMuD,KAAU,cAAWlD,CAAgB,EAC3C,GAAI,CAACkD,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOxD,GAAQO",
|
|
6
|
+
"names": ["DashXProvider_exports", "__export", "DashXContext", "DashXProvider_default", "useWebSocket", "__toCommonJS", "import_jsx_runtime", "import_browser", "import_react", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "identityUid", "identityToken", "autocapture", "maskPersonalDataProperties", "customPersonalDataProperties", "beforeSend", "identityTokenProvider", "beforeSendRef", "stableBeforeSend", "event", "result", "fn", "identityTokenProviderRef", "hasIdentityTokenProvider", "stableIdentityTokenProvider", "provider", "customPersonalDataPropertiesKey", "dashX", "React", "client", "DashX", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "syncManager", "errorEvent", "closeEvent", "message", "error", "attempt", "autocaptureKey", "context"]
|
|
7
7
|
}
|
|
@@ -24,8 +24,15 @@ type DashXProviderProps = ClientParams & {
|
|
|
24
24
|
* Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
|
|
25
25
|
*/
|
|
26
26
|
identityToken?: string | null;
|
|
27
|
+
/**
|
|
28
|
+
* Fetches an identity token from your backend, e.g. a member token that keeps a workspace member
|
|
29
|
+
* online. The client calls it before the socket connects, before each token expires and once after
|
|
30
|
+
* the server refuses one, and reconnects the socket each time. Read through a ref, so an inline
|
|
31
|
+
* function does not recreate the client.
|
|
32
|
+
*/
|
|
33
|
+
identityTokenProvider?: () => Promise<string>;
|
|
27
34
|
};
|
|
28
|
-
declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, autocapture, maskPersonalDataProperties, customPersonalDataProperties, beforeSend, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
|
|
35
|
+
declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, autocapture, maskPersonalDataProperties, customPersonalDataProperties, beforeSend, identityTokenProvider, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
|
|
29
36
|
export declare function useWebSocket(): WebSocketContextType;
|
|
30
37
|
export default DashXProvider;
|
|
31
38
|
export { DashXContext };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as z}from"react/jsx-runtime";import G from"@dashx/browser";import D,{createContext as I,useContext as H,useEffect as d,useRef as f,useState as L,useCallback as b}from"react";const O=I(null),B=I(null);function Y({children:a,publicKey:y,baseUri:W,realtimeBaseUri:p,targetEnvironment:m,targetProduct:C,targetVersion:P,initializeWebSocketOnLoad:h=!1,webSocketQueryParams:M={},identityUid:r,identityToken:s,autocapture:i,maskPersonalDataProperties:R,customPersonalDataProperties:x,beforeSend:w,identityTokenProvider:S}){const E=f(w);E.current=w;const A=b(t=>{let o=t;for(const c of[E.current??[]].flat()){if(!o)break;o=c(o)}return o},[]),X=f(S);X.current=S;const T=!!S,J=b(()=>{const t=X.current;return t?t():Promise.reject(new Error("identityTokenProvider was removed"))},[]),K=JSON.stringify(x??[]),e=D.useMemo(()=>{const t=G.configure({publicKey:y,baseUri:W,realtimeBaseUri:p,targetEnvironment:m,targetProduct:C,targetVersion:P,maskPersonalDataProperties:R,customPersonalDataProperties:x,beforeSend:A,identityTokenProvider:T?J:void 0});return(r!==void 0||s!==void 0)&&t.setIdentity(r,s),t},[y,W,p,m,C,P,R,K,T]),N=JSON.stringify(M??{}),l=D.useMemo(()=>M??{},[N]),[q,u]=L(!1),k=f(null),g=f(new Set),Q=b(t=>(g.current.add(t),()=>{g.current.delete(t)}),[]),v=b(t=>{if(!e){console.error("DashX client not initialized");return}if(e.isWebSocketActive)return;const o={...l,...t},c=()=>{k.current=e.webSocketManager};e.connectWebSocket({queryParams:o,onError:n=>console.error({errorEvent:n}),onClose:n=>{console.log({closeEvent:n}),c(),u(!1)},onMessage:n=>{g.current.forEach(F=>{try{F(n)}catch($){console.error("Error in WebSocket subscriber callback:",$)}})},onOpen:()=>{console.log("WebSocket connected successfully"),c(),u(!0)},onReconnect:n=>{console.log(`WebSocket reconnecting... attempt ${n}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),u(!1)}}),c()},[e,l]);d(()=>{!e||r===void 0&&s===void 0||e.setIdentity(r,s)},[e,r,s]),d(()=>()=>{e?.disconnectWebSocket(),k.current=null,u(!1)},[e]);const j=JSON.stringify(i??!1);return d(()=>{if(!(!e||!i))return e.startAutocapture(i===!0?{}:i),()=>e.stopAutocapture()},[e,j]),d(()=>{h&&v(l)},[h,v,l]),z(O.Provider,{value:e,children:z(B.Provider,{value:{isConnected:q,subscribe:Q,wsManagerRef:k,initializeWebSocket:v},children:a})})}function V(){const a=H(B);if(!a)throw new Error("useWebSocket must be used within a DashXProvider");return a}var U=Y;export{O as DashXContext,U as default,V as useWebSocket};
|
|
2
2
|
//# sourceMappingURL=DashXProvider.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/providers/DashXProvider.tsx"],
|
|
4
|
-
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { BeforeSend, CapturedEvent, Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any>,\n /**\n * The visitor's account uid, addressed on both transports (GraphQL + WS).\n * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to\n * leave it unchanged. Pair with `identityToken` for the same identity.\n */\n identityUid?: string | null,\n /**\n * Identity token (minted with your DashX server SDK's `generateIdentityToken`,\n * or from an exchange endpoint you control). When set, the SDK uses it for both\n * GraphQL (`X-Identity-Token` header) and the WebSocket handshake \u2014 the server\n * identifies the visitor from it, which is the ownership key for InApp Chat.\n * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.\n */\n identityToken?: string | null,\n}\n\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n identityUid,\n identityToken,\n autocapture,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend,\n}: React.PropsWithChildren<DashXProviderProps>) {\n // Read through a ref so an inline `beforeSend` takes effect without recreating the client on\n // every render.\n const beforeSendRef = useRef(beforeSend);\n beforeSendRef.current = beforeSend;\n const stableBeforeSend = useCallback<BeforeSend>((event) => {\n let result: CapturedEvent | null = event;\n for (const fn of [ beforeSendRef.current ?? [] ].flat()) {\n if (!result) break;\n result = fn(result);\n }\n return result;\n }, []);\n\n const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);\n\n const dashX = React.useMemo(\n () => {\n const client = DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend: stableBeforeSend,\n });\n // Apply identity synchronously at creation so a child that starts work in\n // its own mount effect (child effects run before this provider's effects)\n // sees the token already set. Later prop changes go through the effect\n // below; identity is intentionally not a useMemo dep (we don't recreate\n // the client when it changes).\n if (identityUid !== undefined || identityToken !== undefined) {\n client.setIdentity(identityUid, identityToken);\n }\n return client;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataPropertiesKey,\n ],\n );\n\n // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of\n // the effects below, so memoize on its content to keep the reference stable \u2014\n // otherwise those effects (setIdentity / WS init) re-run on every render.\n const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});\n const stableWebSocketQueryParams = React.useMemo(\n () => webSocketQueryParams ?? {},\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [webSocketQueryParamsKey],\n );\n\n // WebSocket state\n const [isConnected, setIsConnected] = useState(false);\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());\n\n const subscribe = useCallback((callback: (message: WebsocketMessageType) => void) => {\n subscribersRef.current.add(callback);\n\n // Return unsubscribe function\n return () => {\n subscribersRef.current.delete(callback);\n };\n }, []);\n\n const initializeWebSocket = useCallback((customQueryParams?: Record<string, any>) => {\n if (!dashX) {\n console.error('DashX client not initialized');\n return;\n }\n\n // Reuse an existing manager \u2014 it owns its own throttled reconnect\n // lifecycle. Tearing it down and creating a new one on every call (e.g.\n // when a consumer re-invokes this as `isConnected` flips to false on each\n // close) resets the per-instance reconnect throttle and reconnects\n // immediately, defeating the backoff. Create one only if none exists.\n if (wsManagerRef.current) {\n return;\n }\n\n const queryParams = {\n publicKey: dashX.publicKey,\n ...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),\n // Provider-level defaults apply to every provider-owned socket \u2014 including\n // when the chat hook (or any consumer) opens the socket first by calling\n // `initializeWebSocket()` with no args. Explicit call-site params override.\n ...stableWebSocketQueryParams,\n ...customQueryParams,\n };\n\n const wsManager = dashX.createWebSocketConnection({\n queryParams,\n onError: (errorEvent: Event) => console.error({ errorEvent }),\n onClose: (closeEvent: CloseEvent) => {\n console.log({ closeEvent });\n setIsConnected(false);\n },\n onMessage: (message: WebsocketMessageType) => {\n // Notify all subscribers\n subscribersRef.current.forEach((callback) => {\n try {\n callback(message);\n } catch (error) {\n console.error('Error in WebSocket subscriber callback:', error);\n }\n });\n },\n onOpen: () => {\n console.log('WebSocket connected successfully');\n setIsConnected(true);\n },\n onReconnect: (attempt: number) => {\n console.log(`WebSocket reconnecting... attempt ${attempt}`);\n },\n onReconnectFailed: () => {\n console.error('WebSocket reconnection failed');\n setIsConnected(false);\n },\n });\n\n wsManagerRef.current = wsManager;\n wsManager.connect();\n }, [dashX, stableWebSocketQueryParams]);\n\n // Forward `identityUid` + `identityToken` into the dashX client so the same\n // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`\n // treats `undefined` as \"leave unchanged\", so setting only `identityToken`\n // won't clobber an existing account uid (and vice versa).\n const previousIdentityTokenRef = useRef(identityToken);\n useEffect(() => {\n if (!dashX || (identityUid === undefined && identityToken === undefined)) {\n return;\n }\n\n dashX.setIdentity(identityUid, identityToken);\n\n // This provider owns the socket (created via `createWebSocketConnection`,\n // not the client's internal manager that `setIdentity` reconnects), so on a\n // token change we recreate it here to put the new identity_token in the WS\n // URL. GraphQL picks up the new header on its own; tracked chat channels\n // re-subscribe on the new socket's `onOpen`.\n const tokenChanged = identityToken !== previousIdentityTokenRef.current;\n previousIdentityTokenRef.current = identityToken;\n if (tokenChanged && wsManagerRef.current) {\n wsManagerRef.current.disconnect();\n wsManagerRef.current = null;\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);\n\n // Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and\n // keeps one, which would leave the discarded client's listeners capturing every page view.\n const autocaptureKey = JSON.stringify(autocapture ?? false);\n useEffect(() => {\n if (!dashX || !autocapture) {\n return;\n }\n\n dashX.startAutocapture(autocapture === true ? {} : autocapture);\n return () => dashX.stopAutocapture();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ dashX, autocaptureKey ]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);\n\n return (\n <DashXContext.Provider value={dashX}>\n <WebSocketContext.Provider\n value={{\n isConnected,\n subscribe,\n wsManagerRef,\n initializeWebSocket\n }}\n >\n {children}\n </WebSocketContext.Provider>\n </DashXContext.Provider>\n );\n}\n\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (!context) {\n throw new Error('useWebSocket must be used within a DashXProvider');\n }\n return context;\n}\n\nexport default DashXProvider;\nexport { DashXContext };\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["jsx", "DashX", "React", "createContext", "useContext", "useEffect", "useRef", "useState", "useCallback", "DashXContext", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "identityUid", "identityToken", "autocapture", "maskPersonalDataProperties", "customPersonalDataProperties", "beforeSend", "beforeSendRef", "stableBeforeSend", "event", "result", "fn", "customPersonalDataPropertiesKey", "dashX", "client", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "
|
|
4
|
+
"sourcesContent": ["import DashX from '@dashx/browser';\nimport React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';\nimport type { BeforeSend, CapturedEvent, Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';\n\nconst DashXContext = createContext<Client | null>(null);\n\ntype WebSocketContextType = {\n isConnected: boolean;\n subscribe: (callback: (message: WebsocketMessageType) => void) => () => void;\n wsManagerRef: React.RefObject<WebSocketManager>;\n initializeWebSocket: (queryParams?: Record<string, any>) => void;\n};\n\nconst WebSocketContext = createContext<WebSocketContextType | null>(null);\n\ntype DashXProviderProps = ClientParams & {\n initializeWebSocketOnLoad?: boolean,\n webSocketQueryParams?: Record<string, any>,\n /**\n * The visitor's account uid, addressed on both transports (GraphQL + WS).\n * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to\n * leave it unchanged. Pair with `identityToken` for the same identity.\n */\n identityUid?: string | null,\n /**\n * Identity token (minted with your DashX server SDK's `generateIdentityToken`,\n * or from an exchange endpoint you control). When set, the SDK uses it for both\n * GraphQL (`X-Identity-Token` header) and the WebSocket handshake \u2014 the server\n * identifies the visitor from it, which is the ownership key for InApp Chat.\n * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.\n */\n identityToken?: string | null,\n /**\n * Fetches an identity token from your backend, e.g. a member token that keeps a workspace member\n * online. The client calls it before the socket connects, before each token expires and once after\n * the server refuses one, and reconnects the socket each time. Read through a ref, so an inline\n * function does not recreate the client.\n */\n identityTokenProvider?: () => Promise<string>,\n}\n\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n identityUid,\n identityToken,\n autocapture,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend,\n identityTokenProvider,\n}: React.PropsWithChildren<DashXProviderProps>) {\n // Read through a ref so an inline `beforeSend` takes effect without recreating the client on\n // every render.\n const beforeSendRef = useRef(beforeSend);\n beforeSendRef.current = beforeSend;\n const stableBeforeSend = useCallback<BeforeSend>((event) => {\n let result: CapturedEvent | null = event;\n for (const fn of [ beforeSendRef.current ?? [] ].flat()) {\n if (!result) break;\n result = fn(result);\n }\n return result;\n }, []);\n\n const identityTokenProviderRef = useRef(identityTokenProvider);\n identityTokenProviderRef.current = identityTokenProvider;\n const hasIdentityTokenProvider = Boolean(identityTokenProvider);\n const stableIdentityTokenProvider = useCallback(() => {\n const provider = identityTokenProviderRef.current;\n return provider ? provider() : Promise.reject(new Error('identityTokenProvider was removed'));\n }, []);\n\n const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);\n\n const dashX = React.useMemo(\n () => {\n const client = DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataProperties,\n beforeSend: stableBeforeSend,\n identityTokenProvider: hasIdentityTokenProvider ? stableIdentityTokenProvider : undefined,\n });\n // Apply identity synchronously at creation so a child that starts work in\n // its own mount effect (child effects run before this provider's effects)\n // sees the token already set. Later prop changes go through the effect\n // below; identity is intentionally not a useMemo dep (we don't recreate\n // the client when it changes).\n if (identityUid !== undefined || identityToken !== undefined) {\n client.setIdentity(identityUid, identityToken);\n }\n return client;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n maskPersonalDataProperties,\n customPersonalDataPropertiesKey,\n hasIdentityTokenProvider,\n ],\n );\n\n // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of\n // the effects below, so memoize on its content to keep the reference stable \u2014\n // otherwise those effects (setIdentity / WS init) re-run on every render.\n const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});\n const stableWebSocketQueryParams = React.useMemo(\n () => webSocketQueryParams ?? {},\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [webSocketQueryParamsKey],\n );\n\n // WebSocket state\n const [isConnected, setIsConnected] = useState(false);\n // The client replaces its manager on every reconnect for a new identity token, so read it fresh.\n const wsManagerRef = useRef<WebSocketManager | null>(null);\n const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());\n\n const subscribe = useCallback((callback: (message: WebsocketMessageType) => void) => {\n subscribersRef.current.add(callback);\n\n // Return unsubscribe function\n return () => {\n subscribersRef.current.delete(callback);\n };\n }, []);\n\n const initializeWebSocket = useCallback((customQueryParams?: Record<string, any>) => {\n if (!dashX) {\n console.error('DashX client not initialized');\n return;\n }\n\n // Reuse the client's socket while it is connected or retrying - it owns its own throttled\n // reconnect lifecycle, and reconnects itself for a new identity token. Starting over then (e.g.\n // when a consumer re-invokes this as `isConnected` flips to false on each close) would reset that\n // throttle. After a terminal close the client starts over with a fresh token.\n if (dashX.isWebSocketActive) {\n return;\n }\n\n // The client adds `publicKey` and `targetEnvironment` itself. Provider-level params apply to\n // every provider-owned socket, including when a hook opens it first with no args.\n const queryParams = {\n ...stableWebSocketQueryParams,\n ...customQueryParams,\n };\n\n const syncManager = () => {\n wsManagerRef.current = dashX.webSocketManager;\n };\n\n dashX.connectWebSocket({\n queryParams,\n onError: (errorEvent: Event) => console.error({ errorEvent }),\n onClose: (closeEvent: CloseEvent) => {\n console.log({ closeEvent });\n syncManager();\n setIsConnected(false);\n },\n onMessage: (message: WebsocketMessageType) => {\n subscribersRef.current.forEach((callback) => {\n try {\n callback(message);\n } catch (error) {\n console.error('Error in WebSocket subscriber callback:', error);\n }\n });\n },\n onOpen: () => {\n console.log('WebSocket connected successfully');\n syncManager();\n setIsConnected(true);\n },\n onReconnect: (attempt: number) => {\n console.log(`WebSocket reconnecting... attempt ${attempt}`);\n },\n onReconnectFailed: () => {\n console.error('WebSocket reconnection failed');\n setIsConnected(false);\n },\n });\n syncManager();\n }, [dashX, stableWebSocketQueryParams]);\n\n // Forward `identityUid` + `identityToken` into the dashX client so the same\n // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`\n // treats `undefined` as \"leave unchanged\", so setting only `identityToken`\n // won't clobber an existing account uid (and vice versa). A new token\n // reconnects the client's socket with it.\n useEffect(() => {\n if (!dashX || (identityUid === undefined && identityToken === undefined)) {\n return;\n }\n\n dashX.setIdentity(identityUid, identityToken);\n }, [ dashX, identityUid, identityToken ]);\n\n // A replaced client (new keys or environment) must not leave its socket running.\n useEffect(() => () => {\n dashX?.disconnectWebSocket();\n wsManagerRef.current = null;\n setIsConnected(false);\n }, [ dashX ]);\n\n // Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and\n // keeps one, which would leave the discarded client's listeners capturing every page view.\n const autocaptureKey = JSON.stringify(autocapture ?? false);\n useEffect(() => {\n if (!dashX || !autocapture) {\n return;\n }\n\n dashX.startAutocapture(autocapture === true ? {} : autocapture);\n return () => dashX.stopAutocapture();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ dashX, autocaptureKey ]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(stableWebSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);\n\n return (\n <DashXContext.Provider value={dashX}>\n <WebSocketContext.Provider\n value={{\n isConnected,\n subscribe,\n wsManagerRef,\n initializeWebSocket\n }}\n >\n {children}\n </WebSocketContext.Provider>\n </DashXContext.Provider>\n );\n}\n\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (!context) {\n throw new Error('useWebSocket must be used within a DashXProvider');\n }\n return context;\n}\n\nexport default DashXProvider;\nexport { DashXContext };\n"],
|
|
5
|
+
"mappings": "AAoPM,cAAAA,MAAA,oBApPN,OAAOC,MAAW,iBAClB,OAAOC,GAAS,iBAAAC,EAAe,cAAAC,EAAY,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,EAAU,eAAAC,MAAmB,QAG3F,MAAMC,EAAeN,EAA6B,IAAI,EAShDO,EAAmBP,EAA2C,IAAI,EA4BxE,SAASQ,EAAc,CACrB,SAAAC,EACA,UAAAC,EACA,QAAAC,EACA,gBAAAC,EACA,kBAAAC,EACA,cAAAC,EACA,cAAAC,EACA,0BAAAC,EAA4B,GAC5B,qBAAAC,EAAuB,CAAC,EACxB,YAAAC,EACA,cAAAC,EACA,YAAAC,EACA,2BAAAC,EACA,6BAAAC,EACA,WAAAC,EACA,sBAAAC,CACF,EAAgD,CAG9C,MAAMC,EAAgBtB,EAAOoB,CAAU,EACvCE,EAAc,QAAUF,EACxB,MAAMG,EAAmBrB,EAAyBsB,GAAU,CAC1D,IAAIC,EAA+BD,EACnC,UAAWE,IAAM,CAAEJ,EAAc,SAAW,CAAC,CAAE,EAAE,KAAK,EAAG,CACvD,GAAI,CAACG,EAAQ,MACbA,EAASC,EAAGD,CAAM,CACpB,CACA,OAAOA,CACT,EAAG,CAAC,CAAC,EA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CAElD,EAAG,CAAEtB,EAA2B6B,EAAqBP,CAA2B,CAAC,EAG/EzC,EAACS,EAAa,SAAb,CAAsB,MAAO6B,EAC5B,SAAAtC,EAACU,EAAiB,SAAjB,CACC,MAAO,CACL,YAAAgC,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAApC,EACH,EACF,CAEJ,CAEO,SAAS8C,GAAe,CAC7B,MAAMC,EAAUvD,EAAWM,CAAgB,EAC3C,GAAI,CAACiD,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOC,EAAQjD",
|
|
6
|
+
"names": ["jsx", "DashX", "React", "createContext", "useContext", "useEffect", "useRef", "useState", "useCallback", "DashXContext", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "identityUid", "identityToken", "autocapture", "maskPersonalDataProperties", "customPersonalDataProperties", "beforeSend", "identityTokenProvider", "beforeSendRef", "stableBeforeSend", "event", "result", "fn", "identityTokenProviderRef", "hasIdentityTokenProvider", "stableIdentityTokenProvider", "provider", "customPersonalDataPropertiesKey", "dashX", "client", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "syncManager", "errorEvent", "closeEvent", "message", "error", "attempt", "autocaptureKey", "useWebSocket", "context", "DashXProvider_default"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashx/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "UNLICENSED",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"clean": "rm -rf .turbo node_modules dist tokens layout *.css"
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@dashx/browser": "^0.
|
|
78
|
+
"@dashx/browser": "^0.15.0",
|
|
79
79
|
"@radix-ui/colors": "^3.0.0",
|
|
80
80
|
"@radix-ui/primitive": "^1.1.3",
|
|
81
81
|
"@radix-ui/react-accessible-icon": "^1.1.8",
|
|
@@ -30,6 +30,13 @@ type DashXProviderProps = ClientParams & {
|
|
|
30
30
|
* Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
|
|
31
31
|
*/
|
|
32
32
|
identityToken?: string | null,
|
|
33
|
+
/**
|
|
34
|
+
* Fetches an identity token from your backend, e.g. a member token that keeps a workspace member
|
|
35
|
+
* online. The client calls it before the socket connects, before each token expires and once after
|
|
36
|
+
* the server refuses one, and reconnects the socket each time. Read through a ref, so an inline
|
|
37
|
+
* function does not recreate the client.
|
|
38
|
+
*/
|
|
39
|
+
identityTokenProvider?: () => Promise<string>,
|
|
33
40
|
}
|
|
34
41
|
|
|
35
42
|
function DashXProvider({
|
|
@@ -48,6 +55,7 @@ function DashXProvider({
|
|
|
48
55
|
maskPersonalDataProperties,
|
|
49
56
|
customPersonalDataProperties,
|
|
50
57
|
beforeSend,
|
|
58
|
+
identityTokenProvider,
|
|
51
59
|
}: React.PropsWithChildren<DashXProviderProps>) {
|
|
52
60
|
// Read through a ref so an inline `beforeSend` takes effect without recreating the client on
|
|
53
61
|
// every render.
|
|
@@ -62,6 +70,14 @@ function DashXProvider({
|
|
|
62
70
|
return result;
|
|
63
71
|
}, []);
|
|
64
72
|
|
|
73
|
+
const identityTokenProviderRef = useRef(identityTokenProvider);
|
|
74
|
+
identityTokenProviderRef.current = identityTokenProvider;
|
|
75
|
+
const hasIdentityTokenProvider = Boolean(identityTokenProvider);
|
|
76
|
+
const stableIdentityTokenProvider = useCallback(() => {
|
|
77
|
+
const provider = identityTokenProviderRef.current;
|
|
78
|
+
return provider ? provider() : Promise.reject(new Error('identityTokenProvider was removed'));
|
|
79
|
+
}, []);
|
|
80
|
+
|
|
65
81
|
const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);
|
|
66
82
|
|
|
67
83
|
const dashX = React.useMemo(
|
|
@@ -76,6 +92,7 @@ function DashXProvider({
|
|
|
76
92
|
maskPersonalDataProperties,
|
|
77
93
|
customPersonalDataProperties,
|
|
78
94
|
beforeSend: stableBeforeSend,
|
|
95
|
+
identityTokenProvider: hasIdentityTokenProvider ? stableIdentityTokenProvider : undefined,
|
|
79
96
|
});
|
|
80
97
|
// Apply identity synchronously at creation so a child that starts work in
|
|
81
98
|
// its own mount effect (child effects run before this provider's effects)
|
|
@@ -97,6 +114,7 @@ function DashXProvider({
|
|
|
97
114
|
targetVersion,
|
|
98
115
|
maskPersonalDataProperties,
|
|
99
116
|
customPersonalDataPropertiesKey,
|
|
117
|
+
hasIdentityTokenProvider,
|
|
100
118
|
],
|
|
101
119
|
);
|
|
102
120
|
|
|
@@ -112,6 +130,7 @@ function DashXProvider({
|
|
|
112
130
|
|
|
113
131
|
// WebSocket state
|
|
114
132
|
const [isConnected, setIsConnected] = useState(false);
|
|
133
|
+
// The client replaces its manager on every reconnect for a new identity token, so read it fresh.
|
|
115
134
|
const wsManagerRef = useRef<WebSocketManager | null>(null);
|
|
116
135
|
const subscribersRef = useRef<Set<(message: WebsocketMessageType) => void>>(new Set());
|
|
117
136
|
|
|
@@ -130,34 +149,34 @@ function DashXProvider({
|
|
|
130
149
|
return;
|
|
131
150
|
}
|
|
132
151
|
|
|
133
|
-
// Reuse
|
|
134
|
-
// lifecycle
|
|
135
|
-
// when a consumer re-invokes this as `isConnected` flips to false on each
|
|
136
|
-
// close
|
|
137
|
-
|
|
138
|
-
if (wsManagerRef.current) {
|
|
152
|
+
// Reuse the client's socket while it is connected or retrying - it owns its own throttled
|
|
153
|
+
// reconnect lifecycle, and reconnects itself for a new identity token. Starting over then (e.g.
|
|
154
|
+
// when a consumer re-invokes this as `isConnected` flips to false on each close) would reset that
|
|
155
|
+
// throttle. After a terminal close the client starts over with a fresh token.
|
|
156
|
+
if (dashX.isWebSocketActive) {
|
|
139
157
|
return;
|
|
140
158
|
}
|
|
141
159
|
|
|
160
|
+
// The client adds `publicKey` and `targetEnvironment` itself. Provider-level params apply to
|
|
161
|
+
// every provider-owned socket, including when a hook opens it first with no args.
|
|
142
162
|
const queryParams = {
|
|
143
|
-
publicKey: dashX.publicKey,
|
|
144
|
-
...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),
|
|
145
|
-
// Provider-level defaults apply to every provider-owned socket — including
|
|
146
|
-
// when the chat hook (or any consumer) opens the socket first by calling
|
|
147
|
-
// `initializeWebSocket()` with no args. Explicit call-site params override.
|
|
148
163
|
...stableWebSocketQueryParams,
|
|
149
164
|
...customQueryParams,
|
|
150
165
|
};
|
|
151
166
|
|
|
152
|
-
const
|
|
167
|
+
const syncManager = () => {
|
|
168
|
+
wsManagerRef.current = dashX.webSocketManager;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
dashX.connectWebSocket({
|
|
153
172
|
queryParams,
|
|
154
173
|
onError: (errorEvent: Event) => console.error({ errorEvent }),
|
|
155
174
|
onClose: (closeEvent: CloseEvent) => {
|
|
156
175
|
console.log({ closeEvent });
|
|
176
|
+
syncManager();
|
|
157
177
|
setIsConnected(false);
|
|
158
178
|
},
|
|
159
179
|
onMessage: (message: WebsocketMessageType) => {
|
|
160
|
-
// Notify all subscribers
|
|
161
180
|
subscribersRef.current.forEach((callback) => {
|
|
162
181
|
try {
|
|
163
182
|
callback(message);
|
|
@@ -168,6 +187,7 @@ function DashXProvider({
|
|
|
168
187
|
},
|
|
169
188
|
onOpen: () => {
|
|
170
189
|
console.log('WebSocket connected successfully');
|
|
190
|
+
syncManager();
|
|
171
191
|
setIsConnected(true);
|
|
172
192
|
},
|
|
173
193
|
onReconnect: (attempt: number) => {
|
|
@@ -178,36 +198,28 @@ function DashXProvider({
|
|
|
178
198
|
setIsConnected(false);
|
|
179
199
|
},
|
|
180
200
|
});
|
|
181
|
-
|
|
182
|
-
wsManagerRef.current = wsManager;
|
|
183
|
-
wsManager.connect();
|
|
201
|
+
syncManager();
|
|
184
202
|
}, [dashX, stableWebSocketQueryParams]);
|
|
185
203
|
|
|
186
204
|
// Forward `identityUid` + `identityToken` into the dashX client so the same
|
|
187
205
|
// identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`
|
|
188
206
|
// treats `undefined` as "leave unchanged", so setting only `identityToken`
|
|
189
|
-
// won't clobber an existing account uid (and vice versa).
|
|
190
|
-
|
|
207
|
+
// won't clobber an existing account uid (and vice versa). A new token
|
|
208
|
+
// reconnects the client's socket with it.
|
|
191
209
|
useEffect(() => {
|
|
192
210
|
if (!dashX || (identityUid === undefined && identityToken === undefined)) {
|
|
193
211
|
return;
|
|
194
212
|
}
|
|
195
213
|
|
|
196
214
|
dashX.setIdentity(identityUid, identityToken);
|
|
215
|
+
}, [ dashX, identityUid, identityToken ]);
|
|
197
216
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
previousIdentityTokenRef.current = identityToken;
|
|
205
|
-
if (tokenChanged && wsManagerRef.current) {
|
|
206
|
-
wsManagerRef.current.disconnect();
|
|
207
|
-
wsManagerRef.current = null;
|
|
208
|
-
initializeWebSocket(stableWebSocketQueryParams);
|
|
209
|
-
}
|
|
210
|
-
}, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);
|
|
217
|
+
// A replaced client (new keys or environment) must not leave its socket running.
|
|
218
|
+
useEffect(() => () => {
|
|
219
|
+
dashX?.disconnectWebSocket();
|
|
220
|
+
wsManagerRef.current = null;
|
|
221
|
+
setIsConnected(false);
|
|
222
|
+
}, [ dashX ]);
|
|
211
223
|
|
|
212
224
|
// Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and
|
|
213
225
|
// keeps one, which would leave the discarded client's listeners capturing every page view.
|
package/CHANGELOG.md
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
All notable changes to `@dashx/react` are documented in this file. Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/).
|
|
4
|
-
|
|
5
|
-
## Unreleased
|
|
6
|
-
|
|
7
|
-
### [0.5.2] - 2026-10-07
|
|
8
|
-
|
|
9
|
-
- **Click and form submit autocapture.** `<DashXProvider autocapture={{ clicks: true }}>` records clicks on links, buttons and other interactive elements, and form submits, as `$autocapture`. `autocapture` alone still captures only page views and page leaves.
|
|
10
|
-
|
|
11
|
-
### Changed
|
|
12
|
-
|
|
13
|
-
- **Requires `@dashx/browser` 0.14.1** (for `clicks`). The range moves from `^0.14.0` to `^0.14.1`.
|
|
14
|
-
|
|
15
|
-
## [0.5.1] - 2026-10-07
|
|
16
|
-
|
|
17
|
-
### Changed
|
|
18
|
-
|
|
19
|
-
- **Requires `@dashx/browser` 0.14.** The range moves from `^0.13.1` to `^0.14.0`, so an app on `@dashx/browser` 0.14 (for `loadInAppChatAgent`) and `DashXProvider` share one client instead of the provider building its own from an older copy. No API changes here.
|
|
20
|
-
|
|
21
|
-
## [0.5.0] - 2026-10-06
|
|
22
|
-
|
|
23
|
-
### Added
|
|
24
|
-
|
|
25
|
-
- **`DashXProvider` accepts `autocapture`.** `<DashXProvider autocapture ...>` (or `autocapture={{ pageleave: false }}`) turns on `@dashx/browser`'s page view / page leave capture for the provider's client. It is started and stopped in an effect, so StrictMode's double render does not leave a second set of listeners behind. Route changes are picked up from the History API, so no router integration is needed.
|
|
26
|
-
|
|
27
|
-
- **`DashXProvider` accepts the privacy options** `maskPersonalDataProperties`, `customPersonalDataProperties` and `beforeSend`, and passes them to the client. Changing either masking option recreates the client. `beforeSend` is read on every event, so an inline function or a changed array takes effect without recreating it.
|
|
28
|
-
|
|
29
|
-
Requires `@dashx/browser` 0.13.1 or later (`startAutocapture` and the privacy options). 0.13.0 was published from a stale build without them.
|
|
30
|
-
|
|
31
|
-
- **README** documents `DashXProvider`, autocapture and the privacy props.
|
|
32
|
-
|
|
33
|
-
## [0.4.1] — 2026-08-05
|
|
34
|
-
|
|
35
|
-
### Changed
|
|
36
|
-
|
|
37
|
-
- **`useInAppChatNotifications`'s `onActivate` now receives the message that raised the notification.**
|
|
38
|
-
|
|
39
|
-
```diff
|
|
40
|
-
- onActivate?: () => void
|
|
41
|
-
+ onActivate?: (message: InAppChatMessageData) => void
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
Notifications are tagged per conversation, so a surface watching more than one thread could raise several at once — but the old zero-argument callback gave the handler no way to tell them apart, and it closed over whichever message arrived last. Clicking an older notification opened the wrong conversation.
|
|
45
|
-
|
|
46
|
-
**Backward compatible.** A `() => void` handler is still assignable and still behaves as before; take the parameter only if you need to route by `message.conversationId`. `InAppChatMessageData` is imported from `@dashx/browser`, same as the existing `renderBody` option on this hook.
|
|
47
|
-
|
|
48
|
-
## [0.4.0] — 2026-07-29
|
|
49
|
-
|
|
50
|
-
### Changed
|
|
51
|
-
|
|
52
|
-
- **BREAKING — In-App Chat no longer creates conversations; the caller supplies one.** `useInAppChat` and both widgets participate in an EXISTING conversation:
|
|
53
|
-
|
|
54
|
-
```diff
|
|
55
|
-
- useInAppChat({ identityId, idempotencyKey, initialMessage? })
|
|
56
|
-
+ useInAppChat({ identityId, conversationId })
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
`idempotencyKey` and `initialMessage` are gone, along with the create-on-mount behaviour. `<InAppChat>` and `<InAppChatButton>` take a required `conversationId` prop in place of `idempotencyKey`/`initialMessage`.
|
|
60
|
-
|
|
61
|
-
**Why.** Creating a chat is now server-only in DashX: identity-token callers are rejected outright, and the operation requires an `accountUid` naming the visitor — a claim no browser should be able to make. The conversation's `data`/`issueProperties` are metadata the agent console trusts, so they must be derived server-side. `@dashx/browser@0.10.0` therefore removes `startInAppChatConversation`, which is what this hook used.
|
|
62
|
-
|
|
63
|
-
**Migration.** Create the conversation in your backend (for JVM services, `dashx-java` ≥ 1.5.0 exposes `DashX.startInAppChatConversation(input)`), return the id to your client, and pass it in:
|
|
64
|
-
|
|
65
|
-
```tsx
|
|
66
|
-
const { conversationId } = useMyBackendChatSession(); // your endpoint
|
|
67
|
-
<InAppChatButton identityId="<chat-identity-id>" conversationId={conversationId} />
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
`conversationId` accepts `null` while you're still fetching it — the hook stays idle (no subscription, no history fetch) rather than guessing, so you can render the widget unconditionally.
|
|
71
|
-
- **`conversationId` is no longer returned from the hook.** The caller now owns it, so echoing it back was noise. Everything else in the response is unchanged: `messages`, `isLoading`, `isConnected`, `error`, `sendMessage`.
|
|
72
|
-
- `sendMessage(text)` returns `false` when there is no `conversationId` yet (or the hook is disabled) — same contract as before, so callers that keep the composer populated on `false` need no change.
|
|
73
|
-
- **`@dashx/browser` dependency raised to `^0.10.0`** (a regular `dependencies` entry, as before), which is the release that removes the creation method.
|
|
74
|
-
|
|
75
|
-
### Unchanged
|
|
76
|
-
|
|
77
|
-
- History fetch, realtime subscribe, optimistic send + reconciliation, reconnect refetch, and the notification hook all behave exactly as before. `<InAppChatButton>` still activates lazily on first open, so a launcher the visitor never opens does no chat work.
|
|
78
|
-
|
|
79
|
-
## [0.3.0] — 2026-06-18
|
|
80
|
-
|
|
81
|
-
### Added
|
|
82
|
-
|
|
83
|
-
- **In-App Chat hook + widgets.** A two-way in-app chat surface for visitors:
|
|
84
|
-
- `useInAppChat({ identityId, idempotencyKey, initialMessage? })` — manages the conversation lifecycle (start → subscribe → fetch history), exposes `messages`, `sendMessage(text)`, and loading/error state, and reconciles optimistic sends against the realtime echoes (deduping by message id and external uid). Refetches history on reconnect so a reply that landed during an outage isn't missed.
|
|
85
|
-
- `<InAppChat>` — the chat surface (header / message list / composer).
|
|
86
|
-
- `<InAppChatButton>` — a floating launcher that opens `<InAppChat>` in a popover. Props: `identityId`, `idempotencyKey`, `position` (`'bottom-right'` | `'bottom-left'` | `'top-right'` | `'top-left'`, default `'bottom-right'`), and `theme` (accent color, mode, roundness, …). The chat mounts lazily on open, so no conversation is created until the visitor opens the launcher.
|
|
87
|
-
|
|
88
|
-
In-App Chat requires a visitor identity token configured on `DashXProvider` (see below); render the chat only once that token is available.
|
|
89
|
-
|
|
90
|
-
Example — `<InAppChatButton>` with a `theme` override (all `ThemeProps` fields are optional and otherwise inherit from a surrounding `<Theme>` / `DashXProvider`):
|
|
91
|
-
|
|
92
|
-
```tsx
|
|
93
|
-
<InAppChatButton
|
|
94
|
-
identityId="<dashx-chat-identity-id>"
|
|
95
|
-
idempotencyKey="main"
|
|
96
|
-
position="bottom-right"
|
|
97
|
-
theme={{
|
|
98
|
-
accentBaseColor: '#6d28d9',
|
|
99
|
-
mode: 'dark',
|
|
100
|
-
roundness: 'large',
|
|
101
|
-
}}
|
|
102
|
-
/>
|
|
103
|
-
```
|
|
104
|
-
- **`DashXProvider` identity props.** New optional `identityUid?` and `identityToken?`. When set, the identity is applied on both transports — the Apollo `X-Identity-Token` header and the WebSocket handshake — which is the visitor auth In-App Chat needs. Pass `null` to clear on logout; omit (`undefined`) to leave unchanged. Pair `identityUid` with `identityToken` to address the same identity on both transports.
|
|
105
|
-
|
|
106
|
-
### Changed
|
|
107
|
-
|
|
108
|
-
- **Bumped `@dashx/browser` to `^0.8.0`** — for the In-App Chat client methods, the `subscribeToChannel` helper, and the `setIdentity` "undefined = leave unchanged" semantics this provider relies on.
|
|
109
|
-
- **Identity is now applied synchronously at client creation**, and the provider reconnects its own WebSocket when `identityToken` changes (so tracked chat channels re-subscribe under the new identity). Existing consumers that pass neither `identityUid` nor `identityToken` are unaffected — no extra `setIdentity` call, no reconnect, and the client is not recreated.
|