@bitpalm/ai-agents 0.7.0 → 0.9.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/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;
@@ -99,13 +110,20 @@ interface ChatClient {
99
110
  readonly conversationId: string | null;
100
111
  /** True while your team has the conversation. Updated by send() and history(). */
101
112
  readonly handoff: boolean;
102
- /** Name, greeting, quick links and whether "Powered by BitPalm" has to show. */
113
+ /**
114
+ * Name, greeting, quick links and whether "Powered by BitPalm" has to show.
115
+ * With the signed userToken of a logged-in user, quick links for their role
116
+ * show and the greeting can use their first name.
117
+ */
103
118
  agent(options?: {
104
119
  url?: string;
120
+ userToken?: string;
105
121
  }): Promise<AgentConfig>;
106
122
  send(message: string, options?: SendOptions): Promise<SendResult>;
107
123
  /** The messages of the current conversation, or of the latest one of this visitor. */
108
124
  history(): Promise<ChatMessage[]>;
125
+ /** New replies of your team and whether someone is typing. Call it every few seconds while handoff is true. */
126
+ updates(): Promise<ChatUpdates>;
109
127
  /** Tells BitPalm who the logged-in user is. */
110
128
  identify(identity: Identity): Promise<void>;
111
129
  /** A photo for the next message, when the agent takes photos. */
@@ -159,6 +177,31 @@ interface BitPalmAgentOptions {
159
177
  * you can show the message yourself, false switches them off.
160
178
  */
161
179
  triggers?: boolean | "events";
180
+ /**
181
+ * Quick links for this embed. They replace the ones from the dashboard.
182
+ * Change them later with setQuickLinks(), for example after login.
183
+ */
184
+ quickLinks?: BitPalmQuickLink[];
185
+ }
186
+ /** A text, or texts per language like { en: "Prices", de: "Preise" }. */
187
+ type BitPalmText = string | Record<string, string>;
188
+ /**
189
+ * A button under the greeting. It sends a question to the agent or opens a url.
190
+ *
191
+ * @example
192
+ * { label: { en: "My rent", de: "Meine Miete" }, question: "When is my rent due?", pages: "/portal/*" }
193
+ */
194
+ interface BitPalmQuickLink {
195
+ /** Button text, at most 40 characters. */
196
+ label: BitPalmText;
197
+ /** What the button sends to the agent, at most 300 characters. */
198
+ question?: BitPalmText;
199
+ /** Instead of a question: a page the button opens (https://, mailto: or tel:). */
200
+ url?: string;
201
+ /** Where it shows: "*" for every page (default), or paths like "/pricing" or "/shop/*", several separated by commas. */
202
+ pages?: string;
203
+ /** Optional, for your own tracking. */
204
+ id?: string;
162
205
  }
163
206
  interface BitPalmIdentifyPayload {
164
207
  /** Stable user id from the host platform (required for signed identify). */
@@ -223,6 +266,14 @@ interface BitPalmAgentInstance {
223
266
  context: (data: BitPalmCustomContext) => void;
224
267
  /** Clear all custom context data. Use after purchase completion, logout, etc. */
225
268
  resetContext: () => void;
269
+ /**
270
+ * Replace the quick links under the greeting, shown at once. At most 8.
271
+ * An empty list shows none, null goes back to the ones from the dashboard.
272
+ *
273
+ * @example
274
+ * widget.setQuickLinks([{ label: "Open a ticket", question: "I want to report a problem." }]);
275
+ */
276
+ setQuickLinks: (links: BitPalmQuickLink[] | null) => void;
226
277
  /**
227
278
  * Programmatically send a message as the user.
228
279
  * Opens the widget if closed, then sends the message to the AI.
@@ -283,6 +334,8 @@ type ChatStatus = "idle" | "streaming" | "error";
283
334
  interface UseBitPalmChatOptions extends ChatClientOptions {
284
335
  /** Load the last conversation of this visitor on start. Defaults to true. */
285
336
  loadHistory?: boolean;
337
+ /** Show your team's replies as they come while it has the conversation. Defaults to true. */
338
+ live?: boolean;
286
339
  }
287
340
  /**
288
341
  * Your own chat UI in React, with BitPalm behind it. Keeps the messages,
@@ -300,9 +353,10 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
300
353
  error: BitPalmApiError | null;
301
354
  agent: AgentConfig | null;
302
355
  handoff: boolean;
356
+ teamTyping: boolean;
303
357
  refresh: () => Promise<void>;
304
358
  reset: () => void;
305
359
  client: ChatClient;
306
360
  };
307
361
 
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 };
362
+ export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type BitPalmQuickLink, 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;
@@ -99,13 +110,20 @@ interface ChatClient {
99
110
  readonly conversationId: string | null;
100
111
  /** True while your team has the conversation. Updated by send() and history(). */
101
112
  readonly handoff: boolean;
102
- /** Name, greeting, quick links and whether "Powered by BitPalm" has to show. */
113
+ /**
114
+ * Name, greeting, quick links and whether "Powered by BitPalm" has to show.
115
+ * With the signed userToken of a logged-in user, quick links for their role
116
+ * show and the greeting can use their first name.
117
+ */
103
118
  agent(options?: {
104
119
  url?: string;
120
+ userToken?: string;
105
121
  }): Promise<AgentConfig>;
106
122
  send(message: string, options?: SendOptions): Promise<SendResult>;
107
123
  /** The messages of the current conversation, or of the latest one of this visitor. */
108
124
  history(): Promise<ChatMessage[]>;
125
+ /** New replies of your team and whether someone is typing. Call it every few seconds while handoff is true. */
126
+ updates(): Promise<ChatUpdates>;
109
127
  /** Tells BitPalm who the logged-in user is. */
110
128
  identify(identity: Identity): Promise<void>;
111
129
  /** A photo for the next message, when the agent takes photos. */
@@ -159,6 +177,31 @@ interface BitPalmAgentOptions {
159
177
  * you can show the message yourself, false switches them off.
160
178
  */
161
179
  triggers?: boolean | "events";
180
+ /**
181
+ * Quick links for this embed. They replace the ones from the dashboard.
182
+ * Change them later with setQuickLinks(), for example after login.
183
+ */
184
+ quickLinks?: BitPalmQuickLink[];
185
+ }
186
+ /** A text, or texts per language like { en: "Prices", de: "Preise" }. */
187
+ type BitPalmText = string | Record<string, string>;
188
+ /**
189
+ * A button under the greeting. It sends a question to the agent or opens a url.
190
+ *
191
+ * @example
192
+ * { label: { en: "My rent", de: "Meine Miete" }, question: "When is my rent due?", pages: "/portal/*" }
193
+ */
194
+ interface BitPalmQuickLink {
195
+ /** Button text, at most 40 characters. */
196
+ label: BitPalmText;
197
+ /** What the button sends to the agent, at most 300 characters. */
198
+ question?: BitPalmText;
199
+ /** Instead of a question: a page the button opens (https://, mailto: or tel:). */
200
+ url?: string;
201
+ /** Where it shows: "*" for every page (default), or paths like "/pricing" or "/shop/*", several separated by commas. */
202
+ pages?: string;
203
+ /** Optional, for your own tracking. */
204
+ id?: string;
162
205
  }
163
206
  interface BitPalmIdentifyPayload {
164
207
  /** Stable user id from the host platform (required for signed identify). */
@@ -223,6 +266,14 @@ interface BitPalmAgentInstance {
223
266
  context: (data: BitPalmCustomContext) => void;
224
267
  /** Clear all custom context data. Use after purchase completion, logout, etc. */
225
268
  resetContext: () => void;
269
+ /**
270
+ * Replace the quick links under the greeting, shown at once. At most 8.
271
+ * An empty list shows none, null goes back to the ones from the dashboard.
272
+ *
273
+ * @example
274
+ * widget.setQuickLinks([{ label: "Open a ticket", question: "I want to report a problem." }]);
275
+ */
276
+ setQuickLinks: (links: BitPalmQuickLink[] | null) => void;
226
277
  /**
227
278
  * Programmatically send a message as the user.
228
279
  * Opens the widget if closed, then sends the message to the AI.
@@ -283,6 +334,8 @@ type ChatStatus = "idle" | "streaming" | "error";
283
334
  interface UseBitPalmChatOptions extends ChatClientOptions {
284
335
  /** Load the last conversation of this visitor on start. Defaults to true. */
285
336
  loadHistory?: boolean;
337
+ /** Show your team's replies as they come while it has the conversation. Defaults to true. */
338
+ live?: boolean;
286
339
  }
287
340
  /**
288
341
  * Your own chat UI in React, with BitPalm behind it. Keeps the messages,
@@ -300,9 +353,10 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
300
353
  error: BitPalmApiError | null;
301
354
  agent: AgentConfig | null;
302
355
  handoff: boolean;
356
+ teamTyping: boolean;
303
357
  refresh: () => Promise<void>;
304
358
  reset: () => void;
305
359
  client: ChatClient;
306
360
  };
307
361
 
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 };
362
+ export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type BitPalmQuickLink, 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(i=>i.startsWith("data:")).map(i=>i.slice(5).trimStart()).join(`
3
- `);if(!t)return null;try{let i=JSON.parse(t);return i&&typeof i.type=="string"?i:null}catch{return null}}function me(n){let t=[],i=n.replace(/\r\n/g,`
4
- `),s=i.indexOf(`
1
+ import{useCallback as Be,useEffect as ie,useRef as se,useState as J}from"react";function gt(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 pt(t,n){let a=t.createElement("div");a.setAttribute("data-bitpalm-trigger",""),a.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;`,a.style.position="fixed",a.style.right="24px",a.style.bottom=`${n.bottom}px`;let s=t.createElement("p");s.style.cssText="font-size:14px;color:#1f2937;margin:0;",s.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()},a.onclick=()=>n.onEngage(),a.append(s,u,f),a}var Ht=["dark","dark-mode","dark-theme","theme-dark"],Dt=["light","light-mode","light-theme","theme-light"],bt=["data-theme","data-color-scheme","data-color-mode","data-mode","data-bs-theme"],vt="(prefers-color-scheme: dark)";function fe(t){return t==="light"||t==="dark"?t:"auto"}function ht(t){if(!t)return null;if(Ht.some(n=>t.classList.contains(n)))return"dark";if(Dt.some(n=>t.classList.contains(n)))return"light";for(let n of bt){let a=(t.getAttribute(n)||"").toLowerCase();if(a.includes("dark"))return"dark";if(a.includes("light"))return"light"}return null}function Ae(t){let n=t/255;return n<=.03928?n/12.92:((n+.055)/1.055)**2.4}function yt(t,n){if(!t)return null;let a=n.getComputedStyle(t).backgroundColor.match(/rgba?\(([^)]+)\)/);if(!a)return null;let[s,u,f,m=1]=a[1].split(/[\s,/]+/).filter(Boolean).map(Number);return[s,u,f,m].some(l=>Number.isNaN(l))||m<.5?null:.2126*Ae(s)+.7152*Ae(u)+.0722*Ae(f)<.2?"dark":"light"}function Ut(t,n){let a=n.getComputedStyle(t.documentElement).colorScheme||"",s=t.querySelector('meta[name="color-scheme"]')?.getAttribute("content")||"",u=`${a} ${s}`.toLowerCase();return u.includes("dark")?u.includes("light")?n.matchMedia?.(vt).matches?"dark":"light":"dark":null}function ne(t=document,n=window){return ht(t.documentElement)??ht(t.body)??yt(t.body,n)??yt(t.documentElement,n)??Ut(t,n)??"light"}function Pe(t,n=document,a=window){let s=ne(n,a),u=!1,f=()=>{u=!1;let d=ne(n,a);d!==s&&(s=d,t(d))},m=()=>{u||(u=!0,typeof a.requestAnimationFrame=="function"?a.requestAnimationFrame(f):setTimeout(f,16))},b=typeof MutationObserver<"u"?new MutationObserver(m):null,l={attributes:!0,attributeFilter:["class","style",...bt]};b?.observe(n.documentElement,l),n.body&&b?.observe(n.body,l);let h=typeof a.matchMedia=="function"?a.matchMedia(vt):null;return h?.addEventListener?.("change",m),()=>{b?.disconnect(),h?.removeEventListener?.("change",m)}}var Nt="https://agents.bitpalm.ai",L="_bp_",Wt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),jt=8e3,wt=4096,xt=`${L}identify_signature`,Et=`${L}identify_fingerprint`,St=`${L}identify_sent_at`,Tt="0 4px 14px rgba(0,0,0,0.18)";function qt(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 g(t,n=180){return t?t.replace(/\s+/g," ").trim().slice(0,n):""}function Ft(t){return t?` ${t.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function G(t,n){for(let a of n)if(t.includes(a))return!0;return!1}function j(t){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(t)}function D(t){let n=g(t,50);if(!n)return"";let a=n.startsWith("+"),s=n.replace(/\D/g,"");return s.length<6?"":`${a?"+":""}${s.slice(0,20)}`}function Ct(t){let n=g(t,140).toLowerCase();return!n||!j(n)?"":n}function X(t,n){for(let a of n){let s=t.querySelector(a),u=g(s?.value);if(u)return u}return""}function zt(t){return g(t.getAttribute("data-bp-field")||t.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function Yt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Qt(t,n){let a=[],s=(l,h=140)=>{let d=g(l,h);d&&a.push(d)};s(n.name),s(n.id),s(n.getAttribute("autocomplete")),s(n.getAttribute("placeholder")),s(n.getAttribute("aria-label")),s(n.getAttribute("data-field")),s(n.getAttribute("data-name")),s(n.getAttribute("data-label")),s(n.getAttribute("data-bp-field")),s(n.getAttribute("data-bitpalm-field"));let u=new Set,f=l=>{let h=g(l,200);!h||u.has(h)||(u.add(h),a.push(h))};for(let l of Array.from(n.labels||[]))f(l.textContent);if(n.id){let l=t.querySelector(`label[for="${Yt(n.id)}"]`);f(l?.textContent)}let m=n.closest("label");f(m?.textContent);let b=n.getAttribute("aria-labelledby");if(b)for(let l of b.split(/\s+/)){if(!l)continue;let h=t.ownerDocument.getElementById(l);f(h?.textContent)}return a}function Jt(t){let n=g(X(t,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),a=D(X(t,["[data-bp-phone]","[data-bitpalm-phone]"])),s=g(X(t,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),u=g(X(t,["[data-bp-first-name]","[data-bitpalm-first-name]"])),f=g(X(t,["[data-bp-last-name]","[data-bitpalm-last-name]"])),m=g(X(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&&Wt.has(d.type.toLowerCase()))continue;let w=zt(d),I=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")||!!w;if(d instanceof HTMLInputElement&&d.type.toLowerCase()==="hidden"&&!I)continue;let p=g(d.value);if(!p)continue;let k=d instanceof HTMLInputElement?d.type.toLowerCase():"",i=Ft(Qt(t,d).join(" "));if(!n&&w==="email"&&j(p)){n=p.toLowerCase();continue}if(!a&&(w==="phone"||w==="tel"||w==="mobile"||w==="whatsapp")){let E=D(p);if(E){a=E;continue}}if(!m&&w==="company"){m=g(p,160);continue}if(!u&&(w==="first-name"||w==="firstname")){u=g(p,100);continue}if(!f&&(w==="last-name"||w==="lastname"||w==="surname")){f=g(p,100);continue}if(!s&&(w==="name"||w==="full-name"||w==="fullname")){!j(p)&&!D(p)&&(s=g(p,140));continue}let c=k==="email"||G(i,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),y=k==="tel"||G(i,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),x=G(i,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),v=G(i,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),M=G(i,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),C=G(i,[" full name "," fullname "," contact name "," name "])&&!c&&!y;if(!n&&c&&j(p)){n=p.toLowerCase();continue}if(!a&&y){let E=D(p);if(E){a=E;continue}}if(!m&&x){m=g(p,160);continue}if(!u&&v){u=g(p,100);continue}if(!f&&M){f=g(p,100);continue}if(!s&&C&&!j(p)&&!D(p)){s=g(p,140);continue}!n&&j(p)&&(n=p.toLowerCase())}if(s&&(j(s)||D(s))&&(s=""),m&&(j(m)||D(m))&&(m=""),s||(s=g([u,f].filter(Boolean).join(" "),140)),s&&n&&s.toLowerCase()===n.toLowerCase()&&(s=""),!!!(n||a)&&!!!(s&&m))return null;let h={...s?{name:s}:{},...n?{email:n}:{},...a?{phone:a}:{},...m?{company:m}:{}};return Object.keys(h).length>0?h:null}function Vt(){if(typeof document<"u"){let t=document.documentElement.lang;if(t)return t.slice(0,2).toLowerCase()}return"en"}function Me(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 a=window.matchMedia("(pointer: coarse)").matches,s=window.matchMedia("(hover: none)").matches,u=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return a&&s&&u<=900}function kt(t){let{slug:n,locale:a=Vt(),baseUrl:s=Nt,token:u,zIndex:f=9999,autoIdentify:m=!0,launcher:b=!0}=t,l=document,h=fe(t.theme),d=h==="auto"?ne():h,w=null,I=gt(t.triggers),p=I,k=null,i=l.createElement("iframe");i.setAttribute("data-bitpalm-chat","");let c=`${s}/t/${n}/widget`,y=new URLSearchParams({locale:a,theme:d});u&&y.set("token",u),p==="off"&&y.set("triggers","off"),i.src=`${c}?${y.toString()}`,i.allow="clipboard-write; microphone",i.setAttribute("allowtransparency","true"),i.loading="lazy",i.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(i.src).origin,v=l.createElement("div");if(v.setAttribute("role","button"),v.setAttribute("aria-label","Chat"),v.setAttribute("data-bitpalm-launcher",""),v.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:${Tt};transition:transform .2s,opacity .3s;opacity:0;`,v.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>',v.onmouseenter=()=>{v.style.transform="scale(1.05)"},v.onmouseleave=()=>{v.style.transform="scale(1)"},v.onclick=()=>te(),b&&l.body.appendChild(v),!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 M=null,C=!1,E=!1,A=!1,T=!1,_=!1,O=()=>{A||(A=!0,l.body.appendChild(i))},N=!1,pe=0,oe={overflow:"",overscrollBehavior:""},B={overflow:"",overscrollBehavior:"",position:"",top:"",left:"",right:"",width:""},$e=()=>{if(N||!_e())return;let o=l.documentElement,r=l.body;pe=window.scrollY||window.pageYOffset||0,oe.overflow=o.style.overflow,oe.overscrollBehavior=o.style.overscrollBehavior,B.overflow=r.style.overflow,B.overscrollBehavior=r.style.overscrollBehavior,B.position=r.style.position,B.top=r.style.top,B.left=r.style.left,B.right=r.style.right,B.width=r.style.width,o.style.overflow="hidden",o.style.overscrollBehavior="none",r.style.overflow="hidden",r.style.overscrollBehavior="none",r.style.position="fixed",r.style.top=`-${pe}px`,r.style.left="0",r.style.right="0",r.style.width="100%",N=!0},V=()=>{if(!N)return;let e=l.documentElement,o=l.body;e.style.overflow=oe.overflow,e.style.overscrollBehavior=oe.overscrollBehavior,o.style.overflow=B.overflow,o.style.overscrollBehavior=B.overscrollBehavior,o.style.position=B.position,o.style.top=B.top,o.style.left=B.left,o.style.right=B.right,o.style.width=B.width,window.scrollTo(0,pe),N=!1},Oe=()=>{let e=_e();i.style.display==="none"&&(i.style.display=""),e?(i.style.width="100vw",i.style.height="100dvh",i.style.left="0",i.style.top="0",i.style.bottom="0",i.style.right="0",$e()):(i.style.width="420px",i.style.height="620px",i.style.bottom="24px",i.style.right="24px",i.style.left="",i.style.top="",V()),i.style.opacity="1",i.style.pointerEvents="auto"},W=()=>{M&&(M.remove(),M=null)},re=()=>{k!==null&&(k=null,Z("trigger_hidden"))},Re=()=>{i.contentWindow?.postMessage({type:"bitpalm-triggers",enabled:p!=="off"},"*")},ae=()=>{},he=()=>{},K=!1,q=new Map;function Z(e,o){let r=q.get(e);if(r)for(let S of r)try{S(o)}catch{}}let He=e=>{if(e.origin===x){if(e.data?.type==="bitpalm-widget-config"){E=!1,C=!0,i.style.display==="none"&&(i.style.display=""),e.data.primaryColor&&(v.style.background=e.data.primaryColor,v.style.boxShadow=e.data.chatShadow==="none"?"none":Tt);let o=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){v.innerHTML="";let r=l.createElement("span");r.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${o}`;let P=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");P?(P.querySelectorAll("script,foreignObject").forEach(Y=>Y.remove()),P.querySelectorAll("*").forEach(Y=>{for(let Q of[...Y.attributes])(Q.name.startsWith("on")||Q.value&&Q.value.includes("javascript:"))&&Y.removeAttribute(Q.name)}),P.setAttribute("width","24"),P.setAttribute("height","24"),P.style.display="block",r.appendChild(P)):r.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>',v.appendChild(r)}else{let r=v.querySelector("svg");r&&(r.style.stroke=o)}b&&(v.style.display="flex",requestAnimationFrame(()=>{v.style.opacity="1"})),Re()}if(e.data?.type==="bitpalm-widget-resize"){let o=e.data.width>0,r=K;K=o,o&&!r&&Z("widget_opened"),!o&&r&&Z("widget_closed");let S=_e();o?(i.style.width=S?"100vw":`${e.data.width}px`,i.style.height=S?"100dvh":`${e.data.height}px`,S?(i.style.left="0",i.style.top="0",i.style.bottom="0",i.style.right="0",$e()):V(),i.style.opacity="1",i.style.pointerEvents="auto"):(V(),i.style.width="1px",i.style.height="1px",i.style.left="",i.style.top="",i.style.opacity="0",i.style.pointerEvents="none"),v.style.display=o||!b?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(E||!C||p==="off")return;let o=typeof e.data.message=="string"?e.data.message:"";if(!o)return;if(p==="events"){k=o,Z("trigger_shown",{message:o,triggerId:e.data.triggerId,triggerType:e.data.triggerType});return}W(),M=pt(l,{message:o,zIndex:f,bottom:b?90:24,onDismiss:()=>{W(),i.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},onEngage:()=>{if(W(),v.style.display="none",Oe(),O(),!T){_=!0;return}i.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:o},"*")}}),l.body.appendChild(M)}e.data?.type==="bitpalm-trigger-hide"&&(W(),re()),e.data?.type==="bitpalm-request-context"&&ae(),e.data?.type==="bitpalm-chat-event"&&e.data.event&&Z(e.data.event,e.data.data),e.data?.type==="bitpalm-widget-blocked"&&(E=!0,C=!1,v.style.display="none",W(),re(),V(),i.style.display="none")}};window.addEventListener("message",He);let R=!1;try{R=localStorage.getItem(`${L}optout`)==="1"}catch{}let le=`${L}vid`,$="";if(!R){try{$=localStorage.getItem(le)||""}catch{}if(!$){let e=l.cookie.match(new RegExp(`(?:^|; )${le}=([^;]+)`));$=e?decodeURIComponent(e[1]):""}$||($=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(le,$)}catch{}try{l.cookie=`${le}=${encodeURIComponent($)};path=/;max-age=31536000;SameSite=Lax`}catch{}}R||Me(()=>{try{let e=new URLSearchParams(location.search),o={};for(let H of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let P=e.get(H);P&&(o[H]=P)}let r=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href,referrer:l.referrer||void 0,...Object.keys(o).length>0?{utm:o}:{}}),S=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(S,new Blob([r],{type:"application/json"})):fetch(S,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}},2e3);let ye="",be="",ve=0;try{ye=sessionStorage.getItem(xt)||"",be=sessionStorage.getItem(Et)||"";let e=parseInt(sessionStorage.getItem(St)||"0",10);Number.isFinite(e)&&e>0&&(ve=e)}catch{}let De=(e,o="")=>{if(R||!$)return;let r={},S=g(e.name,140),H=Ct(e.email),P=D(e.phone),Y=g(e.company,160),Q=g(e.external_user_id,140),ut=g(e.signature,260),ke=Number(e.signed_at);if(S&&(r.name=S),H&&(r.email=H),P&&(r.phone=P),Y&&(r.company=Y),Q&&(r.external_user_id=Q),ut&&(r.signature=ut),Number.isFinite(ke)&&ke>0&&(r.signed_at=Math.floor(ke)),(e.signature_version==="v1"||r.signature)&&(r.signature_version="v1"),(e.identify_source==="manual"||e.identify_source==="form")&&(r.identify_source=e.identify_source),!r.name&&!r.email&&!r.phone&&!r.company&&!r.external_user_id)return;let me=qt(r),Le=[o.toLowerCase(),me].filter(Boolean).join("|"),Ie=Date.now();if(!(Ie-ve<jt&&(Le===ye||me===be))){ye=Le,be=me,ve=Ie;try{sessionStorage.setItem(xt,Le),sessionStorage.setItem(Et,me),sessionStorage.setItem(St,String(Ie))}catch{}try{let mt=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href,referrer:l.referrer||void 0,...r}),ft=`${s}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(ft,new Blob([mt],{type:"application/json"})):fetch(ft,{method:"POST",body:mt,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}},Ue=e=>{if(R||!m||!$)return;let o=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(o instanceof HTMLFormElement))return;let r=(o.getAttribute("data-bp-identify")||o.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(r==="off"||r==="false"||r==="0")return;let S=Jt(o);if(!S)return;let H=[o.getAttribute("id")||"",o.getAttribute("name")||"",o.getAttribute("action")||""].join("|");De({...S,identify_source:"form"},H)};!R&&m&&l.addEventListener("submit",Ue,!0);let ee=parseInt(sessionStorage.getItem(`${L}pages`)||"0")+1;sessionStorage.setItem(`${L}pages`,String(ee));let F=JSON.parse(sessionStorage.getItem(`${L}hist`)||"[]");F.push(location.href),F.length>20&&(F=F.slice(-20)),sessionStorage.setItem(`${L}hist`,JSON.stringify(F));let Ne=Date.now(),ce=parseInt(sessionStorage.getItem(`${L}site_start`)||"0");ce||(ce=Ne,sessionStorage.setItem(`${L}site_start`,String(ce)));let We=[];ae=()=>{let e=!1;try{e=!!localStorage.getItem(`${L}visited`)}catch{e=!1}if(i.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:l.title,returning:e,pageCount:ee,pageHistory:F,loadedAt:Ne,siteStart:ce,locale:a,visitorId:R?"":$},"*"),Xe(),Rt(),!e&&!R)try{localStorage.setItem(`${L}visited`,"1")}catch{}},i.addEventListener("load",()=>{T=!0,ae(),[120,450,1100].forEach(e=>{let o=setTimeout(()=>ae(),e);We.push(o)}),_&&(_=!1,he())}),l.readyState==="loading"?l.addEventListener("DOMContentLoaded",()=>Me(O,1600),{once:!0}):Me(O,1600);let je=history.pushState.bind(history),qe=history.replaceState.bind(history),de=()=>{ee++,sessionStorage.setItem(`${L}pages`,String(ee));let e=JSON.parse(sessionStorage.getItem(`${L}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),F=e,sessionStorage.setItem(`${L}hist`,JSON.stringify(e)),i.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:l.title,pageCount:ee,pageHistory:e,loadedAt:Date.now()},"*"),!R)try{let o=JSON.stringify({tenant_slug:n,visitor_id:$,url:location.href}),r=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(r,new Blob([o],{type:"application/json"})):fetch(r,{method:"POST",body:o,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){je(...e),de()},history.replaceState=function(...e){qe(...e),de()},window.addEventListener("popstate",de);let Fe=-1,we,ze=()=>{clearTimeout(we),we=setTimeout(()=>{let e=Math.max(l.documentElement.scrollHeight,l.body.scrollHeight)-window.innerHeight,o=e>0?Math.round(window.scrollY/e*100):100;o!==Fe&&(Fe=o,i.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:o},"*"))},500)};window.addEventListener("scroll",ze,{passive:!0});let Ye=e=>{e.clientY<=0&&i.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};l.addEventListener("mouseout",Ye);let xe,Qe=!1,Ee=()=>{clearTimeout(xe),!Qe&&(xe=setTimeout(()=>{Qe=!0,i.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Je=["mousemove","keydown","scroll","touchstart"];Je.forEach(e=>l.addEventListener(e,Ee,{passive:!0})),Ee(),he=()=>{i.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=i.src.split("#")[0];i.src=`${e}#bp-open-${Date.now()}`};let te=()=>{if(v.style.display="none",W(),Oe(),O(),!T){_=!0;return}if(k!==null){let e=k;re(),i.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:e},"*");return}he()},Ve=e=>{p=e,e==="off"&&(W(),re()),Re()},Mt=()=>Ve("off"),_t=()=>Ve(I==="off"?"bubble":I),Se=()=>{V(),i.contentWindow?.postMessage({type:"bitpalm-close"},"*")},Ke=e=>{!e||typeof e!="object"||De({external_user_id:g(e.externalUserId,140)||void 0,name:g(e.name,140)||void 0,email:Ct(e.email)||void 0,phone:D(e.phone)||void 0,company:g(e.company,160)||void 0,signature:g(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")},Bt=()=>{K?Se():te()},$t=()=>K,Ge=e=>{if(!e||typeof e!="string")return;let o=e.trim().slice(0,1e4);o&&(K||te(),setTimeout(()=>{i.contentWindow?.postMessage({type:"bitpalm-send-message",message:o},"*")},K?50:500))};function Xe(){i.contentWindow?.postMessage({type:"bitpalm-theme",theme:d},"*")}let ue=e=>{e!==d&&(d=e,Xe())},Ze=e=>{h=fe(e),w?.(),w=null,h==="auto"?(w=Pe(ue),ue(ne())):ue(h)};h==="auto"&&(w=Pe(ue));let et=e=>{let o=e.detail;if(!o||typeof o!="object")return;let r=g(o.slug,120);r&&r!==n||Ze(fe(o.theme))};window.addEventListener("bitpalm-theme",et);let z={},tt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;z={...z,...e};let o=JSON.stringify(z);o.length>wt&&console.warn(`[BitPalm] Custom context exceeds ${wt} bytes (${o.length}). It may be truncated.`),i.contentWindow?.postMessage({type:"bitpalm-custom-context",data:z},"*")},Ot=()=>{z={},i.contentWindow?.postMessage({type:"bitpalm-custom-context",data:{}},"*")},Te=Array.isArray(t.quickLinks)?t.quickLinks:null,nt=Te!==null,it=()=>{i.contentWindow?.postMessage({type:"bitpalm-quick-links",links:Te},"*")},st=e=>{Te=Array.isArray(e)?e.slice(0,8):null,nt=!0,it()};function Rt(){Object.keys(z).length>0&&i.contentWindow?.postMessage({type:"bitpalm-custom-context",data:z},"*"),nt&&it()}let ot=e=>{let o=e.detail;if(!o||typeof o!="object")return;let r=g(o.slug,120);r&&r!==n||st(o.links??null)};window.addEventListener("bitpalm-quick-links",ot);let rt=e=>{let r=e.detail;if(!r||typeof r!="object")return;let S=g(r.slug,120);if(S&&S!==n)return;let{slug:H,...P}=r;tt(P)};window.addEventListener("bitpalm-context",rt);let at=e=>{let r=e.detail;if(!r||typeof r!="object")return;let S=g(r.slug,120);S&&S!==n||Ke(r)};window.addEventListener("bitpalm-identify",at);let Ce=e=>{let o=e.detail,r=g(o?.slug,120);return!r||r===n},lt=e=>{Ce(e)&&te()},ct=e=>{Ce(e)&&Se()},dt=e=>{if(!Ce(e))return;let o=e.detail?.message;typeof o=="string"&&Ge(o)};return window.addEventListener("bitpalm-open",lt),window.addEventListener("bitpalm-close",ct),window.addEventListener("bitpalm-send",dt),{open:te,close:Se,toggle:Bt,isOpen:$t,identify:Ke,context:tt,resetContext:Ot,setQuickLinks:st,send:Ge,on:(e,o)=>(q.has(e)||q.set(e,new Set),q.get(e).add(o),()=>q.get(e)?.delete(o)),off:(e,o)=>{q.get(e)?.delete(o)},setTheme:Ze,disableTriggers:Mt,enableTriggers:_t,destroy:()=>{window.removeEventListener("message",He),window.removeEventListener("scroll",ze),window.removeEventListener("popstate",de),l.removeEventListener("mouseout",Ye),l.removeEventListener("submit",Ue,!0),Je.forEach(e=>l.removeEventListener(e,Ee)),clearTimeout(we),clearTimeout(xe),We.forEach(e=>clearTimeout(e)),history.pushState=je,history.replaceState=qe,window.removeEventListener("bitpalm-identify",at),window.removeEventListener("bitpalm-context",rt),window.removeEventListener("bitpalm-quick-links",ot),window.removeEventListener("bitpalm-theme",et),window.removeEventListener("bitpalm-open",lt),window.removeEventListener("bitpalm-close",ct),window.removeEventListener("bitpalm-send",dt),w?.(),q.clear(),V(),W(),v.remove(),i.remove()}}}function Kt(t){let n=t.split(`
2
+ `).filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()).join(`
3
+ `);if(!n)return null;try{let a=JSON.parse(n);return a&&typeof a.type=="string"?a:null}catch{return null}}function ge(t){let n=[],a=t.replace(/\r\n/g,`
4
+ `),s=a.indexOf(`
5
5
 
6
- `);for(;s>=0;){let m=qt(i.slice(0,s));m&&t.push(m),i=i.slice(s+2),s=i.indexOf(`
6
+ `);for(;s>=0;){let u=Kt(a.slice(0,s));u&&n.push(u),a=a.slice(s+2),s=a.indexOf(`
7
7
 
8
- `)}return{events:t,rest:i}}function Et(n){return me(`${n}
8
+ `)}return{events:n,rest:a}}function Lt(t){return ge(`${t}
9
9
 
10
- `).events}var O=class extends Error{constructor(i,s,m){super(s);this.code=i;this.status=m;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 Gt(n){let t=await n.json().catch(()=>null);return new O(t?.error?.code??"server_error",t?.error?.message??`Request failed (${n.status})`,n.status)}function St(n){if(!n?.key?.startsWith("bp_pk_"))throw new Error("createChatClient needs an app key (bp_pk_\u2026) from the BitPalm dashboard.");let t=(n.baseUrl??zt).replace(/\/+$/,""),i=n.storage===void 0?Yt():n.storage,s=`bitpalm:${n.key.slice(0,14)}`,m=l=>{try{return i?.getItem(`${s}:${l}`)??null}catch{return null}},g=(l,u)=>{try{u===null?i?.removeItem(`${s}:${l}`):i?.setItem(`${s}:${l}`,u)}catch{}},p=n.visitorId??m("visitor")??Jt();n.visitorId||g("visitor",p);let b=m("conversation"),c=!1,w={Authorization:`Bearer ${n.key}`},d=async(l,u)=>{let o=await fetch(`${t}${l}`,{...u,headers:{...w,...u?.headers??{}}});if(!o.ok)throw await Gt(o);return o},y=l=>{b=l,g("conversation",l)},L=(l,u,o)=>{for(let v of l)if(v.type==="delta")u.text+=v.text,o?.(v.text,u.text);else if(v.type==="replace")u.text=v.text,o?.("",u.text);else if(v.type==="done")u.result={text:u.text,conversationId:v.conversationId,...v.cards?{cards:v.cards}:{},...v.handoff?{handoff:!0}:{}};else if(v.type==="error")throw new O("server_error",v.message,500)};return{visitorId:p,get conversationId(){return b},get handoff(){return c},async agent(l){let u=new URLSearchParams({locale:n.locale??"en"});return l?.url&&u.set("url",l.url),(await d(`/api/v1/agent?${u.toString()}`)).json()},async send(l,u={}){let o=await d("/api/v1/chat",{method:"POST",headers:{"Content-Type":"application/json"},signal:u.signal,body:JSON.stringify({message:l,visitorId:p,conversationId:b??void 0,context:u.context,fileIds:u.fileIds})}),v={text:"",result:null},_=o.body&&typeof o.body.getReader=="function"?o.body.getReader():null;if(_){let f=new TextDecoder,S="";for(;;){let{done:E,value:C}=await _.read();if(E)break;let D=me(S+f.decode(C,{stream:!0}));S=D.rest,L(D.events,v,u.onDelta)}L(me(`${S}
10
+ `).events}var U=class extends Error{constructor(a,s,u){super(s);this.code=a;this.status=u;this.name="BitPalmApiError"}},Gt="https://agents.bitpalm.ai";function Xt(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Zt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}async function en(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 It(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??Gt).replace(/\/+$/,""),a=t.storage===void 0?Xt():t.storage,s=`bitpalm:${t.key.slice(0,14)}`,u=i=>{try{return a?.getItem(`${s}:${i}`)??null}catch{return null}},f=(i,c)=>{try{c===null?a?.removeItem(`${s}:${i}`):a?.setItem(`${s}:${i}`,c)}catch{}},m=t.visitorId??u("visitor")??Zt();t.visitorId||f("visitor",m);let b=u("conversation"),l=!1,h=null,d=i=>{for(let c of i)c.fromHuman&&c.createdAt&&(!h||c.createdAt>h)&&(h=c.createdAt)},w={Authorization:`Bearer ${t.key}`},I=async(i,c)=>{let y=await fetch(`${n}${i}`,{...c,headers:{...w,...c?.headers??{}}});if(!y.ok)throw await en(y);return y},p=i=>{b=i,f("conversation",i)},k=(i,c,y)=>{for(let x of i)if(x.type==="delta")c.text+=x.text,y?.(x.text,c.text);else if(x.type==="replace")c.text=x.text,y?.("",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 b},get handoff(){return l},async agent(i){let c=new URLSearchParams({locale:t.locale??"en"});i?.url&&c.set("url",i.url);let y=i?.userToken?{headers:{"X-BitPalm-User-Token":i.userToken}}:void 0;return(await I(`/api/v1/agent?${c.toString()}`,y)).json()},async send(i,c={}){let y=await I("/api/v1/chat",{method:"POST",headers:{"Content-Type":"application/json"},signal:c.signal,body:JSON.stringify({message:i,visitorId:m,conversationId:b??void 0,context:c.context,fileIds:c.fileIds})}),x={text:"",result:null},v=y.body&&typeof y.body.getReader=="function"?y.body.getReader():null;if(v){let C=new TextDecoder,E="";for(;;){let{done:A,value:T}=await v.read();if(A)break;let _=ge(E+C.decode(T,{stream:!0}));E=_.rest,k(_.events,x,c.onDelta)}k(ge(`${E}
11
11
 
12
- `).events,v,u.onDelta)}else L(Et(await o.text()),v,u.onDelta);let T=v.result??{text:v.text,conversationId:b??""};return T.conversationId&&y(T.conversationId),c=T.handoff===!0,T},async history(){let l=new URLSearchParams({visitorId:p});b&&l.set("conversationId",b);let u=await(await d(`/api/v1/chat/history?${l.toString()}`)).json();return u.conversationId&&y(u.conversationId),c=u.handoff===!0,u.messages},async identify(l){await d("/api/v1/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...l,visitorId:p})})},async upload(l,u="photo.jpg"){let o=new FormData;o.append("file",l,u),o.append("visitorId",p),b&&o.append("conversationId",b);let v=await(await d("/api/v1/chat/upload",{method:"POST",body:o})).json();return{id:v.id,url:v.url}},async feedback(l,u){if(!b)throw new O("bad_request","There is no conversation yet.",400);await d("/api/v1/chat/feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:p,conversationId:b,messageIndex:l,feedback:u})})},reset(){y(null),c=!1}}}function un(n){let t=fe(null),i=fe(!1);return Me(()=>{t.current?.setTheme(n.theme??"auto")},[n.theme]),Me(()=>{if(i.current)return;i.current=!0;let{onReady:s,...m}=n;return t.current=xt(m),s?.(t.current),()=>{t.current?.destroy(),t.current=null,i.current=!1}},[]),null}function Tt(n,t){return[...n.slice(0,-1),t]}function Ct(n){let t=n[n.length-1];return t?.role==="assistant"&&!t.text&&!t.cards?.length?n.slice(0,-1):n}function mn(n){let[t]=J(()=>St(n)),[i,s]=J([]),[m,g]=J("idle"),[p,b]=J(null),[c,w]=J(null),[d,y]=J(!1),L=fe(!1),l=fe(0),u=n.loadHistory!==!1;Me(()=>{let T=!0;return t.agent().then(f=>T&&w(f)).catch(()=>{}),u&&t.history().then(f=>{T&&(s(S=>S.length?S:f),y(t.handoff))}).catch(()=>{}),()=>{T=!1}},[t,u]);let o=_e(async(T,f={})=>{let S=T.trim();if(!S&&!f.fileIds?.length)return null;s(E=>[...E,{role:"user",text:S},{role:"assistant",text:""}]),g("streaming"),b(null),L.current=!0,l.current+=1;try{let E=await t.send(S,{...f,onDelta:(C,D)=>s(G=>Tt(G,{role:"assistant",text:D}))});return s(C=>Ct(Tt(C,{role:"assistant",text:E.text,...E.cards?{cards:E.cards}:{}}))),y(E.handoff===!0),g("idle"),E}catch(E){let C=E instanceof O?E:new O("network_error",String(E),0);return s(Ct),b(C),g("error"),null}finally{L.current=!1}},[t]),v=_e(async()=>{if(L.current)return;let T=l.current,f=await t.history();L.current||l.current!==T||(s(f),y(t.handoff))},[t]),_=_e(()=>{t.reset(),s([]),b(null),y(!1),g("idle")},[t]);return{messages:i,send:o,status:m,error:p,agent:c,handoff:d,refresh:v,reset:_,client:t}}export{un as BitPalmAgent,O as BitPalmApiError,mn as useBitPalmChat};
12
+ `).events,x,c.onDelta)}else k(Lt(await y.text()),x,c.onDelta);let M=x.result??{text:x.text,conversationId:b??""};return M.conversationId&&p(M.conversationId),l=M.handoff===!0,M},async history(){let i=new URLSearchParams({visitorId:m});b&&i.set("conversationId",b);let c=await(await I(`/api/v1/chat/history?${i.toString()}`)).json();return c.conversationId&&p(c.conversationId),l=c.handoff===!0,h=null,d(c.messages),c.messages},async updates(){if(!b)return{handoff:!1,teamTyping:!1,messages:[]};let i=new URLSearchParams({visitorId:m,conversationId:b});h&&i.set("after",h);let c=await(await I(`/api/v1/chat/updates?${i.toString()}`)).json(),y=c.messages??[];return d(y),l=c.handoff===!0,{handoff:l,teamTyping:c.teamTyping===!0,messages:y}},async identify(i){await I("/api/v1/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,visitorId:m})})},async upload(i,c="photo.jpg"){let y=new FormData;y.append("file",i,c),y.append("visitorId",m),b&&y.append("conversationId",b);let x=await(await I("/api/v1/chat/upload",{method:"POST",body:y})).json();return{id:x.id,url:x.url}},async feedback(i,c){if(!b)throw new U("bad_request","There is no conversation yet.",400);await I("/api/v1/chat/feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:m,conversationId:b,messageIndex:i,feedback:c})})},reset(){p(null),l=!1,h=null}}}function wn(t){let n=se(null),a=se(!1);ie(()=>{n.current?.setTheme(t.theme??"auto")},[t.theme]);let s=t.quickLinks===void 0?void 0:JSON.stringify(t.quickLinks),u=se(s);return ie(()=>{s!==u.current&&(u.current=s,n.current?.setQuickLinks(s===void 0?null:JSON.parse(s)))},[s]),ie(()=>{if(a.current)return;a.current=!0;let{onReady:f,...m}=t;return n.current=kt(m),f?.(n.current),()=>{n.current?.destroy(),n.current=null,a.current=!1}},[]),null}var tn=3e3;function nn(){return typeof document<"u"&&document.visibilityState==="hidden"}function At(t,n){return[...t.slice(0,-1),n]}function sn(t,n){let a=new Set(t.map(u=>u.id).filter(Boolean)),s=n.filter(u=>!u.id||!a.has(u.id));return s.length?[...t,...s]:t}function Pt(t){let n=t[t.length-1];return n?.role==="assistant"&&!n.text&&!n.cards?.length?t.slice(0,-1):t}function xn(t){let[n]=J(()=>It(t)),[a,s]=J([]),[u,f]=J("idle"),[m,b]=J(null),[l,h]=J(null),[d,w]=J(!1),[I,p]=J(!1),k=se(!1),i=se(0),c=t.loadHistory!==!1,y=t.live!==!1;ie(()=>{let C=!0;return n.agent().then(E=>C&&h(E)).catch(()=>{}),c&&n.history().then(E=>{C&&(s(A=>A.length?A:E),w(n.handoff))}).catch(()=>{}),()=>{C=!1}},[n,c]),ie(()=>{if(!y||!d)return;let C=!1,E=!1,A=async()=>{if(!(C||E||nn())){E=!0;try{let O=await n.updates();if(C)return;p(O.teamTyping),O.messages.length&&s(N=>sn(N,O.messages)),O.handoff||w(!1)}catch{}finally{E=!1}}},T=()=>{A()};A();let _=setInterval(()=>{A()},tn);return typeof document<"u"&&document.addEventListener("visibilitychange",T),()=>{C=!0,clearInterval(_),typeof document<"u"&&document.removeEventListener("visibilitychange",T)}},[n,d,y]);let x=Be(async(C,E={})=>{let A=C.trim();if(!A&&!E.fileIds?.length)return null;s(T=>[...T,{role:"user",text:A},{role:"assistant",text:""}]),f("streaming"),b(null),k.current=!0,i.current+=1;try{let T=await n.send(A,{...E,onDelta:(_,O)=>s(N=>At(N,{role:"assistant",text:O}))});return s(_=>Pt(At(_,{role:"assistant",text:T.text,...T.cards?{cards:T.cards}:{}}))),w(T.handoff===!0),f("idle"),T}catch(T){let _=T instanceof U?T:new U("network_error",String(T),0);return s(Pt),b(_),f("error"),null}finally{k.current=!1}},[n]),v=Be(async()=>{if(k.current)return;let C=i.current,E=await n.history();k.current||i.current!==C||(s(E),w(n.handoff))},[n]),M=Be(()=>{n.reset(),s([]),b(null),w(!1),f("idle")},[n]);return{messages:a,send:x,status:u,error:m,agent:l,handoff:d,teamTyping:d&&I,refresh:v,reset:M,client:n}}export{wn as BitPalmAgent,U as BitPalmApiError,xn as useBitPalmChat};
13
13
  //# sourceMappingURL=react.js.map