@dashx/react 0.4.4 → 0.5.1

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/README.md CHANGED
@@ -0,0 +1,65 @@
1
+ # @dashx/react
2
+
3
+ _DashX SDK for React, built on [`@dashx/browser`](https://www.npmjs.com/package/@dashx/browser)._
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @dashx/react @dashx/browser
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Wrap your app in `DashXProvider`, then reach the client with `useDashXProvider()`:
14
+
15
+ ```tsx
16
+ import { DashXProvider, useDashXProvider } from '@dashx/react'
17
+
18
+ function App() {
19
+ return (
20
+ <DashXProvider publicKey="YOUR_PUBLIC_KEY" targetEnvironment="production">
21
+ <Checkout />
22
+ </DashXProvider>
23
+ )
24
+ }
25
+
26
+ function Checkout() {
27
+ const dashx = useDashXProvider()
28
+
29
+ return <button onClick={() => dashx.track('Clicked Buy')}>Buy</button>
30
+ }
31
+ ```
32
+
33
+ `DashXProvider` accepts every `@dashx/browser` client option as a prop, plus `identityUid` / `identityToken` for the visitor's identity and `initializeWebSocketOnLoad` / `webSocketQueryParams` for the realtime connection.
34
+
35
+ ### Autocapture
36
+
37
+ Pass `autocapture` to record a `$pageview` on load and on every client-side navigation, and a `$pageleave` when the visitor moves on. Route changes are picked up from the browser's History API, so it works with any router and needs no router integration.
38
+
39
+ ```tsx
40
+ <DashXProvider publicKey="..." targetEnvironment="production" autocapture>
41
+ ```
42
+
43
+ Pass `autocapture={{ pageleave: false }}` (or `pageviews: false`) to turn either event off. Autocapture starts when the provider mounts and stops when it unmounts, so React StrictMode's double mount does not record a page twice.
44
+
45
+ Events carry the page, a session id and the landing page's UTM campaign. See the `@dashx/browser` README for what each event contains.
46
+
47
+ ### Privacy
48
+
49
+ ```tsx
50
+ <DashXProvider
51
+ publicKey="..."
52
+ targetEnvironment="production"
53
+ autocapture
54
+ // Replaces ad-click ids (gclid, fbclid, msclkid and similar) in captured URLs and referrers with `<masked>`.
55
+ maskPersonalDataProperties
56
+ // Masks these query parameters too; only applies with maskPersonalDataProperties.
57
+ customPersonalDataProperties={['token', 'email']}
58
+ // Runs on every event, autocaptured or from track(), before it is sent. Return null to drop it.
59
+ beforeSend={(event) => (event.event === '$pageleave' ? null : event)}
60
+ >
61
+ ```
62
+
63
+ - `beforeSend` also takes an array of functions, run in order. The first to return `null` drops the event, and a function that throws drops it too.
64
+ - `beforeSend` is read on every event, so an inline function or a changed array takes effect without re-creating the client.
65
+ - Changing `maskPersonalDataProperties` or `customPersonalDataProperties` re-creates the client.
@@ -25,7 +25,7 @@ type DashXProviderProps = ClientParams & {
25
25
  */
26
26
  identityToken?: string | null;
27
27
  };
28
- declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
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;
29
29
  export declare function useWebSocket(): WebSocketContextType;
30
30
  export default DashXProvider;
31
31
  export { DashXContext };
@@ -1,2 +1,2 @@
1
- "use strict";var O=Object.create;var g=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var J=(n,o)=>{for(var t in o)g(n,t,{get:o[t],enumerable:!0})},M=(n,o,t,b)=>{if(o&&typeof o=="object"||typeof o=="function")for(let c of Q(o))!F.call(n,c)&&c!==t&&g(n,c,{get:()=>o[c],enumerable:!(b=q(o,c))||b.enumerable});return n};var R=(n,o,t)=>(t=n!=null?O(T(n)):{},M(o||!n||!n.__esModule?g(t,"default",{value:n,enumerable:!0}):t,n)),N=n=>M(g({},"__esModule",{value:!0}),n);var B={};J(B,{DashXContext:()=>m,default:()=>A,useWebSocket:()=>j});module.exports=N(B);var S=require("react/jsx-runtime"),E=R(require("@dashx/browser")),e=R(require("react"));const m=(0,e.createContext)(null),x=(0,e.createContext)(null);function $({children:n,publicKey:o,baseUri:t,realtimeBaseUri:b,targetEnvironment:c,targetProduct:k,targetVersion:v,initializeWebSocketOnLoad:C=!1,webSocketQueryParams:h={},identityUid:f,identityToken:a}){const r=e.default.useMemo(()=>{const s=E.default.configure({publicKey:o,baseUri:t,realtimeBaseUri:b,targetEnvironment:c,targetProduct:k,targetVersion:v});return(f!==void 0||a!==void 0)&&s.setIdentity(f,a),s},[o,t,b,c,k,v]),w=JSON.stringify(h??{}),u=e.default.useMemo(()=>h??{},[w]),[X,p]=(0,e.useState)(!1),i=(0,e.useRef)(null),W=(0,e.useRef)(new Set),D=(0,e.useCallback)(s=>(W.current.add(s),()=>{W.current.delete(s)}),[]),d=(0,e.useCallback)(s=>{if(!r){console.error("DashX client not initialized");return}if(i.current)return;const I={publicKey:r.publicKey,...r.targetEnvironment&&{targetEnvironment:r.targetEnvironment},...u,...s},P=r.createWebSocketConnection({queryParams:I,onError:l=>console.error({errorEvent:l}),onClose:l=>{console.log({closeEvent:l}),p(!1)},onMessage:l=>{W.current.forEach(z=>{try{z(l)}catch(K){console.error("Error in WebSocket subscriber callback:",K)}})},onOpen:()=>{console.log("WebSocket connected successfully"),p(!0)},onReconnect:l=>{console.log(`WebSocket reconnecting... attempt ${l}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),p(!1)}});i.current=P,P.connect()},[r,u]),y=(0,e.useRef)(a);return(0,e.useEffect)(()=>{if(!r||f===void 0&&a===void 0)return;r.setIdentity(f,a);const s=a!==y.current;y.current=a,s&&i.current&&(i.current.disconnect(),i.current=null,d(u))},[r,f,a,d,u]),(0,e.useEffect)(()=>{C&&d(u)},[C,d,u]),(0,S.jsx)(m.Provider,{value:r,children:(0,S.jsx)(x.Provider,{value:{isConnected:X,subscribe:D,wsManagerRef:i,initializeWebSocket:d},children:n})})}function j(){const n=(0,e.useContext)(x);if(!n)throw new Error("useWebSocket must be used within a DashXProvider");return n}var A=$;
1
+ "use strict";var F=Object.create;var v=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var L=(n,t)=>{for(var o in t)v(n,o,{get:t[o],enumerable:!0})},D=(n,t,o,b)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of j(t))!H.call(n,c)&&c!==o&&v(n,c,{get:()=>t[c],enumerable:!(b=$(t,c))||b.enumerable});return n};var K=(n,t,o)=>(o=n!=null?F(G(n)):{},D(t||!n||!n.__esModule?v(o,"default",{value:n,enumerable:!0}):o,n)),Y=n=>D(v({},"__esModule",{value:!0}),n);var U={};L(U,{DashXContext:()=>k,default:()=>V,useWebSocket:()=>_});module.exports=Y(U);var m=require("react/jsx-runtime"),I=K(require("@dashx/browser")),e=K(require("react"));const k=(0,e.createContext)(null),O=(0,e.createContext)(null);function Z({children:n,publicKey:t,baseUri:o,realtimeBaseUri:b,targetEnvironment:c,targetProduct:y,targetVersion:h,initializeWebSocketOnLoad:R=!1,webSocketQueryParams:M={},identityUid:d,identityToken:a,autocapture:S,maskPersonalDataProperties:P,customPersonalDataProperties:x,beforeSend:E}){const w=(0,e.useRef)(E);w.current=E;const z=(0,e.useCallback)(s=>{let f=s;for(const p of[w.current??[]].flat()){if(!f)break;f=p(f)}return f},[]),B=JSON.stringify(x??[]),r=e.default.useMemo(()=>{const s=I.default.configure({publicKey:t,baseUri:o,realtimeBaseUri:b,targetEnvironment:c,targetProduct:y,targetVersion:h,maskPersonalDataProperties:P,customPersonalDataProperties:x,beforeSend:z});return(d!==void 0||a!==void 0)&&s.setIdentity(d,a),s},[t,o,b,c,y,h,P,B]),J=JSON.stringify(M??{}),l=e.default.useMemo(()=>M??{},[J]),[N,C]=(0,e.useState)(!1),i=(0,e.useRef)(null),W=(0,e.useRef)(new Set),q=(0,e.useCallback)(s=>(W.current.add(s),()=>{W.current.delete(s)}),[]),g=(0,e.useCallback)(s=>{if(!r){console.error("DashX client not initialized");return}if(i.current)return;const f={publicKey:r.publicKey,...r.targetEnvironment&&{targetEnvironment:r.targetEnvironment},...l,...s},p=r.createWebSocketConnection({queryParams:f,onError:u=>console.error({errorEvent:u}),onClose:u=>{console.log({closeEvent:u}),C(!1)},onMessage:u=>{W.current.forEach(Q=>{try{Q(u)}catch(T){console.error("Error in WebSocket subscriber callback:",T)}})},onOpen:()=>{console.log("WebSocket connected successfully"),C(!0)},onReconnect:u=>{console.log(`WebSocket reconnecting... attempt ${u}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),C(!1)}});i.current=p,p.connect()},[r,l]),X=(0,e.useRef)(a);(0,e.useEffect)(()=>{if(!r||d===void 0&&a===void 0)return;r.setIdentity(d,a);const s=a!==X.current;X.current=a,s&&i.current&&(i.current.disconnect(),i.current=null,g(l))},[r,d,a,g,l]);const A=JSON.stringify(S??!1);return(0,e.useEffect)(()=>{if(!(!r||!S))return r.startAutocapture(S===!0?{}:S),()=>r.stopAutocapture()},[r,A]),(0,e.useEffect)(()=>{R&&g(l)},[R,g,l]),(0,m.jsx)(k.Provider,{value:r,children:(0,m.jsx)(O.Provider,{value:{isConnected:N,subscribe:q,wsManagerRef:i,initializeWebSocket:g},children:n})})}function _(){const n=(0,e.useContext)(O);if(!n)throw new Error("useWebSocket must be used within a DashXProvider");return n}var V=Z;
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 { 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}: React.PropsWithChildren<DashXProviderProps>) {\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 });\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 [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],\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 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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CAAET,EAA2BgB,EAAqBP,CAA2B,CAAC,KAG/E,OAACzB,EAAa,SAAb,CAAsB,MAAOoB,EAC5B,mBAACb,EAAiB,SAAjB,CACC,MAAO,CACL,YAAAmB,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAAvB,EACH,EACF,CAEJ,CAEO,SAASP,GAAe,CAC7B,MAAMyC,KAAU,cAAWpC,CAAgB,EAC3C,GAAI,CAACoC,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAO1C,EAAQO",
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", "dashX", "React", "client", "DashX", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "previousIdentityTokenRef", "tokenChanged", "context"]
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,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,YAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GAwOM,IAAAM,EAAA,6BAxONC,EAAkB,6BAClBC,EAA2F,oBAG3F,MAAMN,KAAe,iBAA6B,IAAI,EAShDO,KAAmB,iBAA2C,IAAI,EAqBxE,SAASC,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,CACF,EAAgD,CAG9C,MAAMC,KAAgB,UAAOD,CAAU,EACvCC,EAAc,QAAUD,EACxB,MAAME,KAAmB,eAAyBC,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,EAECE,EAAkC,KAAK,UAAUP,GAAgC,CAAC,CAAC,EAEnFQ,EAAQ,EAAAC,QAAM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AAe,CAC7B,MAAMoD,KAAU,cAAW/C,CAAgB,EAC3C,GAAI,CAAC+C,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOrD,EAAQO",
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", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "previousIdentityTokenRef", "tokenChanged", "autocaptureKey", "context"]
7
7
  }
