UNPKG

@heartbeep/beeper

Version:

Modern JavaScript SDK for Heartbeep event tracking - beep beep!

3 lines 2.44 kB
import c,{createContext,useRef,useEffect,useContext}from'react';var s=class{constructor(e){this.queue=[];this.isReady=false;if(!e.siteId)throw new Error("[Heartbeep] siteId is required");let t=e.apiUrl||"https://heartbeep.live/api/beep/website";t=t.replace(/\/$/,""),t.includes(e.siteId)||(t=`${t}/${e.siteId}`),this.config={...e,apiUrl:t,debug:e.debug||false},typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.init()):this.init());}init(){this.isReady=true,this.processQueue(),this.config.debug&&console.log("[Heartbeep] Initialized with siteId:",this.config.siteId);}processQueue(){for(;this.queue.length>0;){let e=this.queue.shift();e&&this.track(e.event,e.payload);}}async send(e){this.config.debug&&console.log("[Heartbeep] Tracking event:",e);try{let t=JSON.stringify(e);if(typeof navigator<"u"&&navigator.sendBeacon&&navigator.sendBeacon(this.config.apiUrl,t))return;typeof fetch<"u"&&await fetch(this.config.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0});}catch(t){this.config.debug&&console.error("[Heartbeep] Error tracking event:",t);}}track(e,t){if(!this.isReady){this.queue.push({event:e,payload:t});return}if(typeof window>"u")return;let a={event:e,name:t?.name||document.title,url:window.location.href,timestamp:Date.now(),metadata:t?.metadata};this.send(a);}pageview(e){this.track("pageview",{name:e});}click(e,t){this.track("click",{name:e,metadata:t});}purchase(e,t){this.track("purchase",{name:e,metadata:t});}};var d=createContext(null);function m({children:n,siteId:e,apiUrl:t,debug:a}){let i=useRef(null);useEffect(()=>{if(typeof window<"u"&&!i.current){let r={siteId:e,apiUrl:t,debug:a};i.current=new s(r);}},[e,t,a]);let u={heartbeep:i.current,track:(r,o)=>{i.current?.track(r,o);},pageview:r=>{i.current?.pageview(r);},click:(r,o)=>{i.current?.click(r,o);},purchase:(r,o)=>{i.current?.purchase(r,o);}};return c.createElement(d.Provider,{value:u},n)}function h(){let n=useContext(d);if(!n)throw new Error("useHeartbeep must be used within a HeartbeepProvider");return n}function k({children:n}){let{pageview:e}=h();return useEffect(()=>{e();let t=()=>e();return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]),c.createElement(c.Fragment,null,n)} export{k as AutoPageview,m as HeartbeepProvider,h as useHeartbeep};//# sourceMappingURL=react.mjs.map //# sourceMappingURL=react.mjs.map