@dashx/react 0.2.3 → 0.3.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/cjs/hooks/index.d.ts +3 -0
  3. package/dist/cjs/hooks/index.js +1 -1
  4. package/dist/cjs/hooks/index.js.map +3 -3
  5. package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +27 -0
  6. package/dist/cjs/hooks/use-in-app-chat-notifications.js +2 -0
  7. package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +7 -0
  8. package/dist/cjs/hooks/use-in-app-chat.d.ts +41 -0
  9. package/dist/cjs/hooks/use-in-app-chat.js +2 -0
  10. package/dist/cjs/hooks/use-in-app-chat.js.map +7 -0
  11. package/dist/cjs/providers/DashXProvider.d.ts +15 -1
  12. package/dist/cjs/providers/DashXProvider.js +1 -1
  13. package/dist/cjs/providers/DashXProvider.js.map +3 -3
  14. package/dist/cjs/widgets/InAppChat.d.ts +16 -0
  15. package/dist/cjs/widgets/InAppChat.js +2 -0
  16. package/dist/cjs/widgets/InAppChat.js.map +7 -0
  17. package/dist/cjs/widgets/InAppChatButton.d.ts +12 -0
  18. package/dist/cjs/widgets/InAppChatButton.js +2 -0
  19. package/dist/cjs/widgets/InAppChatButton.js.map +7 -0
  20. package/dist/cjs/widgets/index.d.ts +2 -0
  21. package/dist/cjs/widgets/index.js +1 -1
  22. package/dist/cjs/widgets/index.js.map +3 -3
  23. package/dist/esm/hooks/index.d.ts +3 -0
  24. package/dist/esm/hooks/index.js +1 -1
  25. package/dist/esm/hooks/index.js.map +2 -2
  26. package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +27 -0
  27. package/dist/esm/hooks/use-in-app-chat-notifications.js +2 -0
  28. package/dist/esm/hooks/use-in-app-chat-notifications.js.map +7 -0
  29. package/dist/esm/hooks/use-in-app-chat.d.ts +41 -0
  30. package/dist/esm/hooks/use-in-app-chat.js +2 -0
  31. package/dist/esm/hooks/use-in-app-chat.js.map +7 -0
  32. package/dist/esm/providers/DashXProvider.d.ts +15 -1
  33. package/dist/esm/providers/DashXProvider.js +1 -1
  34. package/dist/esm/providers/DashXProvider.js.map +3 -3
  35. package/dist/esm/widgets/InAppChat.d.ts +16 -0
  36. package/dist/esm/widgets/InAppChat.js +2 -0
  37. package/dist/esm/widgets/InAppChat.js.map +7 -0
  38. package/dist/esm/widgets/InAppChatButton.d.ts +12 -0
  39. package/dist/esm/widgets/InAppChatButton.js +2 -0
  40. package/dist/esm/widgets/InAppChatButton.js.map +7 -0
  41. package/dist/esm/widgets/index.d.ts +2 -0
  42. package/dist/esm/widgets/index.js +1 -1
  43. package/dist/esm/widgets/index.js.map +2 -2
  44. package/package.json +2 -2
  45. package/src/hooks/index.ts +3 -0
  46. package/src/hooks/use-in-app-chat-notifications.ts +117 -0
  47. package/src/hooks/use-in-app-chat.ts +281 -0
  48. package/src/providers/DashXProvider.tsx +74 -7
  49. package/src/widgets/InAppChat.tsx +193 -0
  50. package/src/widgets/InAppChatButton.tsx +103 -0
  51. package/src/widgets/index.ts +2 -0
  52. package/styles.css +6 -0
  53. package/dist/cjs/widgets/NotificationBell.d.ts +0 -2
  54. package/dist/cjs/widgets/NotificationBell.js +0 -2
  55. package/dist/cjs/widgets/NotificationBell.js.map +0 -7
  56. package/dist/esm/widgets/NotificationBell.d.ts +0 -2
  57. package/dist/esm/widgets/NotificationBell.js +0 -2
  58. package/dist/esm/widgets/NotificationBell.js.map +0 -7