@@ -25,7 +25,7 @@ type DashXProviderProps = ClientParams & {
25
25
  */
26
26
  identityToken?: string | null;
27
27
  };
28
- declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
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;
29
29
  export declare function useWebSocket(): WebSocketContextType;
30
30
  export default DashXProvider;
31
31
  export { DashXContext };
@@ -1,2 +1,2 @@
1
- import{jsx as E}from"react/jsx-runtime";import O from"@dashx/browser";import h,{createContext as y,useContext as q,useEffect as P,useRef as b,useState as Q,useCallback as M}from"react";const R=y(null),x=y(null);function T({children:l,publicKey:f,baseUri:d,realtimeBaseUri:g,targetEnvironment:p,targetProduct:W,targetVersion:m,initializeWebSocketOnLoad:S=!1,webSocketQueryParams:k={},identityUid:c,identityToken:o}){const e=h.useMemo(()=>{const n=O.configure({publicKey:f,baseUri:d,realtimeBaseUri:g,targetEnvironment:p,targetProduct:W,targetVersion:m});return(c!==void 0||o!==void 0)&&n.setIdentity(c,o),n},[f,d,g,p,W,m]),w=JSON.stringify(k??{}),r=h.useMemo(()=>k??{},[w]),[X,u]=Q(!1),s=b(null),i=b(new Set),D=M(n=>(i.current.add(n),()=>{i.current.delete(n)}),[]),a=M(n=>{if(!e){console.error("DashX client not initialized");return}if(s.current)return;const I={publicKey:e.publicKey,...e.targetEnvironment&&{targetEnvironment:e.targetEnvironment},...r,...n},C=e.createWebSocketConnection({queryParams:I,onError:t=>console.error({errorEvent:t}),onClose:t=>{console.log({closeEvent:t}),u(!1)},onMessage:t=>{i.current.forEach(z=>{try{z(t)}catch(K){console.error("Error in WebSocket subscriber callback:",K)}})},onOpen:()=>{console.log("WebSocket connected successfully"),u(!0)},onReconnect:t=>{console.log(`WebSocket reconnecting... attempt ${t}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),u(!1)}});s.current=C,C.connect()},[e,r]),v=b(o);return P(()=>{if(!e||c===void 0&&o===void 0)return;e.setIdentity(c,o);const n=o!==v.current;v.current=o,n&&s.current&&(s.current.disconnect(),s.current=null,a(r))},[e,c,o,a,r]),P(()=>{S&&a(r)},[S,a,r]),E(R.Provider,{value:e,children:E(x.Provider,{value:{isConnected:X,subscribe:D,wsManagerRef:s,initializeWebSocket:a},children:l})})}function N(){const l=q(x);if(!l)throw new Error("useWebSocket must be used within a DashXProvider");return l}var $=T;export{R as DashXContext,$ as default,N as useWebSocket};
1
+ import{jsx as I}from"react/jsx-runtime";import F from"@dashx/browser";import X,{createContext as D,useContext as $,useEffect as S,useRef as b,useState as j,useCallback as p}from"react";const K=D(null),O=D(null);function G({children:l,publicKey:v,baseUri:C,realtimeBaseUri:W,targetEnvironment:k,targetProduct:m,targetVersion:y,initializeWebSocketOnLoad:h=!1,webSocketQueryParams:R={},identityUid:a,identityToken:t,autocapture:i,maskPersonalDataProperties:M,customPersonalDataProperties:P,beforeSend:x}){const E=b(x);E.current=x;const z=p(n=>{let c=n;for(const f of[E.current??[]].flat()){if(!c)break;c=f(c)}return c},[]),B=JSON.stringify(P??[]),e=X.useMemo(()=>{const n=F.configure({publicKey:v,baseUri:C,realtimeBaseUri:W,targetEnvironment:k,targetProduct:m,targetVersion:y,maskPersonalDataProperties:M,customPersonalDataProperties:P,beforeSend:z});return(a!==void 0||t!==void 0)&&n.setIdentity(a,t),n},[v,C,W,k,m,y,M,B]),J=JSON.stringify(R??{}),o=X.useMemo(()=>R??{},[J]),[N,d]=j(!1),s=b(null),g=b(new Set),q=p(n=>(g.current.add(n),()=>{g.current.delete(n)}),[]),u=p(n=>{if(!e){console.error("DashX client not initialized");return}if(s.current)return;const c={publicKey:e.publicKey,...e.targetEnvironment&&{targetEnvironment:e.targetEnvironment},...o,...n},f=e.createWebSocketConnection({queryParams:c,onError:r=>console.error({errorEvent:r}),onClose:r=>{console.log({closeEvent:r}),d(!1)},onMessage:r=>{g.current.forEach(Q=>{try{Q(r)}catch(T){console.error("Error in WebSocket subscriber callback:",T)}})},onOpen:()=>{console.log("WebSocket connected successfully"),d(!0)},onReconnect:r=>{console.log(`WebSocket reconnecting... attempt ${r}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),d(!1)}});s.current=f,f.connect()},[e,o]),w=b(t);S(()=>{if(!e||a===void 0&&t===void 0)return;e.setIdentity(a,t);const n=t!==w.current;w.current=t,n&&s.current&&(s.current.disconnect(),s.current=null,u(o))},[e,a,t,u,o]);const A=JSON.stringify(i??!1);return S(()=>{if(!(!e||!i))return e.startAutocapture(i===!0?{}:i),()=>e.stopAutocapture()},[e,A]),S(()=>{h&&u(o)},[h,u,o]),I(K.Provider,{value:e,children:I(O.Provider,{value:{isConnected:N,subscribe:q,wsManagerRef:s,initializeWebSocket:u},children:l})})}function Y(){const l=$(O);if(!l)throw new Error("useWebSocket must be used within a DashXProvider");return l}var Z=G;export{K as DashXContext,Z as default,Y 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 { 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}: React.PropsWithChildren<DashXProviderProps>) {\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 });\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 [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],\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 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": "AA4LM,cAAAA,MAAA,oBA5LN,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,EAqBxE,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,CACF,EAAgD,CAC9C,MAAMC,EAAQrB,EAAM,QAClB,IAAM,CACJ,MAAMsB,EAASvB,EAAM,UAAU,CAC7B,UAAWY,EACX,QAASC,EACT,gBAAiBC,EACjB,kBAAmBC,EACnB,cAAAC,EACA,cAAAC,CACF,CAAC,EAMD,OAAIG,IAAgB,QAAaC,IAAkB,SACjDE,EAAO,YAAYH,EAAaC,CAAa,EAExCE,CACT,EAEA,CAACX,EAAWC,EAASC,EAAiBC,EAAmBC,EAAeC,CAAa,CACvF,EAKMO,EAA0B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AACb,EAAOG,CAA0B,CAAC,EAMhCgB,EAA2BpC,EAAOgB,CAAa,EACrD,OAAAjB,EAAU,IAAM,CACd,GAAI,CAACkB,GAAUF,IAAgB,QAAaC,IAAkB,OAC5D,OAGFC,EAAM,YAAYF,EAAaC,CAAa,EAO5C,MAAMqB,EAAerB,IAAkBoB,EAAyB,QAChEA,EAAyB,QAAUpB,EAC/BqB,GAAgBd,EAAa,UAC/BA,EAAa,QAAQ,WAAW,EAChCA,EAAa,QAAU,KACvBI,EAAoBP,CAA0B,EAElD,EAAG,CAAEH,EAAOF,EAAaC,EAAeW,EAAqBP,CAA2B,CAAC,EAEzFrB,EAAU,IAAM,CACVc,GACFc,EAAoBP,CAA0B,CAElD,EAAG,CAAEP,EAA2Bc,EAAqBP,CAA2B,CAAC,EAG/E1B,EAACS,EAAa,SAAb,CAAsB,MAAOc,EAC5B,SAAAvB,EAACU,EAAiB,SAAjB,CACC,MAAO,CACL,YAAAiB,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAArB,EACH,EACF,CAEJ,CAEO,SAASgC,GAAe,CAC7B,MAAMC,EAAUzC,EAAWM,CAAgB,EAC3C,GAAI,CAACmC,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOC,EAAQnC",
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", "dashX", "client", "webSocketQueryParamsKey", "stableWebSocketQueryParams", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "previousIdentityTokenRef", "tokenChanged", "useWebSocket", "context", "DashXProvider_default"]
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": "AAwOM,cAAAA,MAAA,oBAxON,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,EAqBxE,SAASQ,EAAc,CACrB,SAAAC,EACA,UAAAC,EACA,QAAAC,EACA,gBAAAC,EACA,kBAAAC,EACA,cAAAC,EACA,cAAAC,EACA,0BAAAC,EAA4B,GAC5B,qBAAAC,EAAu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,OAAAlB,EAAU,IAAM,CACd,GAAI,GAAC4B,GAAS,CAACV,GAIf,OAAAU,EAAM,iBAAiBV,IAAgB,GAAO,CAAC,EAAIA,CAAW,EACvD,IAAMU,EAAM,gBAAgB,CAErC,EAAG,CAAEA,EAAOqB,CAAe,CAAC,EAE5BjD,EAAU,IAAM,CACVc,GACFwB,EAAoBP,CAA0B,CAElD,EAAG,CAAEjB,EAA2BwB,EAAqBP,CAA2B,CAAC,EAG/EpC,EAACS,EAAa,SAAb,CAAsB,MAAOwB,EAC5B,SAAAjC,EAACU,EAAiB,SAAjB,CACC,MAAO,CACL,YAAA2B,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAA/B,EACH,EACF,CAEJ,CAEO,SAAS2C,GAAe,CAC7B,MAAMC,EAAUpD,EAAWM,CAAgB,EAC3C,GAAI,CAAC8C,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOC,EAAQ9C",
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", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "previousIdentityTokenRef", "tokenChanged", "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.4.4",
3
+ "version": "0.5.1",
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.12.1",
78
+ "@dashx/browser": "^0.14.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",
@@ -1,6 +1,6 @@
1
1
  import DashX from '@dashx/browser';
