analyzer-analytics 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/analytics.d.ts +204 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.esm.js +1753 -0
- package/dist/analytics.full.min.js +1 -0
- package/dist/analytics.js +1786 -0
- package/dist/analytics.min.js +1 -0
- package/dist/core.d.ts +46 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/network-adapter.d.ts +243 -0
- package/dist/network-adapter.d.ts.map +1 -0
- package/dist/network.d.ts +175 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/slim.d.ts +26 -0
- package/dist/slim.d.ts.map +1 -0
- package/dist/storage.d.ts +88 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/types.d.ts +197 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.d.ts +150 -0
- package/dist/utils.d.ts.map +1 -0
- package/package.json +82 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{var{defineProperty:WZ,getOwnPropertyNames:iZ,getOwnPropertyDescriptor:nZ}=Object,oZ=Object.prototype.hasOwnProperty;var KZ=new WeakMap,sZ=(Z)=>{var $=KZ.get(Z),J;if($)return $;if($=WZ({},"__esModule",{value:!0}),Z&&typeof Z==="object"||typeof Z==="function")iZ(Z).map((H)=>!oZ.call($,H)&&WZ($,H,{get:()=>Z[H],enumerable:!(J=nZ(Z,H))||J.enumerable}));return KZ.set(Z,$),$};var aZ=(Z,$)=>{for(var J in $)WZ(Z,J,{get:$[J],enumerable:!0,configurable:!0,set:(H)=>$[J]=()=>H})};var F0={};aZ(F0,{throttle:()=>bZ,supportsFetch:()=>S,supportsCompression:()=>k,supportsBeacon:()=>n,sortByPriority:()=>LZ,setSessionItem:()=>BZ,setItem:()=>XZ,setDebugMode:()=>m,sendWithRetry:()=>UZ,sendFetch:()=>D,sendBeacon:()=>F,sendAdaptive:()=>HZ,send:()=>cZ,sanitizeProperties:()=>s,sanitizeEventName:()=>o,resetStorageCache:()=>AZ,resetNetworkAdapter:()=>uZ,resetCapabilityCache:()=>IZ,queueOfflineEvents:()=>U,parseQueryString:()=>xZ,onOnline:()=>vZ,isValidUtmParams:()=>jZ,isValidQueuedEvent:()=>OZ,isValidEvent:()=>CZ,isValidConfig:()=>RZ,isStorageAvailable:()=>M,isOffline:()=>v,isDataSaverEnabled:()=>p,isBot:()=>i,getVisitorId:()=>u,getUtmParams:()=>d,getUserAgent:()=>t,getSessionItem:()=>QZ,getSessionId:()=>l,getScreenDimensions:()=>e,getRtt:()=>ZZ,getReferrer:()=>r,getPageUrl:()=>N,getPageTitle:()=>a,getOfflineEvents:()=>y,getNetworkAdapter:()=>gZ,getItem:()=>zZ,getDownlink:()=>VZ,getConnectionType:()=>I,getConnectionInfo:()=>hZ,generateId:()=>g,default:()=>D0,debounce:()=>A,createVisitorId:()=>K,createSessionId:()=>w,createAnalytics:()=>lZ,clearVisitorId:()=>kZ,clearSessionId:()=>NZ,clearOfflineEvents:()=>E,assignPriority:()=>FZ,VERSION:()=>dZ,STORAGE_KEYS:()=>fZ,RetryStrategy:()=>JZ,NetworkError:()=>B,NetworkAdapter:()=>_,EventPriority:()=>qZ,DEFAULT_CONFIG:()=>q,Analytics:()=>h});function O(Z){return typeof Z==="object"&&Z!==null}function jZ(Z){if(!O(Z))return!1;let $=["source","medium","campaign","term","content"];return Object.keys(Z).every((H)=>$.includes(H)&&(Z[H]===void 0||typeof Z[H]==="string"))}function CZ(Z){if(!O(Z))return!1;let $=Z;if(typeof $.event!=="string"||$.event.length===0)return!1;if(typeof $.visitor_id!=="string")return!1;if(typeof $.session_id!=="string")return!1;if(typeof $.page_url!=="string")return!1;if(typeof $.user_agent!=="string")return!1;if(typeof $.timestamp!=="number"||!Number.isFinite($.timestamp))return!1;if(typeof $.screen_width!=="number"||!Number.isFinite($.screen_width))return!1;if(typeof $.screen_height!=="number"||!Number.isFinite($.screen_height))return!1;if(!O($.properties))return!1;if($.page_title!==void 0&&typeof $.page_title!=="string")return!1;if($.referrer!==void 0&&typeof $.referrer!=="string")return!1;if($.utm!==void 0&&!jZ($.utm))return!1;return!0}function RZ(Z){if(!O(Z))return!1;let $=Z;if(typeof $.apiKey!=="string"||$.apiKey.length===0)return!1;if($.endpoint!==void 0&&typeof $.endpoint!=="string")return!1;if($.debug!==void 0&&typeof $.debug!=="boolean")return!1;if($.maxQueueSize!==void 0){if(typeof $.maxQueueSize!=="number"||!Number.isInteger($.maxQueueSize)||$.maxQueueSize<1)return!1}if($.flushInterval!==void 0){if(typeof $.flushInterval!=="number"||!Number.isInteger($.flushInterval)||$.flushInterval<0)return!1}if($.autoTrack!==void 0&&typeof $.autoTrack!=="boolean")return!1;return!0}function OZ(Z){if(!O(Z))return!1;let $=Z;if(typeof $.event!=="string"||$.event.length===0)return!1;if(!O($.properties))return!1;if(typeof $.timestamp!=="number"||!Number.isFinite($.timestamp))return!1;return!0}function K(Z){return Z}function w(Z){return Z}var q={endpoint:"http://localhost:8080",debug:!1,maxQueueSize:10,flushInterval:5000,autoTrack:!0,adaptiveNetwork:!0};var L="_analytics_vid",T="_analytics_sid",wZ="_analytics_test";function P(Z){try{if(typeof window!=="undefined"&&window[Z])return window[Z];if(typeof globalThis!=="undefined"&&globalThis[Z])return globalThis[Z];return null}catch{return null}}var b=new Map;function c(Z){return b.get(Z)??null}function TZ(Z,$){b.set(Z,$)}var C={localStorage:null,sessionStorage:null};function M(Z){if(C[Z]!==null)return C[Z];try{let $=P(Z);if(!$)return C[Z]=!1,!1;return $.setItem(wZ,"test"),$.removeItem(wZ),C[Z]=!0,!0}catch{return C[Z]=!1,!1}}function AZ(){C.localStorage=null,C.sessionStorage=null,b.clear()}function zZ(Z){if(M("localStorage"))try{return P("localStorage")?.getItem(Z)??null}catch{}return c(Z)}function XZ(Z,$){if(M("localStorage"))try{return P("localStorage")?.setItem(Z,$),!0}catch{}return TZ(Z,$),!1}function QZ(Z){if(M("sessionStorage"))try{return P("sessionStorage")?.getItem(Z)??null}catch{}return c(Z)}function BZ(Z,$){if(M("sessionStorage"))try{return P("sessionStorage")?.setItem(Z,$),!0}catch{}return TZ(Z,$),!1}function g(){let Z=Date.now();if(typeof crypto!=="undefined"&&typeof crypto.randomUUID==="function")try{return`${Z}_${crypto.randomUUID()}`}catch{}let $=rZ(8);return`${Z}_${$}`}function rZ(Z){let J="";if(typeof crypto!=="undefined"&&typeof crypto.getRandomValues==="function")try{let H=new Uint8Array(Z);crypto.getRandomValues(H);for(let W=0;W<Z;W++)J+="abcdefghijklmnopqrstuvwxyz0123456789"[H[W]%36];return J}catch{}for(let H=0;H<Z;H++)J+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return J}var x=null;function u(){if(x!==null)return x;let Z=zZ(L);if(Z)return x=K(Z),x;if(M("sessionStorage"))try{if(Z=P("sessionStorage")?.getItem(L)??null,Z)return x=K(Z),x}catch{}if(Z=c(L),Z)return x=K(Z),x;let $=g();if(x=K($),XZ(L,$),M("sessionStorage"))try{P("sessionStorage")?.setItem(L,$)}catch{}return x}function kZ(){if(x=null,M("localStorage"))try{P("localStorage")?.removeItem(L)}catch{}if(M("sessionStorage"))try{P("sessionStorage")?.removeItem(L)}catch{}b.delete(L)}var V=null;function l(){if(V!==null)return V;let Z=QZ(T);if(Z)return V=w(Z),V;if(Z=c(T),Z)return V=w(Z),V;let $=g();return V=w($),BZ(T,$),V}function NZ(){if(V=null,M("sessionStorage"))try{P("sessionStorage")?.removeItem(T)}catch{}b.delete(T)}var fZ={VISITOR_ID:L,SESSION_ID:T};var G={beacon:null,fetch:null,compression:null};function xZ(Z){if(!Z||Z==="?")return{};let $=Z.startsWith("?")?Z.slice(1):Z;if(!$)return{};if(typeof URLSearchParams!=="undefined")try{let W=new URLSearchParams($),j={};return W.forEach((z,X)=>{j[X]=z}),j}catch{}let J={},H=$.split("&");for(let W of H){if(!W)continue;let[j,...z]=W.split("=");if(!j)continue;let X=z.join("=");try{J[decodeURIComponent(j)]=decodeURIComponent(X||"")}catch{J[j]=X||""}}return J}function d(){if(typeof window==="undefined"&&typeof globalThis==="undefined")return{};let Z="";try{if(typeof window!=="undefined"&&window.location){if(Z=window.location.search,!Z&&window.location.hash){let J=window.location.hash.indexOf("?");if(J!==-1)Z=window.location.hash.slice(J)}}}catch{return{}}let $=xZ(Z);return{...$.utm_source&&{source:$.utm_source},...$.utm_medium&&{medium:$.utm_medium},...$.utm_campaign&&{campaign:$.utm_campaign},...$.utm_term&&{term:$.utm_term},...$.utm_content&&{content:$.utm_content}}}function _Z(){if(typeof navigator==="undefined")return null;let Z=navigator;return Z.connection||Z.mozConnection||Z.webkitConnection||null}function hZ(){let Z=_Z();if(!Z)return null;return{effectiveType:Z.effectiveType||"unknown",downlink:Z.downlink,rtt:Z.rtt,saveData:Z.saveData}}function I(){let Z=_Z();if(!Z||!Z.effectiveType)return"unknown";let $=Z.effectiveType;if($==="slow-2g"||$==="2g"||$==="3g"||$==="4g")return $;return"unknown"}var tZ=["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","sogou","exabot","facebot","ia_archiver","headless","phantom","selenium","puppeteer","playwright","webdriver","curl","wget","python-requests","python-urllib","java/","apache-httpclient","okhttp","axios/","bot","crawler","spider","scraper","lighthouse","pagespeed","gtmetrix"];function i(){if(typeof navigator==="undefined")return!1;let Z=navigator.userAgent?.toLowerCase()||"";if(!Z)return!1;for(let $ of tZ)if(Z.includes($))return!0;if(navigator.webdriver===!0)return!0;return!1}function A(Z,$){let J=null;return function(...H){if(J!==null)clearTimeout(J);J=setTimeout(()=>{Z.apply(this,H),J=null},$)}}function bZ(Z,$){let J=!1,H=null;return function(...W){if(!J)Z.apply(this,W),J=!0,setTimeout(()=>{if(J=!1,H!==null)Z.apply(this,H),H=null},$);else H=W}}function n(){if(G.beacon!==null)return G.beacon;let Z=typeof navigator!=="undefined"&&typeof navigator.sendBeacon==="function";return G.beacon=Z,Z}function S(){if(G.fetch!==null)return G.fetch;let Z=typeof fetch==="function";return G.fetch=Z,Z}function k(){if(G.compression!==null)return G.compression;let Z=typeof CompressionStream!=="undefined";return G.compression=Z,Z}function IZ(){G.beacon=null,G.fetch=null,G.compression=null}var eZ=100,Z0=1000,$0=5;function o(Z){if(typeof Z!=="string")return"unknown_event";if(!Z.trim())return"unknown_event";return Z.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"").slice(0,eZ)}function GZ(Z,$){if(Z===null||Z===void 0)return null;if(typeof Z==="string")return Z.slice(0,Z0);if(typeof Z==="number"){if(!Number.isFinite(Z))return null;return Z}if(typeof Z==="boolean")return Z;if(Z instanceof Date)return Z.toISOString();if($>=$0)return"[max depth]";if(Array.isArray(Z))return Z.slice(0,100).map((J)=>GZ(J,$+1));if(typeof Z==="object")try{let J={},H=Object.keys(Z);for(let W of H.slice(0,100)){let j=Z[W];if(j!==void 0)J[W]=GZ(j,$+1)}return J}catch{return"[object]"}return null}function s(Z){if(!Z||typeof Z!=="object"||Array.isArray(Z))return{};try{return GZ(Z,0)}catch{return{}}}function N(){try{if(typeof window!=="undefined"&&window.location)return window.location.href}catch{}return""}function a(){try{if(typeof document!=="undefined"&&document.title)return document.title}catch{}return}function r(){try{if(typeof document!=="undefined"&&document.referrer)return document.referrer}catch{}return}function t(){try{if(typeof navigator!=="undefined"&&navigator.userAgent)return navigator.userAgent}catch{}return""}function e(){try{if(typeof window!=="undefined"&&window.screen)return{width:window.screen.width||0,height:window.screen.height||0}}catch{}return{width:0,height:0}}var MZ="_analytics_offline_queue",EZ="_analytics_sent_requests",SZ=100,mZ=100,J0=65536,H0=1000,PZ=!1;function m(Z){PZ=Z}function Q(Z,...$){if(PZ&&typeof console!=="undefined")console.log(`[Analytics Network] ${Z}`,...$)}function R(Z,$){if(PZ&&typeof console!=="undefined")console.error(`[Analytics Network] ${Z}`,$)}class B extends Error{statusCode;retry;constructor(Z,$,J){super(Z);this.statusCode=$;this.retry=J;if(this.name="NetworkError",Error.captureStackTrace)Error.captureStackTrace(this,B)}}function F(Z,$){try{if(!n())return Q("sendBeacon not available"),!1;let J=JSON.stringify($);if(J.length>J0)return Q("Payload too large for sendBeacon:",J.length),!1;let H=new Blob([J],{type:"application/json"}),W=navigator.sendBeacon(Z,H);if(W)Q("Beacon sent successfully");else Q("Beacon failed to queue");return W}catch(J){return R("sendBeacon error:",J),!1}}async function D(Z,$,J){if(!S())throw new B("Fetch API not available",void 0,!1);try{let H=JSON.stringify($),W={"Content-Type":"application/json"};if(J)W.Authorization=`Bearer ${J}`;let j=await fetch(Z,{method:"POST",headers:W,body:H,keepalive:!0});if(!j.ok){let z=j.status>=500||j.status===429;throw new B(`HTTP error: ${j.status} ${j.statusText}`,j.status,z)}Q("Fetch sent successfully, status:",j.status)}catch(H){if(H instanceof B)throw H;throw new B(H instanceof Error?H.message:"Network request failed",void 0,!0)}}function W0(Z){return new Promise(($)=>setTimeout($,Z))}async function UZ(Z,$,J=3,H){let W;for(let j=0;j<=J;j++)try{await D(Z,$,H),Q("Request succeeded on attempt:",j+1);return}catch(z){if(W=z instanceof B?z:new B("Unknown error",void 0,!0),!W.retry)throw Q("Not retrying, error is not retryable:",W.message),W;if(j>=J){Q("Max retries exceeded");break}let X=H0*Math.pow(2,j);Q(`Retry ${j+1}/${J} after ${X}ms`),await W0(X)}throw W||new B("All retries failed",void 0,!1)}async function j0(Z){if(!k())return Q("CompressionStream not available, returning uncompressed"),Z;try{let $=new Blob([Z],{type:"application/json"}),J=new CompressionStream("gzip"),H=$.stream().pipeThrough(J),W=await new Response(H).blob();return Q(`Compressed ${Z.length} bytes to ${W.size} bytes (${Math.round((1-W.size/Z.length)*100)}% reduction)`),W}catch($){return R("Compression failed, returning uncompressed:",$),Z}}async function YZ(Z,$,J){if(!S())throw new B("Fetch API not available",void 0,!1);try{let H=JSON.stringify($),W=await j0(H),z={"Content-Type":"application/json",...W instanceof Blob&&{"Content-Encoding":"gzip"}};if(J)z.Authorization=`Bearer ${J}`;let X=await fetch(Z,{method:"POST",headers:z,body:W,keepalive:!0});if(!X.ok){let Y=X.status>=500||X.status===429;throw new B(`HTTP error: ${X.status}`,X.status,Y)}Q("Compressed fetch sent successfully")}catch(H){if(H instanceof B)throw H;throw new B(H instanceof Error?H.message:"Compressed send failed",void 0,!0)}}function U(Z){try{if(typeof localStorage==="undefined"){Q("localStorage not available for offline queue");return}let J=[...y(),...Z],H=J.length>SZ?J.slice(-SZ):J;localStorage.setItem(MZ,JSON.stringify(H)),Q(`Queued ${Z.length} offline events (total: ${H.length})`)}catch($){R("Failed to queue offline events:",$)}}function y(){try{if(typeof localStorage==="undefined")return[];let Z=localStorage.getItem(MZ);if(!Z)return[];let $=JSON.parse(Z);if(!Array.isArray($))return Q("Invalid offline queue format, clearing"),E(),[];return $}catch(Z){return R("Failed to get offline events:",Z),[]}}function E(){try{if(typeof localStorage!=="undefined")localStorage.removeItem(MZ),Q("Cleared offline queue")}catch(Z){R("Failed to clear offline events:",Z)}}function v(){if(typeof navigator==="undefined")return!1;return navigator.onLine===!1}function vZ(Z){if(typeof window==="undefined")return()=>{};return window.addEventListener("online",Z),()=>{window.removeEventListener("online",Z)}}function pZ(){try{if(typeof sessionStorage==="undefined")return[];let Z=sessionStorage.getItem(EZ);if(!Z)return[];let $=JSON.parse(Z);if(!Array.isArray($))return[];return $}catch{return[]}}function z0(Z){try{if(typeof sessionStorage!=="undefined")sessionStorage.setItem(EZ,JSON.stringify(Z))}catch{}}function X0(Z){return pZ().includes(Z)}function yZ(Z){try{let $=pZ();$.push(Z);let J=$.length>mZ?$.slice(-mZ):$;z0(J),Q("Marked request as sent:",Z)}catch($){R("Failed to mark request as sent:",$)}}async function cZ(Z,$,J={}){let{useBeacon:H=!0,compress:W=!1,retry:j=!0,requestId:z,apiKey:X}=J;if(z&&X0(z)){Q("Skipping duplicate request:",z);return}if(v()){Q("Offline, queuing events"),U($.events);return}try{if(H&&F(Z,$)){if(z)yZ(z);return}if(W)await YZ(Z,$,X);else if(j)await UZ(Z,$,3,X);else await D(Z,$,X);if(z)yZ(z)}catch(Y){if(R("Send failed:",Y),Y instanceof B&&Y.retry)U($.events)}}var qZ;((H)=>{H[H.LOW=0]="LOW";H[H.NORMAL=1]="NORMAL";H[H.HIGH=2]="HIGH"})(qZ||={});var Q0={maxQueueSize:3,flushInterval:15000,compressionEnabled:!0,batchingStrategy:"aggressive"},B0={maxQueueSize:5,flushInterval:1e4,compressionEnabled:!0,batchingStrategy:"aggressive"},G0={maxQueueSize:10,flushInterval:5000,compressionEnabled:!1,batchingStrategy:"balanced"},x0={maxQueueSize:20,flushInterval:3000,compressionEnabled:!1,batchingStrategy:"conservative"},M0={maxQueueSize:10,flushInterval:20000,compressionEnabled:!0,batchingStrategy:"aggressive"},P0=30000,U0=1000;function $Z(){if(typeof navigator==="undefined")return null;let Z=navigator;return Z.connection||Z.mozConnection||Z.webkitConnection||null}function p(){return $Z()?.saveData===!0}function ZZ(){return $Z()?.rtt??100}function VZ(){return $Z()?.downlink??10}function LZ(Z){return[...Z].sort(($,J)=>J.priority-$.priority)}function FZ(Z){let $=Z.event.toLowerCase();if($.includes("purchase")||$.includes("conversion")||$.includes("signup")||$.includes("error")||$.includes("checkout")||$.includes("subscribe"))return{...Z,priority:2};if($==="pageview"||$.includes("impression")||$.includes("scroll")||$.includes("hover"))return{...Z,priority:0};return{...Z,priority:1}}class JZ{attempts=0;maxRetries;constructor(Z="unknown"){switch(Z){case"slow-2g":this.maxRetries=5;break;case"2g":this.maxRetries=3;break;case"3g":this.maxRetries=2;break;default:this.maxRetries=2}}getBackoffDelay(){let Z=U0*Math.pow(2,this.attempts);return Math.min(Z,P0)}shouldRetry(Z){if(this.attempts>=this.maxRetries)return!1;if(Z instanceof B){if(Z.retry===!1)return!1;if(Z.statusCode!==void 0&&Z.statusCode>=400&&Z.statusCode<500&&Z.statusCode!==429)return!1;return!0}return!0}recordAttempt(){this.attempts++}reset(){this.attempts=0}getAttempts(){return this.attempts}getMaxRetries(){return this.maxRetries}}class _{currentSettings;connection=null;changeCallbacks=[];boundHandleChange;cachedConnectionType="unknown";lastUpdateTime=0;cacheTimeout=1000;constructor(){if(this.connection=$Z(),this.currentSettings=this.computeSettings(),this.boundHandleChange=A(()=>{this.handleConnectionChange()},100),this.connection?.addEventListener)this.connection.addEventListener("change",this.boundHandleChange)}computeSettings(){if(p())return{...M0};switch(this.getConnectionType()){case"slow-2g":return{...Q0};case"2g":return{...B0};case"3g":return{...G0};case"4g":case"unknown":default:return{...x0}}}handleConnectionChange(){this.lastUpdateTime=0;let Z=this.computeSettings();if(Z.maxQueueSize===this.currentSettings.maxQueueSize&&Z.flushInterval===this.currentSettings.flushInterval&&Z.compressionEnabled===this.currentSettings.compressionEnabled)return;this.currentSettings=Z;for(let $ of this.changeCallbacks)try{$(Z)}catch{}}getConnectionType(){let Z=Date.now();if(Z-this.lastUpdateTime<this.cacheTimeout)return this.cachedConnectionType;return this.cachedConnectionType=I(),this.lastUpdateTime=Z,this.cachedConnectionType}getSettings(){return{...this.currentSettings}}onConnectionChange(Z){return this.changeCallbacks.push(Z),()=>{let $=this.changeCallbacks.indexOf(Z);if($>-1)this.changeCallbacks.splice($,1)}}shouldCompress(){if(!k())return!1;if(p())return!0;return this.currentSettings.compressionEnabled}getOptimalBatchSize(){let Z=ZZ(),$=VZ();if(p())return 15;if(Z>500)return Math.min(this.currentSettings.maxQueueSize+5,20);if($<1)return Math.min(this.currentSettings.maxQueueSize+3,15);return this.currentSettings.maxQueueSize}getRetryStrategy(){return new JZ(this.getConnectionType())}isSlowConnection(){let Z=this.getConnectionType();return Z==="slow-2g"||Z==="2g"}getRecommendedTimeout(){let Z=ZZ(),$=this.getConnectionType(),J=1e4;switch($){case"slow-2g":J=30000;break;case"2g":J=20000;break;case"3g":J=15000;break}return J+=Z*2,J}destroy(){if(this.connection?.removeEventListener)this.connection.removeEventListener("change",this.boundHandleChange);this.changeCallbacks=[]}}function Y0(Z){return new Promise(($)=>setTimeout($,Z))}async function HZ(Z,$,J){let H=J.getRetryStrategy(),W=J.shouldCompress();if(J.isSlowConnection()){let z=$.events.map((Y)=>FZ(Y)),X=LZ(z);$={...$,events:X}}let j=I();while(!0)try{if(j==="4g"||j==="unknown"){if(F(Z,$))return}if(W)await YZ(Z,$);else await D(Z,$);return}catch(z){H.recordAttempt();let X=z instanceof Error?z:new Error(String(z));if(!H.shouldRetry(X))throw z;let Y=H.getBackoffDelay();await Y0(Y)}}var f=null;function gZ(){if(!f)f=new _;return f}function uZ(){if(f)f.destroy(),f=null}var q0=100;class h{config;queue=[];visitorId;sessionId;flushTimer=null;isInitialized=!1;lastPageUrl="";boundHandlePageUnload;boundHandleOnline;boundHandleOffline;boundHandlePopstate;debouncedTrackPageView;originalPushState=null;originalReplaceState=null;adapter=null;adapterCleanup=null;useAdaptiveNetwork;constructor(Z){if(!Z.apiKey||typeof Z.apiKey!=="string")throw new Error("[Analytics] API key is required");if(this.config={apiKey:Z.apiKey,endpoint:Z.endpoint??q.endpoint,debug:Z.debug??q.debug,maxQueueSize:Z.maxQueueSize??q.maxQueueSize,flushInterval:Z.flushInterval??q.flushInterval,autoTrack:Z.autoTrack??q.autoTrack,adaptiveNetwork:Z.adaptiveNetwork??q.adaptiveNetwork},m(this.config.debug),this.visitorId=u(),this.sessionId=l(),this.boundHandlePageUnload=this.handlePageUnload.bind(this),this.boundHandleOnline=this.handleOnline.bind(this),this.boundHandleOffline=this.handleOffline.bind(this),this.boundHandlePopstate=this.handlePopstate.bind(this),this.debouncedTrackPageView=A(()=>{this.trackPageViewInternal()},q0),this.useAdaptiveNetwork=this.config.adaptiveNetwork,this.useAdaptiveNetwork)this.initNetworkAdapter();if(i()){this.log("Bot detected, skipping initialization");return}this.init()}init(){if(this.isInitialized)return;if(this.isInitialized=!0,this.lastPageUrl=N(),this.config.autoTrack)this.trackPageViewInternal();if(this.config.autoTrack)this.setupPageViewTracking();if(this.startFlushTimer(),typeof window!=="undefined")window.addEventListener("beforeunload",this.boundHandlePageUnload),window.addEventListener("online",this.boundHandleOnline),window.addEventListener("offline",this.boundHandleOffline);this.sendOfflineEvents(),this.log("Initialized successfully")}initNetworkAdapter(){if(!this.useAdaptiveNetwork)return;try{this.adapter=new _,this.applyAdaptiveSettings(this.adapter.getSettings()),this.adapterCleanup=this.adapter.onConnectionChange((Z)=>{this.applyAdaptiveSettings(Z)})}catch(Z){this.warn("Failed to initialize network adapter",Z),this.adapter=null}}applyAdaptiveSettings(Z){let $=this.config.flushInterval;if(this.config={...this.config,maxQueueSize:Z.maxQueueSize,flushInterval:Z.flushInterval},Z.flushInterval!==$&&this.isInitialized)this.stopFlushTimer(),this.startFlushTimer();this.log("Adapted to network conditions:",Z)}track(Z,$={}){if(!this.isInitialized){this.warn("SDK not initialized, event not tracked");return}try{let J=o(Z),H=s($),W={event:J,properties:H,timestamp:Date.now()};if(this.queue.push(W),this.log(`Tracked event: ${J}`,H),this.queue.length>=this.config.maxQueueSize)this.flush()}catch(J){this.error("Failed to track event",J)}}trackPageView(){this.debouncedTrackPageView()}trackPageViewInternal(){let Z=N();if(Z===this.lastPageUrl&&this.queue.length>0){if(this.queue[this.queue.length-1].event==="pageview")return}this.lastPageUrl=Z,this.track("pageview",{})}async flush(){if(this.queue.length===0)return;let Z=this.queue;this.queue=[];let $=this.buildRawEvents(Z),J={api_key:this.config.apiKey,events:$},H=`${this.config.endpoint}/events`;if(v()){this.log("Offline, queuing events for later"),U($);return}try{if(this.adapter){await HZ(H,J,this.adapter),this.log(`Flushed ${$.length} events via adaptive send`);return}if(F(H,J)){this.log(`Flushed ${$.length} events via beacon`);return}await D(H,J),this.log(`Flushed ${$.length} events via fetch`)}catch(W){this.error("Failed to send events, queuing for retry",W),U($)}}buildRawEvents(Z){let $=N(),J=a(),H=r(),W=t(),j=e(),z=d();return Z.map((X)=>({event:X.event,properties:X.properties,timestamp:X.timestamp,visitor_id:this.visitorId,session_id:this.sessionId,page_url:$,page_title:J,referrer:H,user_agent:W,screen_width:j.width,screen_height:j.height,...Object.keys(z).length>0&&{utm:z}}))}startFlushTimer(){if(this.flushTimer!==null)return;if(this.config.flushInterval<=0)return;this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval),this.log(`Started flush timer: ${this.config.flushInterval}ms`)}stopFlushTimer(){if(this.flushTimer!==null)clearInterval(this.flushTimer),this.flushTimer=null,this.log("Stopped flush timer")}setupPageViewTracking(){if(typeof window==="undefined"||typeof history==="undefined")return;this.wrapHistoryMethod("pushState"),this.wrapHistoryMethod("replaceState"),window.addEventListener("popstate",this.boundHandlePopstate),this.log("Set up SPA navigation tracking")}wrapHistoryMethod(Z){if(typeof history==="undefined")return;let $=history[Z];if(!$)return;if(Z==="pushState")this.originalPushState=$;else this.originalReplaceState=$;let J=this;history[Z]=function(H,W,j){let z=$.apply(this,[H,W,j]);return J.trackPageView(),z}}handlePopstate=()=>{this.trackPageView()};restoreHistoryMethods(){if(typeof history==="undefined")return;if(this.originalPushState)history.pushState=this.originalPushState,this.originalPushState=null;if(this.originalReplaceState)history.replaceState=this.originalReplaceState,this.originalReplaceState=null}handlePageUnload=()=>{if(this.queue.length===0)return;let Z=this.buildRawEvents(this.queue),$={api_key:this.config.apiKey,events:Z},J=`${this.config.endpoint}/events`;if(!F(J,$))U(Z);this.queue=[]};handleOnline=()=>{this.log("Back online, sending queued events"),this.sendOfflineEvents()};handleOffline=()=>{if(this.log("Gone offline, queuing events"),this.queue.length>0){let Z=this.buildRawEvents(this.queue);U(Z),this.queue=[]}};sendOfflineEvents(){let Z=y();if(Z.length===0)return;this.log(`Found ${Z.length} offline events to send`),E();let $={api_key:this.config.apiKey,events:Z},J=`${this.config.endpoint}/events`;if(!F(J,$))D(J,$).catch((H)=>{this.error("Failed to send offline events",H),U(Z)})}setConfig(Z){let $=this.config.flushInterval;if(this.config={...this.config,...Z.endpoint!==void 0&&{endpoint:Z.endpoint},...Z.debug!==void 0&&{debug:Z.debug},...Z.maxQueueSize!==void 0&&{maxQueueSize:Z.maxQueueSize},...Z.flushInterval!==void 0&&{flushInterval:Z.flushInterval},...Z.autoTrack!==void 0&&{autoTrack:Z.autoTrack}},Z.debug!==void 0)m(Z.debug);if(Z.flushInterval!==void 0&&Z.flushInterval!==$)this.stopFlushTimer(),this.startFlushTimer();this.log("Config updated",Z)}getVisitorId(){return this.visitorId}getSessionId(){return this.sessionId}getConfig(){return{...this.config}}getQueueLength(){return this.queue.length}isActive(){return this.isInitialized}destroy(){if(this.log("Destroying instance"),this.queue.length>0)this.handlePageUnload();if(this.stopFlushTimer(),typeof window!=="undefined")window.removeEventListener("beforeunload",this.boundHandlePageUnload),window.removeEventListener("online",this.boundHandleOnline),window.removeEventListener("offline",this.boundHandleOffline),window.removeEventListener("popstate",this.boundHandlePopstate);if(this.restoreHistoryMethods(),this.adapterCleanup)this.adapterCleanup(),this.adapterCleanup=null;if(this.adapter)this.adapter.destroy(),this.adapter=null;this.queue=[],this.isInitialized=!1,this.log("Destroyed")}log(Z,...$){if(this.config.debug&&typeof console!=="undefined")console.log(`[Analytics] ${Z}`,...$)}warn(Z,...$){if(this.config.debug&&typeof console!=="undefined")console.warn(`[Analytics] ${Z}`,...$)}error(Z,...$){if(this.config.debug&&typeof console!=="undefined")console.error(`[Analytics] ${Z}`,...$)}}function lZ(Z){return new h(Z)}var dZ="0.1.0";function V0(){return{version:dZ,instance:null,init(Z,$={}){if(this.instance)this.instance.destroy();return this.instance=new h({apiKey:Z,...$}),this.instance},track(Z,$={}){if(!this.instance){if(typeof console!=="undefined")console.warn("[Analytics] Not initialized. Call analytics.init(apiKey) first.");return}this.instance.track(Z,$)},trackPageView(){if(!this.instance){if(typeof console!=="undefined")console.warn("[Analytics] Not initialized. Call analytics.init(apiKey) first.");return}this.instance.trackPageView()},getVisitorId(){return this.instance?.getVisitorId()??null},getSessionId(){return this.instance?.getSessionId()??null},async flush(){if(this.instance)await this.instance.flush()},destroy(){if(this.instance)this.instance.destroy(),this.instance=null}}}var DZ=V0();function L0(){if(typeof window==="undefined"||typeof document==="undefined")return;window.analytics=DZ;let Z=document.currentScript;if(!Z)return;let $=Z.getAttribute("data-api-key");if(!$)return;let J=Z.getAttribute("data-endpoint")||void 0,H=Z.getAttribute("data-debug")==="true",W=Z.getAttribute("data-auto-track")!=="false",j=Z.getAttribute("data-adaptive")!=="false";DZ.init($,{endpoint:J,debug:H,autoTrack:W,adaptiveNetwork:j})}L0();var D0=DZ;})();
|