@dashx/react 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cjs/hooks/index.d.ts +2 -0
  2. package/dist/cjs/hooks/index.js +1 -1
  3. package/dist/cjs/hooks/index.js.map +3 -3
  4. package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +27 -0
  5. package/dist/cjs/hooks/use-in-app-chat-notifications.js +2 -0
  6. package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +7 -0
  7. package/dist/cjs/hooks/use-in-app-chat.d.ts +4 -1
  8. package/dist/cjs/hooks/use-in-app-chat.js +1 -1
  9. package/dist/cjs/hooks/use-in-app-chat.js.map +3 -3
  10. package/dist/cjs/widgets/InAppChat.d.ts +5 -2
  11. package/dist/cjs/widgets/InAppChat.js +1 -1
  12. package/dist/cjs/widgets/InAppChat.js.map +3 -3
  13. package/dist/cjs/widgets/InAppChatButton.d.ts +1 -1
  14. package/dist/cjs/widgets/InAppChatButton.js +1 -1
  15. package/dist/cjs/widgets/InAppChatButton.js.map +3 -3
  16. package/dist/cjs/widgets/NotificationBell.d.ts +2 -0
  17. package/dist/cjs/widgets/NotificationBell.js +2 -0
  18. package/dist/cjs/widgets/NotificationBell.js.map +7 -0
  19. package/dist/esm/hooks/index.d.ts +2 -0
  20. package/dist/esm/hooks/index.js +1 -1
  21. package/dist/esm/hooks/index.js.map +2 -2
  22. package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +27 -0
  23. package/dist/esm/hooks/use-in-app-chat-notifications.js +2 -0
  24. package/dist/esm/hooks/use-in-app-chat-notifications.js.map +7 -0
  25. package/dist/esm/hooks/use-in-app-chat.d.ts +4 -1
  26. package/dist/esm/hooks/use-in-app-chat.js +1 -1
  27. package/dist/esm/hooks/use-in-app-chat.js.map +3 -3
  28. package/dist/esm/widgets/InAppChat.d.ts +5 -2
  29. package/dist/esm/widgets/InAppChat.js +1 -1
  30. package/dist/esm/widgets/InAppChat.js.map +3 -3
  31. package/dist/esm/widgets/InAppChatButton.d.ts +1 -1
  32. package/dist/esm/widgets/InAppChatButton.js +1 -1
  33. package/dist/esm/widgets/InAppChatButton.js.map +3 -3
  34. package/dist/esm/widgets/NotificationBell.d.ts +2 -0
  35. package/dist/esm/widgets/NotificationBell.js +2 -0
  36. package/dist/esm/widgets/NotificationBell.js.map +7 -0
  37. package/package.json +2 -2
  38. package/src/hooks/index.ts +2 -0
  39. package/src/hooks/use-in-app-chat-notifications.ts +117 -0
  40. package/src/hooks/use-in-app-chat.ts +31 -4
  41. package/src/widgets/InAppChat.tsx +33 -5
  42. package/src/widgets/InAppChatButton.tsx +72 -28
  43. package/styles.css +12 -0
@@ -3,4 +3,6 @@ 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
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';
6
8
  export { default as useProductRelease } from './use-product-release.js';
@@ -1,2 +1,2 @@
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"));
1
+ "use strict";var c=Object.create;var s=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var N=(e,t)=>{for(var o in t)s(e,o,{get:t[o],enumerable:!0})},f=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of A(t))!C.call(e,p)&&p!==o&&s(e,p,{get:()=>t[p],enumerable:!(r=h(t,p))||r.enumerable});return e};var a=(e,t,o)=>(o=e!=null?c(I(e)):{},f(t||!e||!e.__esModule?s(o,"default",{value:e,enumerable:!0}):o,e)),P=e=>f(s({},"__esModule",{value:!0}),e);var b={};N(b,{useAgent:()=>i.default,useDashXProvider:()=>n.default,useInApp:()=>d.default,useInAppChat:()=>m.default,useInAppChatNotifications:()=>x.default,useProductRelease:()=>l.default,useWebSocket:()=>u.useWebSocket});module.exports=P(b);var u=require("../providers/DashXProvider.js"),i=a(require("./use-agent.js")),n=a(require("./use-dashx-provider.js")),d=a(require("./use-in-app.js")),m=a(require("./use-in-app-chat.js")),x=a(require("./use-in-app-chat-notifications.js")),l=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 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"]
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 useInAppChatNotifications } from './use-in-app-chat-notifications.js';\nexport type { InAppChatNotificationOptions } from './use-in-app-chat-notifications.js';\nexport { default as useProductRelease } from './use-product-release.js';\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kOAAAE,EAAAF,GAAA,IAAAG,EAA6B,yCAC7BC,EAAoC,6BACpCC,EAA4C,sCAC5CC,EAAoC,8BACpCC,EAAwC,mCACxCC,EAAqD,iDAErDC,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_in_app_chat_notifications", "import_use_product_release"]
7
7
  }