2
2
  import React, { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';
3
- import type { Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';
3
+ import type { BeforeSend, CapturedEvent, Client, ClientParams, WebSocketManager, WebsocketMessageType } from '@dashx/browser';
4
4
 
5
5
  const DashXContext = createContext<Client | null>(null);
6
6
 
@@ -44,7 +44,26 @@ function DashXProvider({
44
44
  webSocketQueryParams = {},
45
45
  identityUid,
46
46
  identityToken,
47
+ autocapture,
48
+ maskPersonalDataProperties,
49
+ customPersonalDataProperties,
50
+ beforeSend,
47
51
  }: React.PropsWithChildren<DashXProviderProps>) {
52
+ // Read through a ref so an inline `beforeSend` takes effect without recreating the client on
53
+ // every render.
54
+ const beforeSendRef = useRef(beforeSend);
55
+ beforeSendRef.current = beforeSend;
56
+ const stableBeforeSend = useCallback<BeforeSend>((event) => {
57
+ let result: CapturedEvent | null = event;
58
+ for (const fn of [ beforeSendRef.current ?? [] ].flat()) {
59
+ if (!result) break;
60
+ result = fn(result);
61
+ }
62
+ return result;
63
+ }, []);
64
+
65
+ const customPersonalDataPropertiesKey = JSON.stringify(customPersonalDataProperties ?? []);
66
+
48
67
  const dashX = React.useMemo(
49
68
  () => {
50
69
  const client = DashX.configure({
@@ -54,6 +73,9 @@ function DashXProvider({
54
73
  targetEnvironment: targetEnvironment,
55
74
  targetProduct,
56
75
  targetVersion,
76
+ maskPersonalDataProperties,
77
+ customPersonalDataProperties,
78
+ beforeSend: stableBeforeSend,
57
79
  });
58
80
  // Apply identity synchronously at creation so a child that starts work in
59
81
  // its own mount effect (child effects run before this provider's effects)
@@ -66,7 +88,16 @@ function DashXProvider({
66
88
  return client;
67
89
  },
68
90
  // eslint-disable-next-line react-hooks/exhaustive-deps
69
- [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],
91
+ [
92
+ publicKey,
93
+ baseUri,
94
+ realtimeBaseUri,
95
+ targetEnvironment,
96
+ targetProduct,
97
+ targetVersion,
98
+ maskPersonalDataProperties,
99
+ customPersonalDataPropertiesKey,
100
+ ],
70
101
  );
71
102
 
72
103
  // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of
@@ -178,6 +209,19 @@ function DashXProvider({
178
209
  }
179
210
  }, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);
180
211
 
212
+ // Started here rather than passed to `configure`: StrictMode runs the client `useMemo` twice and
213
+ // keeps one, which would leave the discarded client's listeners capturing every page view.
214
+ const autocaptureKey = JSON.stringify(autocapture ?? false);
215
+ useEffect(() => {
216
+ if (!dashX || !autocapture) {
217
+ return;
218
+ }
219
+
220
+ dashX.startAutocapture(autocapture === true ? {} : autocapture);
221
+ return () => dashX.stopAutocapture();
222
+ // eslint-disable-next-line react-hooks/exhaustive-deps
223
+ }, [ dashX, autocaptureKey ]);
224
+
181
225
  useEffect(() => {
182
226
  if (initializeWebSocketOnLoad) {
183
227
  initializeWebSocket(stableWebSocketQueryParams);
package/styles.css CHANGED
@@ -239,6 +239,9 @@ button, input:where([type='button'], [type='reset'], [type='submit']), ::file-se
239
239
  .hidden {
240
240
  display: none;
241
241
  }
242
+ .inline {
243
+ display: inline;
244
+ }
242
245
  .inline-flex {
243
246
  display: inline-flex;
244
247
  }