@@ -0,0 +1,41 @@
1
+ import type { InAppChatMessageData } from '@dashx/browser';
2
+ type UseInAppChatHookProps = {
3
+ identityId: string;
4
+ idempotencyKey: string;
5
+ initialMessage?: string;
6
+ enabled?: boolean;
7
+ onInboundMessage?: (message: InAppChatMessageData) => void;
8
+ };
9
+ type InAppChatMessage = {
10
+ id: string;
11
+ externalUid: string | null;
12
+ renderedContent: any;
13
+ aiRole: string | null;
14
+ createdAt: string;
15
+ turnSeq?: number;
16
+ isPending?: boolean;
17
+ };
18
+ type UseInAppChatHookResponse = {
19
+ conversationId: string | null;
20
+ messages: InAppChatMessage[];
21
+ isLoading: boolean;
22
+ isConnected: boolean;
23
+ error: string | null;
24
+ sendMessage: (text: string) => boolean;
25
+ };
26
+ /**
27
+ * Two-way InApp Chat for a visitor.
28
+ *
29
+ * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
30
+ * `identityToken` (and matching `identityUid`). The chat mutations require
31
+ * identity-token auth — if the chat starts before an identity is resolved, they
32
+ * are rejected and the hook surfaces an auth error. It does NOT auto-retry when
33
+ * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
34
+ * visitor token), so only render the chat once `identityToken` is available —
35
+ * e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
36
+ * this by starting lazily when the visitor opens it, by which point the provider
37
+ * has applied the token.
38
+ */
39
+ declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
40
+ export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
41
+ export default useInAppChat;
@@ -0,0 +1,2 @@
1
+ import _ from"uuid-random";import{useCallback as k,useEffect as q,useRef as M,useState as I}from"react";import D from"./use-dashx-provider.js";import{useWebSocket as F}from"../providers/DashXProvider.js";const L="in_app_chat:conversation:",y=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),$=(e,p)=>{const r=new Map,u=t=>t.externalUid||t.id;return[...e,...p].forEach(t=>{const n=r.get(u(t));(!n||n.isPending)&&r.set(u(t),t)}),[...r.values()].sort((t,n)=>t.createdAt!==n.createdAt?t.createdAt<n.createdAt?-1:1:(t.turnSeq??0)-(n.turnSeq??0))},X=({identityId:e,idempotencyKey:p,initialMessage:r,enabled:u=!0,onInboundMessage:t})=>{const n=D(),{isConnected:m,initializeWebSocket:b}=F(),[x,v]=I(null),[H,R]=I([]),[w,A]=I(!0),[P,l]=I(null),o=M(0),f=M(null),U=M(t);U.current=t;const i=k(a=>{R(s=>$(s,a))},[]);q(()=>{const a=o.current+=1,s=()=>a!==o.current;if(v(null),R([]),l(null),f.current=null,!u)return A(!1),()=>{o.current+=1};A(!0),b();let d;return(async()=>{try{const g=await n.startInAppChatConversation({identityId:e,clientIdempotencyKey:p,...r?{content:{text:r},clientMessageId:`${p.slice(0,122)}-intro`}:{}});if(s())return;const c=g.id;v(c),f.current=c;const h=async()=>{const C=await n.fetchInAppChatMessages({conversationId:c});s()||i(C.map(y))},S=n.subscribeToChannel(`${L}${c}`,C=>{s()||(i([y(C)]),U.current?.(C))},{onReconnectAck:()=>{s()||(l(null),h().catch(()=>{}))}});d=S.unsubscribe;try{await S.ready}catch{s()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(s())return;await h()}catch{s()||l("Failed to start chat")}finally{s()||A(!1)}})(),()=>{o.current+=1,d?.()}},[n,e,p,r,u,b,i]);const E=k(a=>{const s=f.current;if(!a.trim()||!s)return!1;const d=o.current,g=_(),c={id:g,externalUid:`in_app_chat:${g}`,renderedContent:{text:a},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return i([c]),(async()=>{try{const h=await n.sendInAppChatMessage({conversationId:s,identityId:e,content:{text:a},clientMessageId:g});if(d!==o.current)return;i([y(h)])}catch{d===o.current&&l("Failed to send message")}})(),!0},[n,e,i]);return{conversationId:x,messages:H,isLoading:w,isConnected:m,error:P,sendMessage:E}};var W=X;export{W as default};
2
+ //# sourceMappingURL=use-in-app-chat.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/hooks/use-in-app-chat.ts"],
4
+ "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n // When false, the hook is idle: no conversation is started, subscribed, or\n // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor\n // first opens the launcher, while keeping the hook mounted afterwards so its\n // subscription (and thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setError(null);\n conversationIdRef.current = null;\n\n // Idle until enabled (e.g. before the launcher's first open): don't create a\n // conversation, subscribe, or fetch.\n if (!enabled) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
+ "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCAiD7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAAC,GAAGI,EAAM,OAAO,CAAC,EAAE,KAAK,CAACG,EAAGC,IAC9BD,EAAE,YAAcC,EAAE,UAAkBD,EAAE,UAAYC,EAAE,UAAY,GAAK,GACjED,EAAE,SAAW,IAAMC,EAAE,SAAW,EACzC,CACH,EAeMC,EAAe,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,QAAAC,EAAU,GAAM,iBAAAC,CAAiB,IAAuD,CAC1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+B,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIX,IAAeL,EAAc,QAAS,OAE1CG,EAAe,CAAC9B,EAAY6C,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFb,IAAeL,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACV,EAAOL,EAAYmB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAX,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAgB,CAAY,CAChF,EAIA,IAAOK,EAAQpC",
6
+ "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
7
+ }
@@ -10,8 +10,22 @@ type WebSocketContextType = {
10
10
  type DashXProviderProps = ClientParams & {
11
11
  initializeWebSocketOnLoad?: boolean;
12
12
  webSocketQueryParams?: Record<string, any>;
13
+ /**
14
+ * The visitor's account uid, addressed on both transports (GraphQL + WS).
15
+ * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to
16
+ * leave it unchanged. Pair with `identityToken` for the same identity.
17
+ */
18
+ identityUid?: string | null;
19
+ /**
20
+ * Identity token (minted with your DashX server SDK's `generateIdentityToken`,
21
+ * or from an exchange endpoint you control). When set, the SDK uses it for both
22
+ * GraphQL (`X-Identity-Token` header) and the WebSocket handshake — the server
23
+ * identifies the visitor from it, which is the ownership key for InApp Chat.
24
+ * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
25
+ */
26
+ identityToken?: string | null;
13
27
  };
14
- declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
28
+ declare function DashXProvider({ children, publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion, initializeWebSocketOnLoad, webSocketQueryParams, identityUid, identityToken, }: React.PropsWithChildren<DashXProviderProps>): import("react/jsx-runtime").JSX.Element;
15
29
  export declare function useWebSocket(): WebSocketContextType;
16
30
  export default DashXProvider;
17
31
  export { DashXContext };
@@ -1,2 +1,2 @@
1
- import{jsx as S}from"react/jsx-runtime";import E from"@dashx/browser";import X,{createContext as W,useContext as w,useEffect as D,useRef as v,useState as T,useCallback as C}from"react";const m=W(null),y=W(null);function z({children:t,publicKey:a,baseUri:i,realtimeBaseUri:l,targetEnvironment:u,targetProduct:b,targetVersion:d,initializeWebSocketOnLoad:f=!1,webSocketQueryParams:g={}}){const e=X.useMemo(()=>E.configure({publicKey:a,baseUri:i,realtimeBaseUri:l,targetEnvironment:u,targetProduct:b,targetVersion:d}),[a,i,l,u,b,d]),[h,r]=T(!1),s=v(null),c=v(new Set),P=C(n=>(c.current.add(n),()=>{c.current.delete(n)}),[]),k=C(n=>{if(!e){console.error("DashX client not initialized");return}if(s.current)return;const M={publicKey:e.publicKey,...e.targetEnvironment&&{targetEnvironment:e.targetEnvironment},...n},p=e.createWebSocketConnection({queryParams:M,onError:o=>console.error({errorEvent:o}),onClose:o=>{console.log({closeEvent:o}),r(!1)},onMessage:o=>{c.current.forEach(R=>{try{R(o)}catch(x){console.error("Error in WebSocket subscriber callback:",x)}})},onOpen:()=>{console.log("WebSocket connected successfully"),r(!0)},onReconnect:o=>{console.log(`WebSocket reconnecting... attempt ${o}`)},onReconnectFailed:()=>{console.error("WebSocket reconnection failed"),r(!1)}});s.current=p,p.connect()},[e]);return D(()=>{f&&k(g)},[f,g]),S(m.Provider,{value:e,children:S(y.Provider,{value:{isConnected:h,subscribe:P,wsManagerRef:s,initializeWebSocket:k},children:t})})}function O(){const t=w(y);if(!t)throw new Error("useWebSocket must be used within a DashXProvider");return t}var F=z;export{m as DashXContext,F as default,O as useWebSocket};
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};
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\nfunction DashXProvider({\n children,\n publicKey,\n baseUri,\n realtimeBaseUri,\n targetEnvironment,\n targetProduct,\n targetVersion,\n initializeWebSocketOnLoad = false,\n webSocketQueryParams = {},\n}: React.PropsWithChildren<DashXProviderProps>) {\n const dashX = React.useMemo(\n () =>\n DashX.configure({\n publicKey: publicKey,\n baseUri: baseUri,\n realtimeBaseUri: realtimeBaseUri,\n targetEnvironment: targetEnvironment,\n targetProduct,\n targetVersion,\n }),\n [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],\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 ...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]);\n\n useEffect(() => {\n if (initializeWebSocketOnLoad) {\n initializeWebSocket(webSocketQueryParams);\n }\n }, [ initializeWebSocketOnLoad, webSocketQueryParams ]);\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": "AAyHM,cAAAA,MAAA,oBAzHN,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,EAOxE,SAASQ,EAAc,CACrB,SAAAC,EACA,UAAAC,EACA,QAAAC,EACA,gBAAAC,EACA,kBAAAC,EACA,cAAAC,EACA,cAAAC,EACA,0BAAAC,EAA4B,GAC5B,qBAAAC,EAAuB,CAAC,CAC1B,EAAgD,CAC9C,MAAMC,EAAQnB,EAAM,QAClB,IACED,EAAM,UAAU,CACd,UAAWY,EACX,QAASC,EACT,gBAAiBC,EACjB,kBAAmBC,EACnB,cAAAC,EACA,cAAAC,CACF,CAAC,EACH,CAACL,EAAWC,EAASC,EAAiBC,EAAmBC,EAAeC,CAAa,CACvF,EAGM,CAACI,EAAaC,CAAc,EAAIhB,EAAS,EAAK,EAC9CiB,EAAelB,EAAgC,IAAI,EACnDmB,EAAiBnB,EAAqD,IAAI,GAAK,EAE/EoB,EAAYlB,EAAamB,IAC7BF,EAAe,QAAQ,IAAIE,CAAQ,EAG5B,IAAM,CACXF,EAAe,QAAQ,OAAOE,CAAQ,CACxC,GACC,CAAC,CAAC,EAECC,EAAsBpB,EAAaqB,GAA4C,CACnF,GAAI,CAACR,EAAO,CACV,QAAQ,MAAM,8BAA8B,EAC5C,MACF,CAOA,GAAIG,EAAa,QACf,OAGF,MAAMM,EAAc,CAClB,UAAWT,EAAM,UACjB,GAAIA,EAAM,mBAAqB,CAAE,kBAAmBA,EAAM,iBAAkB,EAC5E,GAAGQ,CACL,EAEME,EAAYV,EAAM,0BAA0B,CAChD,YAAAS,EACA,QAAUE,GAAsB,QAAQ,MAAM,CAAE,WAAAA,CAAW,CAAC,EAC5D,QAAUC,GAA2B,CACnC,QAAQ,IAAI,CAAE,WAAAA,CAAW,CAAC,EAC1BV,EAAe,EAAK,CACtB,EACA,UAAYW,GAAkC,CAE5CT,EAAe,QAAQ,QAASE,GAAa,CAC3C,GAAI,CACFA,EAASO,CAAO,CAClB,OAASC,EAAO,CACd,QAAQ,MAAM,0CAA2CA,CAAK,CAChE,CACF,CAAC,CACH,EACA,OAAQ,IAAM,CACZ,QAAQ,IAAI,kCAAkC,EAC9CZ,EAAe,EAAI,CACrB,EACA,YAAca,GAAoB,CAChC,QAAQ,IAAI,qCAAqCA,CAAO,EAAE,CAC5D,EACA,kBAAmB,IAAM,CACvB,QAAQ,MAAM,+BAA+B,EAC7Cb,EAAe,EAAK,CACtB,CACF,CAAC,EAEDC,EAAa,QAAUO,EACvBA,EAAU,QAAQ,CACpB,EAAG,CAACV,CAAK,CAAC,EAEV,OAAAhB,EAAU,IAAM,CACVc,GACFS,EAAoBR,CAAoB,CAE5C,EAAG,CAAED,EAA2BC,CAAqB,CAAC,EAGpDpB,EAACS,EAAa,SAAb,CAAsB,MAAOY,EAC5B,SAAArB,EAACU,EAAiB,SAAjB,CACC,MAAO,CACL,YAAAY,EACA,UAAAI,EACA,aAAAF,EACA,oBAAAI,CACF,EAEC,SAAAhB,EACH,EACF,CAEJ,CAEO,SAASyB,GAAe,CAC7B,MAAMC,EAAUlC,EAAWM,CAAgB,EAC3C,GAAI,CAAC4B,EACH,MAAM,IAAI,MAAM,kDAAkD,EAEpE,OAAOA,CACT,CAEA,IAAOC,EAAQ5B",
6
- "names": ["jsx", "DashX", "React", "createContext", "useContext", "useEffect", "useRef", "useState", "useCallback", "DashXContext", "WebSocketContext", "DashXProvider", "children", "publicKey", "baseUri", "realtimeBaseUri", "targetEnvironment", "targetProduct", "targetVersion", "initializeWebSocketOnLoad", "webSocketQueryParams", "dashX", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "useWebSocket", "context", "DashXProvider_default"]
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,KAAK,UAAUL,GAAwB,CAAC,CAAC,EACnEM,EAA6BxB,EAAM,QACvC,IAAMkB,GAAwB,CAAC,EAE/B,CAACK,CAAuB,CAC1B,EAGM,CAACE,EAAaC,CAAc,EAAIrB,EAAS,EAAK,EAC9CsB,EAAevB,EAAgC,IAAI,EACnDwB,EAAiBxB,EAAqD,IAAI,GAAK,EAE/E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UpB,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"]
7
7
  }
