@dashx/react 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/dist/cjs/hooks/index.d.ts +1 -0
- package/dist/cjs/hooks/index.js +1 -1
- package/dist/cjs/hooks/index.js.map +3 -3
- package/dist/cjs/hooks/use-in-app-chat.d.ts +38 -0
- package/dist/cjs/hooks/use-in-app-chat.js +2 -0
- package/dist/cjs/hooks/use-in-app-chat.js.map +7 -0
- package/dist/cjs/providers/DashXProvider.d.ts +15 -1
- package/dist/cjs/providers/DashXProvider.js +1 -1
- package/dist/cjs/providers/DashXProvider.js.map +3 -3
- package/dist/cjs/widgets/InAppChat.d.ts +13 -0
- package/dist/cjs/widgets/InAppChat.js +2 -0
- package/dist/cjs/widgets/InAppChat.js.map +7 -0
- package/dist/cjs/widgets/InAppChatButton.d.ts +12 -0
- package/dist/cjs/widgets/InAppChatButton.js +2 -0
- package/dist/cjs/widgets/InAppChatButton.js.map +7 -0
- package/dist/cjs/widgets/index.d.ts +2 -0
- package/dist/cjs/widgets/index.js +1 -1
- package/dist/cjs/widgets/index.js.map +3 -3
- package/dist/esm/hooks/index.d.ts +1 -0
- package/dist/esm/hooks/index.js +1 -1
- package/dist/esm/hooks/index.js.map +2 -2
- package/dist/esm/hooks/use-in-app-chat.d.ts +38 -0
- package/dist/esm/hooks/use-in-app-chat.js +2 -0
- package/dist/esm/hooks/use-in-app-chat.js.map +7 -0
- package/dist/esm/providers/DashXProvider.d.ts +15 -1
- package/dist/esm/providers/DashXProvider.js +1 -1
- package/dist/esm/providers/DashXProvider.js.map +3 -3
- package/dist/esm/widgets/InAppChat.d.ts +13 -0
- package/dist/esm/widgets/InAppChat.js +2 -0
- package/dist/esm/widgets/InAppChat.js.map +7 -0
- package/dist/esm/widgets/InAppChatButton.d.ts +12 -0
- package/dist/esm/widgets/InAppChatButton.js +2 -0
- package/dist/esm/widgets/InAppChatButton.js.map +7 -0
- package/dist/esm/widgets/index.d.ts +2 -0
- package/dist/esm/widgets/index.js +1 -1
- package/dist/esm/widgets/index.js.map +2 -2
- package/package.json +2 -2
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use-in-app-chat.ts +254 -0
- package/src/providers/DashXProvider.tsx +74 -7
- package/src/widgets/InAppChat.tsx +165 -0
- package/src/widgets/InAppChatButton.tsx +59 -0
- package/src/widgets/index.ts +2 -0
- package/styles.css +6 -0
- package/dist/cjs/widgets/NotificationBell.d.ts +0 -2
- package/dist/cjs/widgets/NotificationBell.js +0 -2
- package/dist/cjs/widgets/NotificationBell.js.map +0 -7
- package/dist/esm/widgets/NotificationBell.d.ts +0 -2
- package/dist/esm/widgets/NotificationBell.js +0 -2
- package/dist/esm/widgets/NotificationBell.js.map +0 -7
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@dashx/react` are documented in this file. Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [0.3.0] — 2026-06-18
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **In-App Chat hook + widgets.** A two-way in-app chat surface for visitors:
|
|
10
|
+
- `useInAppChat({ identityId, idempotencyKey, initialMessage? })` — manages the conversation lifecycle (start → subscribe → fetch history), exposes `messages`, `sendMessage(text)`, and loading/error state, and reconciles optimistic sends against the realtime echoes (deduping by message id and external uid). Refetches history on reconnect so a reply that landed during an outage isn't missed.
|
|
11
|
+
- `<InAppChat>` — the chat surface (header / message list / composer).
|
|
12
|
+
- `<InAppChatButton>` — a floating launcher that opens `<InAppChat>` in a popover. Props: `identityId`, `idempotencyKey`, `position` (`'bottom-right'` | `'bottom-left'` | `'top-right'` | `'top-left'`, default `'bottom-right'`), and `theme` (accent color, mode, roundness, …). The chat mounts lazily on open, so no conversation is created until the visitor opens the launcher.
|
|
13
|
+
|
|
14
|
+
In-App Chat requires a visitor identity token configured on `DashXProvider` (see below); render the chat only once that token is available.
|
|
15
|
+
|
|
16
|
+
Example — `<InAppChatButton>` with a `theme` override (all `ThemeProps` fields are optional and otherwise inherit from a surrounding `<Theme>` / `DashXProvider`):
|
|
17
|
+
|
|
18
|
+
```tsx
|
|
19
|
+
<InAppChatButton
|
|
20
|
+
identityId="<dashx-chat-identity-id>"
|
|
21
|
+
idempotencyKey="main"
|
|
22
|
+
position="bottom-right"
|
|
23
|
+
theme={{
|
|
24
|
+
accentBaseColor: '#6d28d9',
|
|
25
|
+
mode: 'dark',
|
|
26
|
+
roundness: 'large',
|
|
27
|
+
}}
|
|
28
|
+
/>
|
|
29
|
+
```
|
|
30
|
+
- **`DashXProvider` identity props.** New optional `identityUid?` and `identityToken?`. When set, the identity is applied on both transports — the Apollo `X-Identity-Token` header and the WebSocket handshake — which is the visitor auth In-App Chat needs. Pass `null` to clear on logout; omit (`undefined`) to leave unchanged. Pair `identityUid` with `identityToken` to address the same identity on both transports.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- **Bumped `@dashx/browser` to `^0.8.0`** — for the In-App Chat client methods, the `subscribeToChannel` helper, and the `setIdentity` "undefined = leave unchanged" semantics this provider relies on.
|
|
35
|
+
- **Identity is now applied synchronously at client creation**, and the provider reconnects its own WebSocket when `identityToken` changes (so tracked chat channels re-subscribe under the new identity). Existing consumers that pass neither `identityUid` nor `identityToken` are unaffected — no extra `setIdentity` call, no reconnect, and the client is not recreated.
|
|
@@ -2,4 +2,5 @@ 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';
|
|
5
6
|
export { default as useProductRelease } from './use-product-release.js';
|
package/dist/cjs/hooks/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var A=Object.create;var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var b=(e,o)=>{for(var r in o)s(e,r,{get:o[r],enumerable:!0})},f=(e,o,r,u)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of h(o))!P.call(e,t)&&t!==r&&s(e,t,{get:()=>o[t],enumerable:!(u=c(o,t))||u.enumerable});return e};var a=(e,o,r)=>(r=e!=null?A(I(e)):{},f(o||!e||!e.__esModule?s(r,"default",{value:e,enumerable:!0}):r,e)),g=e=>f(s({},"__esModule",{value:!0}),e);var i={};b(i,{useAgent:()=>d.default,useDashXProvider:()=>l.default,useInApp:()=>m.default,useInAppChat:()=>x.default,useProductRelease:()=>n.default,useWebSocket:()=>p.useWebSocket});module.exports=g(i);var p=require("../providers/DashXProvider.js"),d=a(require("./use-agent.js")),l=a(require("./use-dashx-provider.js")),m=a(require("./use-in-app.js")),x=a(require("./use-in-app-chat.js")),n=a(require("./use-product-release.js"));
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/index.ts"],
|
|
4
|
-
"sourcesContent": ["export { useWebSocket } from '../providers/DashXProvider.js';\nexport { default as useAgent } from './use-agent.js';\nexport { default as useDashXProvider } from './use-dashx-provider.js';\nexport { default as useInApp } from './use-in-app.js';\nexport { default as useProductRelease } from './use-product-release.js';\n"],
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA
|
|
6
|
-
"names": ["hooks_exports", "__export", "__toCommonJS", "import_DashXProvider", "import_use_agent", "import_use_dashx_provider", "import_use_in_app", "import_use_product_release"]
|
|
4
|
+
"sourcesContent": ["export { useWebSocket } from '../providers/DashXProvider.js';\nexport { default as useAgent } from './use-agent.js';\nexport { default as useDashXProvider } from './use-dashx-provider.js';\nexport { default as useInApp } from './use-in-app.js';\nexport { default as useInAppChat } from './use-in-app-chat.js';\nexport { default as useProductRelease } from './use-product-release.js';\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0LAAAE,EAAAF,GAAA,IAAAG,EAA6B,yCAC7BC,EAAoC,6BACpCC,EAA4C,sCAC5CC,EAAoC,8BACpCC,EAAwC,mCACxCC,EAA6C",
|
|
6
|
+
"names": ["hooks_exports", "__export", "__toCommonJS", "import_DashXProvider", "import_use_agent", "import_use_dashx_provider", "import_use_in_app", "import_use_in_app_chat", "import_use_product_release"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type UseInAppChatHookProps = {
|
|
2
|
+
identityId: string;
|
|
3
|
+
idempotencyKey: string;
|
|
4
|
+
initialMessage?: string;
|
|
5
|
+
};
|
|
6
|
+
type InAppChatMessage = {
|
|
7
|
+
id: string;
|
|
8
|
+
externalUid: string | null;
|
|
9
|
+
renderedContent: any;
|
|
10
|
+
aiRole: string | null;
|
|
11
|
+
createdAt: string;
|
|
12
|
+
turnSeq?: number;
|
|
13
|
+
isPending?: boolean;
|
|
14
|
+
};
|
|
15
|
+
type UseInAppChatHookResponse = {
|
|
16
|
+
conversationId: string | null;
|
|
17
|
+
messages: InAppChatMessage[];
|
|
18
|
+
isLoading: boolean;
|
|
19
|
+
isConnected: boolean;
|
|
20
|
+
error: string | null;
|
|
21
|
+
sendMessage: (text: string) => boolean;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Two-way InApp Chat for a visitor.
|
|
25
|
+
*
|
|
26
|
+
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
27
|
+
* `identityToken` (and matching `identityUid`). The chat mutations require
|
|
28
|
+
* identity-token auth — if the chat starts before an identity is resolved, they
|
|
29
|
+
* are rejected and the hook surfaces an auth error. It does NOT auto-retry when
|
|
30
|
+
* a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
|
|
31
|
+
* visitor token), so only render the chat once `identityToken` is available —
|
|
32
|
+
* e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
|
|
33
|
+
* this by starting lazily when the visitor opens it, by which point the provider
|
|
34
|
+
* has applied the token.
|
|
35
|
+
*/
|
|
36
|
+
declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
|
|
37
|
+
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
38
|
+
export default useInAppChat;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var q=Object.create;var I=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var X=(e,n)=>{for(var s in n)I(e,s,{get:n[s],enumerable:!0})},U=(e,n,s,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of F(n))!$.call(e,t)&&t!==s&&I(e,t,{get:()=>n[t],enumerable:!(a=D(n,t))||a.enumerable});return e};var S=(e,n,s)=>(s=e!=null?q(L(e)):{},U(n||!e||!e.__esModule?I(s,"default",{value:e,enumerable:!0}):s,e)),K=e=>U(I({},"__esModule",{value:!0}),e);var z={};X(z,{default:()=>W});module.exports=K(z);var k=S(require("uuid-random")),o=require("react"),m=S(require("./use-dashx-provider.js")),x=require("../providers/DashXProvider.js");const N="in_app_chat:conversation:",M=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),O=(e,n)=>{const s=new Map,a=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const i=s.get(a(t));(!i||i.isPending)&&s.set(a(t),t)}),[...s.values()].sort((t,i)=>t.createdAt!==i.createdAt?t.createdAt<i.createdAt?-1:1:(t.turnSeq??0)-(i.turnSeq??0))},T=({identityId:e,idempotencyKey:n,initialMessage:s})=>{const a=(0,m.default)(),{isConnected:t,initializeWebSocket:i}=(0,x.useWebSocket)(),[H,y]=(0,o.useState)(null),[w,v]=(0,o.useState)([]),[P,b]=(0,o.useState)(!0),[E,d]=(0,o.useState)(null),p=(0,o.useRef)(0),A=(0,o.useRef)(null),u=(0,o.useCallback)(c=>{v(r=>O(r,c))},[]);(0,o.useEffect)(()=>{const c=p.current+=1,r=()=>c!==p.current;y(null),v([]),b(!0),d(null),A.current=null,i();let g;return(async()=>{try{const h=await a.startInAppChatConversation({identityId:e,clientIdempotencyKey:n,...s?{content:{text:s},clientMessageId:`${n.slice(0,122)}-intro`}:{}});if(r())return;const l=h.id;y(l),A.current=l;const C=async()=>{const f=await a.fetchInAppChatMessages({conversationId:l});r()||u(f.map(M))},R=a.subscribeToChannel(`${N}${l}`,f=>{r()||u([M(f)])},{onReconnectAck:()=>{r()||(d(null),C().catch(()=>{}))}});g=R.unsubscribe;try{await R.ready}catch{r()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(r())return;await C()}catch{r()||d("Failed to start chat")}finally{r()||b(!1)}})(),()=>{p.current+=1,g?.()}},[a,e,n,s,i,u]);const _=(0,o.useCallback)(c=>{const r=A.current;if(!c.trim()||!r)return!1;const g=p.current,h=(0,k.default)(),l={id:h,externalUid:`in_app_chat:${h}`,renderedContent:{text:c},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([l]),(async()=>{try{const C=await a.sendInAppChatMessage({conversationId:r,identityId:e,content:{text:c},clientMessageId:h});if(g!==p.current)return;u([M(C)])}catch{g===p.current&&d("Failed to send message")}})(),!0},[a,e,u]);return{conversationId:H,messages:w,isLoading:P,isConnected:t,error:E,sendMessage:_}};var W=T;
|
|
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};\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 }: 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 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 setIsLoading(true);\n setError(null);\n conversationIdRef.current = null;\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()) appendMessages([toUiMessage(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, 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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAA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EAAa,EAAK,CACpC,CACF,GAAG,EAEI,IAAM,CAGXG,EAAc,SAAW,EACzBM,IAAc,CAChB,CACF,EAAG,CAAClB,EAAOH,EAAYC,EAAgBC,EAAgBI,EAAqBW,CAAc,CAAC,EAO3F,MAAMW,KAAc,eACjBC,GAA0B,CACzB,MAAMN,EAASP,EAAkB,QAGjC,GAAI,CAACa,EAAK,KAAK,GAAK,CAACN,EAAQ,MAAO,GAIpC,MAAMJ,EAAaJ,EAAc,QAC3Be,KAAkB,EAAAC,SAAK,EACvBC,EAA+B,CACnC,GAAIF,EACJ,YAAa,eAAeA,CAAe,GAC3C,gBAAiB,CAAE,KAAAD,CAAK,EACxB,OAAQ,OACR,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,UAAW,EACb,EACA,OAAAZ,EAAe,CAACe,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAM9B,EAAM,qBAAqB,CACrD,eAAgBoB,EAChB,WAAAvB,EACA,QAAS,CAAE,KAAA6B,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIX,IAAeJ,EAAc,QAAS,OAE1CE,EAAe,CAAC5B,EAAY4C,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFd,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACX,EAAOH,EAAYiB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAV,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAe,CAAY,CAChF,EAIA,IAAO9C,EAAQiB",
|
|
6
|
+
"names": ["use_in_app_chat_exports", "__export", "use_in_app_chat_default", "__toCommonJS", "import_uuid_random", "import_react", "import_use_dashx_provider", "import_DashXProvider", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
|
|
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
|
-
"use strict";var
|
|
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=$;
|
|
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
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,YAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,
|
|
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", "dashX", "React", "DashX", "isConnected", "setIsConnected", "wsManagerRef", "subscribersRef", "subscribe", "callback", "initializeWebSocket", "customQueryParams", "queryParams", "wsManager", "errorEvent", "closeEvent", "message", "error", "attempt", "context"]
|
|
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,YAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GA4LM,IAAAM,EAAA,6BA5LNC,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,CACF,EAAgD,CAC9C,MAAMC,EAAQ,EAAAC,QAAM,QAClB,IAAM,CACJ,MAAMC,EAAS,EAAAC,QAAM,UAAU,CAC7B,UAAWb,EACX,QAASC,EACT,gBAAiBC,EACjB,kBAAmBC,EACnB,cAAAC,EACA,cAAAC,CACF,CAAC,EAMD,OAAIG,IAAgB,QAAaC,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,CACvB,QAAQ,MAAM,+BAA+B,EAC7Cb,EAAe,EAAK,CACtB,CACF,CAAC,EAEDC,EAAa,QAAUO,EACvBA,EAAU,QAAQ,CACpB,EAAG,CAACf,EAAOK,CAA0B,CAAC,EAMhCgB,KAA2B,UAAOtB,CAAa,EACrD,sBAAU,IAAM,CACd,GAAI,CAACC,GAAUF,IAAgB,QAAaC,IAAkB,OAC5D,OAGFC,EAAM,YAAYF,EAAaC,CAAa,EAO5C,MAAMuB,EAAevB,IAAkBsB,EAAyB,QAChEA,EAAyB,QAAUtB,EAC/BuB,GAAgBd,EAAa,UAC/BA,EAAa,QAAQ,WAAW,EAChCA,EAAa,QAAU,KACvBI,EAAoBP,CAA0B,EAElD,EAAG,CAAEL,EAAOF,EAAaC,EAAea,EAAqBP,CAA2B,CAAC,KAEzF,aAAU,IAAM,CACVT,GACFgB,EAAoBP,CAA0B,CAElD,EAAG,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"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type UseInAppChatHookProps, type UseInAppChatHookResponse } from '../hooks/use-in-app-chat.js';
|
|
2
|
+
type InAppChatProps = UseInAppChatHookResponse & {
|
|
3
|
+
withChatHeader?: boolean;
|
|
4
|
+
withPopoverClose?: boolean;
|
|
5
|
+
borderless?: boolean;
|
|
6
|
+
title?: string;
|
|
7
|
+
};
|
|
8
|
+
declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHeader, withPopoverClose, borderless, title, }: InAppChatProps) => import("react/jsx-runtime").JSX.Element;
|
|
9
|
+
type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & UseInAppChatHookProps;
|
|
10
|
+
declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
|
|
11
|
+
export type { InAppChatProps, InAppChatWrapperProps };
|
|
12
|
+
export { InAppChat };
|
|
13
|
+
export default InAppChatWrapper;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var P=Object.create;var m=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var U=(t,a)=>{for(var r in a)m(t,r,{get:a[r],enumerable:!0})},y=(t,a,r,p)=>{if(a&&typeof a=="object"||typeof a=="function")for(let n of k(a))!R.call(t,n)&&n!==r&&m(t,n,{get:()=>a[n],enumerable:!(p=S(a,n))||p.enumerable});return t};var d=(t,a,r)=>(r=t!=null?P(H(t)):{},y(a||!t||!t.__esModule?m(r,"default",{value:t,enumerable:!0}):r,t)),z=t=>y(m({},"__esModule",{value:!0}),t);var D={};U(D,{InAppChat:()=>g,default:()=>B});module.exports=z(D);var e=require("react/jsx-runtime"),l=d(require("@radix-ui/react-scroll-area")),u=require("react"),c=require("lucide-react"),o=require("../components"),h=require("../utils/cn.js"),C=d(require("../hooks/use-auto-scroll.js")),A=d(require("../hooks/use-in-app-chat.js"));const E=t=>{const a=t.renderedContent;return typeof a=="string"?a:a?.text??""},F=t=>t.aiRole?.toUpperCase()==="USER",g=({messages:t,isLoading:a,error:r,sendMessage:p,withChatHeader:n=!1,withPopoverClose:v=!1,borderless:I=!1,title:w="Chat"})=>{const[i,f]=(0,u.useState)(""),{scrollAreaRef:N,scrollToBottom:x}=(0,C.default)();(0,u.useEffect)(()=>{setTimeout(()=>x({smooth:!0}),0)},[t.length,x]);const b=()=>{i.trim()&&p(i)&&f("")},T=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),b())};return(0,e.jsx)(o.Theme,{asChild:!0,children:(0,e.jsxs)(o.Flex,{direction:"column",className:(0,h.cn)("h-full",!I&&"border border-gray-400/40"),children:[n&&(0,e.jsxs)(o.Flex,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[(0,e.jsx)(o.Heading,{size:3,children:w}),v&&(0,e.jsx)(o.Popover.Close,{children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,e.jsx)(c.X,{})})})]}),(0,e.jsx)(o.Flex,{direction:"column",className:"grow overflow-auto bg-gray-50",children:(0,e.jsxs)(l.Root,{ref:N,className:"h-full grow-1 p-6",children:[(0,e.jsx)(l.Viewport,{className:"h-full",children:(0,e.jsxs)(o.Flex,{direction:"column",gap:3,children:[t.map(s=>(0,e.jsx)("div",{className:(0,h.cn)("max-w-[80%] rounded-lg py-2 px-3",F(s)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:(0,e.jsx)(o.Text,{as:"p",size:2,children:E(s)})},s.externalUid||s.id)),a&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),(0,e.jsx)(l.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:(0,e.jsx)(l.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),(0,e.jsx)(l.Corner,{})]})}),(0,e.jsx)("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:(0,e.jsxs)(o.Flex,{gap:2,align:"end",className:"w-full",children:[(0,e.jsx)("div",{className:"w-full [&_textarea]:!border-none [&_textarea]:!outline-none",children:(0,e.jsx)(o.TextArea,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:T,onChange:s=>f(s),roundness:"none",autogrow:!0})}),(0,e.jsx)("div",{className:"mr-[7px] mb-[7px]",children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:b,isDisabled:!i.trim(),children:(0,e.jsx)(c.Send,{size:20})})})]})})]})})},K=({identityId:t,idempotencyKey:a,initialMessage:r,...p})=>{const n=(0,A.default)({identityId:t,idempotencyKey:a,initialMessage:r});return(0,e.jsx)(g,{...n,...p})};var B=K;
|
|
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';\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> & UseInAppChatHookProps;\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, ...props }: InAppChatWrapperProps) => {\n const chat = useInAppChat({ identityId, idempotencyKey, initialMessage });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAkEU,IAAAK,EAAA,6BAlEVC,EAA4B,0CAC5BC,EAA2C,iBAC3CC,EAAwB,wBAGxBC,EAAsE,yBACtEC,EAAmB,0BACnBC,EAA0B,0CAC1BC,EAIO,0CASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFZ,EAAY,CAAC,CACjB,SAAAe,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAS,EAAE,EACzC,CAAE,cAAAC,EAAe,eAAAC,CAAe,KAAI,EAAAC,SAAc,KAExD,aAAU,IAAM,CACd,WAAW,IAAMD,EAAe,CAAE,OAAQ,EAAK,CAAC,EAAG,CAAC,CACtD,EAAG,CAACX,EAAS,OAAQW,CAAc,CAAC,EAEpC,MAAME,EAAe,IAAM,CACpBL,EAAW,KAAK,GAKjBL,EAAYK,CAAU,GAAGC,EAAc,EAAE,CAC/C,EAEMK,EAAiBC,GAA0C,CAC3DA,EAAE,MAAQ,SAAW,CAACA,EAAE,WAC1BA,EAAE,eAAe,EACjBF,EAAa,EAEjB,EAEA,SACE,OAAC,SAAM,QAAO,GACZ,oBAAC,QAAK,UAAU,SAAS,aAAW,MAAG,SAAU,CAACP,GAAc,2BAA2B,EACxF,UAAAF,MACC,QAAC,QAAK,MAAM,SAAS,QAAQ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AE7B,mBAAC,QAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAIMS,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,GAAGC,CAAM,IAA6B,CAC5G,MAAMC,KAAO,EAAAC,SAAa,CAAE,WAAAL,EAAY,eAAAC,EAAgB,eAAAC,CAAe,CAAC,EACxE,SAAO,OAACnC,EAAA,CAAW,GAAGqC,EAAO,GAAGD,EAAO,CACzC,EAMA,IAAOnC,EAAQ+B",
|
|
6
|
+
"names": ["InAppChat_exports", "__export", "InAppChat", "InAppChat_default", "__toCommonJS", "import_jsx_runtime", "ScrollArea", "import_react", "import_lucide_react", "import_components", "import_cn", "import_use_auto_scroll", "import_use_in_app_chat", "messageText", "message", "content", "isOutgoing", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "useAutoScroll", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "props", "chat", "useInAppChat"]
|
|
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, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
|
|
11
|
+
export type { InAppChatButtonProps };
|
|
12
|
+
export default InAppChatButton;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var l=Object.create;var h=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var u=(t,o)=>{for(var e in o)h(t,e,{get:o[e],enumerable:!0})},s=(t,o,e,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of P(o))!C.call(t,i)&&i!==e&&h(t,i,{get:()=>o[i],enumerable:!(n=g(o,i))||n.enumerable});return t};var c=(t,o,e)=>(e=t!=null?l(f(t)):{},s(o||!t||!t.__esModule?h(e,"default",{value:t,enumerable:!0}):e,t)),d=t=>s(h({},"__esModule",{value:!0}),t);var A={};u(A,{default:()=>y});module.exports=d(A);var p=require("react/jsx-runtime"),v=require("react"),a=require("lucide-react"),r=require("../components"),m=c(require("./InAppChat.js"));const I={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},b=({identityId:t,idempotencyKey:o,position:e="bottom-right",theme:n,...i})=>(0,p.jsx)(r.Theme,{...n,children:(0,p.jsx)(r.Flex,{className:`fixed z-50 ${I[e]}`,children:(0,p.jsxs)(r.Popover.Root,{children:[(0,p.jsx)(r.Popover.Trigger,{children:(0,p.jsx)(r.Button,{shape:"square",roundness:"full",variant:"fill",size:"large",children:(0,p.jsx)(a.MessageCircle,{})})}),(0,p.jsx)(r.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:(0,p.jsx)(m.default,{identityId:t,idempotencyKey:o,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...i})})]})})});var y=b;
|
|
2
|
+
//# sourceMappingURL=InAppChatButton.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/widgets/InAppChatButton.tsx"],
|
|
4
|
+
"sourcesContent": ["import React from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport InAppChat, { type InAppChatWrapperProps } from './InAppChat.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 position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* Radix unmounts Content while closed, so the chat hook (start \u2192\n subscribe \u2192 fetch) runs only once the visitor opens the launcher \u2014\n no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n identityId={identityId}\n idempotencyKey={idempotencyKey}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n);\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAgCM,IAAAI,EAAA,6BAhCNC,EAAkB,iBAClBC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,6BAYtD,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,OACE,OAAC,SAAO,GAAGD,EACT,mBAAC,QAAK,UAAW,cAAcL,EAAeI,CAAQ,CAAC,GACrD,oBAAC,UAAQ,KAAR,CACC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,mBAAC,kBAAc,EACjB,EACF,KAIA,OAAC,UAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,mBAAC,EAAAG,QAAA,CACC,WAAYL,EACZ,eAAgBC,EAChB,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGG,EACN,EACF,GACF,EACF,EACF,EAKF,IAAOb,EAAQQ",
|
|
6
|
+
"names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "position", "theme", "props", "InAppChat"]
|
|
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
|
-
"use strict";var
|
|
1
|
+
"use strict";var C=Object.create;var f=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var a in t)f(e,a,{get:t[a],enumerable:!0})},s=(e,t,a,p)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of c(t))!B.call(e,o)&&o!==a&&f(e,o,{get:()=>t[o],enumerable:!(p=P(t,o))||p.enumerable});return e};var r=(e,t,a)=>(a=e!=null?C(A(e)):{},s(t||!e||!e.__esModule?f(a,"default",{value:e,enumerable:!0}):a,e)),g=e=>s(f({},"__esModule",{value:!0}),e);var v={};I(v,{Chat:()=>l.default,ChatPopover:()=>u.default,InAppChat:()=>d.default,InAppChatButton:()=>m.default,MessageBell:()=>x.default,Preference:()=>n.default,Preferences:()=>h.default});module.exports=g(v);var l=r(require("./Chat.js")),u=r(require("./ChatPopover.js")),d=r(require("./InAppChat.js")),m=r(require("./InAppChatButton.js")),x=r(require("./MessageBell.js")),n=r(require("./Preference.js")),h=r(require("./Preferences.js"));
|
|
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,
|
|
6
|
-
"names": ["widgets_exports", "__export", "__toCommonJS", "import_Chat", "import_ChatPopover", "import_MessageBell", "import_Preference", "import_Preferences"]
|
|
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kMAAAE,EAAAF,GAAA,IAAAG,EAAgC,wBAChCC,EAAuC,+BACvCC,EAAqC,6BACrCC,EAA2C,mCAC3CC,EAAuC,+BACvCC,EAAsC,8BACtCC,EAAuC",
|
|
6
|
+
"names": ["widgets_exports", "__export", "__toCommonJS", "import_Chat", "import_ChatPopover", "import_InAppChat", "import_InAppChatButton", "import_MessageBell", "import_Preference", "import_Preferences"]
|
|
7
7
|
}
|
|
@@ -2,4 +2,5 @@ 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';
|
|
5
6
|
export { default as useProductRelease } from './use-product-release.js';
|
package/dist/esm/hooks/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useWebSocket as r}from"../providers/DashXProvider.js";import{default as
|
|
1
|
+
import{useWebSocket as r}from"../providers/DashXProvider.js";import{default as a}from"./use-agent.js";import{default as u}from"./use-dashx-provider.js";import{default as p}from"./use-in-app.js";import{default as l}from"./use-in-app-chat.js";import{default as x}from"./use-product-release.js";export{a as useAgent,u as useDashXProvider,p as useInApp,l as useInAppChat,x as useProductRelease,r as useWebSocket};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/hooks/index.ts"],
|
|
4
|
-
"sourcesContent": ["export { useWebSocket } from '../providers/DashXProvider.js';\nexport { default as useAgent } from './use-agent.js';\nexport { default as useDashXProvider } from './use-dashx-provider.js';\nexport { default as useInApp } from './use-in-app.js';\nexport { default as useProductRelease } from './use-product-release.js';\n"],
|
|
5
|
-
"mappings": "AAAA,OAAS,gBAAAA,MAAoB,gCAC7B,OAAoB,WAAXC,MAA2B,iBACpC,OAAoB,WAAXA,MAAmC,0BAC5C,OAAoB,WAAXA,MAA2B,kBACpC,OAAoB,WAAXA,MAAoC",
|
|
4
|
+
"sourcesContent": ["export { useWebSocket } from '../providers/DashXProvider.js';\nexport { default as useAgent } from './use-agent.js';\nexport { default as useDashXProvider } from './use-dashx-provider.js';\nexport { default as useInApp } from './use-in-app.js';\nexport { default as useInAppChat } from './use-in-app-chat.js';\nexport { default as useProductRelease } from './use-product-release.js';\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,gBAAAA,MAAoB,gCAC7B,OAAoB,WAAXC,MAA2B,iBACpC,OAAoB,WAAXA,MAAmC,0BAC5C,OAAoB,WAAXA,MAA2B,kBACpC,OAAoB,WAAXA,MAA+B,uBACxC,OAAoB,WAAXA,MAAoC",
|
|
6
6
|
"names": ["useWebSocket", "default"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type UseInAppChatHookProps = {
|
|
2
|
+
identityId: string;
|
|
3
|
+
idempotencyKey: string;
|
|
4
|
+
initialMessage?: string;
|
|
5
|
+
};
|
|
6
|
+
type InAppChatMessage = {
|
|
7
|
+
id: string;
|
|
8
|
+
externalUid: string | null;
|
|
9
|
+
renderedContent: any;
|
|
10
|
+
aiRole: string | null;
|
|
11
|
+
createdAt: string;
|
|
12
|
+
turnSeq?: number;
|
|
13
|
+
isPending?: boolean;
|
|
14
|
+
};
|
|
15
|
+
type UseInAppChatHookResponse = {
|
|
16
|
+
conversationId: string | null;
|
|
17
|
+
messages: InAppChatMessage[];
|
|
18
|
+
isLoading: boolean;
|
|
19
|
+
isConnected: boolean;
|
|
20
|
+
error: string | null;
|
|
21
|
+
sendMessage: (text: string) => boolean;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Two-way InApp Chat for a visitor.
|
|
25
|
+
*
|
|
26
|
+
* PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
|
|
27
|
+
* `identityToken` (and matching `identityUid`). The chat mutations require
|
|
28
|
+
* identity-token auth — if the chat starts before an identity is resolved, they
|
|
29
|
+
* are rejected and the hook surfaces an auth error. It does NOT auto-retry when
|
|
30
|
+
* a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
|
|
31
|
+
* visitor token), so only render the chat once `identityToken` is available —
|
|
32
|
+
* e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
|
|
33
|
+
* this by starting lazily when the visitor opens it, by which point the provider
|
|
34
|
+
* has applied the token.
|
|
35
|
+
*/
|
|
36
|
+
declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
|
|
37
|
+
export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
|
|
38
|
+
export default useInAppChat;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import w from"uuid-random";import{useCallback as R,useEffect as P,useRef as U,useState as C}from"react";import E from"./use-dashx-provider.js";import{useWebSocket as _}from"../providers/DashXProvider.js";const q="in_app_chat:conversation:",f=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),D=(e,u)=>{const o=new Map,s=n=>n.externalUid||n.id;return[...e,...u].forEach(n=>{const r=o.get(s(n));(!r||r.isPending)&&o.set(s(n),n)}),[...o.values()].sort((n,r)=>n.createdAt!==r.createdAt?n.createdAt<r.createdAt?-1:1:(n.turnSeq??0)-(r.turnSeq??0))},F=({identityId:e,idempotencyKey:u,initialMessage:o})=>{const s=E(),{isConnected:n,initializeWebSocket:r}=_(),[S,M]=C(null),[k,y]=C([]),[m,v]=C(!0),[x,l]=C(null),i=U(0),I=U(null),c=R(a=>{y(t=>D(t,a))},[]);P(()=>{const a=i.current+=1,t=()=>a!==i.current;M(null),y([]),v(!0),l(null),I.current=null,r();let d;return(async()=>{try{const g=await s.startInAppChatConversation({identityId:e,clientIdempotencyKey:u,...o?{content:{text:o},clientMessageId:`${u.slice(0,122)}-intro`}:{}});if(t())return;const p=g.id;M(p),I.current=p;const h=async()=>{const A=await s.fetchInAppChatMessages({conversationId:p});t()||c(A.map(f))},b=s.subscribeToChannel(`${q}${p}`,A=>{t()||c([f(A)])},{onReconnectAck:()=>{t()||(l(null),h().catch(()=>{}))}});d=b.unsubscribe;try{await b.ready}catch{t()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(t())return;await h()}catch{t()||l("Failed to start chat")}finally{t()||v(!1)}})(),()=>{i.current+=1,d?.()}},[s,e,u,o,r,c]);const H=R(a=>{const t=I.current;if(!a.trim()||!t)return!1;const d=i.current,g=w(),p={id:g,externalUid:`in_app_chat:${g}`,renderedContent:{text:a},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return c([p]),(async()=>{try{const h=await s.sendInAppChatMessage({conversationId:t,identityId:e,content:{text:a},clientMessageId:g});if(d!==i.current)return;c([f(h)])}catch{d===i.current&&l("Failed to send message")}})(),!0},[s,e,c]);return{conversationId:S,messages:k,isLoading:m,isConnected:n,error:x,sendMessage:H}};var N=F;export{N 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};\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 }: 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 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 setIsLoading(true);\n setError(null);\n conversationIdRef.current = null;\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()) appendMessages([toUiMessage(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, 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,gCAwC7B,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,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AAY,EAClC,UAAW,EACb,EACA,OAAAZ,EAAe,CAACc,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAM5B,EAAM,qBAAqB,CACrD,eAAgBmB,EAChB,WAAAtB,EACA,QAAS,CAAE,KAAA4B,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIX,IAAeJ,EAAc,QAAS,OAE1CE,EAAe,CAAC3B,EAAY0C,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFb,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACV,EAAOH,EAAYgB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAV,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAe,CAAY,CAChF,EAIA,IAAOK,EAAQjC",
|
|
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", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "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
|
|
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
|