@bitpalm/ai-agents 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/headless.cjs +6 -6
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +14 -1
- package/dist/headless.d.ts +14 -1
- package/dist/headless.js +7 -7
- package/dist/headless.js.map +1 -1
- package/dist/react.cjs +8 -8
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +17 -1
- package/dist/react.d.ts +17 -1
- package/dist/react.js +8 -8
- package/dist/react.js.map +1 -1
- package/package.json +1 -1
package/dist/react.d.cts
CHANGED
|
@@ -13,6 +13,8 @@ interface ChatCard {
|
|
|
13
13
|
};
|
|
14
14
|
}
|
|
15
15
|
interface ChatMessage {
|
|
16
|
+
/** Set on messages from history() and updates(). */
|
|
17
|
+
id?: string;
|
|
16
18
|
role: "user" | "assistant";
|
|
17
19
|
text: string;
|
|
18
20
|
createdAt?: string;
|
|
@@ -81,6 +83,15 @@ interface SendResult {
|
|
|
81
83
|
*/
|
|
82
84
|
handoff?: boolean;
|
|
83
85
|
}
|
|
86
|
+
/** What happened while your team has the conversation. */
|
|
87
|
+
interface ChatUpdates {
|
|
88
|
+
/** False once your team gave the conversation back to the agent. */
|
|
89
|
+
handoff: boolean;
|
|
90
|
+
/** Someone of your team is typing right now. */
|
|
91
|
+
teamTyping: boolean;
|
|
92
|
+
/** Replies of your team since the last call, oldest first. */
|
|
93
|
+
messages: ChatMessage[];
|
|
94
|
+
}
|
|
84
95
|
interface Identity {
|
|
85
96
|
name?: string;
|
|
86
97
|
email?: string;
|
|
@@ -106,6 +117,8 @@ interface ChatClient {
|
|
|
106
117
|
send(message: string, options?: SendOptions): Promise<SendResult>;
|
|
107
118
|
/** The messages of the current conversation, or of the latest one of this visitor. */
|
|
108
119
|
history(): Promise<ChatMessage[]>;
|
|
120
|
+
/** New replies of your team and whether someone is typing. Call it every few seconds while handoff is true. */
|
|
121
|
+
updates(): Promise<ChatUpdates>;
|
|
109
122
|
/** Tells BitPalm who the logged-in user is. */
|
|
110
123
|
identify(identity: Identity): Promise<void>;
|
|
111
124
|
/** A photo for the next message, when the agent takes photos. */
|
|
@@ -283,6 +296,8 @@ type ChatStatus = "idle" | "streaming" | "error";
|
|
|
283
296
|
interface UseBitPalmChatOptions extends ChatClientOptions {
|
|
284
297
|
/** Load the last conversation of this visitor on start. Defaults to true. */
|
|
285
298
|
loadHistory?: boolean;
|
|
299
|
+
/** Show your team's replies as they come while it has the conversation. Defaults to true. */
|
|
300
|
+
live?: boolean;
|
|
286
301
|
}
|
|
287
302
|
/**
|
|
288
303
|
* Your own chat UI in React, with BitPalm behind it. Keeps the messages,
|
|
@@ -300,9 +315,10 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
|
|
|
300
315
|
error: BitPalmApiError | null;
|
|
301
316
|
agent: AgentConfig | null;
|
|
302
317
|
handoff: boolean;
|
|
318
|
+
teamTyping: boolean;
|
|
303
319
|
refresh: () => Promise<void>;
|
|
304
320
|
reset: () => void;
|
|
305
321
|
client: ChatClient;
|
|
306
322
|
};
|
|
307
323
|
|
|
308
|
-
export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
|
|
324
|
+
export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type ChatUpdates, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
|
package/dist/react.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ interface ChatCard {
|
|
|
13
13
|
};
|
|
14
14
|
}
|
|
15
15
|
interface ChatMessage {
|
|
16
|
+
/** Set on messages from history() and updates(). */
|
|
17
|
+
id?: string;
|
|
16
18
|
role: "user" | "assistant";
|
|
17
19
|
text: string;
|
|
18
20
|
createdAt?: string;
|
|
@@ -81,6 +83,15 @@ interface SendResult {
|
|
|
81
83
|
*/
|
|
82
84
|
handoff?: boolean;
|
|
83
85
|
}
|
|
86
|
+
/** What happened while your team has the conversation. */
|
|
87
|
+
interface ChatUpdates {
|
|
88
|
+
/** False once your team gave the conversation back to the agent. */
|
|
89
|
+
handoff: boolean;
|
|
90
|
+
/** Someone of your team is typing right now. */
|
|
91
|
+
teamTyping: boolean;
|
|
92
|
+
/** Replies of your team since the last call, oldest first. */
|
|
93
|
+
messages: ChatMessage[];
|
|
94
|
+
}
|
|
84
95
|
interface Identity {
|
|
85
96
|
name?: string;
|
|
86
97
|
email?: string;
|
|
@@ -106,6 +117,8 @@ interface ChatClient {
|
|
|
106
117
|
send(message: string, options?: SendOptions): Promise<SendResult>;
|
|
107
118
|
/** The messages of the current conversation, or of the latest one of this visitor. */
|
|
108
119
|
history(): Promise<ChatMessage[]>;
|
|
120
|
+
/** New replies of your team and whether someone is typing. Call it every few seconds while handoff is true. */
|
|
121
|
+
updates(): Promise<ChatUpdates>;
|
|
109
122
|
/** Tells BitPalm who the logged-in user is. */
|
|
110
123
|
identify(identity: Identity): Promise<void>;
|
|
111
124
|
/** A photo for the next message, when the agent takes photos. */
|
|
@@ -283,6 +296,8 @@ type ChatStatus = "idle" | "streaming" | "error";
|
|
|
283
296
|
interface UseBitPalmChatOptions extends ChatClientOptions {
|
|
284
297
|
/** Load the last conversation of this visitor on start. Defaults to true. */
|
|
285
298
|
loadHistory?: boolean;
|
|
299
|
+
/** Show your team's replies as they come while it has the conversation. Defaults to true. */
|
|
300
|
+
live?: boolean;
|
|
286
301
|
}
|
|
287
302
|
/**
|
|
288
303
|
* Your own chat UI in React, with BitPalm behind it. Keeps the messages,
|
|
@@ -300,9 +315,10 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
|
|
|
300
315
|
error: BitPalmApiError | null;
|
|
301
316
|
agent: AgentConfig | null;
|
|
302
317
|
handoff: boolean;
|
|
318
|
+
teamTyping: boolean;
|
|
303
319
|
refresh: () => Promise<void>;
|
|
304
320
|
reset: () => void;
|
|
305
321
|
client: ChatClient;
|
|
306
322
|
};
|
|
307
323
|
|
|
308
|
-
export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
|
|
324
|
+
export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type ChatUpdates, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
|
package/dist/react.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{useCallback as _e,useEffect as Me,useRef as fe,useState as J}from"react";function ct(n){if(n===!1)return"off";if(typeof n=="string"){let t=n.trim().toLowerCase();if(["false","off","0","no","none"].includes(t))return"off";if(t==="events")return"events"}return"bubble"}function dt(n,t){let i=n.createElement("div");i.setAttribute("data-bitpalm-trigger",""),i.style.cssText=`max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${t.zIndex-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`,i.style.position="fixed",i.style.right="24px",i.style.bottom=`${t.bottom}px`;let s=n.createElement("p");s.style.cssText="font-size:14px;color:#1f2937;margin:0;",s.textContent=t.message;let m=n.createElement("div");m.style.cssText="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;";let g=n.createElement("button");return g.type="button",g.setAttribute("aria-label","Close"),g.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",g.textContent="\u2715",g.onclick=p=>{p.stopPropagation(),t.onDismiss()},i.onclick=()=>t.onEngage(),i.append(s,m,g),i}var _t=["dark","dark-mode","dark-theme","theme-dark"],Mt=["light","light-mode","light-theme","theme-light"],ft=["data-theme","data-color-scheme","data-color-mode","data-mode","data-bs-theme"],gt="(prefers-color-scheme: dark)";function ue(n){return n==="light"||n==="dark"?n:"auto"}function ut(n){if(!n)return null;if(_t.some(t=>n.classList.contains(t)))return"dark";if(Mt.some(t=>n.classList.contains(t)))return"light";for(let t of ft){let i=(n.getAttribute(t)||"").toLowerCase();if(i.includes("dark"))return"dark";if(i.includes("light"))return"light"}return null}function Ae(n){let t=n/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function mt(n,t){if(!n)return null;let i=t.getComputedStyle(n).backgroundColor.match(/rgba?\(([^)]+)\)/);if(!i)return null;let[s,m,g,p=1]=i[1].split(/[\s,/]+/).filter(Boolean).map(Number);return[s,m,g,p].some(c=>Number.isNaN(c))||p<.5?null:.2126*Ae(s)+.7152*Ae(m)+.0722*Ae(g)<.2?"dark":"light"}function Bt(n,t){let i=t.getComputedStyle(n.documentElement).colorScheme||"",s=n.querySelector('meta[name="color-scheme"]')?.getAttribute("content")||"",m=`${i} ${s}`.toLowerCase();return m.includes("dark")?m.includes("light")?t.matchMedia?.(gt).matches?"dark":"light":"dark":null}function Z(n=document,t=window){return ut(n.documentElement)??ut(n.body)??mt(n.body,t)??mt(n.documentElement,t)??Bt(n,t)??"light"}function Le(n,t=document,i=window){let s=Z(t,i),m=!1,g=()=>{m=!1;let d=Z(t,i);d!==s&&(s=d,n(d))},p=()=>{m||(m=!0,typeof i.requestAnimationFrame=="function"?i.requestAnimationFrame(g):setTimeout(g,16))},b=typeof MutationObserver<"u"?new MutationObserver(p):null,c={attributes:!0,attributeFilter:["class","style",...ft]};b?.observe(t.documentElement,c),t.body&&b?.observe(t.body,c);let w=typeof i.matchMedia=="function"?i.matchMedia(gt):null;return w?.addEventListener?.("change",p),()=>{b?.disconnect(),w?.removeEventListener?.("change",p)}}var $t="https://agents.bitpalm.ai",I="_bp_",Ot=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),Rt=8e3,pt=4096,ht=`${I}identify_signature`,yt=`${I}identify_fingerprint`,bt=`${I}identify_sent_at`,vt="0 4px 14px rgba(0,0,0,0.18)";function Ht(n){return[n.external_user_id||"",n.email||"",n.phone||"",n.name||"",n.company||"",n.signature||"",n.signed_at!=null?String(n.signed_at):"",n.signature_version||"",n.identify_source||""].join("|").toLowerCase()}function h(n,t=180){return n?n.replace(/\s+/g," ").trim().slice(0,t):""}function Dt(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function z(n,t){for(let i of t)if(n.includes(i))return!0;return!1}function H(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function $(n){let t=h(n,50);if(!t)return"";let i=t.startsWith("+"),s=t.replace(/\D/g,"");return s.length<6?"":`${i?"+":""}${s.slice(0,20)}`}function wt(n){let t=h(n,140).toLowerCase();return!t||!H(t)?"":t}function Y(n,t){for(let i of t){let s=n.querySelector(i),m=h(s?.value);if(m)return m}return""}function Ut(n){return h(n.getAttribute("data-bp-field")||n.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function Nt(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wt(n,t){let i=[],s=(c,w=140)=>{let d=h(c,w);d&&i.push(d)};s(t.name),s(t.id),s(t.getAttribute("autocomplete")),s(t.getAttribute("placeholder")),s(t.getAttribute("aria-label")),s(t.getAttribute("data-field")),s(t.getAttribute("data-name")),s(t.getAttribute("data-label")),s(t.getAttribute("data-bp-field")),s(t.getAttribute("data-bitpalm-field"));let m=new Set,g=c=>{let w=h(c,200);!w||m.has(w)||(m.add(w),i.push(w))};for(let c of Array.from(t.labels||[]))g(c.textContent);if(t.id){let c=n.querySelector(`label[for="${Nt(t.id)}"]`);g(c?.textContent)}let p=t.closest("label");g(p?.textContent);let b=t.getAttribute("aria-labelledby");if(b)for(let c of b.split(/\s+/)){if(!c)continue;let w=n.ownerDocument.getElementById(c);g(w?.textContent)}return i}function jt(n){let t=h(Y(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),i=$(Y(n,["[data-bp-phone]","[data-bitpalm-phone]"])),s=h(Y(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),m=h(Y(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),g=h(Y(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),p=h(Y(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let d of Array.from(n.elements)){if(!(d instanceof HTMLInputElement||d instanceof HTMLTextAreaElement||d instanceof HTMLSelectElement)||d.disabled||d instanceof HTMLInputElement&&Ot.has(d.type.toLowerCase()))continue;let y=Ut(d),L=d.hasAttribute("data-bp-email")||d.hasAttribute("data-bitpalm-email")||d.hasAttribute("data-bp-phone")||d.hasAttribute("data-bitpalm-phone")||d.hasAttribute("data-bp-name")||d.hasAttribute("data-bitpalm-name")||d.hasAttribute("data-bp-full-name")||d.hasAttribute("data-bitpalm-full-name")||d.hasAttribute("data-bp-first-name")||d.hasAttribute("data-bitpalm-first-name")||d.hasAttribute("data-bp-last-name")||d.hasAttribute("data-bitpalm-last-name")||d.hasAttribute("data-bp-company")||d.hasAttribute("data-bitpalm-company")||!!y;if(d instanceof HTMLInputElement&&d.type.toLowerCase()==="hidden"&&!L)continue;let l=h(d.value);if(!l)continue;let u=d instanceof HTMLInputElement?d.type.toLowerCase():"",o=Dt(Wt(n,d).join(" "));if(!t&&y==="email"&&H(l)){t=l.toLowerCase();continue}if(!i&&(y==="phone"||y==="tel"||y==="mobile"||y==="whatsapp")){let C=$(l);if(C){i=C;continue}}if(!p&&y==="company"){p=h(l,160);continue}if(!m&&(y==="first-name"||y==="firstname")){m=h(l,100);continue}if(!g&&(y==="last-name"||y==="lastname"||y==="surname")){g=h(l,100);continue}if(!s&&(y==="name"||y==="full-name"||y==="fullname")){!H(l)&&!$(l)&&(s=h(l,140));continue}let v=u==="email"||z(o,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),_=u==="tel"||z(o,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),T=z(o,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),f=z(o,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),S=z(o,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),E=z(o,[" full name "," fullname "," contact name "," name "])&&!v&&!_;if(!t&&v&&H(l)){t=l.toLowerCase();continue}if(!i&&_){let C=$(l);if(C){i=C;continue}}if(!p&&T){p=h(l,160);continue}if(!m&&f){m=h(l,100);continue}if(!g&&S){g=h(l,100);continue}if(!s&&E&&!H(l)&&!$(l)){s=h(l,140);continue}!t&&H(l)&&(t=l.toLowerCase())}if(s&&(H(s)||$(s))&&(s=""),p&&(H(p)||$(p))&&(p=""),s||(s=h([m,g].filter(Boolean).join(" "),140)),s&&t&&s.toLowerCase()===t.toLowerCase()&&(s=""),!!!(t||i)&&!!!(s&&p))return null;let w={...s?{name:s}:{},...t?{email:t}:{},...i?{phone:i}:{},...p?{company:p}:{}};return Object.keys(w).length>0?w:null}function Ft(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function ke(n,t=1200){if(typeof window<"u"&&"requestIdleCallback"in window){window.requestIdleCallback(n,{timeout:t});return}setTimeout(n,Math.min(t,300))}function Pe(){if(typeof window>"u")return!1;let n=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(n))return!0;let i=window.matchMedia("(pointer: coarse)").matches,s=window.matchMedia("(hover: none)").matches,m=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return i&&s&&m<=900}function xt(n){let{slug:t,locale:i=Ft(),baseUrl:s=$t,token:m,zIndex:g=9999,autoIdentify:p=!0,launcher:b=!0}=n,c=document,w=ue(n.theme),d=w==="auto"?Z():w,y=null,L=ct(n.triggers),l=L,u=null,o=c.createElement("iframe");o.setAttribute("data-bitpalm-chat","");let v=`${s}/t/${t}/widget`,_=new URLSearchParams({locale:i,theme:d});m&&_.set("token",m),l==="off"&&_.set("triggers","off"),o.src=`${v}?${_.toString()}`,o.allow="clipboard-write; microphone",o.setAttribute("allowtransparency","true"),o.loading="lazy",o.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${g};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;let T=new URL(o.src).origin,f=c.createElement("div");if(f.setAttribute("role","button"),f.setAttribute("aria-label","Chat"),f.setAttribute("data-bitpalm-launcher",""),f.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${g-1};background:#171717;box-shadow:${vt};transition:transform .2s,opacity .3s;opacity:0;`,f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',f.onmouseenter=()=>{f.style.transform="scale(1.05)"},f.onmouseleave=()=>{f.style.transform="scale(1)"},f.onclick=()=>Q(),b&&c.body.appendChild(f),!c.getElementById("_bp_fade")){let e=c.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",c.head.appendChild(e)}let S=null,E=!1,C=!1,D=!1,G=!1,ee=!1,te=()=>{D||(D=!0,c.body.appendChild(o))},ne=!1,ge=0,oe={overflow:"",overscrollBehavior:""},k={overflow:"",overscrollBehavior:"",position:"",top:"",left:"",right:"",width:""},Be=()=>{if(ne||!Pe())return;let r=c.documentElement,a=c.body;ge=window.scrollY||window.pageYOffset||0,oe.overflow=r.style.overflow,oe.overscrollBehavior=r.style.overscrollBehavior,k.overflow=a.style.overflow,k.overscrollBehavior=a.style.overscrollBehavior,k.position=a.style.position,k.top=a.style.top,k.left=a.style.left,k.right=a.style.right,k.width=a.style.width,r.style.overflow="hidden",r.style.overscrollBehavior="none",a.style.overflow="hidden",a.style.overscrollBehavior="none",a.style.position="fixed",a.style.top=`-${ge}px`,a.style.left="0",a.style.right="0",a.style.width="100%",ne=!0},F=()=>{if(!ne)return;let e=c.documentElement,r=c.body;e.style.overflow=oe.overflow,e.style.overscrollBehavior=oe.overscrollBehavior,r.style.overflow=k.overflow,r.style.overscrollBehavior=k.overscrollBehavior,r.style.position=k.position,r.style.top=k.top,r.style.left=k.left,r.style.right=k.right,r.style.width=k.width,window.scrollTo(0,ge),ne=!1},$e=()=>{let e=Pe();o.style.display==="none"&&(o.style.display=""),e?(o.style.width="100vw",o.style.height="100dvh",o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):(o.style.width="420px",o.style.height="620px",o.style.bottom="24px",o.style.right="24px",o.style.left="",o.style.top="",F()),o.style.opacity="1",o.style.pointerEvents="auto"},R=()=>{S&&(S.remove(),S=null)},re=()=>{u!==null&&(u=null,K("trigger_hidden"))},Oe=()=>{o.contentWindow?.postMessage({type:"bitpalm-triggers",enabled:l!=="off"},"*")},ie=()=>{},pe=()=>{},q=!1,U=new Map;function K(e,r){let a=U.get(e);if(a)for(let x of a)try{x(r)}catch{}}let Re=e=>{if(e.origin===T){if(e.data?.type==="bitpalm-widget-config"){C=!1,E=!0,o.style.display==="none"&&(o.style.display=""),e.data.primaryColor&&(f.style.background=e.data.primaryColor,f.style.boxShadow=e.data.chatShadow==="none"?"none":vt);let r=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){f.innerHTML="";let a=c.createElement("span");a.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${r}`;let A=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");A?(A.querySelectorAll("script,foreignObject").forEach(W=>W.remove()),A.querySelectorAll("*").forEach(W=>{for(let j of[...W.attributes])(j.name.startsWith("on")||j.value&&j.value.includes("javascript:"))&&W.removeAttribute(j.name)}),A.setAttribute("width","24"),A.setAttribute("height","24"),A.style.display="block",a.appendChild(A)):a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',f.appendChild(a)}else{let a=f.querySelector("svg");a&&(a.style.stroke=r)}b&&(f.style.display="flex",requestAnimationFrame(()=>{f.style.opacity="1"})),Oe()}if(e.data?.type==="bitpalm-widget-resize"){let r=e.data.width>0,a=q;q=r,r&&!a&&K("widget_opened"),!r&&a&&K("widget_closed");let x=Pe();r?(o.style.width=x?"100vw":`${e.data.width}px`,o.style.height=x?"100dvh":`${e.data.height}px`,x?(o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):F(),o.style.opacity="1",o.style.pointerEvents="auto"):(F(),o.style.width="1px",o.style.height="1px",o.style.left="",o.style.top="",o.style.opacity="0",o.style.pointerEvents="none"),f.style.display=r||!b?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(C||!E||l==="off")return;let r=typeof e.data.message=="string"?e.data.message:"";if(!r)return;if(l==="events"){u=r,K("trigger_shown",{message:r,triggerId:e.data.triggerId,triggerType:e.data.triggerType});return}R(),S=dt(c,{message:r,zIndex:g,bottom:b?90:24,onDismiss:()=>{R(),o.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},onEngage:()=>{if(R(),f.style.display="none",$e(),te(),!G){ee=!0;return}o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:r},"*")}}),c.body.appendChild(S)}e.data?.type==="bitpalm-trigger-hide"&&(R(),re()),e.data?.type==="bitpalm-request-context"&&ie(),e.data?.type==="bitpalm-chat-event"&&e.data.event&&K(e.data.event,e.data.data),e.data?.type==="bitpalm-widget-blocked"&&(C=!0,E=!1,f.style.display="none",R(),re(),F(),o.style.display="none")}};window.addEventListener("message",Re);let M=!1;try{M=localStorage.getItem(`${I}optout`)==="1"}catch{}let se=`${I}vid`,P="";if(!M){try{P=localStorage.getItem(se)||""}catch{}if(!P){let e=c.cookie.match(new RegExp(`(?:^|; )${se}=([^;]+)`));P=e?decodeURIComponent(e[1]):""}P||(P=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(se,P)}catch{}try{c.cookie=`${se}=${encodeURIComponent(P)};path=/;max-age=31536000;SameSite=Lax`}catch{}}M||ke(()=>{try{let e=new URLSearchParams(location.search),r={};for(let B of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let A=e.get(B);A&&(r[B]=A)}let a=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href,referrer:c.referrer||void 0,...Object.keys(r).length>0?{utm:r}:{}}),x=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(x,new Blob([a],{type:"application/json"})):fetch(x,{method:"POST",body:a,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}},2e3);let he="",ye="",be=0;try{he=sessionStorage.getItem(ht)||"",ye=sessionStorage.getItem(yt)||"";let e=parseInt(sessionStorage.getItem(bt)||"0",10);Number.isFinite(e)&&e>0&&(be=e)}catch{}let He=(e,r="")=>{if(M||!P)return;let a={},x=h(e.name,140),B=wt(e.email),A=$(e.phone),W=h(e.company,160),j=h(e.external_user_id,140),st=h(e.signature,260),Te=Number(e.signed_at);if(x&&(a.name=x),B&&(a.email=B),A&&(a.phone=A),W&&(a.company=W),j&&(a.external_user_id=j),st&&(a.signature=st),Number.isFinite(Te)&&Te>0&&(a.signed_at=Math.floor(Te)),(e.signature_version==="v1"||a.signature)&&(a.signature_version="v1"),(e.identify_source==="manual"||e.identify_source==="form")&&(a.identify_source=e.identify_source),!a.name&&!a.email&&!a.phone&&!a.company&&!a.external_user_id)return;let de=Ht(a),Ce=[r.toLowerCase(),de].filter(Boolean).join("|"),Ie=Date.now();if(!(Ie-be<Rt&&(Ce===he||de===ye))){he=Ce,ye=de,be=Ie;try{sessionStorage.setItem(ht,Ce),sessionStorage.setItem(yt,de),sessionStorage.setItem(bt,String(Ie))}catch{}try{let at=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href,referrer:c.referrer||void 0,...a}),lt=`${s}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(lt,new Blob([at],{type:"application/json"})):fetch(lt,{method:"POST",body:at,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}},De=e=>{if(M||!p||!P)return;let r=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(r instanceof HTMLFormElement))return;let a=(r.getAttribute("data-bp-identify")||r.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(a==="off"||a==="false"||a==="0")return;let x=jt(r);if(!x)return;let B=[r.getAttribute("id")||"",r.getAttribute("name")||"",r.getAttribute("action")||""].join("|");He({...x,identify_source:"form"},B)};!M&&p&&c.addEventListener("submit",De,!0);let V=parseInt(sessionStorage.getItem(`${I}pages`)||"0")+1;sessionStorage.setItem(`${I}pages`,String(V));let N=JSON.parse(sessionStorage.getItem(`${I}hist`)||"[]");N.push(location.href),N.length>20&&(N=N.slice(-20)),sessionStorage.setItem(`${I}hist`,JSON.stringify(N));let Ue=Date.now(),ae=parseInt(sessionStorage.getItem(`${I}site_start`)||"0");ae||(ae=Ue,sessionStorage.setItem(`${I}site_start`,String(ae)));let Ne=[];ie=()=>{let e=!1;try{e=!!localStorage.getItem(`${I}visited`)}catch{e=!1}if(o.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:c.title,returning:e,pageCount:V,pageHistory:N,loadedAt:Ue,siteStart:ae,locale:i,visitorId:M?"":P},"*"),Qe(),!e&&!M)try{localStorage.setItem(`${I}visited`,"1")}catch{}},o.addEventListener("load",()=>{G=!0,ie(),[120,450,1100].forEach(e=>{let r=setTimeout(()=>ie(),e);Ne.push(r)}),ee&&(ee=!1,pe())}),c.readyState==="loading"?c.addEventListener("DOMContentLoaded",()=>ke(te,1600),{once:!0}):ke(te,1600);let We=history.pushState.bind(history),je=history.replaceState.bind(history),le=()=>{V++,sessionStorage.setItem(`${I}pages`,String(V));let e=JSON.parse(sessionStorage.getItem(`${I}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),N=e,sessionStorage.setItem(`${I}hist`,JSON.stringify(e)),o.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:c.title,pageCount:V,pageHistory:e,loadedAt:Date.now()},"*"),!M)try{let r=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href}),a=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(a,new Blob([r],{type:"application/json"})):fetch(a,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){We(...e),le()},history.replaceState=function(...e){je(...e),le()},window.addEventListener("popstate",le);let Fe=-1,ve,qe=()=>{clearTimeout(ve),ve=setTimeout(()=>{let e=Math.max(c.documentElement.scrollHeight,c.body.scrollHeight)-window.innerHeight,r=e>0?Math.round(window.scrollY/e*100):100;r!==Fe&&(Fe=r,o.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:r},"*"))},500)};window.addEventListener("scroll",qe,{passive:!0});let ze=e=>{e.clientY<=0&&o.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};c.addEventListener("mouseout",ze);let we,Ye=!1,xe=()=>{clearTimeout(we),!Ye&&(we=setTimeout(()=>{Ye=!0,o.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Je=["mousemove","keydown","scroll","touchstart"];Je.forEach(e=>c.addEventListener(e,xe,{passive:!0})),xe(),pe=()=>{o.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=o.src.split("#")[0];o.src=`${e}#bp-open-${Date.now()}`};let Q=()=>{if(f.style.display="none",R(),$e(),te(),!G){ee=!0;return}if(u!==null){let e=u;re(),o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:e},"*");return}pe()},Ge=e=>{l=e,e==="off"&&(R(),re()),Oe()},It=()=>Ge("off"),At=()=>Ge(L==="off"?"bubble":L),Ee=()=>{F(),o.contentWindow?.postMessage({type:"bitpalm-close"},"*")},Ke=e=>{!e||typeof e!="object"||He({external_user_id:h(e.externalUserId,140)||void 0,name:h(e.name,140)||void 0,email:wt(e.email)||void 0,phone:$(e.phone)||void 0,company:h(e.company,160)||void 0,signature:h(e.signature,260)||void 0,signed_at:Number.isFinite(Number(e.signedAt))?Math.floor(Number(e.signedAt)):void 0,signature_version:e.signatureVersion==="v1"?"v1":void 0,identify_source:"manual"},"manual")},Lt=()=>{q?Ee():Q()},kt=()=>q,Ve=e=>{if(!e||typeof e!="string")return;let r=e.trim().slice(0,1e4);r&&(q||Q(),setTimeout(()=>{o.contentWindow?.postMessage({type:"bitpalm-send-message",message:r},"*")},q?50:500))};function Qe(){o.contentWindow?.postMessage({type:"bitpalm-theme",theme:d},"*")}let ce=e=>{e!==d&&(d=e,Qe())},Xe=e=>{w=ue(e),y?.(),y=null,w==="auto"?(y=Le(ce),ce(Z())):ce(w)};w==="auto"&&(y=Le(ce));let Ze=e=>{let r=e.detail;if(!r||typeof r!="object")return;let a=h(r.slug,120);a&&a!==t||Xe(ue(r.theme))};window.addEventListener("bitpalm-theme",Ze);let X={},et=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;X={...X,...e};let r=JSON.stringify(X);r.length>pt&&console.warn(`[BitPalm] Custom context exceeds ${pt} bytes (${r.length}). It may be truncated.`),o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:X},"*")},Pt=()=>{X={},o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:{}},"*")},tt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let x=h(a.slug,120);if(x&&x!==t)return;let{slug:B,...A}=a;et(A)};window.addEventListener("bitpalm-context",tt);let nt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let x=h(a.slug,120);x&&x!==t||Ke(a)};window.addEventListener("bitpalm-identify",nt);let Se=e=>{let r=e.detail,a=h(r?.slug,120);return!a||a===t},ot=e=>{Se(e)&&Q()},rt=e=>{Se(e)&&Ee()},it=e=>{if(!Se(e))return;let r=e.detail?.message;typeof r=="string"&&Ve(r)};return window.addEventListener("bitpalm-open",ot),window.addEventListener("bitpalm-close",rt),window.addEventListener("bitpalm-send",it),{open:Q,close:Ee,toggle:Lt,isOpen:kt,identify:Ke,context:et,resetContext:Pt,send:Ve,on:(e,r)=>(U.has(e)||U.set(e,new Set),U.get(e).add(r),()=>U.get(e)?.delete(r)),off:(e,r)=>{U.get(e)?.delete(r)},setTheme:Xe,disableTriggers:It,enableTriggers:At,destroy:()=>{window.removeEventListener("message",Re),window.removeEventListener("scroll",qe),window.removeEventListener("popstate",le),c.removeEventListener("mouseout",ze),c.removeEventListener("submit",De,!0),Je.forEach(e=>c.removeEventListener(e,xe)),clearTimeout(ve),clearTimeout(we),Ne.forEach(e=>clearTimeout(e)),history.pushState=We,history.replaceState=je,window.removeEventListener("bitpalm-identify",nt),window.removeEventListener("bitpalm-context",tt),window.removeEventListener("bitpalm-theme",Ze),window.removeEventListener("bitpalm-open",ot),window.removeEventListener("bitpalm-close",rt),window.removeEventListener("bitpalm-send",it),y?.(),U.clear(),F(),R(),f.remove(),o.remove()}}}function qt(n){let t=n.split(`
|
|
2
|
-
`).filter(
|
|
3
|
-
`);if(!
|
|
4
|
-
`),s
|
|
1
|
+
import{useCallback as Me,useEffect as fe,useRef as ge,useState as J}from"react";function ct(t){if(t===!1)return"off";if(typeof t=="string"){let n=t.trim().toLowerCase();if(["false","off","0","no","none"].includes(n))return"off";if(n==="events")return"events"}return"bubble"}function dt(t,n){let s=t.createElement("div");s.setAttribute("data-bitpalm-trigger",""),s.style.cssText=`max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${n.zIndex-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`,s.style.position="fixed",s.style.right="24px",s.style.bottom=`${n.bottom}px`;let i=t.createElement("p");i.style.cssText="font-size:14px;color:#1f2937;margin:0;",i.textContent=n.message;let u=t.createElement("div");u.style.cssText="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;";let f=t.createElement("button");return f.type="button",f.setAttribute("aria-label","Close"),f.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",f.textContent="\u2715",f.onclick=m=>{m.stopPropagation(),n.onDismiss()},s.onclick=()=>n.onEngage(),s.append(i,u,f),s}var _t=["dark","dark-mode","dark-theme","theme-dark"],Mt=["light","light-mode","light-theme","theme-light"],ft=["data-theme","data-color-scheme","data-color-mode","data-mode","data-bs-theme"],gt="(prefers-color-scheme: dark)";function ue(t){return t==="light"||t==="dark"?t:"auto"}function ut(t){if(!t)return null;if(_t.some(n=>t.classList.contains(n)))return"dark";if(Mt.some(n=>t.classList.contains(n)))return"light";for(let n of ft){let s=(t.getAttribute(n)||"").toLowerCase();if(s.includes("dark"))return"dark";if(s.includes("light"))return"light"}return null}function Le(t){let n=t/255;return n<=.03928?n/12.92:((n+.055)/1.055)**2.4}function mt(t,n){if(!t)return null;let s=n.getComputedStyle(t).backgroundColor.match(/rgba?\(([^)]+)\)/);if(!s)return null;let[i,u,f,m=1]=s[1].split(/[\s,/]+/).filter(Boolean).map(Number);return[i,u,f,m].some(l=>Number.isNaN(l))||m<.5?null:.2126*Le(i)+.7152*Le(u)+.0722*Le(f)<.2?"dark":"light"}function Bt(t,n){let s=n.getComputedStyle(t.documentElement).colorScheme||"",i=t.querySelector('meta[name="color-scheme"]')?.getAttribute("content")||"",u=`${s} ${i}`.toLowerCase();return u.includes("dark")?u.includes("light")?n.matchMedia?.(gt).matches?"dark":"light":"dark":null}function ne(t=document,n=window){return ut(t.documentElement)??ut(t.body)??mt(t.body,n)??mt(t.documentElement,n)??Bt(t,n)??"light"}function ke(t,n=document,s=window){let i=ne(n,s),u=!1,f=()=>{u=!1;let d=ne(n,s);d!==i&&(i=d,t(d))},m=()=>{u||(u=!0,typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(f):setTimeout(f,16))},y=typeof MutationObserver<"u"?new MutationObserver(m):null,l={attributes:!0,attributeFilter:["class","style",...ft]};y?.observe(n.documentElement,l),n.body&&y?.observe(n.body,l);let h=typeof s.matchMedia=="function"?s.matchMedia(gt):null;return h?.addEventListener?.("change",m),()=>{y?.disconnect(),h?.removeEventListener?.("change",m)}}var $t="https://agents.bitpalm.ai",A="_bp_",Ot=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),Rt=8e3,pt=4096,ht=`${A}identify_signature`,yt=`${A}identify_fingerprint`,bt=`${A}identify_sent_at`,vt="0 4px 14px rgba(0,0,0,0.18)";function Ht(t){return[t.external_user_id||"",t.email||"",t.phone||"",t.name||"",t.company||"",t.signature||"",t.signed_at!=null?String(t.signed_at):"",t.signature_version||"",t.identify_source||""].join("|").toLowerCase()}function p(t,n=180){return t?t.replace(/\s+/g," ").trim().slice(0,n):""}function Dt(t){return t?` ${t.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function K(t,n){for(let s of n)if(t.includes(s))return!0;return!1}function j(t){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(t)}function D(t){let n=p(t,50);if(!n)return"";let s=n.startsWith("+"),i=n.replace(/\D/g,"");return i.length<6?"":`${s?"+":""}${i.slice(0,20)}`}function wt(t){let n=p(t,140).toLowerCase();return!n||!j(n)?"":n}function Q(t,n){for(let s of n){let i=t.querySelector(s),u=p(i?.value);if(u)return u}return""}function Ut(t){return p(t.getAttribute("data-bp-field")||t.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function Nt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wt(t,n){let s=[],i=(l,h=140)=>{let d=p(l,h);d&&s.push(d)};i(n.name),i(n.id),i(n.getAttribute("autocomplete")),i(n.getAttribute("placeholder")),i(n.getAttribute("aria-label")),i(n.getAttribute("data-field")),i(n.getAttribute("data-name")),i(n.getAttribute("data-label")),i(n.getAttribute("data-bp-field")),i(n.getAttribute("data-bitpalm-field"));let u=new Set,f=l=>{let h=p(l,200);!h||u.has(h)||(u.add(h),s.push(h))};for(let l of Array.from(n.labels||[]))f(l.textContent);if(n.id){let l=t.querySelector(`label[for="${Nt(n.id)}"]`);f(l?.textContent)}let m=n.closest("label");f(m?.textContent);let y=n.getAttribute("aria-labelledby");if(y)for(let l of y.split(/\s+/)){if(!l)continue;let h=t.ownerDocument.getElementById(l);f(h?.textContent)}return s}function jt(t){let n=p(Q(t,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),s=D(Q(t,["[data-bp-phone]","[data-bitpalm-phone]"])),i=p(Q(t,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),u=p(Q(t,["[data-bp-first-name]","[data-bitpalm-first-name]"])),f=p(Q(t,["[data-bp-last-name]","[data-bitpalm-last-name]"])),m=p(Q(t,["[data-bp-company]","[data-bitpalm-company]"]));for(let d of Array.from(t.elements)){if(!(d instanceof HTMLInputElement||d instanceof HTMLTextAreaElement||d instanceof HTMLSelectElement)||d.disabled||d instanceof HTMLInputElement&&Ot.has(d.type.toLowerCase()))continue;let v=Ut(d),L=d.hasAttribute("data-bp-email")||d.hasAttribute("data-bitpalm-email")||d.hasAttribute("data-bp-phone")||d.hasAttribute("data-bitpalm-phone")||d.hasAttribute("data-bp-name")||d.hasAttribute("data-bitpalm-name")||d.hasAttribute("data-bp-full-name")||d.hasAttribute("data-bitpalm-full-name")||d.hasAttribute("data-bp-first-name")||d.hasAttribute("data-bitpalm-first-name")||d.hasAttribute("data-bp-last-name")||d.hasAttribute("data-bitpalm-last-name")||d.hasAttribute("data-bp-company")||d.hasAttribute("data-bitpalm-company")||!!v;if(d instanceof HTMLInputElement&&d.type.toLowerCase()==="hidden"&&!L)continue;let g=p(d.value);if(!g)continue;let I=d instanceof HTMLInputElement?d.type.toLowerCase():"",o=Dt(Wt(t,d).join(" "));if(!n&&v==="email"&&j(g)){n=g.toLowerCase();continue}if(!s&&(v==="phone"||v==="tel"||v==="mobile"||v==="whatsapp")){let E=D(g);if(E){s=E;continue}}if(!m&&v==="company"){m=p(g,160);continue}if(!u&&(v==="first-name"||v==="firstname")){u=p(g,100);continue}if(!f&&(v==="last-name"||v==="lastname"||v==="surname")){f=p(g,100);continue}if(!i&&(v==="name"||v==="full-name"||v==="fullname")){!j(g)&&!D(g)&&(i=p(g,140));continue}let c=I==="email"||K(o,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),w=I==="tel"||K(o,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),x=K(o,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),b=K(o,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),_=K(o,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),C=K(o,[" full name "," fullname "," contact name "," name "])&&!c&&!w;if(!n&&c&&j(g)){n=g.toLowerCase();continue}if(!s&&w){let E=D(g);if(E){s=E;continue}}if(!m&&x){m=p(g,160);continue}if(!u&&b){u=p(g,100);continue}if(!f&&_){f=p(g,100);continue}if(!i&&C&&!j(g)&&!D(g)){i=p(g,140);continue}!n&&j(g)&&(n=g.toLowerCase())}if(i&&(j(i)||D(i))&&(i=""),m&&(j(m)||D(m))&&(m=""),i||(i=p([u,f].filter(Boolean).join(" "),140)),i&&n&&i.toLowerCase()===n.toLowerCase()&&(i=""),!!!(n||s)&&!!!(i&&m))return null;let h={...i?{name:i}:{},...n?{email:n}:{},...s?{phone:s}:{},...m?{company:m}:{}};return Object.keys(h).length>0?h:null}function Ft(){if(typeof document<"u"){let t=document.documentElement.lang;if(t)return t.slice(0,2).toLowerCase()}return"en"}function Pe(t,n=1200){if(typeof window<"u"&&"requestIdleCallback"in window){window.requestIdleCallback(t,{timeout:n});return}setTimeout(t,Math.min(n,300))}function _e(){if(typeof window>"u")return!1;let t=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(t))return!0;let s=window.matchMedia("(pointer: coarse)").matches,i=window.matchMedia("(hover: none)").matches,u=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return s&&i&&u<=900}function xt(t){let{slug:n,locale:s=Ft(),baseUrl:i=$t,token:u,zIndex:f=9999,autoIdentify:m=!0,launcher:y=!0}=t,l=document,h=ue(t.theme),d=h==="auto"?ne():h,v=null,L=ct(t.triggers),g=L,I=null,o=l.createElement("iframe");o.setAttribute("data-bitpalm-chat","");let c=`${i}/t/${n}/widget`,w=new URLSearchParams({locale:s,theme:d});u&&w.set("token",u),g==="off"&&w.set("triggers","off"),o.src=`${c}?${w.toString()}`,o.allow="clipboard-write; microphone",o.setAttribute("allowtransparency","true"),o.loading="lazy",o.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${f};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;let x=new URL(o.src).origin,b=l.createElement("div");if(b.setAttribute("role","button"),b.setAttribute("aria-label","Chat"),b.setAttribute("data-bitpalm-launcher",""),b.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${f-1};background:#171717;box-shadow:${vt};transition:transform .2s,opacity .3s;opacity:0;`,b.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',b.onmouseenter=()=>{b.style.transform="scale(1.05)"},b.onmouseleave=()=>{b.style.transform="scale(1)"},b.onclick=()=>ee(),y&&l.body.appendChild(b),!l.getElementById("_bp_fade")){let e=l.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",l.head.appendChild(e)}let _=null,C=!1,E=!1,k=!1,T=!1,M=!1,O=()=>{k||(k=!0,l.body.appendChild(o))},N=!1,pe=0,oe={overflow:"",overscrollBehavior:""},B={overflow:"",overscrollBehavior:"",position:"",top:"",left:"",right:"",width:""},Be=()=>{if(N||!_e())return;let r=l.documentElement,a=l.body;pe=window.scrollY||window.pageYOffset||0,oe.overflow=r.style.overflow,oe.overscrollBehavior=r.style.overscrollBehavior,B.overflow=a.style.overflow,B.overscrollBehavior=a.style.overscrollBehavior,B.position=a.style.position,B.top=a.style.top,B.left=a.style.left,B.right=a.style.right,B.width=a.style.width,r.style.overflow="hidden",r.style.overscrollBehavior="none",a.style.overflow="hidden",a.style.overscrollBehavior="none",a.style.position="fixed",a.style.top=`-${pe}px`,a.style.left="0",a.style.right="0",a.style.width="100%",N=!0},V=()=>{if(!N)return;let e=l.documentElement,r=l.body;e.style.overflow=oe.overflow,e.style.overscrollBehavior=oe.overscrollBehavior,r.style.overflow=B.overflow,r.style.overscrollBehavior=B.overscrollBehavior,r.style.position=B.position,r.style.top=B.top,r.style.left=B.left,r.style.right=B.right,r.style.width=B.width,window.scrollTo(0,pe),N=!1},$e=()=>{let e=_e();o.style.display==="none"&&(o.style.display=""),e?(o.style.width="100vw",o.style.height="100dvh",o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):(o.style.width="420px",o.style.height="620px",o.style.bottom="24px",o.style.right="24px",o.style.left="",o.style.top="",V()),o.style.opacity="1",o.style.pointerEvents="auto"},W=()=>{_&&(_.remove(),_=null)},ie=()=>{I!==null&&(I=null,X("trigger_hidden"))},Oe=()=>{o.contentWindow?.postMessage({type:"bitpalm-triggers",enabled:g!=="off"},"*")},re=()=>{},he=()=>{},G=!1,F=new Map;function X(e,r){let a=F.get(e);if(a)for(let S of a)try{S(r)}catch{}}let Re=e=>{if(e.origin===x){if(e.data?.type==="bitpalm-widget-config"){E=!1,C=!0,o.style.display==="none"&&(o.style.display=""),e.data.primaryColor&&(b.style.background=e.data.primaryColor,b.style.boxShadow=e.data.chatShadow==="none"?"none":vt);let r=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){b.innerHTML="";let a=l.createElement("span");a.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${r}`;let P=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");P?(P.querySelectorAll("script,foreignObject").forEach(z=>z.remove()),P.querySelectorAll("*").forEach(z=>{for(let Y of[...z.attributes])(Y.name.startsWith("on")||Y.value&&Y.value.includes("javascript:"))&&z.removeAttribute(Y.name)}),P.setAttribute("width","24"),P.setAttribute("height","24"),P.style.display="block",a.appendChild(P)):a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',b.appendChild(a)}else{let a=b.querySelector("svg");a&&(a.style.stroke=r)}y&&(b.style.display="flex",requestAnimationFrame(()=>{b.style.opacity="1"})),Oe()}if(e.data?.type==="bitpalm-widget-resize"){let r=e.data.width>0,a=G;G=r,r&&!a&&X("widget_opened"),!r&&a&&X("widget_closed");let S=_e();r?(o.style.width=S?"100vw":`${e.data.width}px`,o.style.height=S?"100dvh":`${e.data.height}px`,S?(o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):V(),o.style.opacity="1",o.style.pointerEvents="auto"):(V(),o.style.width="1px",o.style.height="1px",o.style.left="",o.style.top="",o.style.opacity="0",o.style.pointerEvents="none"),b.style.display=r||!y?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(E||!C||g==="off")return;let r=typeof e.data.message=="string"?e.data.message:"";if(!r)return;if(g==="events"){I=r,X("trigger_shown",{message:r,triggerId:e.data.triggerId,triggerType:e.data.triggerType});return}W(),_=dt(l,{message:r,zIndex:f,bottom:y?90:24,onDismiss:()=>{W(),o.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},onEngage:()=>{if(W(),b.style.display="none",$e(),O(),!T){M=!0;return}o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:r},"*")}}),l.body.appendChild(_)}e.data?.type==="bitpalm-trigger-hide"&&(W(),ie()),e.data?.type==="bitpalm-request-context"&&re(),e.data?.type==="bitpalm-chat-event"&&e.data.event&&X(e.data.event,e.data.data),e.data?.type==="bitpalm-widget-blocked"&&(E=!0,C=!1,b.style.display="none",W(),ie(),V(),o.style.display="none")}};window.addEventListener("message",Re);let R=!1;try{R=localStorage.getItem(`${A}optout`)==="1"}catch{}let se=`${A}vid`,$="";if(!R){try{$=localStorage.getItem(se)||""}catch{}if(!$){let e=l.cookie.match(new RegExp(`(?:^|; )${se}=([^;]+)`));$=e?decodeURIComponent(e[1]):""}$||($=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(se,$)}catch{}try{l.cookie=`${se}=${encodeURIComponent($)};path=/;max-age=31536000;SameSite=Lax`}catch{}}R||Pe(()=>{try{let e=new URLSearchParams(location.search),r={};for(let H of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let P=e.get(H);P&&(r[H]=P)}let a=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href,referrer:l.referrer||void 0,...Object.keys(r).length>0?{utm:r}:{}}),S=`${i}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(S,new Blob([a],{type:"application/json"})):fetch(S,{method:"POST",body:a,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}},2e3);let ye="",be="",ve=0;try{ye=sessionStorage.getItem(ht)||"",be=sessionStorage.getItem(yt)||"";let e=parseInt(sessionStorage.getItem(bt)||"0",10);Number.isFinite(e)&&e>0&&(ve=e)}catch{}let He=(e,r="")=>{if(R||!$)return;let a={},S=p(e.name,140),H=wt(e.email),P=D(e.phone),z=p(e.company,160),Y=p(e.external_user_id,140),st=p(e.signature,260),Ce=Number(e.signed_at);if(S&&(a.name=S),H&&(a.email=H),P&&(a.phone=P),z&&(a.company=z),Y&&(a.external_user_id=Y),st&&(a.signature=st),Number.isFinite(Ce)&&Ce>0&&(a.signed_at=Math.floor(Ce)),(e.signature_version==="v1"||a.signature)&&(a.signature_version="v1"),(e.identify_source==="manual"||e.identify_source==="form")&&(a.identify_source=e.identify_source),!a.name&&!a.email&&!a.phone&&!a.company&&!a.external_user_id)return;let de=Ht(a),Ie=[r.toLowerCase(),de].filter(Boolean).join("|"),Ae=Date.now();if(!(Ae-ve<Rt&&(Ie===ye||de===be))){ye=Ie,be=de,ve=Ae;try{sessionStorage.setItem(ht,Ie),sessionStorage.setItem(yt,de),sessionStorage.setItem(bt,String(Ae))}catch{}try{let at=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href,referrer:l.referrer||void 0,...a}),lt=`${i}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(lt,new Blob([at],{type:"application/json"})):fetch(lt,{method:"POST",body:at,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}},De=e=>{if(R||!m||!$)return;let r=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(r instanceof HTMLFormElement))return;let a=(r.getAttribute("data-bp-identify")||r.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(a==="off"||a==="false"||a==="0")return;let S=jt(r);if(!S)return;let H=[r.getAttribute("id")||"",r.getAttribute("name")||"",r.getAttribute("action")||""].join("|");He({...S,identify_source:"form"},H)};!R&&m&&l.addEventListener("submit",De,!0);let Z=parseInt(sessionStorage.getItem(`${A}pages`)||"0")+1;sessionStorage.setItem(`${A}pages`,String(Z));let q=JSON.parse(sessionStorage.getItem(`${A}hist`)||"[]");q.push(location.href),q.length>20&&(q=q.slice(-20)),sessionStorage.setItem(`${A}hist`,JSON.stringify(q));let Ue=Date.now(),ae=parseInt(sessionStorage.getItem(`${A}site_start`)||"0");ae||(ae=Ue,sessionStorage.setItem(`${A}site_start`,String(ae)));let Ne=[];re=()=>{let e=!1;try{e=!!localStorage.getItem(`${A}visited`)}catch{e=!1}if(o.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:l.title,returning:e,pageCount:Z,pageHistory:q,loadedAt:Ue,siteStart:ae,locale:s,visitorId:R?"":$},"*"),Qe(),!e&&!R)try{localStorage.setItem(`${A}visited`,"1")}catch{}},o.addEventListener("load",()=>{T=!0,re(),[120,450,1100].forEach(e=>{let r=setTimeout(()=>re(),e);Ne.push(r)}),M&&(M=!1,he())}),l.readyState==="loading"?l.addEventListener("DOMContentLoaded",()=>Pe(O,1600),{once:!0}):Pe(O,1600);let We=history.pushState.bind(history),je=history.replaceState.bind(history),le=()=>{Z++,sessionStorage.setItem(`${A}pages`,String(Z));let e=JSON.parse(sessionStorage.getItem(`${A}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),q=e,sessionStorage.setItem(`${A}hist`,JSON.stringify(e)),o.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:l.title,pageCount:Z,pageHistory:e,loadedAt:Date.now()},"*"),!R)try{let r=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href}),a=`${i}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(a,new Blob([r],{type:"application/json"})):fetch(a,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){We(...e),le()},history.replaceState=function(...e){je(...e),le()},window.addEventListener("popstate",le);let Fe=-1,we,qe=()=>{clearTimeout(we),we=setTimeout(()=>{let e=Math.max(l.documentElement.scrollHeight,l.body.scrollHeight)-window.innerHeight,r=e>0?Math.round(window.scrollY/e*100):100;r!==Fe&&(Fe=r,o.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:r},"*"))},500)};window.addEventListener("scroll",qe,{passive:!0});let ze=e=>{e.clientY<=0&&o.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};l.addEventListener("mouseout",ze);let xe,Ye=!1,Ee=()=>{clearTimeout(xe),!Ye&&(xe=setTimeout(()=>{Ye=!0,o.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Je=["mousemove","keydown","scroll","touchstart"];Je.forEach(e=>l.addEventListener(e,Ee,{passive:!0})),Ee(),he=()=>{o.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=o.src.split("#")[0];o.src=`${e}#bp-open-${Date.now()}`};let ee=()=>{if(b.style.display="none",W(),$e(),O(),!T){M=!0;return}if(I!==null){let e=I;ie(),o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:e},"*");return}he()},Ve=e=>{g=e,e==="off"&&(W(),ie()),Oe()},It=()=>Ve("off"),At=()=>Ve(L==="off"?"bubble":L),Se=()=>{V(),o.contentWindow?.postMessage({type:"bitpalm-close"},"*")},Ge=e=>{!e||typeof e!="object"||He({external_user_id:p(e.externalUserId,140)||void 0,name:p(e.name,140)||void 0,email:wt(e.email)||void 0,phone:D(e.phone)||void 0,company:p(e.company,160)||void 0,signature:p(e.signature,260)||void 0,signed_at:Number.isFinite(Number(e.signedAt))?Math.floor(Number(e.signedAt)):void 0,signature_version:e.signatureVersion==="v1"?"v1":void 0,identify_source:"manual"},"manual")},Lt=()=>{G?Se():ee()},kt=()=>G,Ke=e=>{if(!e||typeof e!="string")return;let r=e.trim().slice(0,1e4);r&&(G||ee(),setTimeout(()=>{o.contentWindow?.postMessage({type:"bitpalm-send-message",message:r},"*")},G?50:500))};function Qe(){o.contentWindow?.postMessage({type:"bitpalm-theme",theme:d},"*")}let ce=e=>{e!==d&&(d=e,Qe())},Xe=e=>{h=ue(e),v?.(),v=null,h==="auto"?(v=ke(ce),ce(ne())):ce(h)};h==="auto"&&(v=ke(ce));let Ze=e=>{let r=e.detail;if(!r||typeof r!="object")return;let a=p(r.slug,120);a&&a!==n||Xe(ue(r.theme))};window.addEventListener("bitpalm-theme",Ze);let te={},et=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;te={...te,...e};let r=JSON.stringify(te);r.length>pt&&console.warn(`[BitPalm] Custom context exceeds ${pt} bytes (${r.length}). It may be truncated.`),o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:te},"*")},Pt=()=>{te={},o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:{}},"*")},tt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let S=p(a.slug,120);if(S&&S!==n)return;let{slug:H,...P}=a;et(P)};window.addEventListener("bitpalm-context",tt);let nt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let S=p(a.slug,120);S&&S!==n||Ge(a)};window.addEventListener("bitpalm-identify",nt);let Te=e=>{let r=e.detail,a=p(r?.slug,120);return!a||a===n},ot=e=>{Te(e)&&ee()},it=e=>{Te(e)&&Se()},rt=e=>{if(!Te(e))return;let r=e.detail?.message;typeof r=="string"&&Ke(r)};return window.addEventListener("bitpalm-open",ot),window.addEventListener("bitpalm-close",it),window.addEventListener("bitpalm-send",rt),{open:ee,close:Se,toggle:Lt,isOpen:kt,identify:Ge,context:et,resetContext:Pt,send:Ke,on:(e,r)=>(F.has(e)||F.set(e,new Set),F.get(e).add(r),()=>F.get(e)?.delete(r)),off:(e,r)=>{F.get(e)?.delete(r)},setTheme:Xe,disableTriggers:It,enableTriggers:At,destroy:()=>{window.removeEventListener("message",Re),window.removeEventListener("scroll",qe),window.removeEventListener("popstate",le),l.removeEventListener("mouseout",ze),l.removeEventListener("submit",De,!0),Je.forEach(e=>l.removeEventListener(e,Ee)),clearTimeout(we),clearTimeout(xe),Ne.forEach(e=>clearTimeout(e)),history.pushState=We,history.replaceState=je,window.removeEventListener("bitpalm-identify",nt),window.removeEventListener("bitpalm-context",tt),window.removeEventListener("bitpalm-theme",Ze),window.removeEventListener("bitpalm-open",ot),window.removeEventListener("bitpalm-close",it),window.removeEventListener("bitpalm-send",rt),v?.(),F.clear(),V(),W(),b.remove(),o.remove()}}}function qt(t){let n=t.split(`
|
|
2
|
+
`).filter(s=>s.startsWith("data:")).map(s=>s.slice(5).trimStart()).join(`
|
|
3
|
+
`);if(!n)return null;try{let s=JSON.parse(n);return s&&typeof s.type=="string"?s:null}catch{return null}}function me(t){let n=[],s=t.replace(/\r\n/g,`
|
|
4
|
+
`),i=s.indexOf(`
|
|
5
5
|
|
|
6
|
-
`);for(;
|
|
6
|
+
`);for(;i>=0;){let u=qt(s.slice(0,i));u&&n.push(u),s=s.slice(i+2),i=s.indexOf(`
|
|
7
7
|
|
|
8
|
-
`)}return{events:
|
|
8
|
+
`)}return{events:n,rest:s}}function Et(t){return me(`${t}
|
|
9
9
|
|
|
10
|
-
`).events}var
|
|
10
|
+
`).events}var U=class extends Error{constructor(s,i,u){super(i);this.code=s;this.status=u;this.name="BitPalmApiError"}},zt="https://agents.bitpalm.ai";function Yt(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Jt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}async function Vt(t){let n=await t.json().catch(()=>null);return new U(n?.error?.code??"server_error",n?.error?.message??`Request failed (${t.status})`,t.status)}function St(t){if(!t?.key?.startsWith("bp_pk_"))throw new Error("createChatClient needs an app key (bp_pk_\u2026) from the BitPalm dashboard.");let n=(t.baseUrl??zt).replace(/\/+$/,""),s=t.storage===void 0?Yt():t.storage,i=`bitpalm:${t.key.slice(0,14)}`,u=o=>{try{return s?.getItem(`${i}:${o}`)??null}catch{return null}},f=(o,c)=>{try{c===null?s?.removeItem(`${i}:${o}`):s?.setItem(`${i}:${o}`,c)}catch{}},m=t.visitorId??u("visitor")??Jt();t.visitorId||f("visitor",m);let y=u("conversation"),l=!1,h=null,d=o=>{for(let c of o)c.fromHuman&&c.createdAt&&(!h||c.createdAt>h)&&(h=c.createdAt)},v={Authorization:`Bearer ${t.key}`},L=async(o,c)=>{let w=await fetch(`${n}${o}`,{...c,headers:{...v,...c?.headers??{}}});if(!w.ok)throw await Vt(w);return w},g=o=>{y=o,f("conversation",o)},I=(o,c,w)=>{for(let x of o)if(x.type==="delta")c.text+=x.text,w?.(x.text,c.text);else if(x.type==="replace")c.text=x.text,w?.("",c.text);else if(x.type==="done")c.result={text:c.text,conversationId:x.conversationId,...x.cards?{cards:x.cards}:{},...x.handoff?{handoff:!0}:{}};else if(x.type==="error")throw new U("server_error",x.message,500)};return{visitorId:m,get conversationId(){return y},get handoff(){return l},async agent(o){let c=new URLSearchParams({locale:t.locale??"en"});return o?.url&&c.set("url",o.url),(await L(`/api/v1/agent?${c.toString()}`)).json()},async send(o,c={}){let w=await L("/api/v1/chat",{method:"POST",headers:{"Content-Type":"application/json"},signal:c.signal,body:JSON.stringify({message:o,visitorId:m,conversationId:y??void 0,context:c.context,fileIds:c.fileIds})}),x={text:"",result:null},b=w.body&&typeof w.body.getReader=="function"?w.body.getReader():null;if(b){let C=new TextDecoder,E="";for(;;){let{done:k,value:T}=await b.read();if(k)break;let M=me(E+C.decode(T,{stream:!0}));E=M.rest,I(M.events,x,c.onDelta)}I(me(`${E}
|
|
11
11
|
|
|
12
|
-
`).events,
|
|
12
|
+
`).events,x,c.onDelta)}else I(Et(await w.text()),x,c.onDelta);let _=x.result??{text:x.text,conversationId:y??""};return _.conversationId&&g(_.conversationId),l=_.handoff===!0,_},async history(){let o=new URLSearchParams({visitorId:m});y&&o.set("conversationId",y);let c=await(await L(`/api/v1/chat/history?${o.toString()}`)).json();return c.conversationId&&g(c.conversationId),l=c.handoff===!0,h=null,d(c.messages),c.messages},async updates(){if(!y)return{handoff:!1,teamTyping:!1,messages:[]};let o=new URLSearchParams({visitorId:m,conversationId:y});h&&o.set("after",h);let c=await(await L(`/api/v1/chat/updates?${o.toString()}`)).json(),w=c.messages??[];return d(w),l=c.handoff===!0,{handoff:l,teamTyping:c.teamTyping===!0,messages:w}},async identify(o){await L("/api/v1/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o,visitorId:m})})},async upload(o,c="photo.jpg"){let w=new FormData;w.append("file",o,c),w.append("visitorId",m),y&&w.append("conversationId",y);let x=await(await L("/api/v1/chat/upload",{method:"POST",body:w})).json();return{id:x.id,url:x.url}},async feedback(o,c){if(!y)throw new U("bad_request","There is no conversation yet.",400);await L("/api/v1/chat/feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:m,conversationId:y,messageIndex:o,feedback:c})})},reset(){g(null),l=!1,h=null}}}function gn(t){let n=ge(null),s=ge(!1);return fe(()=>{n.current?.setTheme(t.theme??"auto")},[t.theme]),fe(()=>{if(s.current)return;s.current=!0;let{onReady:i,...u}=t;return n.current=xt(u),i?.(n.current),()=>{n.current?.destroy(),n.current=null,s.current=!1}},[]),null}var Gt=3e3;function Kt(){return typeof document<"u"&&document.visibilityState==="hidden"}function Tt(t,n){return[...t.slice(0,-1),n]}function Qt(t,n){let s=new Set(t.map(u=>u.id).filter(Boolean)),i=n.filter(u=>!u.id||!s.has(u.id));return i.length?[...t,...i]:t}function Ct(t){let n=t[t.length-1];return n?.role==="assistant"&&!n.text&&!n.cards?.length?t.slice(0,-1):t}function pn(t){let[n]=J(()=>St(t)),[s,i]=J([]),[u,f]=J("idle"),[m,y]=J(null),[l,h]=J(null),[d,v]=J(!1),[L,g]=J(!1),I=ge(!1),o=ge(0),c=t.loadHistory!==!1,w=t.live!==!1;fe(()=>{let C=!0;return n.agent().then(E=>C&&h(E)).catch(()=>{}),c&&n.history().then(E=>{C&&(i(k=>k.length?k:E),v(n.handoff))}).catch(()=>{}),()=>{C=!1}},[n,c]),fe(()=>{if(!w||!d)return;let C=!1,E=!1,k=async()=>{if(!(C||E||Kt())){E=!0;try{let O=await n.updates();if(C)return;g(O.teamTyping),O.messages.length&&i(N=>Qt(N,O.messages)),O.handoff||v(!1)}catch{}finally{E=!1}}},T=()=>{k()};k();let M=setInterval(()=>{k()},Gt);return typeof document<"u"&&document.addEventListener("visibilitychange",T),()=>{C=!0,clearInterval(M),typeof document<"u"&&document.removeEventListener("visibilitychange",T)}},[n,d,w]);let x=Me(async(C,E={})=>{let k=C.trim();if(!k&&!E.fileIds?.length)return null;i(T=>[...T,{role:"user",text:k},{role:"assistant",text:""}]),f("streaming"),y(null),I.current=!0,o.current+=1;try{let T=await n.send(k,{...E,onDelta:(M,O)=>i(N=>Tt(N,{role:"assistant",text:O}))});return i(M=>Ct(Tt(M,{role:"assistant",text:T.text,...T.cards?{cards:T.cards}:{}}))),v(T.handoff===!0),f("idle"),T}catch(T){let M=T instanceof U?T:new U("network_error",String(T),0);return i(Ct),y(M),f("error"),null}finally{I.current=!1}},[n]),b=Me(async()=>{if(I.current)return;let C=o.current,E=await n.history();I.current||o.current!==C||(i(E),v(n.handoff))},[n]),_=Me(()=>{n.reset(),i([]),y(null),v(!1),f("idle")},[n]);return{messages:s,send:x,status:u,error:m,agent:l,handoff:d,teamTyping:d&&L,refresh:b,reset:_,client:n}}export{gn as BitPalmAgent,U as BitPalmApiError,pn as useBitPalmChat};
|
|
13
13
|
//# sourceMappingURL=react.js.map
|