UNPKG

better-analytics

Version:

Zero-dependency micro-analytics JavaScript SDK < 3KB gzipped with React/Next.js/Expo support

2 lines (1 loc) 5.79 kB
var n=null,c=null;function o(){return process.env.NODE_ENV==="development"}function h(r){n=r,r.batch&&(c=new d({endpoint:r.endpoint||"https://better-analytics.app/api/collect",apiKey:r.apiKey,...r.batch})),o()?r.debug&&(console.log("\u{1F680} Better Analytics Server initialized"),console.log("\u{1F3F7}\uFE0F Site:",r.site),console.log("\u{1F4CD} Endpoint:",r.endpoint||"https://better-analytics.app/api/collect"),console.log("\u26A1 Runtime:",l()),r.batch&&console.log("\u{1F4E6} Batching enabled:",r.batch)):r.debug&&(console.log("\u{1F680} Better Analytics Server initialized"),console.log("\u{1F4CD} Endpoint:",r.endpoint||"https://better-analytics.app/api/collect"),console.log("\u{1F3F7}\uFE0F Site:",r.site),console.log("\u26A1 Runtime:",l()),r.batch&&console.log("\u{1F4E6} Batching enabled:",r.batch))}async function u(r,e,t){if(typeof window<"u")throw new Error("trackServer() is only for server environments. Use track() for client-side.");if(!n){console.warn("Better Analytics Server: Not initialized. Call initServer() first.");return}let s=g(t),i={event:r,timestamp:Date.now(),site:n.site,url:s.origin,referrer:s.referer||"",server:s,...t?.user&&{user:t.user},...e&&{props:e},...t?.meta&&{meta:t.meta}};if(o()){if(console.log("\u{1F4E6} Server Data:",i),n.debug){let a=n.endpoint||"https://better-analytics.app/api/collect (default)";console.log("\u{1F4CA} Better Analytics Server Event:",r),console.log("\u{1F4CD} Endpoint:",a),console.log("\u{1F3F7}\uFE0F Site:",n.site),console.log("\u{1F310} Origin:",s.origin)}}else n.debug&&(console.log("\u{1F4CA} Better Analytics Server Event (debug):",r),console.log("\u{1F4E6} Server Data:",i));if(!o())if(c)c.add(i);else{let a=p(i);t?.waitUntil?t.waitUntil(a):await a}}async function y(r,e){await u("pageview",{path:r},e)}async function S(r,e,t){await u("identify",{userId:r,...e},{...t,user:{...t?.user,id:r}})}function g(r){let e=v(r);return{userAgent:e["user-agent"],ip:e["x-forwarded-for"]||e["x-real-ip"]||e["cf-connecting-ip"],country:e["cf-ipcountry"]||e["x-vercel-ip-country"]||e["x-country"],region:e["x-vercel-ip-region"]||e["cf-region"],city:e["x-vercel-ip-city"]||e["cf-city"],referer:e.referer||e.referrer,origin:e.origin||e["x-forwarded-host"]||e.host||"unknown",runtime:l(),framework:f()}}function v(r){let e;if(r?.headers?e=r.headers:r?.request&&(e=r.request.headers),!e)return{};let t={};if(e instanceof Headers)e.forEach((s,i)=>{t[i.toLowerCase()]=s});else for(let[s,i]of Object.entries(e))t[s.toLowerCase()]=Array.isArray(i)?i[0]:i;return t}function l(){return n?.runtime?n.runtime:typeof EdgeRuntime<"u"||process.env.NEXT_RUNTIME==="edge"?"edge":typeof caches<"u"&&"default"in caches?"cloudflare":typeof Deno<"u"?"deno":"node"}function f(){return process.env.VERCEL?"vercel":process.env.NEXT_RUNTIME?"nextjs":process.env.NUXT?"nuxt":process.env.GATSBY?"gatsby":process.env.NETLIFY?"netlify":"unknown"}async function p(r){if(n)try{let e=n.endpoint||"https://better-analytics.app/api/collect",t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"better-analytics-server/1.0","X-BA-Server":"1",...n.apiKey&&{Authorization:`Bearer ${n.apiKey}`}},body:JSON.stringify({...r,_server:!0})});o()?n.debug&&(t.ok?console.log("\u2705 Server Event sent:",r.event):console.error(`\u274C Server Event failed: HTTP ${t.status}`),console.log(" \u{1F4E1} Endpoint:",e)):n.debug&&(t.ok?(console.log("\u2705 Better Analytics Server: Event sent successfully"),console.log(" \u{1F4E1} Endpoint:",e),console.log(" \u{1F4CA} Event:",r.event)):console.error(`\u274C Better Analytics Server: HTTP ${t.status}`,await t.text()))}catch(e){o()?n.debug&&console.error("Server Event failed:",e):n.debug&&console.error("Better Analytics Server: Failed to send event",e)}}var d=class{constructor(e){this.config=e;this.queue=[];this.sending=!1}add(e){this.queue.push(e),o()?n?.debug&&(console.log("\u{1F4E6} Server Event queued for batch:",e.event),console.log(" \u{1F4C8} Queue size:",this.queue.length)):n?.debug&&(console.log("\u{1F4E6} Better Analytics Server: Event queued for batch"),console.log(" \u{1F4CA} Event:",e.event),console.log(" \u{1F4C8} Queue size:",this.queue.length)),this.queue.length>=(this.config.size||50)?this.flush():this.timer||(this.timer=setTimeout(()=>this.flush(),this.config.interval||5e3))}async flush(){if(this.sending||this.queue.length===0)return;this.sending=!0;let e=this.queue.splice(0);this.timer&&(clearTimeout(this.timer),this.timer=void 0);try{await this.sendBatch(e)}catch(t){this.queue.unshift(...e),n?.debug&&console.error("Better Analytics Server: Batch send failed",t)}finally{this.sending=!1}}async sendBatch(e){o()?n?.debug&&(console.log("\u{1F680} Server Batch sending:",e.length,"events"),console.log(" \u{1F4E1} Endpoint:",this.config.endpoint)):n?.debug&&(console.log("\u{1F680} Better Analytics Server: Sending batch"),console.log(" \u{1F4E6} Events count:",e.length),console.log(" \u{1F4E1} Endpoint:",this.config.endpoint));let t=await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"better-analytics-server/1.0","X-BA-Server":"1","X-BA-Batch":"1",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`}},body:JSON.stringify({events:e,_batch:!0})});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);o()?n?.debug&&console.log("\u2705 Server Batch sent:",e.length,"events"):n?.debug&&(console.log("\u2705 Better Analytics Server: Batch sent successfully"),console.log(" \u{1F4E6} Events processed:",e.length))}};function m(r,e){return{sessionId:r,deviceId:e}}function b(){return(r,e,t)=>{r.track=(s,i)=>u(s,i,{headers:r.headers,user:{sessionId:r.cookies?.ba_session,deviceId:r.cookies?.ba_device,id:r.user?.id}}),t()}}export{h as a,u as b,y as c,S as d,m as e,b as f};