@@ -0,0 +1,27 @@
1
+ import type { InAppChatMessageData } from '@dashx/browser';
2
+ type InAppChatNotificationOptions = {
3
+ title?: string;
4
+ icon?: string;
5
+ renderBody?: (message: InAppChatMessageData) => string;
6
+ requestPermissionOn?: 'firstOpen' | 'manual';
7
+ };
8
+ type UseInAppChatNotificationsProps = {
9
+ isOpen: boolean;
10
+ enabled?: boolean;
11
+ options?: InAppChatNotificationOptions;
12
+ onActivate?: () => void;
13
+ };
14
+ /**
15
+ * Foreground browser notifications for incoming In-App Chat messages. Returns a
16
+ * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it
17
+ * fires a notification only for agent/AI replies that arrive while the chat
18
+ * isn't focused (panel closed, or tab hidden/unfocused) and only once the
19
+ * visitor has granted permission.
20
+ */
21
+ declare const useInAppChatNotifications: ({ isOpen, enabled, options, onActivate, }: UseInAppChatNotificationsProps) => {
22
+ handleInboundMessage: (message: InAppChatMessageData) => void;
23
+ requestPermission: () => Promise<NotificationPermission>;
24
+ requestPermissionOnOpen: () => void;
25
+ };
26
+ export type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };
27
+ export default useInAppChatNotifications;
@@ -0,0 +1,2 @@
1
+ "use strict";var A=Object.create;var c=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var g=(t,e)=>{for(var r in e)c(t,r,{get:e[r],enumerable:!0})},h=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of O(e))!b.call(t,n)&&n!==r&&c(t,n,{get:()=>e[n],enumerable:!(i=N(e,n))||i.enumerable});return t};var R=(t,e,r)=>(r=t!=null?A(P(t)):{},h(e||!t||!t.__esModule?c(r,"default",{value:t,enumerable:!0}):r,t)),q=t=>h(c({},"__esModule",{value:!0}),t);var D={};g(D,{default:()=>U});module.exports=q(D);var o=require("react"),l=R(require("./use-dashx-provider.js"));const v=t=>typeof t=="string"?t:t?.text??t?.body??"",x=({isOpen:t,enabled:e=!0,options:r,onActivate:i})=>{const n=(0,l.default)(),p=(0,o.useRef)(t);p.current=t;const u=(0,o.useRef)(e);u.current=e;const s=(0,o.useRef)(r);s.current=r;const f=(0,o.useRef)(i);f.current=i;const m=()=>!(!p.current||typeof document>"u"||document.hidden||typeof document.hasFocus=="function"&&!document.hasFocus()),C=(0,o.useCallback)(a=>{if(!u.current||(a.aiRole??"").toUpperCase()==="USER"||m())return;const d=s.current?.renderBody?.(a)??v(a.renderedContent);d&&n.showInAppChatNotification?.({title:s.current?.title??"New message",body:d,icon:s.current?.icon,tag:a.conversationId?`in_app_chat:${a.conversationId}`:void 0,onClick:()=>f.current?.()})},[n]),I=(0,o.useCallback)(()=>n.requestNotificationPermission?.()??Promise.resolve("denied"),[n]),y=(0,o.useCallback)(()=>{u.current&&(s.current?.requestPermissionOn??"firstOpen")==="firstOpen"&&n.requestNotificationPermission?.().catch(()=>{})},[n]);return{handleInboundMessage:C,requestPermission:I,requestPermissionOnOpen:y}};var U=x;
2
+ //# sourceMappingURL=use-in-app-chat-notifications.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/hooks/use-in-app-chat-notifications.ts"],
4
+ "sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel.\n onActivate?: () => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAoC,iBAGpCC,EAA6B,sCA8B7B,MAAMC,EAAmBC,GACnB,OAAOA,GAAY,SAAiBA,EACjCA,GAAS,MAAQA,GAAS,MAAQ,GAUrCC,EAA4B,CAAC,CACjC,OAAAC,EACA,QAAAC,EAAU,GACV,QAAAC,EACA,WAAAC,CACF,IAAsC,CACpC,MAAMC,KAAQ,EAAAC,SAAiB,EAIzBC,KAAY,UAAON,CAAM,EAC/BM,EAAU,QAAUN,EACpB,MAAMO,KAAa,UAAON,CAAO,EACjCM,EAAW,QAAUN,EACrB,MAAMO,KAAa,UAAON,CAAO,EACjCM,EAAW,QAAUN,EACrB,MAAMO,KAAgB,UAAON,CAAU,EACvCM,EAAc,QAAUN,EAExB,MAAMO,EAAgB,IAChB,GAACJ,EAAU,SACX,OAAO,SAAa,KACpB,SAAS,QACT,OAAO,SAAS,UAAa,YAAc,CAAC,SAAS,SAAS,GAI9DK,KAAuB,eAC1BC,GAAkC,CAKjC,GAJI,CAACL,EAAW,UAEXK,EAAQ,QAAU,IAAI,YAAY,IAAM,QAEzCF,EAAc,EAAG,OAErB,MAAMG,EAAOL,EAAW,SAAS,aAAaI,CAAO,GAAKf,EAAgBe,EAAQ,eAAe,EAC5FC,GAELT,EAAM,4BAA4B,CAChC,MAAOI,EAAW,SAAS,OAAS,cACpC,KAAAK,EACA,KAAML,EAAW,SAAS,KAC1B,IAAKI,EAAQ,eAAiB,eAAeA,EAAQ,cAAc,GAAK,OACxE,QAAS,IAAMH,EAAc,UAAU,CACzC,CAAC,CACH,EACA,CAACL,CAAK,CACR,EAEMU,KAAoB,eACxB,IAAMV,EAAM,gCAAgC,GAAK,QAAQ,QAAQ,QAAiB,EAClF,CAACA,CAAK,CACR,EAQMW,KAA0B,eAAY,IAAM,CAC3CR,EAAW,UACXC,EAAW,SAAS,qBAAuB,eAAiB,aACjEJ,EAAM,gCAAgC,EAAE,MAAM,IAAM,CAAC,CAAC,CACxD,EAAG,CAACA,CAAK,CAAC,EAEV,MAAO,CAAE,qBAAAO,EAAsB,kBAAAG,EAAmB,wBAAAC,CAAwB,CAC5E,EAIA,IAAOtB,EAAQM",
6
+ "names": ["use_in_app_chat_notifications_exports", "__export", "use_in_app_chat_notifications_default", "__toCommonJS", "import_react", "import_use_dashx_provider", "textFromContent", "content", "useInAppChatNotifications", "isOpen", "enabled", "options", "onActivate", "dashX", "useDashXProvider", "isOpenRef", "enabledRef", "optionsRef", "onActivateRef", "isChatFocused", "handleInboundMessage", "message", "body", "requestPermission", "requestPermissionOnOpen"]
7
+ }
@@ -1,7 +1,10 @@
1
+ import type { InAppChatMessageData } from '@dashx/browser';
1
2
  type UseInAppChatHookProps = {
2
3
  identityId: string;
3
4
  idempotencyKey: string;
4
5
  initialMessage?: string;
6
+ enabled?: boolean;
7
+ onInboundMessage?: (message: InAppChatMessageData) => void;
5
8
  };
