@bitpalm/ai-agents 0.8.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/README.md +14 -0
- package/dist/headless.cjs +4 -4
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +6 -1
- package/dist/headless.d.ts +6 -1
- package/dist/headless.js +8 -8
- package/dist/headless.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +34 -1
- package/dist/index.d.ts +34 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/react.cjs +8 -8
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +40 -2
- package/dist/react.d.ts +40 -2
- package/dist/react.js +8 -8
- package/dist/react.js.map +1 -1
- package/dist/widget.global.js +1 -1
- package/dist/widget.global.js.map +1 -1
- package/package.json +1 -1
package/dist/react.d.cts
CHANGED
|
@@ -110,9 +110,14 @@ interface ChatClient {
|
|
|
110
110
|
readonly conversationId: string | null;
|
|
111
111
|
/** True while your team has the conversation. Updated by send() and history(). */
|
|
112
112
|
readonly handoff: boolean;
|
|
113
|
-
/**
|
|
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
|
+
*/
|
|
114
118
|
agent(options?: {
|
|
115
119
|
url?: string;
|
|
120
|
+
userToken?: string;
|
|
116
121
|
}): Promise<AgentConfig>;
|
|
117
122
|
send(message: string, options?: SendOptions): Promise<SendResult>;
|
|
118
123
|
/** The messages of the current conversation, or of the latest one of this visitor. */
|
|
@@ -172,6 +177,31 @@ interface BitPalmAgentOptions {
|
|
|
172
177
|
* you can show the message yourself, false switches them off.
|
|
173
178
|
*/
|
|
174
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;
|
|
175
205
|
}
|
|
176
206
|
interface BitPalmIdentifyPayload {
|
|
177
207
|
/** Stable user id from the host platform (required for signed identify). */
|
|
@@ -236,6 +266,14 @@ interface BitPalmAgentInstance {
|
|
|
236
266
|
context: (data: BitPalmCustomContext) => void;
|
|
237
267
|
/** Clear all custom context data. Use after purchase completion, logout, etc. */
|
|
238
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;
|
|
239
277
|
/**
|
|
240
278
|
* Programmatically send a message as the user.
|
|
241
279
|
* Opens the widget if closed, then sends the message to the AI.
|
|
@@ -321,4 +359,4 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
|
|
|
321
359
|
client: ChatClient;
|
|
322
360
|
};
|
|
323
361
|
|
|
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 };
|
|
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
|
@@ -110,9 +110,14 @@ interface ChatClient {
|
|
|
110
110
|
readonly conversationId: string | null;
|
|
111
111
|
/** True while your team has the conversation. Updated by send() and history(). */
|
|
112
112
|
readonly handoff: boolean;
|
|
113
|
-
/**
|
|
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
|
+
*/
|
|
114
118
|
agent(options?: {
|
|
115
119
|
url?: string;
|
|
120
|
+
userToken?: string;
|
|
116
121
|
}): Promise<AgentConfig>;
|
|
117
122
|
send(message: string, options?: SendOptions): Promise<SendResult>;
|
|
118
123
|
/** The messages of the current conversation, or of the latest one of this visitor. */
|
|
@@ -172,6 +177,31 @@ interface BitPalmAgentOptions {
|
|
|
172
177
|
* you can show the message yourself, false switches them off.
|
|
173
178
|
*/
|
|
174
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;
|
|
175
205
|
}
|
|
176
206
|
interface BitPalmIdentifyPayload {
|
|
177
207
|
/** Stable user id from the host platform (required for signed identify). */
|
|
@@ -236,6 +266,14 @@ interface BitPalmAgentInstance {
|
|
|
236
266
|
context: (data: BitPalmCustomContext) => void;
|
|
237
267
|
/** Clear all custom context data. Use after purchase completion, logout, etc. */
|
|
238
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;
|
|
239
277
|
/**
|
|
240
278
|
* Programmatically send a message as the user.
|
|
241
279
|
* Opens the widget if closed, then sends the message to the AI.
|
|
@@ -321,4 +359,4 @@ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
|
|
|
321
359
|
client: ChatClient;
|
|
322
360
|
};
|
|
323
361
|
|
|
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 };
|
|
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 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(
|
|
3
|
-
`);if(!n)return null;try{let
|
|
4
|
-
`),
|
|
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(;
|
|
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:n,rest:
|
|
8
|
+
`)}return{events:n,rest:a}}function Lt(t){return ge(`${t}
|
|
9
9
|
|
|
10
|
-
`).events}var U=class extends Error{constructor(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,x,c.onDelta)}else
|
|
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
|