@bitpalm/ai-agents 0.1.12 → 0.1.13
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 +21 -3
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +8 -0
- package/dist/react.d.ts +8 -0
- package/dist/react.js +1 -1
- 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 +18 -10
package/dist/react.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var Y=(a,r)=>{for(var c in r)P(a,c,{get:r[c],enumerable:!0})},G=(a,r,c,u)=>{if(r&&typeof r=="object"||typeof r=="function")for(let g of q(r))!F.call(a,g)&&g!==c&&P(a,g,{get:()=>r[g],enumerable:!(u=J(r,g))||u.enumerable});return a};var V=a=>G(P({},"__esModule",{value:!0}),a);var Q={};Y(Q,{BitPalmAgent:()=>X});module.exports=V(Q);var x=require("react");var Z="https://agents.bitpalm.ae",l="_bp_";function K(){if(typeof document<"u"){let a=document.documentElement.lang;if(a)return a.slice(0,2).toLowerCase()}return"en"}function z(a){let{slug:r,locale:c=K(),baseUrl:u=Z,zIndex:g=9999}=a,o=document,e=o.createElement("iframe"),L=`${u}/t/${r}/widget`;e.src=`${L}${L.includes("?")?"&":"?"}locale=${c}`,e.allow="clipboard-write",e.setAttribute("allowtransparency","true"),e.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;`,o.body.appendChild(e);let N=new URL(e.src).origin,n=o.createElement("div");if(n.setAttribute("role","button"),n.setAttribute("aria-label","Chat"),n.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:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',n.onmouseenter=()=>{n.style.transform="scale(1.1)"},n.onmouseleave=()=>{n.style.transform="scale(1)"},n.onclick=()=>D(),o.body.appendChild(n),!o.getElementById("_bp_fade")){let t=o.createElement("style");t.id="_bp_fade",t.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",o.head.appendChild(t)}let m=null,h=()=>{m&&(m.remove(),m=null)},_=t=>{if(t.origin===N){if(t.data?.type==="bitpalm-widget-config"){t.data.primaryColor&&(n.style.background=t.data.primaryColor,n.style.boxShadow=t.data.chatShadow==="none"?"none":`0 0 15px ${t.data.primaryColor}50`);let i=t.data.chatButtonIconColor||"black";if(t.data.chatButtonIconSvg){n.innerHTML="";let s=o.createElement("span");s.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${i}`;let d=new DOMParser().parseFromString(t.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");d?(d.querySelectorAll("script,foreignObject").forEach($=>$.remove()),d.querySelectorAll("*").forEach($=>{for(let I of[...$.attributes])(I.name.startsWith("on")||I.value&&I.value.includes("javascript:"))&&$.removeAttribute(I.name)}),d.setAttribute("width","24"),d.setAttribute("height","24"),d.style.display="block",s.appendChild(d)):s.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>',n.appendChild(s)}else{let s=n.querySelector("svg");s&&(s.style.stroke=i)}n.style.display="flex",requestAnimationFrame(()=>{n.style.opacity="1"})}if(t.data?.type==="bitpalm-widget-resize"){let i=t.data.width>0,s=window.innerWidth<=640;i?(e.style.width=s?`${window.innerWidth}px`:`${t.data.width}px`,e.style.height=s?`${window.innerHeight}px`:`${t.data.height}px`,s&&(e.style.left="0",e.style.top="0"),e.style.opacity="1",e.style.pointerEvents="auto"):(e.style.width="1px",e.style.height="1px",e.style.left="",e.style.top="",e.style.opacity="0",e.style.pointerEvents="none"),n.style.display=i?"none":"flex"}if(t.data?.type==="bitpalm-trigger-show"){h(),m=o.createElement("div"),m.style.cssText=`position:fixed;bottom:90px;right:24px;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:${g-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let i=(t.data.message||"").replace(/</g,"<");m.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${i}</p><div style="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;"></div>`;let s=o.createElement("button");s.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;",s.innerHTML="✕",s.onclick=w=>{w.stopPropagation(),h(),e.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},m.onclick=()=>{h(),n.style.display="none",e.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},m.appendChild(s),o.body.appendChild(m)}t.data?.type==="bitpalm-trigger-hide"&&h(),t.data?.type==="bitpalm-widget-blocked"&&(n.style.display="none",h(),e.style.display="none")}};window.addEventListener("message",_);let y=!1;try{y=localStorage.getItem(`${l}optout`)==="1"}catch{}let v=`${l}vid`,p="";if(!y){try{p=localStorage.getItem(v)||""}catch{}if(!p){let t=o.cookie.match(new RegExp(`(?:^|; )${v}=([^;]+)`));p=t?decodeURIComponent(t[1]):""}p||(p=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(v,p)}catch{}try{o.cookie=`${v}=${encodeURIComponent(p)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!y)try{let t=new URLSearchParams(location.search),i={};for(let B of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let d=t.get(B);d&&(i[B]=d)}let s=JSON.stringify({tenant_slug:r,visitor_id:p,url:location.href,referrer:o.referrer||void 0,...Object.keys(i).length>0?{utm:i}:{}}),w=`${u}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(w,new Blob([s],{type:"application/json"})):fetch(w,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let b=parseInt(sessionStorage.getItem(`${l}pages`)||"0")+1;sessionStorage.setItem(`${l}pages`,String(b));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 M=Date.now(),S=parseInt(sessionStorage.getItem(`${l}site_start`)||"0");S||(S=M,sessionStorage.setItem(`${l}site_start`,String(S))),e.addEventListener("load",()=>{let t=!!localStorage.getItem(`${l}visited`);e.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:o.title,returning:t,pageCount:b,pageHistory:f,loadedAt:M,siteStart:S,locale:c,visitorId:y?"":p},"*"),!t&&!y&&localStorage.setItem(`${l}visited`,"1")});let C=history.pushState.bind(history),O=history.replaceState.bind(history),E=()=>{b++,sessionStorage.setItem(`${l}pages`,String(b));let t=JSON.parse(sessionStorage.getItem(`${l}hist`)||"[]");if(t.push(location.href),t.length>20&&t.splice(0,t.length-20),sessionStorage.setItem(`${l}hist`,JSON.stringify(t)),e.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:o.title,pageCount:b,pageHistory:t,loadedAt:Date.now()},"*"),!y)try{let i=JSON.stringify({tenant_slug:r,visitor_id:p,url:location.href}),s=`${u}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(s,new Blob([i],{type:"application/json"})):fetch(s,{method:"POST",body:i,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...t){C(...t),E()},history.replaceState=function(...t){O(...t),E()},window.addEventListener("popstate",E);let W=-1,A,R=()=>{clearTimeout(A),A=setTimeout(()=>{let t=Math.max(o.documentElement.scrollHeight,o.body.scrollHeight)-window.innerHeight,i=t>0?Math.round(window.scrollY/t*100):100;i!==W&&(W=i,e.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:i},"*"))},500)};window.addEventListener("scroll",R,{passive:!0});let U=t=>{t.clientY<=0&&e.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};o.addEventListener("mouseout",U);let k,j=!1,T=()=>{clearTimeout(k),!j&&(k=setTimeout(()=>{j=!0,e.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},H=["mousemove","keydown","scroll","touchstart"];H.forEach(t=>o.addEventListener(t,T,{passive:!0})),T();let D=()=>{n.style.display="none",h(),e.contentWindow?.postMessage({type:"bitpalm-open"},"*");let t=e.src.split("#")[0];e.src=`${t}#bp-open-${Date.now()}`};return{open:D,close:()=>{e.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",_),window.removeEventListener("scroll",R),window.removeEventListener("popstate",E),o.removeEventListener("mouseout",U),H.forEach(t=>o.removeEventListener(t,T)),clearTimeout(A),clearTimeout(k),history.pushState=C,history.replaceState=O,h(),n.remove(),e.remove()}}}function X(a){let r=(0,x.useRef)(null),c=(0,x.useRef)(!1);return(0,x.useEffect)(()=>{if(!c.current)return c.current=!0,r.current=z(a),()=>{r.current?.destroy(),r.current=null,c.current=!1}},[]),null}0&&(module.exports={BitPalmAgent});
|
|
1
|
+
"use strict";var U=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var at=(n,o)=>{for(var l in o)U(n,l,{get:o[l],enumerable:!0})},it=(n,o,l,c)=>{if(o&&typeof o=="object"||typeof o=="function")for(let p of nt(o))!ot.call(n,p)&&p!==l&&U(n,p,{get:()=>o[p],enumerable:!(c=et(o,p))||c.enumerable});return n};var st=n=>it(U({},"__esModule",{value:!0}),n);var ut={};at(ut,{BitPalmAgent:()=>mt});module.exports=st(ut);var P=require("react");var rt="https://agents.bitpalm.ae",g="_bp_",lt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]);function f(n,o=180){return n?n.replace(/\s+/g," ").trim().slice(0,o):""}function ct(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function E(n,o){for(let l of o)if(n.includes(l))return!0;return!1}function N(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function D(n){let o=f(n,50);if(!o)return"";let l=o.startsWith("+"),c=o.replace(/\D/g,"");return c.length<6?"":`${l?"+":""}${c.slice(0,20)}`}function k(n,o){for(let l of o){let c=n.querySelector(l),p=f(c?.value);if(p)return p}return""}function pt(n){let o=f(k(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),l=D(k(n,["[data-bp-phone]","[data-bitpalm-phone]"])),c=f(k(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),p=f(k(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),x=f(k(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),v=f(k(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let t of Array.from(n.elements)){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)||t.disabled||t instanceof HTMLInputElement&<.has(t.type.toLowerCase()))continue;let O=t.hasAttribute("data-bp-email")||t.hasAttribute("data-bitpalm-email")||t.hasAttribute("data-bp-phone")||t.hasAttribute("data-bitpalm-phone")||t.hasAttribute("data-bp-name")||t.hasAttribute("data-bitpalm-name")||t.hasAttribute("data-bp-full-name")||t.hasAttribute("data-bitpalm-full-name")||t.hasAttribute("data-bp-first-name")||t.hasAttribute("data-bitpalm-first-name")||t.hasAttribute("data-bp-last-name")||t.hasAttribute("data-bitpalm-last-name")||t.hasAttribute("data-bp-company")||t.hasAttribute("data-bitpalm-company");if(t instanceof HTMLInputElement&&t.type.toLowerCase()==="hidden"&&!O)continue;let d=f(t.value);if(!d)continue;let B=t instanceof HTMLInputElement?t.type.toLowerCase():"",a=ct([t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("placeholder"),t.getAttribute("aria-label"),t.getAttribute("data-field"),t.getAttribute("data-name")].filter(Boolean).join(" ")),h=B==="email"||E(a,[" email "," e mail "," mail "," correo "]),b=B==="tel"||E(a,[" phone "," mobile "," tel "," whatsapp "," handy "," telefon "," kontakt "]),_=E(a,[" company "," firma "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),w=E(a,[" first name "," firstname "," given name "," given name "," givenname "," vorname "]),L=E(a,[" last name "," lastname "," family name "," familyname "," surname "," nachname "]),m=E(a,[" full name "," fullname "," contact name "," name "])&&!h&&!b;if(!o&&h&&N(d)){o=d.toLowerCase();continue}if(!l&&b){let $=D(d);if($){l=$;continue}}if(!v&&_){v=f(d,160);continue}if(!p&&w){p=f(d,100);continue}if(!x&&L){x=f(d,100);continue}if(!c&&m&&!N(d)&&!D(d)){c=f(d,140);continue}!o&&N(d)&&E(a,[" mail "," email "," e mail "])&&(o=d.toLowerCase())}c||(c=f([p,x].filter(Boolean).join(" "),140));let i={...c?{name:c}:{},...o?{email:o}:{},...l?{phone:l}:{},...v?{company:v}:{}};return Object.keys(i).length>0?i:null}function dt(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function tt(n){let{slug:o,locale:l=dt(),baseUrl:c=rt,token:p,zIndex:x=9999,autoIdentify:v=!0}=n,i=document,t=i.createElement("iframe"),O=`${c}/t/${o}/widget`,d=new URLSearchParams({locale:l});p&&d.set("token",p),t.src=`${O}?${d.toString()}`,t.allow="clipboard-write",t.setAttribute("allowtransparency","true"),t.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${x};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,i.body.appendChild(t);let B=new URL(t.src).origin,a=i.createElement("div");if(a.setAttribute("role","button"),a.setAttribute("aria-label","Chat"),a.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:${x-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',a.onmouseenter=()=>{a.style.transform="scale(1.1)"},a.onmouseleave=()=>{a.style.transform="scale(1)"},a.onclick=()=>Q(),i.body.appendChild(a),!i.getElementById("_bp_fade")){let e=i.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",i.head.appendChild(e)}let h=null,b=()=>{h&&(h.remove(),h=null)},_=e=>{if(e.origin===B){if(e.data?.type==="bitpalm-widget-config"){e.data.primaryColor&&(a.style.background=e.data.primaryColor,a.style.boxShadow=e.data.chatShadow==="none"?"none":`0 0 15px ${e.data.primaryColor}50`);let s=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){a.innerHTML="";let r=i.createElement("span");r.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${s}`;let u=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");u?(u.querySelectorAll("script,foreignObject").forEach(S=>S.remove()),u.querySelectorAll("*").forEach(S=>{for(let A of[...S.attributes])(A.name.startsWith("on")||A.value&&A.value.includes("javascript:"))&&S.removeAttribute(A.name)}),u.setAttribute("width","24"),u.setAttribute("height","24"),u.style.display="block",r.appendChild(u)):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>',a.appendChild(r)}else{let r=a.querySelector("svg");r&&(r.style.stroke=s)}a.style.display="flex",requestAnimationFrame(()=>{a.style.opacity="1"})}if(e.data?.type==="bitpalm-widget-resize"){let s=e.data.width>0,r=window.innerWidth<=640;s?(t.style.width=r?`${window.innerWidth}px`:`${e.data.width}px`,t.style.height=r?`${window.innerHeight}px`:`${e.data.height}px`,r&&(t.style.left="0",t.style.top="0"),t.style.opacity="1",t.style.pointerEvents="auto"):(t.style.width="1px",t.style.height="1px",t.style.left="",t.style.top="",t.style.opacity="0",t.style.pointerEvents="none"),a.style.display=s?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){b(),h=i.createElement("div"),h.style.cssText=`position:fixed;bottom:90px;right:24px;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:${x-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let s=(e.data.message||"").replace(/</g,"<");h.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${s}</p><div style="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;"></div>`;let r=i.createElement("button");r.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;",r.innerHTML="✕",r.onclick=y=>{y.stopPropagation(),b(),t.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},h.onclick=()=>{b(),a.style.display="none",t.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},h.appendChild(r),i.body.appendChild(h)}e.data?.type==="bitpalm-trigger-hide"&&b(),e.data?.type==="bitpalm-widget-blocked"&&(a.style.display="none",b(),t.style.display="none")}};window.addEventListener("message",_);let w=!1;try{w=localStorage.getItem(`${g}optout`)==="1"}catch{}let L=`${g}vid`,m="";if(!w){try{m=localStorage.getItem(L)||""}catch{}if(!m){let e=i.cookie.match(new RegExp(`(?:^|; )${L}=([^;]+)`));m=e?decodeURIComponent(e[1]):""}m||(m=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(L,m)}catch{}try{i.cookie=`${L}=${encodeURIComponent(m)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!w)try{let e=new URLSearchParams(location.search),s={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let u=e.get(T);u&&(s[T]=u)}let r=JSON.stringify({tenant_slug:o,visitor_id:m,url:location.href,referrer:i.referrer||void 0,...Object.keys(s).length>0?{utm:s}:{}}),y=`${c}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(y,new Blob([r],{type:"application/json"})):fetch(y,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let $="",z=0,F=e=>{if(w||!v||!m)return;let s=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(s instanceof HTMLFormElement))return;let r=(s.getAttribute("data-bp-identify")||s.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(r==="off"||r==="false"||r==="0")return;let y=pt(s);if(!y)return;let T=[s.getAttribute("id")||"",s.getAttribute("name")||"",s.getAttribute("action")||"",y.email||"",y.phone||"",y.name||"",y.company||""].join("|").toLowerCase(),u=Date.now();if(!(T===$&&u-z<8e3)){$=T,z=u;try{let S=JSON.stringify({tenant_slug:o,visitor_id:m,url:location.href,referrer:i.referrer||void 0,...y}),A=`${c}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(A,new Blob([S],{type:"application/json"})):fetch(A,{method:"POST",body:S,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!w&&v&&i.addEventListener("submit",F,!0);let M=parseInt(sessionStorage.getItem(`${g}pages`)||"0")+1;sessionStorage.setItem(`${g}pages`,String(M));let I=JSON.parse(sessionStorage.getItem(`${g}hist`)||"[]");I.push(location.href),I.length>20&&(I=I.slice(-20)),sessionStorage.setItem(`${g}hist`,JSON.stringify(I));let q=Date.now(),C=parseInt(sessionStorage.getItem(`${g}site_start`)||"0");C||(C=q,sessionStorage.setItem(`${g}site_start`,String(C))),t.addEventListener("load",()=>{let e=!!localStorage.getItem(`${g}visited`);t.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:i.title,returning:e,pageCount:M,pageHistory:I,loadedAt:q,siteStart:C,locale:l,visitorId:w?"":m},"*"),!e&&!w&&localStorage.setItem(`${g}visited`,"1")});let J=history.pushState.bind(history),Y=history.replaceState.bind(history),H=()=>{M++,sessionStorage.setItem(`${g}pages`,String(M));let e=JSON.parse(sessionStorage.getItem(`${g}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),sessionStorage.setItem(`${g}hist`,JSON.stringify(e)),t.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:i.title,pageCount:M,pageHistory:e,loadedAt:Date.now()},"*"),!w)try{let s=JSON.stringify({tenant_slug:o,visitor_id:m,url:location.href}),r=`${c}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(r,new Blob([s],{type:"application/json"})):fetch(r,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){J(...e),H()},history.replaceState=function(...e){Y(...e),H()},window.addEventListener("popstate",H);let G=-1,j,V=()=>{clearTimeout(j),j=setTimeout(()=>{let e=Math.max(i.documentElement.scrollHeight,i.body.scrollHeight)-window.innerHeight,s=e>0?Math.round(window.scrollY/e*100):100;s!==G&&(G=s,t.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:s},"*"))},500)};window.addEventListener("scroll",V,{passive:!0});let Z=e=>{e.clientY<=0&&t.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};i.addEventListener("mouseout",Z);let W,K=!1,R=()=>{clearTimeout(W),!K&&(W=setTimeout(()=>{K=!0,t.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},X=["mousemove","keydown","scroll","touchstart"];X.forEach(e=>i.addEventListener(e,R,{passive:!0})),R();let Q=()=>{a.style.display="none",b(),t.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=t.src.split("#")[0];t.src=`${e}#bp-open-${Date.now()}`};return{open:Q,close:()=>{t.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",_),window.removeEventListener("scroll",V),window.removeEventListener("popstate",H),i.removeEventListener("mouseout",Z),i.removeEventListener("submit",F,!0),X.forEach(e=>i.removeEventListener(e,R)),clearTimeout(j),clearTimeout(W),history.pushState=J,history.replaceState=Y,b(),a.remove(),t.remove()}}}function mt(n){let o=(0,P.useRef)(null),l=(0,P.useRef)(!1);return(0,P.useEffect)(()=>{if(!l.current)return l.current=!0,o.current=tt(n),()=>{o.current?.destroy(),o.current=null,l.current=!1}},[]),null}0&&(module.exports={BitPalmAgent});
|
|
2
2
|
//# sourceMappingURL=react.cjs.map
|
package/dist/react.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts","../src/widget.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { createWidget } from \"./widget\";\nimport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type BitPalmAgentProps = BitPalmAgentOptions;\n\n/**\n * React component that mounts the BitPalm AI agent widget.\n *\n * @example\n * ```tsx\n * import { BitPalmAgent } from '@bitpalm/ai-agents/react';\n *\n * export default function App() {\n * return <BitPalmAgent slug=\"my-agent\" />;\n * }\n * ```\n */\nexport function BitPalmAgent(props: BitPalmAgentProps): null {\n const instanceRef = useRef<BitPalmAgentInstance | null>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n if (mountedRef.current) return;\n mountedRef.current = true;\n\n instanceRef.current = createWidget(props);\n\n return () => {\n instanceRef.current?.destroy();\n instanceRef.current = null;\n mountedRef.current = false;\n };\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n return null;\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n zIndex = 9999,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n iframe.src = `${widgetUrl}${widgetUrl.includes(\"?\") ? \"&\" : \"?\"}locale=${locale}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.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:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.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>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = window.innerWidth <= 640;\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;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:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"<\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"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;\"></div>`;\n const close = d.createElement(\"button\");\n close.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;\";\n close.innerHTML = \"✕\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n const returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\");\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget, destroy };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkC,iBCElC,IAAMC,EAAmB,4BACnBC,EAAiB,OAEvB,SAASC,GAAuB,CAC9B,GAAI,OAAO,SAAa,IAAa,CACnC,IAAMC,EAAO,SAAS,gBAAgB,KACtC,GAAIA,EAAM,OAAOA,EAAK,MAAM,EAAG,CAAC,EAAE,YAAY,CAChD,CACA,MAAO,IACT,CAEO,SAASC,EAAaC,EAAoD,CAC/E,GAAM,CACJ,KAAAC,EACA,OAAAC,EAASL,EAAa,EACtB,QAAAM,EAAUR,EACV,OAAAS,EAAS,IACX,EAAIJ,EAEEK,EAAI,SAGJC,EAASD,EAAE,cAAc,QAAQ,EACjCE,EAAY,GAAGJ,CAAO,MAAMF,CAAI,UACtCK,EAAO,IAAM,GAAGC,CAAS,GAAGA,EAAU,SAAS,GAAG,EAAI,IAAM,GAAG,UAAUL,CAAM,GAC/EI,EAAO,MAAQ,kBACfA,EAAO,aAAa,oBAAqB,MAAM,EAC/CA,EAAO,MAAM,QAAU,4EAA4E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ErBD,EAAY,QAAUE,EAAaH,CAAK,EAEjC,IAAM,CACXC,EAAY,SAAS,QAAQ,EAC7BA,EAAY,QAAU,KACtBC,EAAW,QAAU,EACvB,CACF,EAAG,CAAC,CAAC,EAEE,IACT","names":["react_exports","__export","BitPalmAgent","__toCommonJS","import_react","DEFAULT_BASE_URL","STORAGE_PREFIX","detectLocale","lang","createWidget","options","slug","locale","baseUrl","zIndex","d","iframe","widgetUrl","origin","btn","openWidget","s","bubble","removeBubble","handleMessage","e","ic","sp","svg","el","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","pageCount","hist","loadedAt","siteStart","returning","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","BitPalmAgent","props","instanceRef","mountedRef","createWidget"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts","../src/widget.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { createWidget } from \"./widget\";\nimport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type BitPalmAgentProps = BitPalmAgentOptions;\n\n/**\n * React component that mounts the BitPalm AI agent widget.\n *\n * @example\n * ```tsx\n * import { BitPalmAgent } from '@bitpalm/ai-agents/react';\n *\n * export default function App() {\n * return <BitPalmAgent slug=\"my-agent\" />;\n * }\n * ```\n */\nexport function BitPalmAgent(props: BitPalmAgentProps): null {\n const instanceRef = useRef<BitPalmAgentInstance | null>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n if (mountedRef.current) return;\n mountedRef.current = true;\n\n instanceRef.current = createWidget(props);\n\n return () => {\n instanceRef.current?.destroy();\n instanceRef.current = null;\n mountedRef.current = false;\n };\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n return null;\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\nconst IGNORED_INPUT_TYPES = new Set([\"password\", \"file\", \"checkbox\", \"radio\", \"submit\", \"button\", \"reset\", \"image\"]);\n\ntype IdentityPayload = {\n name?: string;\n email?: string;\n phone?: string;\n company?: string;\n};\n\nfunction normalizeText(value: string | null | undefined, maxLen = 180): string {\n if (!value) return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, maxLen);\n}\n\nfunction normalizeTokens(value: string | null | undefined): string {\n if (!value) return \"\";\n return ` ${value.toLowerCase().replace(/[_-]+/g, \" \").replace(/[^a-z0-9\\s@.]/g, \" \").replace(/\\s+/g, \" \").trim()} `;\n}\n\nfunction includesAny(haystack: string, needles: string[]): boolean {\n for (const needle of needles) {\n if (haystack.includes(needle)) return true;\n }\n return false;\n}\n\nfunction isEmail(value: string): boolean {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/i.test(value);\n}\n\nfunction normalizePhone(value: string): string {\n const trimmed = normalizeText(value, 50);\n if (!trimmed) return \"\";\n const hasPlus = trimmed.startsWith(\"+\");\n const digits = trimmed.replace(/\\D/g, \"\");\n if (digits.length < 6) return \"\";\n return `${hasPlus ? \"+\" : \"\"}${digits.slice(0, 20)}`;\n}\n\nfunction getExplicitValue(form: HTMLFormElement, selectors: string[]): string {\n for (const selector of selectors) {\n const el = form.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(selector);\n const value = normalizeText(el?.value);\n if (value) return value;\n }\n return \"\";\n}\n\nfunction extractIdentityFromForm(form: HTMLFormElement): IdentityPayload | null {\n let email = normalizeText(getExplicitValue(form, [\n \"[data-bp-email]\",\n \"[data-bitpalm-email]\",\n ]), 140).toLowerCase();\n\n let phone = normalizePhone(getExplicitValue(form, [\n \"[data-bp-phone]\",\n \"[data-bitpalm-phone]\",\n ]));\n\n let name = normalizeText(getExplicitValue(form, [\n \"[data-bp-name]\",\n \"[data-bitpalm-name]\",\n \"[data-bp-full-name]\",\n \"[data-bitpalm-full-name]\",\n ]));\n\n let firstName = normalizeText(getExplicitValue(form, [\n \"[data-bp-first-name]\",\n \"[data-bitpalm-first-name]\",\n ]));\n\n let lastName = normalizeText(getExplicitValue(form, [\n \"[data-bp-last-name]\",\n \"[data-bitpalm-last-name]\",\n ]));\n\n let company = normalizeText(getExplicitValue(form, [\n \"[data-bp-company]\",\n \"[data-bitpalm-company]\",\n ]));\n\n for (const rawEl of Array.from(form.elements)) {\n if (!(rawEl instanceof HTMLInputElement || rawEl instanceof HTMLTextAreaElement || rawEl instanceof HTMLSelectElement)) continue;\n if (rawEl.disabled) continue;\n if (rawEl instanceof HTMLInputElement && IGNORED_INPUT_TYPES.has(rawEl.type.toLowerCase())) continue;\n\n const explicitField =\n rawEl.hasAttribute(\"data-bp-email\") ||\n rawEl.hasAttribute(\"data-bitpalm-email\") ||\n rawEl.hasAttribute(\"data-bp-phone\") ||\n rawEl.hasAttribute(\"data-bitpalm-phone\") ||\n rawEl.hasAttribute(\"data-bp-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-name\") ||\n rawEl.hasAttribute(\"data-bp-full-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-full-name\") ||\n rawEl.hasAttribute(\"data-bp-first-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-first-name\") ||\n rawEl.hasAttribute(\"data-bp-last-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-last-name\") ||\n rawEl.hasAttribute(\"data-bp-company\") ||\n rawEl.hasAttribute(\"data-bitpalm-company\");\n\n if (rawEl instanceof HTMLInputElement && rawEl.type.toLowerCase() === \"hidden\" && !explicitField) continue;\n\n const value = normalizeText(rawEl.value);\n if (!value) continue;\n\n const type = rawEl instanceof HTMLInputElement ? rawEl.type.toLowerCase() : \"\";\n const tokens = normalizeTokens([\n rawEl.name,\n rawEl.id,\n rawEl.getAttribute(\"autocomplete\"),\n rawEl.getAttribute(\"placeholder\"),\n rawEl.getAttribute(\"aria-label\"),\n rawEl.getAttribute(\"data-field\"),\n rawEl.getAttribute(\"data-name\"),\n ].filter(Boolean).join(\" \"));\n\n const emailLike = type === \"email\" || includesAny(tokens, [\" email \", \" e mail \", \" mail \", \" correo \"]);\n const phoneLike = type === \"tel\" || includesAny(tokens, [\" phone \", \" mobile \", \" tel \", \" whatsapp \", \" handy \", \" telefon \", \" kontakt \"]);\n const companyLike = includesAny(tokens, [\" company \", \" firma \", \" organization \", \" organisation \", \" business \", \" unternehmen \", \" agency \", \" brokerage \"]);\n const firstNameLike = includesAny(tokens, [\" first name \", \" firstname \", \" given name \", \" given name \", \" givenname \", \" vorname \"]);\n const lastNameLike = includesAny(tokens, [\" last name \", \" lastname \", \" family name \", \" familyname \", \" surname \", \" nachname \"]);\n const fullNameLike = includesAny(tokens, [\" full name \", \" fullname \", \" contact name \", \" name \"]) && !emailLike && !phoneLike;\n\n if (!email && emailLike && isEmail(value)) {\n email = value.toLowerCase();\n continue;\n }\n if (!phone && phoneLike) {\n const normalized = normalizePhone(value);\n if (normalized) {\n phone = normalized;\n continue;\n }\n }\n if (!company && companyLike) {\n company = normalizeText(value, 160);\n continue;\n }\n if (!firstName && firstNameLike) {\n firstName = normalizeText(value, 100);\n continue;\n }\n if (!lastName && lastNameLike) {\n lastName = normalizeText(value, 100);\n continue;\n }\n if (!name && fullNameLike && !isEmail(value) && !normalizePhone(value)) {\n name = normalizeText(value, 140);\n continue;\n }\n\n if (!email && isEmail(value) && includesAny(tokens, [\" mail \", \" email \", \" e mail \"])) {\n email = value.toLowerCase();\n }\n }\n\n if (!name) {\n name = normalizeText([firstName, lastName].filter(Boolean).join(\" \"), 140);\n }\n\n const identity: IdentityPayload = {\n ...(name ? { name } : {}),\n ...(email ? { email } : {}),\n ...(phone ? { phone } : {}),\n ...(company ? { company } : {}),\n };\n\n return Object.keys(identity).length > 0 ? identity : null;\n}\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n token,\n zIndex = 9999,\n autoIdentify = true,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n const qs = new URLSearchParams({ locale });\n if (token) qs.set(\"token\", token);\n iframe.src = `${widgetUrl}?${qs.toString()}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.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:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.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>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = window.innerWidth <= 640;\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;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:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"<\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"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;\"></div>`;\n const close = d.createElement(\"button\");\n close.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;\";\n close.innerHTML = \"✕\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Auto-identify visitor from form submissions on host page ---\n let lastIdentitySignature = \"\";\n let lastIdentitySentAt = 0;\n const handleFormSubmit = (event: Event) => {\n if (optedOut || !autoIdentify || !visitorId) return;\n\n const form = event.target instanceof HTMLFormElement\n ? event.target\n : event.target instanceof Element\n ? event.target.closest(\"form\")\n : null;\n if (!(form instanceof HTMLFormElement)) return;\n\n const formIdentifySetting = (form.getAttribute(\"data-bp-identify\") || form.getAttribute(\"data-bitpalm-identify\") || \"\").toLowerCase();\n if (formIdentifySetting === \"off\" || formIdentifySetting === \"false\" || formIdentifySetting === \"0\") return;\n\n const identity = extractIdentityFromForm(form);\n if (!identity) return;\n\n const signature = [\n form.getAttribute(\"id\") || \"\",\n form.getAttribute(\"name\") || \"\",\n form.getAttribute(\"action\") || \"\",\n identity.email || \"\",\n identity.phone || \"\",\n identity.name || \"\",\n identity.company || \"\",\n ].join(\"|\").toLowerCase();\n\n const now = Date.now();\n if (signature === lastIdentitySignature && now - lastIdentitySentAt < 8000) return;\n lastIdentitySignature = signature;\n lastIdentitySentAt = now;\n\n try {\n const payload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...identity,\n });\n const identifyUrl = `${baseUrl}/api/widget/identify`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(identifyUrl, new Blob([payload], { type: \"application/json\" }));\n } else {\n fetch(identifyUrl, { method: \"POST\", body: payload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch {\n // ignore\n }\n };\n\n if (!optedOut && autoIdentify) {\n d.addEventListener(\"submit\", handleFormSubmit, true);\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n const returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\");\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n d.removeEventListener(\"submit\", handleFormSubmit, true);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget, destroy };\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,KAAA,eAAAC,GAAAH,IAAA,IAAAI,EAAkC,iBCElC,IAAMC,GAAmB,4BACnBC,EAAiB,OACjBC,GAAsB,IAAI,IAAI,CAAC,WAAY,OAAQ,WAAY,QAAS,SAAU,SAAU,QAAS,OAAO,CAAC,EASnH,SAASC,EAAcC,EAAkCC,EAAS,IAAa,CAC7E,OAAKD,EACEA,EAAM,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAGC,CAAM,EADrC,EAErB,CAEA,SAASC,GAAgBF,EAA0C,CACjE,OAAKA,EACE,IAAIA,E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QAAS,EAAK,CAAC,CAAC,EAC/EA,EAAU,EAGV,IAAMtD,EAAa,IAAM,CACvBD,EAAI,MAAM,QAAU,OACpBI,EAAa,EAEbR,EAAO,eAAe,YAAY,CAAE,KAAM,cAAe,EAAG,GAAG,EAE/D,IAAM6D,EAAO7D,EAAO,IAAI,MAAM,GAAG,EAAE,CAAC,EACpCA,EAAO,IAAM,GAAG6D,CAAI,YAAY,KAAK,IAAI,CAAC,EAC5C,EAsBA,MAAO,CAAE,KAAMxD,EAAY,MApBP,IAAM,CACxBL,EAAO,eAAe,YAAY,CAAE,KAAM,eAAgB,EAAG,GAAG,CAClE,EAkB+C,QAhB/B,IAAM,CACpB,OAAO,oBAAoB,UAAWS,CAAa,EACnD,OAAO,oBAAoB,SAAU4C,CAAY,EACjD,OAAO,oBAAoB,WAAYP,CAAK,EAC5C/C,EAAE,oBAAoB,WAAYyD,CAAc,EAChDzD,EAAE,oBAAoB,SAAUiC,EAAkB,EAAI,EACtD4B,EAAW,QAASzC,GAAOpB,EAAE,oBAAoBoB,EAAIwC,CAAS,CAAC,EAC/D,aAAaP,CAAa,EAC1B,aAAaK,CAAS,EACtB,QAAQ,UAAYb,EACpB,QAAQ,aAAeC,EACvBrC,EAAa,EACbJ,EAAI,OAAO,EACXJ,EAAO,OAAO,CAChB,CAEuD,CACzD,CDpjBO,SAAS8D,GAAaC,EAAgC,CAC3D,IAAMC,KAAc,UAAoC,IAAI,EACtDC,KAAa,UAAO,EAAK,EAE/B,sBAAU,IAAM,CACd,GAAI,CAAAA,EAAW,QACf,OAAAA,EAAW,QAAU,GAErBD,EAAY,QAAUE,GAAaH,CAAK,EAEjC,IAAM,CACXC,EAAY,SAAS,QAAQ,EAC7BA,EAAY,QAAU,KACtBC,EAAW,QAAU,EACvB,CACF,EAAG,CAAC,CAAC,EAEE,IACT","names":["react_exports","__export","BitPalmAgent","__toCommonJS","import_react","DEFAULT_BASE_URL","STORAGE_PREFIX","IGNORED_INPUT_TYPES","normalizeText","value","maxLen","normalizeTokens","includesAny","haystack","needles","needle","isEmail","normalizePhone","trimmed","hasPlus","digits","getExplicitValue","form","selectors","selector","el","extractIdentityFromForm","email","phone","name","firstName","lastName","company","rawEl","explicitField","type","tokens","emailLike","phoneLike","companyLike","firstNameLike","lastNameLike","fullNameLike","normalized","identity","detectLocale","lang","createWidget","options","slug","locale","baseUrl","token","zIndex","autoIdentify","d","iframe","widgetUrl","qs","origin","btn","openWidget","s","bubble","removeBubble","handleMessage","ic","sp","svg","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","lastIdentitySignature","lastIdentitySentAt","handleFormSubmit","event","formIdentifySetting","signature","now","payload","identifyUrl","pageCount","hist","loadedAt","siteStart","returning","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","BitPalmAgent","props","instanceRef","mountedRef","createWidget"]}
|
package/dist/react.d.cts
CHANGED
|
@@ -5,8 +5,16 @@ interface BitPalmAgentOptions {
|
|
|
5
5
|
locale?: string;
|
|
6
6
|
/** Base URL of the agent platform. Defaults to "https://agents.bitpalm.ae". */
|
|
7
7
|
baseUrl?: string;
|
|
8
|
+
/** Embed token for restricted/private agents. */
|
|
9
|
+
token?: string;
|
|
8
10
|
/** z-index for the widget elements. Defaults to 9999. */
|
|
9
11
|
zIndex?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Automatically detect form submissions on the host page and attach
|
|
14
|
+
* captured identity fields (email/phone/name/company) to the current visitor.
|
|
15
|
+
* Defaults to true.
|
|
16
|
+
*/
|
|
17
|
+
autoIdentify?: boolean;
|
|
10
18
|
}
|
|
11
19
|
interface BitPalmAgentInstance {
|
|
12
20
|
/** Open the chat widget programmatically. */
|
package/dist/react.d.ts
CHANGED
|
@@ -5,8 +5,16 @@ interface BitPalmAgentOptions {
|
|
|
5
5
|
locale?: string;
|
|
6
6
|
/** Base URL of the agent platform. Defaults to "https://agents.bitpalm.ae". */
|
|
7
7
|
baseUrl?: string;
|
|
8
|
+
/** Embed token for restricted/private agents. */
|
|
9
|
+
token?: string;
|
|
8
10
|
/** z-index for the widget elements. Defaults to 9999. */
|
|
9
11
|
zIndex?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Automatically detect form submissions on the host page and attach
|
|
14
|
+
* captured identity fields (email/phone/name/company) to the current visitor.
|
|
15
|
+
* Defaults to true.
|
|
16
|
+
*/
|
|
17
|
+
autoIdentify?: boolean;
|
|
10
18
|
}
|
|
11
19
|
interface BitPalmAgentInstance {
|
|
12
20
|
/** Open the chat widget programmatically. */
|
package/dist/react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useEffect as q,useRef as D}from"react";var N="https://agents.bitpalm.ae",r="_bp_";function J(){if(typeof document<"u"){let g=document.documentElement.lang;if(g)return g.slice(0,2).toLowerCase()}return"en"}function H(g){let{slug:p,locale:m=J(),baseUrl:E=N,zIndex:$=9999}=g,o=document,e=o.createElement("iframe"),B=`${E}/t/${p}/widget`;e.src=`${B}${B.includes("?")?"&":"?"}locale=${m}`,e.allow="clipboard-write",e.setAttribute("allowtransparency","true"),e.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${$};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,o.body.appendChild(e);let z=new URL(e.src).origin,n=o.createElement("div");if(n.setAttribute("role","button"),n.setAttribute("aria-label","Chat"),n.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:${$-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',n.onmouseenter=()=>{n.style.transform="scale(1.1)"},n.onmouseleave=()=>{n.style.transform="scale(1)"},n.onclick=()=>j(),o.body.appendChild(n),!o.getElementById("_bp_fade")){let t=o.createElement("style");t.id="_bp_fade",t.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",o.head.appendChild(t)}let c=null,d=()=>{c&&(c.remove(),c=null)},P=t=>{if(t.origin===z){if(t.data?.type==="bitpalm-widget-config"){t.data.primaryColor&&(n.style.background=t.data.primaryColor,n.style.boxShadow=t.data.chatShadow==="none"?"none":`0 0 15px ${t.data.primaryColor}50`);let i=t.data.chatButtonIconColor||"black";if(t.data.chatButtonIconSvg){n.innerHTML="";let s=o.createElement("span");s.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${i}`;let l=new DOMParser().parseFromString(t.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");l?(l.querySelectorAll("script,foreignObject").forEach(v=>v.remove()),l.querySelectorAll("*").forEach(v=>{for(let S of[...v.attributes])(S.name.startsWith("on")||S.value&&S.value.includes("javascript:"))&&v.removeAttribute(S.name)}),l.setAttribute("width","24"),l.setAttribute("height","24"),l.style.display="block",s.appendChild(l)):s.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>',n.appendChild(s)}else{let s=n.querySelector("svg");s&&(s.style.stroke=i)}n.style.display="flex",requestAnimationFrame(()=>{n.style.opacity="1"})}if(t.data?.type==="bitpalm-widget-resize"){let i=t.data.width>0,s=window.innerWidth<=640;i?(e.style.width=s?`${window.innerWidth}px`:`${t.data.width}px`,e.style.height=s?`${window.innerHeight}px`:`${t.data.height}px`,s&&(e.style.left="0",e.style.top="0"),e.style.opacity="1",e.style.pointerEvents="auto"):(e.style.width="1px",e.style.height="1px",e.style.left="",e.style.top="",e.style.opacity="0",e.style.pointerEvents="none"),n.style.display=i?"none":"flex"}if(t.data?.type==="bitpalm-trigger-show"){d(),c=o.createElement("div"),c.style.cssText=`position:fixed;bottom:90px;right:24px;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:${$-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let i=(t.data.message||"").replace(/</g,"<");c.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${i}</p><div style="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;"></div>`;let s=o.createElement("button");s.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;",s.innerHTML="✕",s.onclick=f=>{f.stopPropagation(),d(),e.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},c.onclick=()=>{d(),n.style.display="none",e.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},c.appendChild(s),o.body.appendChild(c)}t.data?.type==="bitpalm-trigger-hide"&&d(),t.data?.type==="bitpalm-widget-blocked"&&(n.style.display="none",d(),e.style.display="none")}};window.addEventListener("message",P);let h=!1;try{h=localStorage.getItem(`${r}optout`)==="1"}catch{}let b=`${r}vid`,a="";if(!h){try{a=localStorage.getItem(b)||""}catch{}if(!a){let t=o.cookie.match(new RegExp(`(?:^|; )${b}=([^;]+)`));a=t?decodeURIComponent(t[1]):""}a||(a=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(b,a)}catch{}try{o.cookie=`${b}=${encodeURIComponent(a)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!h)try{let t=new URLSearchParams(location.search),i={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let l=t.get(T);l&&(i[T]=l)}let s=JSON.stringify({tenant_slug:p,visitor_id:a,url:location.href,referrer:o.referrer||void 0,...Object.keys(i).length>0?{utm:i}:{}}),f=`${E}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(f,new Blob([s],{type:"application/json"})):fetch(f,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let y=parseInt(sessionStorage.getItem(`${r}pages`)||"0")+1;sessionStorage.setItem(`${r}pages`,String(y));let u=JSON.parse(sessionStorage.getItem(`${r}hist`)||"[]");u.push(location.href),u.length>20&&(u=u.slice(-20)),sessionStorage.setItem(`${r}hist`,JSON.stringify(u));let L=Date.now(),w=parseInt(sessionStorage.getItem(`${r}site_start`)||"0");w||(w=L,sessionStorage.setItem(`${r}site_start`,String(w))),e.addEventListener("load",()=>{let t=!!localStorage.getItem(`${r}visited`);e.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:o.title,returning:t,pageCount:y,pageHistory:u,loadedAt:L,siteStart:w,locale:m,visitorId:h?"":a},"*"),!t&&!h&&localStorage.setItem(`${r}visited`,"1")});let _=history.pushState.bind(history),M=history.replaceState.bind(history),x=()=>{y++,sessionStorage.setItem(`${r}pages`,String(y));let t=JSON.parse(sessionStorage.getItem(`${r}hist`)||"[]");if(t.push(location.href),t.length>20&&t.splice(0,t.length-20),sessionStorage.setItem(`${r}hist`,JSON.stringify(t)),e.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:o.title,pageCount:y,pageHistory:t,loadedAt:Date.now()},"*"),!h)try{let i=JSON.stringify({tenant_slug:p,visitor_id:a,url:location.href}),s=`${E}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(s,new Blob([i],{type:"application/json"})):fetch(s,{method:"POST",body:i,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...t){_(...t),x()},history.replaceState=function(...t){M(...t),x()},window.addEventListener("popstate",x);let C=-1,I,O=()=>{clearTimeout(I),I=setTimeout(()=>{let t=Math.max(o.documentElement.scrollHeight,o.body.scrollHeight)-window.innerHeight,i=t>0?Math.round(window.scrollY/t*100):100;i!==C&&(C=i,e.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:i},"*"))},500)};window.addEventListener("scroll",O,{passive:!0});let W=t=>{t.clientY<=0&&e.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};o.addEventListener("mouseout",W);let A,R=!1,k=()=>{clearTimeout(A),!R&&(A=setTimeout(()=>{R=!0,e.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},U=["mousemove","keydown","scroll","touchstart"];U.forEach(t=>o.addEventListener(t,k,{passive:!0})),k();let j=()=>{n.style.display="none",d(),e.contentWindow?.postMessage({type:"bitpalm-open"},"*");let t=e.src.split("#")[0];e.src=`${t}#bp-open-${Date.now()}`};return{open:j,close:()=>{e.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",P),window.removeEventListener("scroll",O),window.removeEventListener("popstate",x),o.removeEventListener("mouseout",W),U.forEach(t=>o.removeEventListener(t,k)),clearTimeout(I),clearTimeout(A),history.pushState=_,history.replaceState=M,d(),n.remove(),e.remove()}}}function K(g){let p=D(null),m=D(!1);return q(()=>{if(!m.current)return m.current=!0,p.current=H(g),()=>{p.current?.destroy(),p.current=null,m.current=!1}},[]),null}export{K as BitPalmAgent};
|
|
1
|
+
import{useEffect as it,useRef as Q}from"react";var tt="https://agents.bitpalm.ae",u="_bp_",et=new Set(["password","file","checkbox","radio","submit","button","reset","image"]);function g(o,r=180){return o?o.replace(/\s+/g," ").trim().slice(0,r):""}function nt(o){return o?` ${o.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function E(o,r){for(let l of r)if(o.includes(l))return!0;return!1}function R(o){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(o)}function U(o){let r=g(o,50);if(!r)return"";let l=r.startsWith("+"),c=r.replace(/\D/g,"");return c.length<6?"":`${l?"+":""}${c.slice(0,20)}`}function k(o,r){for(let l of r){let c=o.querySelector(l),w=g(c?.value);if(w)return w}return""}function ot(o){let r=g(k(o,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),l=U(k(o,["[data-bp-phone]","[data-bitpalm-phone]"])),c=g(k(o,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),w=g(k(o,["[data-bp-first-name]","[data-bitpalm-first-name]"])),x=g(k(o,["[data-bp-last-name]","[data-bitpalm-last-name]"])),v=g(k(o,["[data-bp-company]","[data-bitpalm-company]"]));for(let t of Array.from(o.elements)){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)||t.disabled||t instanceof HTMLInputElement&&et.has(t.type.toLowerCase()))continue;let H=t.hasAttribute("data-bp-email")||t.hasAttribute("data-bitpalm-email")||t.hasAttribute("data-bp-phone")||t.hasAttribute("data-bitpalm-phone")||t.hasAttribute("data-bp-name")||t.hasAttribute("data-bitpalm-name")||t.hasAttribute("data-bp-full-name")||t.hasAttribute("data-bitpalm-full-name")||t.hasAttribute("data-bp-first-name")||t.hasAttribute("data-bitpalm-first-name")||t.hasAttribute("data-bp-last-name")||t.hasAttribute("data-bitpalm-last-name")||t.hasAttribute("data-bp-company")||t.hasAttribute("data-bitpalm-company");if(t instanceof HTMLInputElement&&t.type.toLowerCase()==="hidden"&&!H)continue;let p=g(t.value);if(!p)continue;let P=t instanceof HTMLInputElement?t.type.toLowerCase():"",n=nt([t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("placeholder"),t.getAttribute("aria-label"),t.getAttribute("data-field"),t.getAttribute("data-name")].filter(Boolean).join(" ")),f=P==="email"||E(n,[" email "," e mail "," mail "," correo "]),y=P==="tel"||E(n,[" phone "," mobile "," tel "," whatsapp "," handy "," telefon "," kontakt "]),B=E(n,[" company "," firma "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),b=E(n,[" first name "," firstname "," given name "," given name "," givenname "," vorname "]),L=E(n,[" last name "," lastname "," family name "," familyname "," surname "," nachname "]),d=E(n,[" full name "," fullname "," contact name "," name "])&&!f&&!y;if(!r&&f&&R(p)){r=p.toLowerCase();continue}if(!l&&y){let $=U(p);if($){l=$;continue}}if(!v&&B){v=g(p,160);continue}if(!w&&b){w=g(p,100);continue}if(!x&&L){x=g(p,100);continue}if(!c&&d&&!R(p)&&!U(p)){c=g(p,140);continue}!r&&R(p)&&E(n,[" mail "," email "," e mail "])&&(r=p.toLowerCase())}c||(c=g([w,x].filter(Boolean).join(" "),140));let a={...c?{name:c}:{},...r?{email:r}:{},...l?{phone:l}:{},...v?{company:v}:{}};return Object.keys(a).length>0?a:null}function at(){if(typeof document<"u"){let o=document.documentElement.lang;if(o)return o.slice(0,2).toLowerCase()}return"en"}function X(o){let{slug:r,locale:l=at(),baseUrl:c=tt,token:w,zIndex:x=9999,autoIdentify:v=!0}=o,a=document,t=a.createElement("iframe"),H=`${c}/t/${r}/widget`,p=new URLSearchParams({locale:l});w&&p.set("token",w),t.src=`${H}?${p.toString()}`,t.allow="clipboard-write",t.setAttribute("allowtransparency","true"),t.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${x};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,a.body.appendChild(t);let P=new URL(t.src).origin,n=a.createElement("div");if(n.setAttribute("role","button"),n.setAttribute("aria-label","Chat"),n.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:${x-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',n.onmouseenter=()=>{n.style.transform="scale(1.1)"},n.onmouseleave=()=>{n.style.transform="scale(1)"},n.onclick=()=>K(),a.body.appendChild(n),!a.getElementById("_bp_fade")){let e=a.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",a.head.appendChild(e)}let f=null,y=()=>{f&&(f.remove(),f=null)},B=e=>{if(e.origin===P){if(e.data?.type==="bitpalm-widget-config"){e.data.primaryColor&&(n.style.background=e.data.primaryColor,n.style.boxShadow=e.data.chatShadow==="none"?"none":`0 0 15px ${e.data.primaryColor}50`);let i=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){n.innerHTML="";let s=a.createElement("span");s.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${i}`;let m=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");m?(m.querySelectorAll("script,foreignObject").forEach(S=>S.remove()),m.querySelectorAll("*").forEach(S=>{for(let A of[...S.attributes])(A.name.startsWith("on")||A.value&&A.value.includes("javascript:"))&&S.removeAttribute(A.name)}),m.setAttribute("width","24"),m.setAttribute("height","24"),m.style.display="block",s.appendChild(m)):s.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>',n.appendChild(s)}else{let s=n.querySelector("svg");s&&(s.style.stroke=i)}n.style.display="flex",requestAnimationFrame(()=>{n.style.opacity="1"})}if(e.data?.type==="bitpalm-widget-resize"){let i=e.data.width>0,s=window.innerWidth<=640;i?(t.style.width=s?`${window.innerWidth}px`:`${e.data.width}px`,t.style.height=s?`${window.innerHeight}px`:`${e.data.height}px`,s&&(t.style.left="0",t.style.top="0"),t.style.opacity="1",t.style.pointerEvents="auto"):(t.style.width="1px",t.style.height="1px",t.style.left="",t.style.top="",t.style.opacity="0",t.style.pointerEvents="none"),n.style.display=i?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){y(),f=a.createElement("div"),f.style.cssText=`position:fixed;bottom:90px;right:24px;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:${x-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let i=(e.data.message||"").replace(/</g,"<");f.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${i}</p><div style="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;"></div>`;let s=a.createElement("button");s.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;",s.innerHTML="✕",s.onclick=h=>{h.stopPropagation(),y(),t.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},f.onclick=()=>{y(),n.style.display="none",t.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},f.appendChild(s),a.body.appendChild(f)}e.data?.type==="bitpalm-trigger-hide"&&y(),e.data?.type==="bitpalm-widget-blocked"&&(n.style.display="none",y(),t.style.display="none")}};window.addEventListener("message",B);let b=!1;try{b=localStorage.getItem(`${u}optout`)==="1"}catch{}let L=`${u}vid`,d="";if(!b){try{d=localStorage.getItem(L)||""}catch{}if(!d){let e=a.cookie.match(new RegExp(`(?:^|; )${L}=([^;]+)`));d=e?decodeURIComponent(e[1]):""}d||(d=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(L,d)}catch{}try{a.cookie=`${L}=${encodeURIComponent(d)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!b)try{let e=new URLSearchParams(location.search),i={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let m=e.get(T);m&&(i[T]=m)}let s=JSON.stringify({tenant_slug:r,visitor_id:d,url:location.href,referrer:a.referrer||void 0,...Object.keys(i).length>0?{utm:i}:{}}),h=`${c}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(h,new Blob([s],{type:"application/json"})):fetch(h,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let $="",N=0,D=e=>{if(b||!v||!d)return;let i=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(i instanceof HTMLFormElement))return;let s=(i.getAttribute("data-bp-identify")||i.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(s==="off"||s==="false"||s==="0")return;let h=ot(i);if(!h)return;let T=[i.getAttribute("id")||"",i.getAttribute("name")||"",i.getAttribute("action")||"",h.email||"",h.phone||"",h.name||"",h.company||""].join("|").toLowerCase(),m=Date.now();if(!(T===$&&m-N<8e3)){$=T,N=m;try{let S=JSON.stringify({tenant_slug:r,visitor_id:d,url:location.href,referrer:a.referrer||void 0,...h}),A=`${c}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(A,new Blob([S],{type:"application/json"})):fetch(A,{method:"POST",body:S,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!b&&v&&a.addEventListener("submit",D,!0);let M=parseInt(sessionStorage.getItem(`${u}pages`)||"0")+1;sessionStorage.setItem(`${u}pages`,String(M));let I=JSON.parse(sessionStorage.getItem(`${u}hist`)||"[]");I.push(location.href),I.length>20&&(I=I.slice(-20)),sessionStorage.setItem(`${u}hist`,JSON.stringify(I));let z=Date.now(),_=parseInt(sessionStorage.getItem(`${u}site_start`)||"0");_||(_=z,sessionStorage.setItem(`${u}site_start`,String(_))),t.addEventListener("load",()=>{let e=!!localStorage.getItem(`${u}visited`);t.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:a.title,returning:e,pageCount:M,pageHistory:I,loadedAt:z,siteStart:_,locale:l,visitorId:b?"":d},"*"),!e&&!b&&localStorage.setItem(`${u}visited`,"1")});let F=history.pushState.bind(history),q=history.replaceState.bind(history),C=()=>{M++,sessionStorage.setItem(`${u}pages`,String(M));let e=JSON.parse(sessionStorage.getItem(`${u}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),sessionStorage.setItem(`${u}hist`,JSON.stringify(e)),t.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:a.title,pageCount:M,pageHistory:e,loadedAt:Date.now()},"*"),!b)try{let i=JSON.stringify({tenant_slug:r,visitor_id:d,url:location.href}),s=`${c}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(s,new Blob([i],{type:"application/json"})):fetch(s,{method:"POST",body:i,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){F(...e),C()},history.replaceState=function(...e){q(...e),C()},window.addEventListener("popstate",C);let J=-1,O,Y=()=>{clearTimeout(O),O=setTimeout(()=>{let e=Math.max(a.documentElement.scrollHeight,a.body.scrollHeight)-window.innerHeight,i=e>0?Math.round(window.scrollY/e*100):100;i!==J&&(J=i,t.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:i},"*"))},500)};window.addEventListener("scroll",Y,{passive:!0});let G=e=>{e.clientY<=0&&t.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};a.addEventListener("mouseout",G);let j,V=!1,W=()=>{clearTimeout(j),!V&&(j=setTimeout(()=>{V=!0,t.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Z=["mousemove","keydown","scroll","touchstart"];Z.forEach(e=>a.addEventListener(e,W,{passive:!0})),W();let K=()=>{n.style.display="none",y(),t.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=t.src.split("#")[0];t.src=`${e}#bp-open-${Date.now()}`};return{open:K,close:()=>{t.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",B),window.removeEventListener("scroll",Y),window.removeEventListener("popstate",C),a.removeEventListener("mouseout",G),a.removeEventListener("submit",D,!0),Z.forEach(e=>a.removeEventListener(e,W)),clearTimeout(O),clearTimeout(j),history.pushState=F,history.replaceState=q,y(),n.remove(),t.remove()}}}function dt(o){let r=Q(null),l=Q(!1);return it(()=>{if(!l.current)return l.current=!0,r.current=X(o),()=>{r.current?.destroy(),r.current=null,l.current=!1}},[]),null}export{dt as BitPalmAgent};
|
|
2
2
|
//# sourceMappingURL=react.js.map
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts","../src/widget.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { createWidget } from \"./widget\";\nimport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type BitPalmAgentProps = BitPalmAgentOptions;\n\n/**\n * React component that mounts the BitPalm AI agent widget.\n *\n * @example\n * ```tsx\n * import { BitPalmAgent } from '@bitpalm/ai-agents/react';\n *\n * export default function App() {\n * return <BitPalmAgent slug=\"my-agent\" />;\n * }\n * ```\n */\nexport function BitPalmAgent(props: BitPalmAgentProps): null {\n const instanceRef = useRef<BitPalmAgentInstance | null>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n if (mountedRef.current) return;\n mountedRef.current = true;\n\n instanceRef.current = createWidget(props);\n\n return () => {\n instanceRef.current?.destroy();\n instanceRef.current = null;\n mountedRef.current = false;\n };\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n return null;\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n zIndex = 9999,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n iframe.src = `${widgetUrl}${widgetUrl.includes(\"?\") ? \"&\" : \"?\"}locale=${locale}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.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:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.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>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = window.innerWidth <= 640;\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;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:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"<\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"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;\"></div>`;\n const close = d.createElement(\"button\");\n close.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;\";\n close.innerHTML = \"✕\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n const returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\");\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget, destroy };\n}\n"],"mappings":"AAAA,OAAS,aAAAA,EAAW,UAAAC,MAAc,QCElC,IAAMC,EAAmB,4BACnBC,EAAiB,OAEvB,SAASC,GAAuB,CAC9B,GAAI,OAAO,SAAa,IAAa,CACnC,IAAMC,EAAO,SAAS,gBAAgB,KACtC,GAAIA,EAAM,OAAOA,EAAK,MAAM,EAAG,C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B,WAAYP,CAAK,EAC5CvC,EAAE,oBAAoB,WAAYiD,CAAc,EAChDI,EAAW,QAAShC,GAAOrB,EAAE,oBAAoBqB,EAAI+B,CAAS,CAAC,EAC/D,aAAaP,CAAa,EAC1B,aAAaK,CAAS,EACtB,QAAQ,UAAYb,EACpB,QAAQ,aAAeC,EACvB9B,EAAa,EACbJ,EAAI,OAAO,EACXH,EAAO,OAAO,CAChB,CAEuD,CACzD,CD3UO,SAASsD,EAAaC,EAAgC,CAC3D,IAAMC,EAAcC,EAAoC,IAAI,EACtDC,EAAaD,EAAO,EAAK,EAE/B,OAAAE,EAAU,IAAM,CACd,GAAI,CAAAD,EAAW,QACf,OAAAA,EAAW,QAAU,GAErBF,EAAY,QAAUI,EAAaL,CAAK,EAEjC,IAAM,CACXC,EAAY,SAAS,QAAQ,EAC7BA,EAAY,QAAU,KACtBE,EAAW,QAAU,EACvB,CACF,EAAG,CAAC,CAAC,EAEE,IACT","names":["useEffect","useRef","DEFAULT_BASE_URL","STORAGE_PREFIX","detectLocale","lang","createWidget","options","slug","locale","baseUrl","zIndex","d","iframe","widgetUrl","origin","btn","openWidget","s","bubble","removeBubble","handleMessage","e","ic","sp","svg","el","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","pageCount","hist","loadedAt","siteStart","returning","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","BitPalmAgent","props","instanceRef","useRef","mountedRef","useEffect","createWidget"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts","../src/widget.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { createWidget } from \"./widget\";\nimport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nexport type BitPalmAgentProps = BitPalmAgentOptions;\n\n/**\n * React component that mounts the BitPalm AI agent widget.\n *\n * @example\n * ```tsx\n * import { BitPalmAgent } from '@bitpalm/ai-agents/react';\n *\n * export default function App() {\n * return <BitPalmAgent slug=\"my-agent\" />;\n * }\n * ```\n */\nexport function BitPalmAgent(props: BitPalmAgentProps): null {\n const instanceRef = useRef<BitPalmAgentInstance | null>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n if (mountedRef.current) return;\n mountedRef.current = true;\n\n instanceRef.current = createWidget(props);\n\n return () => {\n instanceRef.current?.destroy();\n instanceRef.current = null;\n mountedRef.current = false;\n };\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n return null;\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\nconst IGNORED_INPUT_TYPES = new Set([\"password\", \"file\", \"checkbox\", \"radio\", \"submit\", \"button\", \"reset\", \"image\"]);\n\ntype IdentityPayload = {\n name?: string;\n email?: string;\n phone?: string;\n company?: string;\n};\n\nfunction normalizeText(value: string | null | undefined, maxLen = 180): string {\n if (!value) return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, maxLen);\n}\n\nfunction normalizeTokens(value: string | null | undefined): string {\n if (!value) return \"\";\n return ` ${value.toLowerCase().replace(/[_-]+/g, \" \").replace(/[^a-z0-9\\s@.]/g, \" \").replace(/\\s+/g, \" \").trim()} `;\n}\n\nfunction includesAny(haystack: string, needles: string[]): boolean {\n for (const needle of needles) {\n if (haystack.includes(needle)) return true;\n }\n return false;\n}\n\nfunction isEmail(value: string): boolean {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/i.test(value);\n}\n\nfunction normalizePhone(value: string): string {\n const trimmed = normalizeText(value, 50);\n if (!trimmed) return \"\";\n const hasPlus = trimmed.startsWith(\"+\");\n const digits = trimmed.replace(/\\D/g, \"\");\n if (digits.length < 6) return \"\";\n return `${hasPlus ? \"+\" : \"\"}${digits.slice(0, 20)}`;\n}\n\nfunction getExplicitValue(form: HTMLFormElement, selectors: string[]): string {\n for (const selector of selectors) {\n const el = form.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(selector);\n const value = normalizeText(el?.value);\n if (value) return value;\n }\n return \"\";\n}\n\nfunction extractIdentityFromForm(form: HTMLFormElement): IdentityPayload | null {\n let email = normalizeText(getExplicitValue(form, [\n \"[data-bp-email]\",\n \"[data-bitpalm-email]\",\n ]), 140).toLowerCase();\n\n let phone = normalizePhone(getExplicitValue(form, [\n \"[data-bp-phone]\",\n \"[data-bitpalm-phone]\",\n ]));\n\n let name = normalizeText(getExplicitValue(form, [\n \"[data-bp-name]\",\n \"[data-bitpalm-name]\",\n \"[data-bp-full-name]\",\n \"[data-bitpalm-full-name]\",\n ]));\n\n let firstName = normalizeText(getExplicitValue(form, [\n \"[data-bp-first-name]\",\n \"[data-bitpalm-first-name]\",\n ]));\n\n let lastName = normalizeText(getExplicitValue(form, [\n \"[data-bp-last-name]\",\n \"[data-bitpalm-last-name]\",\n ]));\n\n let company = normalizeText(getExplicitValue(form, [\n \"[data-bp-company]\",\n \"[data-bitpalm-company]\",\n ]));\n\n for (const rawEl of Array.from(form.elements)) {\n if (!(rawEl instanceof HTMLInputElement || rawEl instanceof HTMLTextAreaElement || rawEl instanceof HTMLSelectElement)) continue;\n if (rawEl.disabled) continue;\n if (rawEl instanceof HTMLInputElement && IGNORED_INPUT_TYPES.has(rawEl.type.toLowerCase())) continue;\n\n const explicitField =\n rawEl.hasAttribute(\"data-bp-email\") ||\n rawEl.hasAttribute(\"data-bitpalm-email\") ||\n rawEl.hasAttribute(\"data-bp-phone\") ||\n rawEl.hasAttribute(\"data-bitpalm-phone\") ||\n rawEl.hasAttribute(\"data-bp-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-name\") ||\n rawEl.hasAttribute(\"data-bp-full-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-full-name\") ||\n rawEl.hasAttribute(\"data-bp-first-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-first-name\") ||\n rawEl.hasAttribute(\"data-bp-last-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-last-name\") ||\n rawEl.hasAttribute(\"data-bp-company\") ||\n rawEl.hasAttribute(\"data-bitpalm-company\");\n\n if (rawEl instanceof HTMLInputElement && rawEl.type.toLowerCase() === \"hidden\" && !explicitField) continue;\n\n const value = normalizeText(rawEl.value);\n if (!value) continue;\n\n const type = rawEl instanceof HTMLInputElement ? rawEl.type.toLowerCase() : \"\";\n const tokens = normalizeTokens([\n rawEl.name,\n rawEl.id,\n rawEl.getAttribute(\"autocomplete\"),\n rawEl.getAttribute(\"placeholder\"),\n rawEl.getAttribute(\"aria-label\"),\n rawEl.getAttribute(\"data-field\"),\n rawEl.getAttribute(\"data-name\"),\n ].filter(Boolean).join(\" \"));\n\n const emailLike = type === \"email\" || includesAny(tokens, [\" email \", \" e mail \", \" mail \", \" correo \"]);\n const phoneLike = type === \"tel\" || includesAny(tokens, [\" phone \", \" mobile \", \" tel \", \" whatsapp \", \" handy \", \" telefon \", \" kontakt \"]);\n const companyLike = includesAny(tokens, [\" company \", \" firma \", \" organization \", \" organisation \", \" business \", \" unternehmen \", \" agency \", \" brokerage \"]);\n const firstNameLike = includesAny(tokens, [\" first name \", \" firstname \", \" given name \", \" given name \", \" givenname \", \" vorname \"]);\n const lastNameLike = includesAny(tokens, [\" last name \", \" lastname \", \" family name \", \" familyname \", \" surname \", \" nachname \"]);\n const fullNameLike = includesAny(tokens, [\" full name \", \" fullname \", \" contact name \", \" name \"]) && !emailLike && !phoneLike;\n\n if (!email && emailLike && isEmail(value)) {\n email = value.toLowerCase();\n continue;\n }\n if (!phone && phoneLike) {\n const normalized = normalizePhone(value);\n if (normalized) {\n phone = normalized;\n continue;\n }\n }\n if (!company && companyLike) {\n company = normalizeText(value, 160);\n continue;\n }\n if (!firstName && firstNameLike) {\n firstName = normalizeText(value, 100);\n continue;\n }\n if (!lastName && lastNameLike) {\n lastName = normalizeText(value, 100);\n continue;\n }\n if (!name && fullNameLike && !isEmail(value) && !normalizePhone(value)) {\n name = normalizeText(value, 140);\n continue;\n }\n\n if (!email && isEmail(value) && includesAny(tokens, [\" mail \", \" email \", \" e mail \"])) {\n email = value.toLowerCase();\n }\n }\n\n if (!name) {\n name = normalizeText([firstName, lastName].filter(Boolean).join(\" \"), 140);\n }\n\n const identity: IdentityPayload = {\n ...(name ? { name } : {}),\n ...(email ? { email } : {}),\n ...(phone ? { phone } : {}),\n ...(company ? { company } : {}),\n };\n\n return Object.keys(identity).length > 0 ? identity : null;\n}\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n token,\n zIndex = 9999,\n autoIdentify = true,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n const qs = new URLSearchParams({ locale });\n if (token) qs.set(\"token\", token);\n iframe.src = `${widgetUrl}?${qs.toString()}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.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:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.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>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = window.innerWidth <= 640;\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;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:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"<\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"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;\"></div>`;\n const close = d.createElement(\"button\");\n close.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;\";\n close.innerHTML = \"✕\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Auto-identify visitor from form submissions on host page ---\n let lastIdentitySignature = \"\";\n let lastIdentitySentAt = 0;\n const handleFormSubmit = (event: Event) => {\n if (optedOut || !autoIdentify || !visitorId) return;\n\n const form = event.target instanceof HTMLFormElement\n ? event.target\n : event.target instanceof Element\n ? event.target.closest(\"form\")\n : null;\n if (!(form instanceof HTMLFormElement)) return;\n\n const formIdentifySetting = (form.getAttribute(\"data-bp-identify\") || form.getAttribute(\"data-bitpalm-identify\") || \"\").toLowerCase();\n if (formIdentifySetting === \"off\" || formIdentifySetting === \"false\" || formIdentifySetting === \"0\") return;\n\n const identity = extractIdentityFromForm(form);\n if (!identity) return;\n\n const signature = [\n form.getAttribute(\"id\") || \"\",\n form.getAttribute(\"name\") || \"\",\n form.getAttribute(\"action\") || \"\",\n identity.email || \"\",\n identity.phone || \"\",\n identity.name || \"\",\n identity.company || \"\",\n ].join(\"|\").toLowerCase();\n\n const now = Date.now();\n if (signature === lastIdentitySignature && now - lastIdentitySentAt < 8000) return;\n lastIdentitySignature = signature;\n lastIdentitySentAt = now;\n\n try {\n const payload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...identity,\n });\n const identifyUrl = `${baseUrl}/api/widget/identify`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(identifyUrl, new Blob([payload], { type: \"application/json\" }));\n } else {\n fetch(identifyUrl, { method: \"POST\", body: payload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch {\n // ignore\n }\n };\n\n if (!optedOut && autoIdentify) {\n d.addEventListener(\"submit\", handleFormSubmit, true);\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n const returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\");\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n d.removeEventListener(\"submit\", handleFormSubmit, true);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget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D,IAAMC,EAAcC,EAAoC,IAAI,EACtDC,EAAaD,EAAO,EAAK,EAE/B,OAAAE,GAAU,IAAM,CACd,GAAI,CAAAD,EAAW,QACf,OAAAA,EAAW,QAAU,GAErBF,EAAY,QAAUI,EAAaL,CAAK,EAEjC,IAAM,CACXC,EAAY,SAAS,QAAQ,EAC7BA,EAAY,QAAU,KACtBE,EAAW,QAAU,EACvB,CACF,EAAG,CAAC,CAAC,EAEE,IACT","names":["useEffect","useRef","DEFAULT_BASE_URL","STORAGE_PREFIX","IGNORED_INPUT_TYPES","normalizeText","value","maxLen","normalizeTokens","includesAny","haystack","needles","needle","isEmail","normalizePhone","trimmed","hasPlus","digits","getExplicitValue","form","selectors","selector","el","extractIdentityFromForm","email","phone","name","firstName","lastName","company","rawEl","explicitField","type","tokens","emailLike","phoneLike","companyLike","firstNameLike","lastNameLike","fullNameLike","normalized","identity","detectLocale","lang","createWidget","options","slug","locale","baseUrl","token","zIndex","autoIdentify","d","iframe","widgetUrl","qs","origin","btn","openWidget","s","bubble","removeBubble","handleMessage","ic","sp","svg","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","lastIdentitySignature","lastIdentitySentAt","handleFormSubmit","event","formIdentifySetting","signature","now","payload","identifyUrl","pageCount","hist","loadedAt","siteStart","returning","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","BitPalmAgent","props","instanceRef","useRef","mountedRef","useEffect","createWidget"]}
|
package/dist/widget.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var BitPalmAgents=(()=>{var _=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var F=(i,r)=>{for(var m in r)_(i,m,{get:r[m],enumerable:!0})},Y=(i,r,m,y)=>{if(r&&typeof r=="object"||typeof r=="function")for(let d of J(r))!q.call(i,d)&&d!==m&&_(i,d,{get:()=>r[d],enumerable:!(y=N(r,d))||y.enumerable});return i};var G=i=>Y(_({},"__esModule",{value:!0}),i);var K={};F(K,{createWidget:()=>I});var V="https://agents.bitpalm.ae",l="_bp_";function Z(){if(typeof document<"u"){let i=document.documentElement.lang;if(i)return i.slice(0,2).toLowerCase()}return"en"}function I(i){let{slug:r,locale:m=Z(),baseUrl:y=V,zIndex:d=9999}=i,o=document,e=o.createElement("iframe"),A=`${y}/t/${r}/widget`;e.src=`${A}${A.includes("?")?"&":"?"}locale=${m}`,e.allow="clipboard-write",e.setAttribute("allowtransparency","true"),e.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${d};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,o.body.appendChild(e);let z=new URL(e.src).origin,n=o.createElement("div");if(n.setAttribute("role","button"),n.setAttribute("aria-label","Chat"),n.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:${d-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',n.onmouseenter=()=>{n.style.transform="scale(1.1)"},n.onmouseleave=()=>{n.style.transform="scale(1)"},n.onclick=()=>R(),o.body.appendChild(n),!o.getElementById("_bp_fade")){let t=o.createElement("style");t.id="_bp_fade",t.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",o.head.appendChild(t)}let g=null,h=()=>{g&&(g.remove(),g=null)},C=t=>{if(t.origin===z){if(t.data?.type==="bitpalm-widget-config"){t.data.primaryColor&&(n.style.background=t.data.primaryColor,n.style.boxShadow=t.data.chatShadow==="none"?"none":`0 0 15px ${t.data.primaryColor}50`);let a=t.data.chatButtonIconColor||"black";if(t.data.chatButtonIconSvg){n.innerHTML="";let s=o.createElement("span");s.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${a}`;let p=new DOMParser().parseFromString(t.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");p?(p.querySelectorAll("script,foreignObject").forEach(E=>E.remove()),p.querySelectorAll("*").forEach(E=>{for(let $ of[...E.attributes])($.name.startsWith("on")||$.value&&$.value.includes("javascript:"))&&E.removeAttribute($.name)}),p.setAttribute("width","24"),p.setAttribute("height","24"),p.style.display="block",s.appendChild(p)):s.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>',n.appendChild(s)}else{let s=n.querySelector("svg");s&&(s.style.stroke=a)}n.style.display="flex",requestAnimationFrame(()=>{n.style.opacity="1"})}if(t.data?.type==="bitpalm-widget-resize"){let a=t.data.width>0,s=window.innerWidth<=640;a?(e.style.width=s?`${window.innerWidth}px`:`${t.data.width}px`,e.style.height=s?`${window.innerHeight}px`:`${t.data.height}px`,s&&(e.style.left="0",e.style.top="0"),e.style.opacity="1",e.style.pointerEvents="auto"):(e.style.width="1px",e.style.height="1px",e.style.left="",e.style.top="",e.style.opacity="0",e.style.pointerEvents="none"),n.style.display=a?"none":"flex"}if(t.data?.type==="bitpalm-trigger-show"){h(),g=o.createElement("div"),g.style.cssText=`position:fixed;bottom:90px;right:24px;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:${d-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let a=(t.data.message||"").replace(/</g,"<");g.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${a}</p><div style="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;"></div>`;let s=o.createElement("button");s.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;",s.innerHTML="✕",s.onclick=w=>{w.stopPropagation(),h(),e.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},g.onclick=()=>{h(),n.style.display="none",e.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},g.appendChild(s),o.body.appendChild(g)}t.data?.type==="bitpalm-trigger-hide"&&h(),t.data?.type==="bitpalm-widget-blocked"&&(n.style.display="none",h(),e.style.display="none")}};window.addEventListener("message",C);let u=!1;try{u=localStorage.getItem(`${l}optout`)==="1"}catch{}let x=`${l}vid`,c="";if(!u){try{c=localStorage.getItem(x)||""}catch{}if(!c){let t=o.cookie.match(new RegExp(`(?:^|; )${x}=([^;]+)`));c=t?decodeURIComponent(t[1]):""}c||(c=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(x,c)}catch{}try{o.cookie=`${x}=${encodeURIComponent(c)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!u)try{let t=new URLSearchParams(location.search),a={};for(let M of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let p=t.get(M);p&&(a[M]=p)}let s=JSON.stringify({tenant_slug:r,visitor_id:c,url:location.href,referrer:o.referrer||void 0,...Object.keys(a).length>0?{utm:a}:{}}),w=`${y}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(w,new Blob([s],{type:"application/json"})):fetch(w,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let b=parseInt(sessionStorage.getItem(`${l}pages`)||"0")+1;sessionStorage.setItem(`${l}pages`,String(b));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 B=Date.now(),v=parseInt(sessionStorage.getItem(`${l}site_start`)||"0");v||(v=B,sessionStorage.setItem(`${l}site_start`,String(v))),e.addEventListener("load",()=>{let t=!!localStorage.getItem(`${l}visited`);e.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:o.title,returning:t,pageCount:b,pageHistory:f,loadedAt:B,siteStart:v,locale:m,visitorId:u?"":c},"*"),!t&&!u&&localStorage.setItem(`${l}visited`,"1")});let O=history.pushState.bind(history),P=history.replaceState.bind(history),S=()=>{b++,sessionStorage.setItem(`${l}pages`,String(b));let t=JSON.parse(sessionStorage.getItem(`${l}hist`)||"[]");if(t.push(location.href),t.length>20&&t.splice(0,t.length-20),sessionStorage.setItem(`${l}hist`,JSON.stringify(t)),e.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:o.title,pageCount:b,pageHistory:t,loadedAt:Date.now()},"*"),!u)try{let a=JSON.stringify({tenant_slug:r,visitor_id:c,url:location.href}),s=`${y}/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{}};history.pushState=function(...t){O(...t),S()},history.replaceState=function(...t){P(...t),S()},window.addEventListener("popstate",S);let W=-1,T,U=()=>{clearTimeout(T),T=setTimeout(()=>{let t=Math.max(o.documentElement.scrollHeight,o.body.scrollHeight)-window.innerHeight,a=t>0?Math.round(window.scrollY/t*100):100;a!==W&&(W=a,e.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:a},"*"))},500)};window.addEventListener("scroll",U,{passive:!0});let H=t=>{t.clientY<=0&&e.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};o.addEventListener("mouseout",H);let k,j=!1,L=()=>{clearTimeout(k),!j&&(k=setTimeout(()=>{j=!0,e.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},D=["mousemove","keydown","scroll","touchstart"];D.forEach(t=>o.addEventListener(t,L,{passive:!0})),L();let R=()=>{n.style.display="none",h(),e.contentWindow?.postMessage({type:"bitpalm-open"},"*");let t=e.src.split("#")[0];e.src=`${t}#bp-open-${Date.now()}`};return{open:R,close:()=>{e.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",C),window.removeEventListener("scroll",U),window.removeEventListener("popstate",S),o.removeEventListener("mouseout",H),D.forEach(t=>o.removeEventListener(t,L)),clearTimeout(T),clearTimeout(k),history.pushState=O,history.replaceState=P,h(),n.remove(),e.remove()}}}if(typeof document<"u"){let i=document.currentScript;if(i?.dataset.slug){let r=()=>{I({slug:i.dataset.slug,locale:i.dataset.locale,baseUrl:i.dataset.baseUrl,zIndex:i.dataset.zIndex?Number(i.dataset.zIndex):void 0})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r()}}return G(K);})();
|
|
1
|
+
"use strict";var BitPalmAgents=(()=>{var z=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var at=(n,a)=>{for(var c in a)z(n,c,{get:a[c],enumerable:!0})},ot=(n,a,c,l)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of et(a))!nt.call(n,d)&&d!==c&&z(n,d,{get:()=>a[d],enumerable:!(l=tt(a,d))||l.enumerable});return n};var it=n=>ot(z({},"__esModule",{value:!0}),n);var mt={};at(mt,{createWidget:()=>H});var st="https://agents.bitpalm.ae",f="_bp_",rt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]);function g(n,a=180){return n?n.replace(/\s+/g," ").trim().slice(0,a):""}function lt(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function L(n,a){for(let c of a)if(n.includes(c))return!0;return!1}function N(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function D(n){let a=g(n,50);if(!a)return"";let c=a.startsWith("+"),l=a.replace(/\D/g,"");return l.length<6?"":`${c?"+":""}${l.slice(0,20)}`}function k(n,a){for(let c of a){let l=n.querySelector(c),d=g(l?.value);if(d)return d}return""}function ct(n){let a=g(k(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),c=D(k(n,["[data-bp-phone]","[data-bitpalm-phone]"])),l=g(k(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),d=g(k(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),x=g(k(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),v=g(k(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let t of Array.from(n.elements)){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)||t.disabled||t instanceof HTMLInputElement&&rt.has(t.type.toLowerCase()))continue;let O=t.hasAttribute("data-bp-email")||t.hasAttribute("data-bitpalm-email")||t.hasAttribute("data-bp-phone")||t.hasAttribute("data-bitpalm-phone")||t.hasAttribute("data-bp-name")||t.hasAttribute("data-bitpalm-name")||t.hasAttribute("data-bp-full-name")||t.hasAttribute("data-bitpalm-full-name")||t.hasAttribute("data-bp-first-name")||t.hasAttribute("data-bitpalm-first-name")||t.hasAttribute("data-bp-last-name")||t.hasAttribute("data-bitpalm-last-name")||t.hasAttribute("data-bp-company")||t.hasAttribute("data-bitpalm-company");if(t instanceof HTMLInputElement&&t.type.toLowerCase()==="hidden"&&!O)continue;let p=g(t.value);if(!p)continue;let C=t instanceof HTMLInputElement?t.type.toLowerCase():"",o=lt([t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("placeholder"),t.getAttribute("aria-label"),t.getAttribute("data-field"),t.getAttribute("data-name")].filter(Boolean).join(" ")),h=C==="email"||L(o,[" email "," e mail "," mail "," correo "]),b=C==="tel"||L(o,[" phone "," mobile "," tel "," whatsapp "," handy "," telefon "," kontakt "]),_=L(o,[" company "," firma "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),w=L(o,[" first name "," firstname "," given name "," given name "," givenname "," vorname "]),A=L(o,[" last name "," lastname "," family name "," familyname "," surname "," nachname "]),m=L(o,[" full name "," fullname "," contact name "," name "])&&!h&&!b;if(!a&&h&&N(p)){a=p.toLowerCase();continue}if(!c&&b){let $=D(p);if($){c=$;continue}}if(!v&&_){v=g(p,160);continue}if(!d&&w){d=g(p,100);continue}if(!x&&A){x=g(p,100);continue}if(!l&&m&&!N(p)&&!D(p)){l=g(p,140);continue}!a&&N(p)&&L(o,[" mail "," email "," e mail "])&&(a=p.toLowerCase())}l||(l=g([d,x].filter(Boolean).join(" "),140));let i={...l?{name:l}:{},...a?{email:a}:{},...c?{phone:c}:{},...v?{company:v}:{}};return Object.keys(i).length>0?i:null}function dt(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function H(n){let{slug:a,locale:c=dt(),baseUrl:l=st,token:d,zIndex:x=9999,autoIdentify:v=!0}=n,i=document,t=i.createElement("iframe"),O=`${l}/t/${a}/widget`,p=new URLSearchParams({locale:c});d&&p.set("token",d),t.src=`${O}?${p.toString()}`,t.allow="clipboard-write",t.setAttribute("allowtransparency","true"),t.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${x};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,i.body.appendChild(t);let C=new URL(t.src).origin,o=i.createElement("div");if(o.setAttribute("role","button"),o.setAttribute("aria-label","Chat"),o.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:${x-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,o.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',o.onmouseenter=()=>{o.style.transform="scale(1.1)"},o.onmouseleave=()=>{o.style.transform="scale(1)"},o.onclick=()=>Q(),i.body.appendChild(o),!i.getElementById("_bp_fade")){let e=i.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",i.head.appendChild(e)}let h=null,b=()=>{h&&(h.remove(),h=null)},_=e=>{if(e.origin===C){if(e.data?.type==="bitpalm-widget-config"){e.data.primaryColor&&(o.style.background=e.data.primaryColor,o.style.boxShadow=e.data.chatShadow==="none"?"none":`0 0 15px ${e.data.primaryColor}50`);let s=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){o.innerHTML="";let r=i.createElement("span");r.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${s}`;let u=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");u?(u.querySelectorAll("script,foreignObject").forEach(S=>S.remove()),u.querySelectorAll("*").forEach(S=>{for(let E of[...S.attributes])(E.name.startsWith("on")||E.value&&E.value.includes("javascript:"))&&S.removeAttribute(E.name)}),u.setAttribute("width","24"),u.setAttribute("height","24"),u.style.display="block",r.appendChild(u)):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>',o.appendChild(r)}else{let r=o.querySelector("svg");r&&(r.style.stroke=s)}o.style.display="flex",requestAnimationFrame(()=>{o.style.opacity="1"})}if(e.data?.type==="bitpalm-widget-resize"){let s=e.data.width>0,r=window.innerWidth<=640;s?(t.style.width=r?`${window.innerWidth}px`:`${e.data.width}px`,t.style.height=r?`${window.innerHeight}px`:`${e.data.height}px`,r&&(t.style.left="0",t.style.top="0"),t.style.opacity="1",t.style.pointerEvents="auto"):(t.style.width="1px",t.style.height="1px",t.style.left="",t.style.top="",t.style.opacity="0",t.style.pointerEvents="none"),o.style.display=s?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){b(),h=i.createElement("div"),h.style.cssText=`position:fixed;bottom:90px;right:24px;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:${x-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let s=(e.data.message||"").replace(/</g,"<");h.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${s}</p><div style="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;"></div>`;let r=i.createElement("button");r.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;",r.innerHTML="✕",r.onclick=y=>{y.stopPropagation(),b(),t.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},h.onclick=()=>{b(),o.style.display="none",t.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},h.appendChild(r),i.body.appendChild(h)}e.data?.type==="bitpalm-trigger-hide"&&b(),e.data?.type==="bitpalm-widget-blocked"&&(o.style.display="none",b(),t.style.display="none")}};window.addEventListener("message",_);let w=!1;try{w=localStorage.getItem(`${f}optout`)==="1"}catch{}let A=`${f}vid`,m="";if(!w){try{m=localStorage.getItem(A)||""}catch{}if(!m){let e=i.cookie.match(new RegExp(`(?:^|; )${A}=([^;]+)`));m=e?decodeURIComponent(e[1]):""}m||(m=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(A,m)}catch{}try{i.cookie=`${A}=${encodeURIComponent(m)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!w)try{let e=new URLSearchParams(location.search),s={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let u=e.get(T);u&&(s[T]=u)}let r=JSON.stringify({tenant_slug:a,visitor_id:m,url:location.href,referrer:i.referrer||void 0,...Object.keys(s).length>0?{utm:s}:{}}),y=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(y,new Blob([r],{type:"application/json"})):fetch(y,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let $="",R=0,F=e=>{if(w||!v||!m)return;let s=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(s instanceof HTMLFormElement))return;let r=(s.getAttribute("data-bp-identify")||s.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(r==="off"||r==="false"||r==="0")return;let y=ct(s);if(!y)return;let T=[s.getAttribute("id")||"",s.getAttribute("name")||"",s.getAttribute("action")||"",y.email||"",y.phone||"",y.name||"",y.company||""].join("|").toLowerCase(),u=Date.now();if(!(T===$&&u-R<8e3)){$=T,R=u;try{let S=JSON.stringify({tenant_slug:a,visitor_id:m,url:location.href,referrer:i.referrer||void 0,...y}),E=`${l}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(E,new Blob([S],{type:"application/json"})):fetch(E,{method:"POST",body:S,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!w&&v&&i.addEventListener("submit",F,!0);let M=parseInt(sessionStorage.getItem(`${f}pages`)||"0")+1;sessionStorage.setItem(`${f}pages`,String(M));let I=JSON.parse(sessionStorage.getItem(`${f}hist`)||"[]");I.push(location.href),I.length>20&&(I=I.slice(-20)),sessionStorage.setItem(`${f}hist`,JSON.stringify(I));let q=Date.now(),P=parseInt(sessionStorage.getItem(`${f}site_start`)||"0");P||(P=q,sessionStorage.setItem(`${f}site_start`,String(P))),t.addEventListener("load",()=>{let e=!!localStorage.getItem(`${f}visited`);t.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:i.title,returning:e,pageCount:M,pageHistory:I,loadedAt:q,siteStart:P,locale:c,visitorId:w?"":m},"*"),!e&&!w&&localStorage.setItem(`${f}visited`,"1")});let J=history.pushState.bind(history),Y=history.replaceState.bind(history),B=()=>{M++,sessionStorage.setItem(`${f}pages`,String(M));let e=JSON.parse(sessionStorage.getItem(`${f}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),sessionStorage.setItem(`${f}hist`,JSON.stringify(e)),t.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:i.title,pageCount:M,pageHistory:e,loadedAt:Date.now()},"*"),!w)try{let s=JSON.stringify({tenant_slug:a,visitor_id:m,url:location.href}),r=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(r,new Blob([s],{type:"application/json"})):fetch(r,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){J(...e),B()},history.replaceState=function(...e){Y(...e),B()},window.addEventListener("popstate",B);let G=-1,U,V=()=>{clearTimeout(U),U=setTimeout(()=>{let e=Math.max(i.documentElement.scrollHeight,i.body.scrollHeight)-window.innerHeight,s=e>0?Math.round(window.scrollY/e*100):100;s!==G&&(G=s,t.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:s},"*"))},500)};window.addEventListener("scroll",V,{passive:!0});let Z=e=>{e.clientY<=0&&t.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};i.addEventListener("mouseout",Z);let W,K=!1,j=()=>{clearTimeout(W),!K&&(W=setTimeout(()=>{K=!0,t.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},X=["mousemove","keydown","scroll","touchstart"];X.forEach(e=>i.addEventListener(e,j,{passive:!0})),j();let Q=()=>{o.style.display="none",b(),t.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=t.src.split("#")[0];t.src=`${e}#bp-open-${Date.now()}`};return{open:Q,close:()=>{t.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",_),window.removeEventListener("scroll",V),window.removeEventListener("popstate",B),i.removeEventListener("mouseout",Z),i.removeEventListener("submit",F,!0),X.forEach(e=>i.removeEventListener(e,j)),clearTimeout(U),clearTimeout(W),history.pushState=J,history.replaceState=Y,b(),o.remove(),t.remove()}}}function pt(n){if(n==null)return;let a=n.trim().toLowerCase();if(["1","true","yes","on"].includes(a))return!0;if(["0","false","no","off"].includes(a))return!1}if(typeof document<"u"){let n=document.currentScript;if(n?.dataset.slug){let a=()=>{H({slug:n.dataset.slug,locale:n.dataset.locale,baseUrl:n.dataset.baseUrl,token:n.dataset.token,zIndex:n.dataset.zIndex?Number(n.dataset.zIndex):void 0,autoIdentify:pt(n.dataset.autoIdentify)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a):a()}}return it(mt);})();
|
|
2
2
|
//# sourceMappingURL=widget.global.js.map
|