6
9
  type InAppChatMessage = {
7
10
  id: string;
@@ -33,6 +36,6 @@ type UseInAppChatHookResponse = {
33
36
  * this by starting lazily when the visitor opens it, by which point the provider
34
37
  * has applied the token.
35
38
  */
36
- declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
39
+ declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
37
40
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
38
41
  export default useInAppChat;
@@ -1,2 +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;
1
+ "use strict";var L=Object.create;var A=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var O=(e,n)=>{for(var s in n)A(e,s,{get:n[s],enumerable:!0})},k=(e,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of X(n))!N.call(e,t)&&t!==s&&A(e,t,{get:()=>n[t],enumerable:!(i=$(n,t))||i.enumerable});return e};var m=(e,n,s)=>(s=e!=null?L(K(e)):{},k(n||!e||!e.__esModule?A(s,"default",{value:e,enumerable:!0}):s,e)),T=e=>k(A({},"__esModule",{value:!0}),e);var G={};O(G,{default:()=>B});module.exports=T(G);var x=m(require("uuid-random")),r=require("react"),H=m(require("./use-dashx-provider.js")),w=require("../providers/DashXProvider.js");const W="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}),z=(e,n)=>{const s=new Map,i=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const o=s.get(i(t));(!o||o.isPending)&&s.set(i(t),t)}),[...s.values()].sort((t,o)=>t.createdAt!==o.createdAt?t.createdAt<o.createdAt?-1:1:(t.turnSeq??0)-(o.turnSeq??0))},j=({identityId:e,idempotencyKey:n,initialMessage:s,enabled:i=!0,onInboundMessage:t})=>{const o=(0,H.default)(),{isConnected:P,initializeWebSocket:b}=(0,w.useWebSocket)(),[E,v]=(0,r.useState)(null),[_,R]=(0,r.useState)([]),[q,f]=(0,r.useState)(!0),[D,d]=(0,r.useState)(null),c=(0,r.useRef)(0),M=(0,r.useRef)(null),U=(0,r.useRef)(t);U.current=t;const u=(0,r.useCallback)(p=>{R(a=>z(a,p))},[]);(0,r.useEffect)(()=>{const p=c.current+=1,a=()=>p!==c.current;if(v(null),R([]),d(null),M.current=null,!i)return f(!1),()=>{c.current+=1};f(!0),b();let g;return(async()=>{try{const h=await o.startInAppChatConversation({identityId:e,clientIdempotencyKey:n,...s?{content:{text:s},clientMessageId:`${n.slice(0,122)}-intro`}:{}});if(a())return;const l=h.id;v(l),M.current=l;const C=async()=>{const I=await o.fetchInAppChatMessages({conversationId:l});a()||u(I.map(y))},S=o.subscribeToChannel(`${W}${l}`,I=>{a()||(u([y(I)]),U.current?.(I))},{onReconnectAck:()=>{a()||(d(null),C().catch(()=>{}))}});g=S.unsubscribe;try{await S.ready}catch{a()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(a())return;await C()}catch{a()||d("Failed to start chat")}finally{a()||f(!1)}})(),()=>{c.current+=1,g?.()}},[o,e,n,s,i,b,u]);const F=(0,r.useCallback)(p=>{const a=M.current;if(!p.trim()||!a)return!1;const g=c.current,h=(0,x.default)(),l={id:h,externalUid:`in_app_chat:${h}`,renderedContent:{text:p},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([l]),(async()=>{try{const C=await o.sendInAppChatMessage({conversationId:a,identityId:e,content:{text:p},clientMessageId:h});if(g!==c.current)return;u([y(C)])}catch{g===c.current&&d("Failed to send message")}})(),!0},[o,e,u]);return{conversationId:E,messages:_,isLoading:q,isConnected:P,error:D,sendMessage:F}};var B=j;
2
2
  //# sourceMappingURL=use-in-app-chat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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,eAAAC,EAAAH,GAAA,IAAAI,EAAiB,0BACjBC,EAAyD,iBAGzDC,EAA6B,sCAC7BC,EAA6B,yCAwC7B,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,CAAe,IAAuD,CACxH,MAAMC,KAAQ,EAAAC,SAAiB,EACzB,CAAE,YAAAC,EAAa,oBAAAC,CAAoB,KAAI,gBAAa,EAEpD,CAACC,EAAgBC,CAAiB,KAAI,YAAwB,IAAI,EAClE,CAACC,EAAUC,CAAW,KAAI,YAA6B,CAAC,CAAC,EACzD,CAACC,EAAWC,CAAY,KAAI,YAAS,EAAI,EACzC,C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id_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"]
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAiB,0BACjBC,EAAyD,iBAGzDC,EAA6B,sCAC7BC,EAA6B,yCAiD7B,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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BY,CAAc,CAAC,EAOpG,MAAMW,KAAc,eACjBC,GAA0B,CACzB,MAAMN,EAASR,EAAkB,QAGjC,GAAI,CAACc,EAAK,KAAK,GAAK,CAACN,EAAQ,MAAO,GAIpC,MAAMJ,EAAaL,EAAc,QAC3BgB,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,MAAM/B,EAAM,qBAAqB,CACrD,eAAgBqB,EAChB,WAAA1B,EACA,QAAS,CAAE,KAAAgC,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIX,IAAeL,EAAc,QAAS,OAE1CG,EAAe,CAAC/B,EAAY+C,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFd,IAAeL,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACX,EAAOL,EAAYoB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAX,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAgB,CAAY,CAChF,EAIA,IAAOjD,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", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "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", "uuid", "optimistic", "serverMessage"]
7
7
  }