@@ -0,0 +1,16 @@
1
+ import { type UseInAppChatHookProps, type UseInAppChatHookResponse } from '../hooks/use-in-app-chat.js';
2
+ import { type InAppChatNotificationOptions } from '../hooks/use-in-app-chat-notifications.js';
3
+ type InAppChatProps = UseInAppChatHookResponse & {
4
+ withChatHeader?: boolean;
5
+ withPopoverClose?: boolean;
6
+ borderless?: boolean;
7
+ title?: string;
8
+ };
9
+ declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHeader, withPopoverClose, borderless, title, }: InAppChatProps) => import("react/jsx-runtime").JSX.Element;
10
+ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
11
+ notifications?: boolean | InAppChatNotificationOptions;
12
+ };
13
+ declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
14
+ export type { InAppChatProps, InAppChatWrapperProps };
15
+ export { InAppChat };
16
+ export default InAppChatWrapper;
@@ -0,0 +1,2 @@
1
+ import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as b,Flex as s,Heading as T,Popover as S,Text as c,TextArea as k,Theme as H}from"../components";import{cn as x}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",y=({messages:o,isLoading:a,error:l,sendMessage:r,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:d=!1,title:C="Chat"})=>{const[i,h]=w(""),{scrollAreaRef:A,scrollToBottom:g}=R();v(()=>{setTimeout(()=>g({smooth:!0}),0)},[o.length,g]);const f=()=>{i.trim()&&r(i)&&h("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),f())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:x("h-full",!d&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(b,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow-1 p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:x("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(c,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(c,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),l&&e(c,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:l})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:!border-none [&_textarea]:!outline-none",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:I,onChange:t=>h(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(b,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:f,isDisabled:!i.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,idempotencyKey:a,initialMessage:l,notifications:r=!0,...u})=>{const m=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),d=U({identityId:o,idempotencyKey:a,initialMessage:l,onInboundMessage:m.handleInboundMessage});return e(y,{...d,...u})};var _=E;export{y as InAppChat,_ as default};
2
+ //# sourceMappingURL=InAppChat.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/widgets/InAppChat.tsx"],
4
+ "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow-1 p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:!border-none [&_textarea]:!outline-none\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
+ "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP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EAAY,eAAAC,EAAgB,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlI,MAAMC,EAAW5B,EAA0B,CACzC,OAAQ,GACR,QAAS0B,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO9B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO7C,EAACsB,EAAA,CAAW,GAAGwB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQR",
6
+ "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "notifications", "props", "notifier", "chat", "InAppChat_default"]
7
+ }
@@ -0,0 +1,12 @@
1
+ import { type ThemeProps } from '../components';
2
+ import { type InAppChatWrapperProps } from './InAppChat.js';
3
+ type LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
4
+ type InAppChatButtonProps = InAppChatWrapperProps & {
5
+ /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */
6
+ position?: LauncherPosition;
7
+ /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
+ theme?: ThemeProps;
9
+ };
10
+ declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
+ export type { InAppChatButtonProps };
12
+ export default InAppChatButton;
@@ -0,0 +1,2 @@
1
+ import{jsx as t,jsxs as w}from"react/jsx-runtime";import{useCallback as i,useRef as I,useState as A}from"react";import{MessageCircle as O}from"lucide-react";import{Button as v,Flex as T,Popover as p,Theme as y}from"../components";import{InAppChat as B}from"./InAppChat.js";import R from"../hooks/use-in-app-chat.js";import x from"../hooks/use-in-app-chat-notifications.js";const L={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},S=({identityId:h,idempotencyKey:l,initialMessage:u,notifications:e=!0,position:m="bottom-right",theme:f,...c})=>{const[o,n]=A(!1),r=I(!1);o&&(r.current=!0);const g=r.current,C=i(()=>n(!0),[]),{handleInboundMessage:P,requestPermissionOnOpen:s}=x({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:C}),d=i(a=>{a&&s(),n(a)},[s]),b=R({identityId:h,idempotencyKey:l,initialMessage:u,enabled:g,onInboundMessage:P});return t(y,{...f,children:t(T,{className:`fixed z-50 ${L[m]}`,children:w(p.Root,{open:o,onOpenChange:d,children:[t(p.Trigger,{children:t(v,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(O,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(B,{...b,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...c})})]})})})};var H=S;export{H as default};
2
+ //# sourceMappingURL=InAppChatButton.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/widgets/InAppChatButton.tsx"],
4
+ "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n initialMessage,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first\n // open the hook is idle, so no conversation is created on page load.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
+ "mappings": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,EAAInB,EAAS,EAAK,EAMpCoB,EAAerB,EAAO,EAAK,EAC7BmB,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,EAAOxB,EAAY,IAAMqB,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,EAAIhB,EAA0B,CAClF,OAAAU,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKG,EAAmB3B,EACtB4B,GAAsB,CACjBA,GAAUF,EAAwB,EACtCL,EAAUO,CAAQ,CACpB,EACA,CAACF,CAAuB,CAC1B,EAEMG,EAAOpB,EAAa,CACxB,WAAAI,EACA,eAAAC,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,OACE3B,EAACS,EAAA,CAAO,GAAGW,EACT,SAAApB,EAACO,EAAA,CAAK,UAAW,cAAcM,EAAeM,CAAQ,CAAC,GACrD,SAAAlB,EAACO,EAAQ,KAAR,CAAa,KAAMc,EAAQ,aAAcO,EACxC,UAAA7B,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGqB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQlB",
6
+ "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
7
+ }
@@ -1,5 +1,7 @@
1
1
  export { default as Chat } from './Chat.js';
2
2
  export { default as ChatPopover } from './ChatPopover.js';
3
+ export { default as InAppChat } from './InAppChat.js';
4
+ export { default as InAppChatButton } from './InAppChatButton.js';
3
5
  export { default as MessageBell } from './MessageBell.js';
4
6
  export { default as Preference } from './Preference.js';
5
7
  export { default as Preferences } from './Preferences.js';
@@ -1,2 +1,2 @@
1
- import{default as a}from"./Chat.js";import{default as o}from"./ChatPopover.js";import{default as s}from"./MessageBell.js";import{default as p}from"./Preference.js";import{default as m}from"./Preferences.js";export{a as Chat,o as ChatPopover,s as MessageBell,p as Preference,m as Preferences};
1
+ import{default as a}from"./Chat.js";import{default as o}from"./ChatPopover.js";import{default as p}from"./InAppChat.js";import{default as l}from"./InAppChatButton.js";import{default as d}from"./MessageBell.js";import{default as x}from"./Preference.js";import{default as h}from"./Preferences.js";export{a as Chat,o as ChatPopover,p as InAppChat,l as InAppChatButton,d as MessageBell,x as Preference,h as Preferences};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/index.ts"],
4
- "sourcesContent": ["export { default as Chat } from './Chat.js';\nexport { default as ChatPopover } from './ChatPopover.js';\nexport { default as MessageBell } from './MessageBell.js';\nexport { default as Preference } from './Preference.js';\nexport { default as Preferences } from './Preferences.js';\n"],
5
- "mappings": "AAAA,OAAoB,WAAXA,MAAuB,YAChC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA6B,kBACtC,OAAoB,WAAXA,MAA8B",
4
+ "sourcesContent": ["export { default as Chat } from './Chat.js';\nexport { default as ChatPopover } from './ChatPopover.js';\nexport { default as InAppChat } from './InAppChat.js';\nexport { default as InAppChatButton } from './InAppChatButton.js';\nexport { default as MessageBell } from './MessageBell.js';\nexport { default as Preference } from './Preference.js';\nexport { default as Preferences } from './Preferences.js';\n"],
5
+ "mappings": "AAAA,OAAoB,WAAXA,MAAuB,YAChC,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA4B,iBACrC,OAAoB,WAAXA,MAAkC,uBAC3C,OAAoB,WAAXA,MAA8B,mBACvC,OAAoB,WAAXA,MAA6B,kBACtC,OAAoB,WAAXA,MAA8B",
6
6
  "names": ["default"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dashx/react",
3
- "version": "0.2.3",
3
+ "version": "0.3.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.7.4",
78
+ "@dashx/browser": "^0.8.1",
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",
@@ -2,4 +2,7 @@ export { useWebSocket } from '../providers/DashXProvider.js';
2
2
  export { default as useAgent } from './use-agent.js';
3
3
  export { default as useDashXProvider } from './use-dashx-provider.js';
4
4
  export { default as useInApp } from './use-in-app.js';
5
+ export { default as useInAppChat } from './use-in-app-chat.js';
6
+ export { default as useInAppChatNotifications } from './use-in-app-chat-notifications.js';
7
+ export type { InAppChatNotificationOptions } from './use-in-app-chat-notifications.js';
5
8
  export { default as useProductRelease } from './use-product-release.js';
@@ -0,0 +1,117 @@
1
+ import { useCallback, useRef } from 'react';
2
+ import type { InAppChatMessageData } from '@dashx/browser';
3
+
4
+ import useDashXProvider from './use-dashx-provider.js';
5
+
6
+ type InAppChatNotificationOptions = {
7
+ // Notification title. Defaults to 'New message'.
8
+ title?: string;
9
+ // Icon URL shown in the notification.
10
+ icon?: string;
11
+ // Custom body text from the inbound message; defaults to the message text.
12
+ renderBody?: (message: InAppChatMessageData) => string;
13
+ // When to request notification permission. 'firstOpen' (the default for the
14
+ // launcher) requests it the first time the visitor opens chat — a real user
15
+ // gesture, which browsers require for a non-penalized prompt. 'manual' never
16
+ // auto-requests (use for always-visible surfaces, where the embedder drives
17
+ // the prompt via the returned `requestPermission`).
18
+ requestPermissionOn?: 'firstOpen' | 'manual';
19
+ };
20
+
21
+ type UseInAppChatNotificationsProps = {
22
+ // Whether the chat surface is currently open/visible. Combined with tab
23
+ // visibility + window focus to decide if the visitor is actively looking at
24
+ // chat (in which case we don't notify).
25
+ isOpen: boolean;
26
+ // `false` disables notifications entirely.
27
+ enabled?: boolean;
28
+ options?: InAppChatNotificationOptions;
29
+ // Invoked when the visitor clicks a notification — focus is handled by the
30
+ // SDK; this opens the chat panel.
31
+ onActivate?: () => void;
32
+ };
33
+
34
+ const textFromContent = (content: any): string => {
35
+ if (typeof content === 'string') return content;
36
+ return content?.text ?? content?.body ?? '';
37
+ };
38
+
39
+ /**
40
+ * Foreground browser notifications for incoming In-App Chat messages. Returns a
41
+ * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it
42
+ * fires a notification only for agent/AI replies that arrive while the chat
43
+ * isn't focused (panel closed, or tab hidden/unfocused) and only once the
44
+ * visitor has granted permission.
45
+ */
46
+ const useInAppChatNotifications = ({
47
+ isOpen,
48
+ enabled = true,
49
+ options,
50
+ onActivate,
51
+ }: UseInAppChatNotificationsProps) => {
52
+ const dashX = useDashXProvider();
53
+
54
+ // Latest values for the message handler, so it stays referentially stable
55
+ // (it's wired into the chat hook's subscription).
56
+ const isOpenRef = useRef(isOpen);
57
+ isOpenRef.current = isOpen;
58
+ const enabledRef = useRef(enabled);
59
+ enabledRef.current = enabled;
60
+ const optionsRef = useRef(options);
61
+ optionsRef.current = options;
62
+ const onActivateRef = useRef(onActivate);
63
+ onActivateRef.current = onActivate;
64
+
65
+ const isChatFocused = (): boolean => {
66
+ if (!isOpenRef.current) return false;
67
+ if (typeof document === 'undefined') return false;
68
+ if (document.hidden) return false;
69
+ if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;
70
+ return true;
71
+ };
72
+
73
+ const handleInboundMessage = useCallback(
74
+ (message: InAppChatMessageData) => {
75
+ if (!enabledRef.current) return;
76
+ // Agent/AI replies only — never the visitor's own echoed message.
77
+ if ((message.aiRole ?? '').toUpperCase() === 'USER') return;
78
+ // Don't interrupt a visitor who's actively looking at the chat.
79
+ if (isChatFocused()) return;
80
+
81
+ const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);
82
+ if (!body) return;
83
+
84
+ dashX.showInAppChatNotification?.({
85
+ title: optionsRef.current?.title ?? 'New message',
86
+ body,
87
+ icon: optionsRef.current?.icon,
88
+ tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,
89
+ onClick: () => onActivateRef.current?.(),
90
+ });
91
+ },
92
+ [dashX],
93
+ );
94
+
95
+ const requestPermission = useCallback(
96
+ () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),
97
+ [dashX],
98
+ );
99
+
100
+ // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)
101
+ // so the permission prompt lands inside the browser's transient activation
102
+ // window. Requesting from an effect after the click has unwound is
103
+ // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'
104
+ // skips it), and is safe to call on every open (no-ops once permission is
105
+ // decided — see Client.requestNotificationPermission).
106
+ const requestPermissionOnOpen = useCallback(() => {
107
+ if (!enabledRef.current) return;
108
+ if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;
109
+ dashX.requestNotificationPermission?.().catch(() => {});
110
+ }, [dashX]);
111
+
112
+ return { handleInboundMessage, requestPermission, requestPermissionOnOpen };
113
+ };
114
+
115
+ export type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };
116
+
117
+ export default useInAppChatNotifications;