@@ -1,4 +1,5 @@
1
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';
2
3
  type InAppChatProps = UseInAppChatHookResponse & {
3
4
  withChatHeader?: boolean;
4
5
  withPopoverClose?: boolean;
@@ -6,8 +7,10 @@ type InAppChatProps = UseInAppChatHookResponse & {
6
7
  title?: string;
7
8
  };
8
9
  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;
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;
11
14
  export type { InAppChatProps, InAppChatWrapperProps };
12
15
  export { InAppChat };
13
16
  export default InAppChatWrapper;
@@ -1,2 +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;
1
+ "use strict";var S=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var z=(t,a)=>{for(var r in a)u(t,r,{get:a[r],enumerable:!0})},A=(t,a,r,p)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of H(a))!U.call(t,s)&&s!==r&&u(t,s,{get:()=>a[s],enumerable:!(p=k(a,s))||p.enumerable});return t};var m=(t,a,r)=>(r=t!=null?S(R(t)):{},A(a||!t||!t.__esModule?u(r,"default",{value:t,enumerable:!0}):r,t)),M=t=>A(u({},"__esModule",{value:!0}),t);var B={};z(B,{InAppChat:()=>b,default:()=>K});module.exports=M(B);var e=require("react/jsx-runtime"),l=m(require("@radix-ui/react-scroll-area")),d=require("react"),c=require("lucide-react"),o=require("../components"),f=require("../utils/cn.js"),I=m(require("../hooks/use-auto-scroll.js")),v=m(require("../hooks/use-in-app-chat.js")),w=m(require("../hooks/use-in-app-chat-notifications.js"));const O=t=>{const a=t.renderedContent;return typeof a=="string"?a:a?.text??""},E=t=>t.aiRole?.toUpperCase()==="USER",b=({messages:t,isLoading:a,error:r,sendMessage:p,withChatHeader:s=!1,withPopoverClose:h=!1,borderless:g=!1,title:N="Chat"})=>{const[i,x]=(0,d.useState)(""),{scrollAreaRef:P,scrollToBottom:y}=(0,I.default)();(0,d.useEffect)(()=>{setTimeout(()=>y({smooth:!0}),0)},[t.length,y]);const C=()=>{i.trim()&&p(i)&&x("")},T=n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),C())};return(0,e.jsx)(o.Theme,{asChild:!0,children:(0,e.jsxs)(o.Flex,{direction:"column",className:(0,f.cn)("h-full",!g&&"border border-gray-400/40"),children:[s&&(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:N}),h&&(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:P,className:"h-full grow p-6",children:[(0,e.jsx)(l.Viewport,{className:"h-full",children:(0,e.jsxs)(o.Flex,{direction:"column",gap:3,children:[t.map(n=>(0,e.jsx)("div",{className:(0,f.cn)("max-w-[80%] rounded-lg py-2 px-3",E(n)?"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:O(n)})},n.externalUid||n.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:n=>x(n),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:C,isDisabled:!i.trim(),children:(0,e.jsx)(c.Send,{size:20})})})]})})]})})},F=({identityId:t,idempotencyKey:a,initialMessage:r,notifications:p=!0,...s})=>{const h=(0,w.default)({isOpen:!0,enabled:p!==!1,options:{requestPermissionOn:"manual",...typeof p=="object"?p:void 0}}),g=(0,v.default)({identityId:t,idempotencyKey:a,initialMessage:r,onInboundMessage:h.handleInboundMessage});return(0,e.jsx)(b,{...g,...s})};var K=F;
2
2
  //# sourceMappingURL=InAppChat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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,CA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,oBAAC,OAAI,UAAU,8DACb,mBAAC,YACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOmB,EACP,UAAWM,EACX,SAAWE,GAASP,EAAcO,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,KACA,OAAC,OAAI,UAAU,oBACb,mBAAC,UACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAASH,EACT,WAAY,CAACL,EAAW,KAAK,EAE7B,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"]
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 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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAqEU,IAAAK,EAAA,6BArEVC,EAA4B,0CAC5BC,EAA2C,iBAC3CC,EAAwB,wBAGxBC,EAAsE,yBACtEC,EAAmB,0BACnBC,EAA0B,0CAC1BC,EAIO,0CACPC,EAEO,wDASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFb,EAAY,CAAC,CACjB,SAAAgB,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,E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yBAExD,EAGDC,MACC,OAAC,QACC,GAAG,IACH,KAAM,EACN,UAAU,iEAET,SAAAA,EACH,GAEJ,EACF,KACA,OAACd,EAAW,UAAX,CAAqB,YAAY,WAAW,UAAU,6BACrD,mBAACA,EAAW,MAAX,CAAiB,UAAU,iCAAiC,EAC/D,KACA,OAACA,EAAW,OAAX,EAAkB,GACrB,EACF,KAEA,OAAC,OAAI,UAAU,gDACb,oBAAC,QAAK,IAAK,EAAG,MAAM,MAAM,UAAU,SAClC,oBAAC,OAAI,UAAU,8DACb,mBAAC,YACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOoB,EACP,UAAWM,EACX,SAAWE,GAASP,EAAcO,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,KACA,OAAC,OAAI,UAAU,oBACb,mBAAC,UACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAASH,EACT,WAAY,CAACL,EAAW,KAAK,EAE7B,mBAAC,QAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAaMS,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlI,MAAMC,KAAW,EAAAC,SAA0B,CACzC,OAAQ,GACR,QAASH,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKI,KAAO,EAAAC,SAAa,CACxB,WAAAR,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,SAAO,OAACvC,EAAA,CAAW,GAAGyC,EAAO,GAAGH,EAAO,CACzC,EAMA,IAAOrC,EAAQgC",
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", "import_use_in_app_chat_notifications", "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", "notifications", "props", "notifier", "useInAppChatNotifications", "chat", "useInAppChat"]
7
7
  }
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
7
7
  /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
8
  theme?: ThemeProps;
9
9
  };
10
- declare const InAppChatButton: ({ identityId, idempotencyKey, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
10
+ declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
11
  export type { InAppChatButtonProps };
12
12
  export default InAppChatButton;
@@ -1,2 +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;
1
+ "use strict";var R=Object.create;var i=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},c=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of L(e))!w.call(t,r)&&r!==o&&i(t,r,{get:()=>e[r],enumerable:!(a=x(e,r))||a.enumerable});return t};var g=(t,e,o)=>(o=t!=null?R(S(t)):{},c(e||!t||!t.__esModule?i(o,"default",{value:t,enumerable:!0}):o,t)),N=t=>c(i({},"__esModule",{value:!0}),t);var W={};M(W,{default:()=>F});module.exports=N(W);var p=require("react/jsx-runtime"),s=require("react"),C=require("lucide-react"),n=require("../components"),P=require("./InAppChat.js"),d=g(require("../hooks/use-in-app-chat.js")),b=g(require("../hooks/use-in-app-chat-notifications.js"));const q={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},z=({identityId:t,idempotencyKey:e,initialMessage:o,notifications:a=!0,position:r="bottom-right",theme:I,...A})=>{const[h,l]=(0,s.useState)(!1),u=(0,s.useRef)(!1);h&&(u.current=!0);const O=u.current,v=(0,s.useCallback)(()=>l(!0),[]),{handleInboundMessage:T,requestPermissionOnOpen:m}=(0,b.default)({isOpen:h,enabled:a!==!1,options:typeof a=="object"?a:void 0,onActivate:v}),y=(0,s.useCallback)(f=>{f&&m(),l(f)},[m]),B=(0,d.default)({identityId:t,idempotencyKey:e,initialMessage:o,enabled:O,onInboundMessage:T});return(0,p.jsx)(n.Theme,{...I,children:(0,p.jsx)(n.Flex,{className:`fixed z-50 ${q[r]}`,children:(0,p.jsxs)(n.Popover.Root,{open:h,onOpenChange:y,children:[(0,p.jsx)(n.Popover.Trigger,{children:(0,p.jsx)(n.Button,{shape:"square",roundness:"full",variant:"fill",size:"large",children:(0,p.jsx)(C.MessageCircle,{})})}),(0,p.jsx)(n.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:(0,p.jsx)(P.InAppChat,{...B,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...A})})]})})})};var F=z;
2
2
  //# sourceMappingURL=InAppChatButton.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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"]
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": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GA2EQ,IAAAI,EAAA,6BA3ERC,EAAqD,iBACrDC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,0BACtDC,EAAyB,0CACzBC,EAAsC,wDAYtC,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,KAAI,YAAS,EAAK,EAMpCC,KAAe,UAAO,EAAK,EAC7BF,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,KAAO,eAAY,IAAMH,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,KAAI,EAAAC,SAA0B,CAClF,OAAAP,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKI,KAAmB,eACtBC,GAAsB,CACjBA,GAAUH,EAAwB,EACtCL,EAAUQ,CAAQ,CACpB,EACA,CAACH,CAAuB,CAC1B,EAEMI,KAAO,EAAAC,SAAa,CACxB,WAAAlB,EACA,eAAAC,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,SACE,OAAC,SAAO,GAAGP,EACT,mBAAC,QAAK,UAAW,cAAcP,EAAeM,CAAQ,CAAC,GACrD,oBAAC,UAAQ,KAAR,CAAa,KAAMG,EAAQ,aAAcQ,EACxC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,mBAAC,kBAAc,EACjB,EACF,KAKA,OAAC,UAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,mBAAC,aACE,GAAGE,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGX,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOjB,EAAQU",
6
+ "names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "useInAppChatNotifications", "handleOpenChange", "nextOpen", "chat", "useInAppChat"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ declare const NotificationBell: () => import("react/jsx-runtime").JSX.Element;
2
+ export default NotificationBell;
@@ -0,0 +1,2 @@
1
+ "use strict";var l=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var m=(a,r)=>{for(var n in r)l(a,n,{get:r[n],enumerable:!0})},T=(a,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of u(r))!c.call(a,o)&&o!==n&&l(a,o,{get:()=>r[o],enumerable:!(s=g(r,o))||s.enumerable});return a};var h=a=>T(l({},"__esModule",{value:!0}),a);var f={};m(f,{default:()=>x});module.exports=h(f);var t=require("react/jsx-runtime"),d=require("date-fns"),p=require("../hooks/index.js"),e=require("../components"),i=require("../icons/index.js");const v=()=>{let{markNotificationAsRead:a,markNotificationAsUnread:r,notifications:n,unreadNotificationsCount:s}=(0,p.useInApp)();return(0,t.jsx)(e.Theme,{children:(0,t.jsxs)(e.Popover.Root,{children:[(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Popover.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:s?"fill":"ghost",children:(0,t.jsx)(i.Inbox,{})})})}),(0,t.jsx)(e.Tooltip.Content,{content:"Notification"})]}),(0,t.jsxs)(e.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:[(0,t.jsx)(e.Popover.Header,{asChild:!0,children:(0,t.jsxs)(e.Flex,{justify:"between",align:"center",children:[(0,t.jsx)(e.Heading,{size:3,children:"Notifications"}),(0,t.jsx)(e.Popover.Close,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,t.jsx)(i.X,{})})})]})}),(0,t.jsx)(e.Popover.Body,{children:(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[n.length===0&&(0,t.jsx)(e.Flex,{justify:"center",align:"center",children:(0,t.jsx)(e.Text,{variant:"tertiary",size:2,children:"No notifications yet."})}),n.map(o=>(0,t.jsx)(e.Card,{children:(0,t.jsxs)(e.Flex,{align:"center",gap:4,justify:"between",children:[(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[(0,t.jsx)(e.Text,{as:"p",variant:"secondary",weight:"semibold",size:2,children:o.renderedContent.body}),(0,t.jsx)(e.Text,{size:1,variant:"tertiary",children:(0,d.intlFormatDistance)(o.sentAt,new Date)})]}),(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",variant:"ghost",roundness:"full",mode:o.readAt?"subtle":"distinct",onPress:()=>{o.readAt?r(o.id):a(o.id)},children:o.readAt?(0,t.jsx)(i.MailOpen,{}):(0,t.jsx)(i.Mail,{})})}),(0,t.jsx)(e.Tooltip.Content,{content:o.readAt?"Mark as unread":"Mark as read"})]})]})},o.id))]})}),(0,t.jsx)(e.Popover.Footer,{asChild:!0,children:(0,t.jsx)(e.Text,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var x=v;
2
+ //# sourceMappingURL=NotificationBell.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/widgets/NotificationBell.tsx"],
4
+ "sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </Text>\n </Popover.Footer>\n </Popover.Content>\n </Popover.Root>\n </Theme>\n );\n};\n\nexport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,WAAW,KAAM,EACtD,SAAAA,EAAa,gBAAgB,KAChC,KACA,OAAC,QAAK,KAAM,EAAG,QAAQ,WACpB,kCAAmBA,EAAa,OAAQ,IAAI,IAAM,EACrD,GACF,KACA,QAAC,UAAQ,KAAR,CACC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UACC,MAAM,SACN,QAAQ,QACR,UAAU,OACV,KAAMA,EAAa,OAAS,SAAW,WACvC,QAAS,IAAM,CACTA,EAAa,OACfH,EAAyBG,EAAa,EAAE,EAExCJ,EAAuBI,EAAa,EAAE,CAE1C,EAEC,SAAAA,EAAa,UAAS,OAAC,aAAS,KAAK,OAAC,SAAK,EAC9C,EACF,KACA,OAAC,UAAQ,QAAR,CACC,QAASA,EAAa,OAAS,iBAAmB,eACpD,GACF,GACF,GAhCSA,EAAa,EAiCxB,CACD,GACH,EACF,KACA,OAAC,UAAQ,OAAR,CAAe,QAAO,GACrB,mBAAC,QAAK,GAAG,IAAI,MAAM,SAAS,MAAM,SAAS,QAAQ,WAAW,KAAM,EAAG,4BAEvE,EACF,GACF,GACF,EACF,CAEJ,EAEA,IAAOZ,EAAQO",
6
+ "names": ["NotificationBell_exports", "__export", "NotificationBell_default", "__toCommonJS", "import_jsx_runtime", "import_date_fns", "import_hooks", "import_components", "import_icons", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification"]
7
+ }
@@ -3,4 +3,6 @@ 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
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';
6
8
  export { default as useProductRelease } from './use-product-release.js';
@@ -1,2 +1,2 @@
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};
1
+ import{useWebSocket as o}from"../providers/DashXProvider.js";import{default as p}from"./use-agent.js";import{default as r}from"./use-dashx-provider.js";import{default as u}from"./use-in-app.js";import{default as n}from"./use-in-app-chat.js";import{default as m}from"./use-in-app-chat-notifications.js";import{default as l}from"./use-product-release.js";export{p as useAgent,r as useDashXProvider,u as useInApp,n as useInAppChat,m as useInAppChatNotifications,l as useProductRelease,o 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 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",
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 useInAppChatNotifications } from './use-in-app-chat-notifications.js';\nexport type { InAppChatNotificationOptions } from './use-in-app-chat-notifications.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,MAA4C,qCAErD,OAAoB,WAAXA,MAAoC",
6
6
  "names": ["useWebSocket", "default"]
7
7
  }
@@ -0,0 +1,27 @@
1
+ import type { InAppChatMessageData } from '@dashx/browser';
2
+ type InAppChatNotificationOptions = {
3
+ title?: string;
4
+ icon?: string;
5
+ renderBody?: (message: InAppChatMessageData) => string;
6
+ requestPermissionOn?: 'firstOpen' | 'manual';
7
+ };
8
+ type UseInAppChatNotificationsProps = {
9
+ isOpen: boolean;
10
+ enabled?: boolean;
11
+ options?: InAppChatNotificationOptions;
12
+ onActivate?: () => void;
13
+ };
14
+ /**
15
+ * Foreground browser notifications for incoming In-App Chat messages. Returns a
16
+ * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it
17
+ * fires a notification only for agent/AI replies that arrive while the chat
18
+ * isn't focused (panel closed, or tab hidden/unfocused) and only once the
19
+ * visitor has granted permission.
20
+ */
21
+ declare const useInAppChatNotifications: ({ isOpen, enabled, options, onActivate, }: UseInAppChatNotificationsProps) => {
22
+ handleInboundMessage: (message: InAppChatMessageData) => void;
23
+ requestPermission: () => Promise<NotificationPermission>;
24
+ requestPermissionOnOpen: () => void;
25
+ };
26
+ export type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };
27
+ export default useInAppChatNotifications;
@@ -0,0 +1,2 @@
1
+ import{useCallback as s,useRef as o}from"react";import I from"./use-dashx-provider.js";const y=t=>typeof t=="string"?t:t?.text??t?.body??"",A=({isOpen:t,enabled:a=!0,options:c,onActivate:u})=>{const e=I(),p=o(t);p.current=t;const i=o(a);i.current=a;const n=o(c);n.current=c;const f=o(u);f.current=u;const h=()=>!(!p.current||typeof document>"u"||document.hidden||typeof document.hasFocus=="function"&&!document.hasFocus()),l=s(r=>{if(!i.current||(r.aiRole??"").toUpperCase()==="USER"||h())return;const d=n.current?.renderBody?.(r)??y(r.renderedContent);d&&e.showInAppChatNotification?.({title:n.current?.title??"New message",body:d,icon:n.current?.icon,tag:r.conversationId?`in_app_chat:${r.conversationId}`:void 0,onClick:()=>f.current?.()})},[e]),m=s(()=>e.requestNotificationPermission?.()??Promise.resolve("denied"),[e]),C=s(()=>{i.current&&(n.current?.requestPermissionOn??"firstOpen")==="firstOpen"&&e.requestNotificationPermission?.().catch(()=>{})},[e]);return{handleInboundMessage:l,requestPermission:m,requestPermissionOnOpen:C}};var P=A;export{P as default};
2
+ //# sourceMappingURL=use-in-app-chat-notifications.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/hooks/use-in-app-chat-notifications.ts"],
4
+ "sourcesContent": ["import { useCallback, useRef } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\n\ntype InAppChatNotificationOptions = {\n // Notification title. Defaults to 'New message'.\n title?: string;\n // Icon URL shown in the notification.\n icon?: string;\n // Custom body text from the inbound message; defaults to the message text.\n renderBody?: (message: InAppChatMessageData) => string;\n // When to request notification permission. 'firstOpen' (the default for the\n // launcher) requests it the first time the visitor opens chat \u2014 a real user\n // gesture, which browsers require for a non-penalized prompt. 'manual' never\n // auto-requests (use for always-visible surfaces, where the embedder drives\n // the prompt via the returned `requestPermission`).\n requestPermissionOn?: 'firstOpen' | 'manual';\n};\n\ntype UseInAppChatNotificationsProps = {\n // Whether the chat surface is currently open/visible. Combined with tab\n // visibility + window focus to decide if the visitor is actively looking at\n // chat (in which case we don't notify).\n isOpen: boolean;\n // `false` disables notifications entirely.\n enabled?: boolean;\n options?: InAppChatNotificationOptions;\n // Invoked when the visitor clicks a notification \u2014 focus is handled by the\n // SDK; this opens the chat panel.\n onActivate?: () => void;\n};\n\nconst textFromContent = (content: any): string => {\n if (typeof content === 'string') return content;\n return content?.text ?? content?.body ?? '';\n};\n\n/**\n * Foreground browser notifications for incoming In-App Chat messages. Returns a\n * `handleInboundMessage` to pass as `useInAppChat`'s `onInboundMessage`; it\n * fires a notification only for agent/AI replies that arrive while the chat\n * isn't focused (panel closed, or tab hidden/unfocused) and only once the\n * visitor has granted permission.\n */\nconst useInAppChatNotifications = ({\n isOpen,\n enabled = true,\n options,\n onActivate,\n}: UseInAppChatNotificationsProps) => {\n const dashX = useDashXProvider();\n\n // Latest values for the message handler, so it stays referentially stable\n // (it's wired into the chat hook's subscription).\n const isOpenRef = useRef(isOpen);\n isOpenRef.current = isOpen;\n const enabledRef = useRef(enabled);\n enabledRef.current = enabled;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const onActivateRef = useRef(onActivate);\n onActivateRef.current = onActivate;\n\n const isChatFocused = (): boolean => {\n if (!isOpenRef.current) return false;\n if (typeof document === 'undefined') return false;\n if (document.hidden) return false;\n if (typeof document.hasFocus === 'function' && !document.hasFocus()) return false;\n return true;\n };\n\n const handleInboundMessage = useCallback(\n (message: InAppChatMessageData) => {\n if (!enabledRef.current) return;\n // Agent/AI replies only \u2014 never the visitor's own echoed message.\n if ((message.aiRole ?? '').toUpperCase() === 'USER') return;\n // Don't interrupt a visitor who's actively looking at the chat.\n if (isChatFocused()) return;\n\n const body = optionsRef.current?.renderBody?.(message) ?? textFromContent(message.renderedContent);\n if (!body) return;\n\n dashX.showInAppChatNotification?.({\n title: optionsRef.current?.title ?? 'New message',\n body,\n icon: optionsRef.current?.icon,\n tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,\n onClick: () => onActivateRef.current?.(),\n });\n },\n [dashX],\n );\n\n const requestPermission = useCallback(\n () => dashX.requestNotificationPermission?.() ?? Promise.resolve('denied' as const),\n [dashX],\n );\n\n // Call this SYNCHRONOUSLY from the surface's open event (a real user gesture)\n // so the permission prompt lands inside the browser's transient activation\n // window. Requesting from an effect after the click has unwound is\n // ignored/rejected by some browsers. Honors `requestPermissionOn` ('manual'\n // skips it), and is safe to call on every open (no-ops once permission is\n // decided \u2014 see Client.requestNotificationPermission).\n const requestPermissionOnOpen = useCallback(() => {\n if (!enabledRef.current) return;\n if ((optionsRef.current?.requestPermissionOn ?? 'firstOpen') !== 'firstOpen') return;\n dashX.requestNotificationPermission?.().catch(() => {});\n }, [dashX]);\n\n return { handleInboundMessage, requestPermission, requestPermissionOnOpen };\n};\n\nexport type { InAppChatNotificationOptions, UseInAppChatNotificationsProps };\n\nexport default useInAppChatNotifications;\n"],
5
+ "mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,MAAc,QAGpC,OAAOC,MAAsB,0BA8B7B,MAAMC,EAAmBC,GACnB,OAAOA,GAAY,SAAiBA,EACjCA,GAAS,MAAQA,GAAS,MAAQ,GAUrCC,EAA4B,CAAC,CACjC,OAAAC,EACA,QAAAC,EAAU,GACV,QAAAC,EACA,WAAAC,CACF,IAAsC,CACpC,MAAMC,EAAQR,EAAiB,EAIzBS,EAAYV,EAAOK,CAAM,EAC/BK,EAAU,QAAUL,EACpB,MAAMM,EAAaX,EAAOM,CAAO,EACjCK,EAAW,QAAUL,EACrB,MAAMM,EAAaZ,EAAOO,CAAO,EACjCK,EAAW,QAAUL,EACrB,MAAMM,EAAgBb,EAAOQ,CAAU,EACvCK,EAAc,QAAUL,EAExB,MAAMM,EAAgB,IAChB,GAACJ,EAAU,SACX,OAAO,SAAa,KACpB,SAAS,QACT,OAAO,SAAS,UAAa,YAAc,CAAC,SAAS,SAAS,GAI9DK,EAAuBhB,EAC1BiB,GAAkC,CAKjC,GAJI,CAACL,EAAW,UAEXK,EAAQ,QAAU,IAAI,YAAY,IAAM,QAEzCF,EAAc,EAAG,OAErB,MAAMG,EAAOL,EAAW,SAAS,aAAaI,CAAO,GAAKd,EAAgBc,EAAQ,eAAe,EAC5FC,GAELR,EAAM,4BAA4B,CAChC,MAAOG,EAAW,SAAS,OAAS,cACpC,KAAAK,EACA,KAAML,EAAW,SAAS,KAC1B,IAAKI,EAAQ,eAAiB,eAAeA,EAAQ,cAAc,GAAK,OACxE,QAAS,IAAMH,EAAc,UAAU,CACzC,CAAC,CACH,EACA,CAACJ,CAAK,CACR,EAEMS,EAAoBnB,EACxB,IAAMU,EAAM,gCAAgC,GAAK,QAAQ,QAAQ,QAAiB,EAClF,CAACA,CAAK,CACR,EAQMU,EAA0BpB,EAAY,IAAM,CAC3CY,EAAW,UACXC,EAAW,SAAS,qBAAuB,eAAiB,aACjEH,EAAM,gCAAgC,EAAE,MAAM,IAAM,CAAC,CAAC,CACxD,EAAG,CAACA,CAAK,CAAC,EAEV,MAAO,CAAE,qBAAAM,EAAsB,kBAAAG,EAAmB,wBAAAC,CAAwB,CAC5E,EAIA,IAAOC,EAAQhB",
6
+ "names": ["useCallback", "useRef", "useDashXProvider", "textFromContent", "content", "useInAppChatNotifications", "isOpen", "enabled", "options", "onActivate", "dashX", "isOpenRef", "enabledRef", "optionsRef", "onActivateRef", "isChatFocused", "handleInboundMessage", "message", "body", "requestPermission", "requestPermissionOnOpen", "use_in_app_chat_notifications_default"]
7
+ }
@@ -1,7 +1,10 @@
1
+ import type { InAppChatMessageData } from '@dashx/browser';
1
2
  type UseInAppChatHookProps = {
2
3
  identityId: string;
3
4
  idempotencyKey: string;
4
5
  initialMessage?: string;
6
+ enabled?: boolean;
7
+ onInboundMessage?: (message: InAppChatMessageData) => void;
5
8
  };
6
9
  type InAppChatMessage = {
7
10
  id: string;
@@ -33,6 +36,6 @@ type UseInAppChatHookResponse = {
33
36
  * this by starting lazily when the visitor opens it, by which point the provider
34
37
  * has applied the token.
35
38
  */
36
- declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
39
+ declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
37
40
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
38
41
  export default useInAppChat;
@@ -1,2 +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};
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
2
  //# sourceMappingURL=use-in-app-chat.js.map