@faststats/web 0.0.1 → 0.0.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @faststats/web
2
+
3
+ ## 0.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - f1f66de: feat: add track event function
package/dist/module.d.ts CHANGED
@@ -399,6 +399,7 @@ declare global {
399
399
  }
400
400
  //#endregion
401
401
  //#region src/analytics.d.ts
402
+ declare function trackEvent(eventName: string, properties?: Record<string, unknown>): void;
402
403
  type Dict = Record<string, unknown>;
403
404
  interface SamplingOptions {
404
405
  percentage?: number;
@@ -454,6 +455,7 @@ declare global {
454
455
  __FA_optIn?: () => void;
455
456
  __FA_optOut?: () => void;
456
457
  __FA_isTrackingDisabled?: () => boolean;
458
+ __FA_trackEvent?: (eventName: string, properties?: Record<string, unknown>) => void;
457
459
  __FA_webAnalyticsInstance?: WebAnalytics;
458
460
  }
459
461
  }
@@ -499,4 +501,4 @@ declare class WebAnalytics {
499
501
  private links;
500
502
  }
501
503
  //#endregion
502
- export { type ConsentMode, type IdentifyOptions, WebAnalytics, type WebAnalyticsOptions };
504
+ export { type ConsentMode, type IdentifyOptions, WebAnalytics, type WebAnalyticsOptions, trackEvent };
package/dist/module.js CHANGED
@@ -65,6 +65,10 @@ function normalizeSamplingPercentage(value) {
65
65
 
66
66
  //#endregion
67
67
  //#region src/analytics.ts
68
+ function trackEvent(eventName, properties) {
69
+ if (typeof window === "undefined" || isTrackingDisabled()) return;
70
+ window.__FA_webAnalyticsInstance?.track(eventName, properties ?? {});
71
+ }
68
72
  function isTrackingDisabled() {
69
73
  if (typeof localStorage === "undefined") return false;
70
74
  const value = localStorage.getItem("disable-faststats");
@@ -176,6 +180,7 @@ var WebAnalytics = class {
176
180
  window.__FA_setConsentMode = (mode) => this.setConsentMode(mode);
177
181
  window.__FA_optIn = () => this.optIn();
178
182
  window.__FA_optOut = () => this.optOut();
183
+ window.__FA_trackEvent = (eventName, props) => this.track(eventName, props ?? {});
179
184
  window.__FA_isTrackingDisabled = isTrackingDisabled;
180
185
  const opts = this.options;
181
186
  const hasWebVitalsSampling = opts.webVitals?.sampling?.percentage !== void 0;
@@ -400,4 +405,4 @@ var WebAnalytics = class {
400
405
  };
401
406
 
402
407
  //#endregion
403
- export { WebAnalytics };
408
+ export { WebAnalytics, trackEvent };
@@ -1 +1 @@
1
- var FA_Script=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e?``:n()}function n(){if(typeof localStorage>`u`)return``;let e=localStorage.getItem(`faststats_anon_id`);if(e)return e;let t=crypto.randomUUID();return localStorage.setItem(`faststats_anon_id`,t),t}function r(e){return e||typeof localStorage>`u`?``:(localStorage.removeItem(`faststats_anon_id`),n())}function i(){if(typeof sessionStorage>`u`)return``;let e=sessionStorage.getItem(`session_id`),t=sessionStorage.getItem(`session_timestamp`);if(e&&t){if(Date.now()-Number.parseInt(t,10)<18e5)return sessionStorage.setItem(`session_timestamp`,Date.now().toString()),e;sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`)}let n=Date.now().toString(),r=crypto.randomUUID();return sessionStorage.setItem(`session_id`,r),sessionStorage.setItem(`session_timestamp`,n),sessionStorage.setItem(`session_start`,n),r}function a(){return typeof sessionStorage>`u`?``:(sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`),i())}function o(){typeof sessionStorage>`u`||sessionStorage.getItem(`session_id`)&&sessionStorage.setItem(`session_timestamp`,Date.now().toString())}function s(){if(typeof sessionStorage>`u`)return Date.now();let e=sessionStorage.getItem(`session_start`);if(e)return Number.parseInt(e,10);let t=sessionStorage.getItem(`session_timestamp`);return t?Number.parseInt(t,10):Date.now()}function c(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}function l(){if(typeof localStorage>`u`)return!1;let e=localStorage.getItem(`disable-faststats`);return e===`true`||e===`1`}async function u(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`}=e,s=n instanceof Blob?n:new Blob([n],{type:r});if(navigator.sendBeacon?.(t,s))return a&&console.log(`${o} ✓ Sent via beacon`),!0;try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:!0}),s=e.ok;return a&&(s?console.log(`${o} ✓ Sent via fetch`):console.warn(`${o} ✗ Failed: ${e.status}`)),s}catch{return a&&console.warn(`${o} ✗ Failed to send`),!1}}function d(e){for(;e&&!(e.tagName===`A`&&e.href);)e=e.parentNode;return e}function f(){let e={};if(!location.search)return e;let t=new URLSearchParams(location.search);for(let n of[`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`]){let r=t.get(n);r&&(e[n]=r)}return e}var p=class{endpoint;debug;baseUrl;started=!1;pageKey=``;navTimer=null;heartbeatTimer=null;scrollDepth=0;pageEntryTime=0;pagePath=``;pageUrl=``;pageHash=``;hasLeftCurrentPage=!1;scrollHandler=null;consentMode;cookielessWhilePending;constructor(e){this.options=e,this.endpoint=e.endpoint??`https://metrics.faststats.dev/v1/web`,this.debug=e.debug??!1,this.consentMode=e.consent?.mode??`granted`,this.cookielessWhilePending=e.consent?.cookielessWhilePending??!0;let t=typeof document<`u`?document.currentScript:null,n=t?.src?t.src.substring(0,t.src.lastIndexOf(`/`)):``;this.baseUrl=(e.baseUrl??n)||(typeof window<`u`?window.location.origin:``),(e.autoTrack??!0)&&this.init()}log(e){this.debug&&console.log(`[Analytics] ${e}`)}init(){if(!(typeof window>`u`)){if(l()){this.log(`disabled`);return}`requestIdleCallback`in window?window.requestIdleCallback(()=>this.start()):setTimeout(()=>this.start(),1)}}start(){if(this.started||typeof window>`u`)return;if(window.__FA_webAnalyticsInstance&&window.__FA_webAnalyticsInstance!==this){this.log(`already started by another instance`);return}if(l()){this.log(`disabled`);return}this.started=!0,window.__FA_webAnalyticsInstance=this,window.__FA_getAnonymousId=()=>t(this.isCookielessMode()),window.__FA_getSessionId=i,window.__FA_sendData=u,window.__FA_identify=(e,t,n)=>this.identify(e,t,n),window.__FA_logout=e=>this.logout(e),window.__FA_setConsentMode=e=>this.setConsentMode(e),window.__FA_optIn=()=>this.optIn(),window.__FA_optOut=()=>this.optOut(),window.__FA_isTrackingDisabled=l;let e=this.options,n=e.webVitals?.sampling?.percentage!==void 0,r=e.replayOptions?.samplingPercentage!==void 0||e.sessionReplays?.sampling?.percentage!==void 0;if((e.errorTracking?.enabled??e.trackErrors)&&this.load(`error`,`__FA_ErrorTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,getCommonData:()=>({url:location.href,page:location.pathname,referrer:document.referrer||null})}),(e.webVitals?.enabled??e.trackWebVitals??n)&&this.load(`web-vitals`,`__FA_WebVitalsTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,samplingPercentage:c(e.webVitals?.sampling?.percentage)}),e.sessionReplays?.enabled??e.trackReplay??r){let t=e.replayOptions??{};this.load(`replay`,`__FA_ReplayTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,...t,samplingPercentage:c(t.samplingPercentage??e.sessionReplays?.sampling?.percentage)})}this.enterPage(),this.pageview({trigger:`load`}),this.links(),this.trackScroll(),this.startHeartbeat(),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.leavePage():this.startHeartbeat()}),window.addEventListener(`pagehide`,()=>this.leavePage()),window.addEventListener(`popstate`,()=>this.navigate()),e.trackHash&&window.addEventListener(`hashchange`,()=>this.navigate()),this.patch()}load(e,t,n){let r=document.createElement(`script`);r.src=`${this.baseUrl}/${e}.js`,r.async=!0,r.onload=()=>{let r=window[t];r&&(new r(n).start(),this.log(`${e} loaded`))},r.onerror=()=>{this.debug&&console.warn(`[Analytics] ${e} failed`)},document.head.appendChild(r)}pageview(e={}){let t=`${location.pathname}|${this.options.trackHash??!1?location.hash:``}`;t!==this.pageKey&&(this.pageKey=t,this.send(`pageview`,e))}track(e,t={}){this.send(e,t)}identify(e,n,r={}){if(l()||this.isCookielessMode())return;let i=e.trim(),a=n.trim();!i||!a||u({url:this.endpoint.replace(/\/v1\/web$/,`/v1/identify`),data:JSON.stringify({token:this.options.siteKey,identifier:t(!1),externalId:i,email:a,name:r.name?.trim()||void 0,phone:r.phone?.trim()||void 0,avatarUrl:r.avatarUrl?.trim()||void 0,traits:r.traits??{}}),contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] identify`})}logout(e=!0){l()||(e&&r(this.isCookielessMode()),a())}setConsentMode(e){this.consentMode=e}optIn(){this.setConsentMode(`granted`)}optOut(){this.setConsentMode(`denied`)}getConsentMode(){return this.consentMode}isCookielessMode(){return this.options.cookieless||this.consentMode===`denied`?!0:this.consentMode===`pending`?this.cookielessWhilePending:!1}send(e,n={}){let r=t(this.isCookielessMode()),a=JSON.stringify({token:this.options.siteKey,...r?{userId:r}:{},sessionId:i(),data:{event:e,page:location.pathname,referrer:document.referrer||null,title:document.title||``,url:location.href,...f(),...n}});this.log(e),u({url:this.endpoint,data:a,contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] ${e}`})}enterPage(){this.pageEntryTime=Date.now(),this.pagePath=location.pathname,this.pageUrl=location.href,this.pageHash=location.hash,this.scrollDepth=0,this.hasLeftCurrentPage=!1}leavePage(){if(this.hasLeftCurrentPage)return;this.hasLeftCurrentPage=!0;let e=Date.now();this.send(`page_leave`,{page:this.pagePath,url:this.pageUrl,time_on_page:e-this.pageEntryTime,scroll_depth:this.scrollDepth,session_duration:e-s()})}trackScroll(){this.scrollHandler&&window.removeEventListener(`scroll`,this.scrollHandler);let e=()=>{let e=document.documentElement,t=document.body,n=window.innerHeight,r=Math.max(e.scrollHeight,t.scrollHeight);if(r<=n){this.scrollDepth=100;return}let i=Math.min(100,Math.round(((window.scrollY||e.scrollTop)+n)/r*100));i>this.scrollDepth&&(this.scrollDepth=i)};this.scrollHandler=e,e(),window.addEventListener(`scroll`,e,{passive:!0})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{if(document.visibilityState===`hidden`){clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;return}o()},300*1e3)}navigate(){this.navTimer&&clearTimeout(this.navTimer),this.navTimer=setTimeout(()=>{this.navTimer=null;let e=location.pathname!==this.pagePath,t=(this.options.trackHash??!1)&&location.hash!==this.pageHash;!e&&!t||(this.leavePage(),this.enterPage(),this.trackScroll(),this.pageview({trigger:`navigation`}))},300)}patch(){let e=()=>this.navigate();for(let t of[`pushState`,`replaceState`]){let n=history[t];history[t]=function(...t){let r=n.apply(this,t);return e(),r}}}links(){let e=e=>{let t=d(e.target);t&&t.host!==location.host&&this.track(`outbound_link`,{outbound_link:t.href})};document.addEventListener(`click`,e),document.addEventListener(`auxclick`,e)}};function m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1}function h(e){if(e==null||e.trim()===``)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(100,t))}function g(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`pending`)return`pending`;if(t===`granted`)return`granted`;if(t===`denied`)return`denied`}return typeof window<`u`&&(window.WebAnalytics=p,window.__FA_isTrackingDisabled=l,(()=>{let e=document.currentScript;if(!e)return;let t=e,n=e=>t.getAttribute(`data-${e}`),r=n(`sitekey`);if(!r)return;let i={siteKey:r},a=n(`endpoint`);a&&(i.endpoint=a);let o=n(`debug`);o&&(i.debug=o===`true`);let s=m(n(`trackErrors`));s!==void 0&&(i.trackErrors=s,i.errorTracking={enabled:s});let c=m(n(`webVitals`)),l=h(n(`web-vitals-sampling`));(c!==void 0||l!==void 0)&&(c!==void 0&&(i.trackWebVitals=c),i.webVitals={enabled:c,sampling:l===void 0?void 0:{percentage:l}});let u=m(n(`replay`)),d=h(n(`replay-sampling`));(u!==void 0||d!==void 0)&&(u!==void 0&&(i.trackReplay=u),i.sessionReplays={enabled:u,sampling:d===void 0?void 0:{percentage:d}});let f=m(n(`cookieless`));f!==void 0&&(i.cookieless=f);let _=g(n(`consent-mode`)),v=m(n(`cookieless-while-pending`));(_!==void 0||v!==void 0)&&(i.consent={mode:_,cookielessWhilePending:v}),new p(i)})()),e.WebAnalytics=p,e.isTrackingDisabled=l,e.sendData=u,e})({});
1
+ var FA_Script=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e?``:n()}function n(){if(typeof localStorage>`u`)return``;let e=localStorage.getItem(`faststats_anon_id`);if(e)return e;let t=crypto.randomUUID();return localStorage.setItem(`faststats_anon_id`,t),t}function r(e){return e||typeof localStorage>`u`?``:(localStorage.removeItem(`faststats_anon_id`),n())}function i(){if(typeof sessionStorage>`u`)return``;let e=sessionStorage.getItem(`session_id`),t=sessionStorage.getItem(`session_timestamp`);if(e&&t){if(Date.now()-Number.parseInt(t,10)<18e5)return sessionStorage.setItem(`session_timestamp`,Date.now().toString()),e;sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`)}let n=Date.now().toString(),r=crypto.randomUUID();return sessionStorage.setItem(`session_id`,r),sessionStorage.setItem(`session_timestamp`,n),sessionStorage.setItem(`session_start`,n),r}function a(){return typeof sessionStorage>`u`?``:(sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`),i())}function o(){typeof sessionStorage>`u`||sessionStorage.getItem(`session_id`)&&sessionStorage.setItem(`session_timestamp`,Date.now().toString())}function s(){if(typeof sessionStorage>`u`)return Date.now();let e=sessionStorage.getItem(`session_start`);if(e)return Number.parseInt(e,10);let t=sessionStorage.getItem(`session_timestamp`);return t?Number.parseInt(t,10):Date.now()}function c(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}function l(){if(typeof localStorage>`u`)return!1;let e=localStorage.getItem(`disable-faststats`);return e===`true`||e===`1`}async function u(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`}=e,s=n instanceof Blob?n:new Blob([n],{type:r});if(navigator.sendBeacon?.(t,s))return a&&console.log(`${o} ✓ Sent via beacon`),!0;try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:!0}),s=e.ok;return a&&(s?console.log(`${o} ✓ Sent via fetch`):console.warn(`${o} ✗ Failed: ${e.status}`)),s}catch{return a&&console.warn(`${o} ✗ Failed to send`),!1}}function d(e){for(;e&&!(e.tagName===`A`&&e.href);)e=e.parentNode;return e}function f(){let e={};if(!location.search)return e;let t=new URLSearchParams(location.search);for(let n of[`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`]){let r=t.get(n);r&&(e[n]=r)}return e}var p=class{endpoint;debug;baseUrl;started=!1;pageKey=``;navTimer=null;heartbeatTimer=null;scrollDepth=0;pageEntryTime=0;pagePath=``;pageUrl=``;pageHash=``;hasLeftCurrentPage=!1;scrollHandler=null;consentMode;cookielessWhilePending;constructor(e){this.options=e,this.endpoint=e.endpoint??`https://metrics.faststats.dev/v1/web`,this.debug=e.debug??!1,this.consentMode=e.consent?.mode??`granted`,this.cookielessWhilePending=e.consent?.cookielessWhilePending??!0;let t=typeof document<`u`?document.currentScript:null,n=t?.src?t.src.substring(0,t.src.lastIndexOf(`/`)):``;this.baseUrl=(e.baseUrl??n)||(typeof window<`u`?window.location.origin:``),(e.autoTrack??!0)&&this.init()}log(e){this.debug&&console.log(`[Analytics] ${e}`)}init(){if(!(typeof window>`u`)){if(l()){this.log(`disabled`);return}`requestIdleCallback`in window?window.requestIdleCallback(()=>this.start()):setTimeout(()=>this.start(),1)}}start(){if(this.started||typeof window>`u`)return;if(window.__FA_webAnalyticsInstance&&window.__FA_webAnalyticsInstance!==this){this.log(`already started by another instance`);return}if(l()){this.log(`disabled`);return}this.started=!0,window.__FA_webAnalyticsInstance=this,window.__FA_getAnonymousId=()=>t(this.isCookielessMode()),window.__FA_getSessionId=i,window.__FA_sendData=u,window.__FA_identify=(e,t,n)=>this.identify(e,t,n),window.__FA_logout=e=>this.logout(e),window.__FA_setConsentMode=e=>this.setConsentMode(e),window.__FA_optIn=()=>this.optIn(),window.__FA_optOut=()=>this.optOut(),window.__FA_trackEvent=(e,t)=>this.track(e,t??{}),window.__FA_isTrackingDisabled=l;let e=this.options,n=e.webVitals?.sampling?.percentage!==void 0,r=e.replayOptions?.samplingPercentage!==void 0||e.sessionReplays?.sampling?.percentage!==void 0;if((e.errorTracking?.enabled??e.trackErrors)&&this.load(`error`,`__FA_ErrorTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,getCommonData:()=>({url:location.href,page:location.pathname,referrer:document.referrer||null})}),(e.webVitals?.enabled??e.trackWebVitals??n)&&this.load(`web-vitals`,`__FA_WebVitalsTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,samplingPercentage:c(e.webVitals?.sampling?.percentage)}),e.sessionReplays?.enabled??e.trackReplay??r){let t=e.replayOptions??{};this.load(`replay`,`__FA_ReplayTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,...t,samplingPercentage:c(t.samplingPercentage??e.sessionReplays?.sampling?.percentage)})}this.enterPage(),this.pageview({trigger:`load`}),this.links(),this.trackScroll(),this.startHeartbeat(),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.leavePage():this.startHeartbeat()}),window.addEventListener(`pagehide`,()=>this.leavePage()),window.addEventListener(`popstate`,()=>this.navigate()),e.trackHash&&window.addEventListener(`hashchange`,()=>this.navigate()),this.patch()}load(e,t,n){let r=document.createElement(`script`);r.src=`${this.baseUrl}/${e}.js`,r.async=!0,r.onload=()=>{let r=window[t];r&&(new r(n).start(),this.log(`${e} loaded`))},r.onerror=()=>{this.debug&&console.warn(`[Analytics] ${e} failed`)},document.head.appendChild(r)}pageview(e={}){let t=`${location.pathname}|${this.options.trackHash??!1?location.hash:``}`;t!==this.pageKey&&(this.pageKey=t,this.send(`pageview`,e))}track(e,t={}){this.send(e,t)}identify(e,n,r={}){if(l()||this.isCookielessMode())return;let i=e.trim(),a=n.trim();!i||!a||u({url:this.endpoint.replace(/\/v1\/web$/,`/v1/identify`),data:JSON.stringify({token:this.options.siteKey,identifier:t(!1),externalId:i,email:a,name:r.name?.trim()||void 0,phone:r.phone?.trim()||void 0,avatarUrl:r.avatarUrl?.trim()||void 0,traits:r.traits??{}}),contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] identify`})}logout(e=!0){l()||(e&&r(this.isCookielessMode()),a())}setConsentMode(e){this.consentMode=e}optIn(){this.setConsentMode(`granted`)}optOut(){this.setConsentMode(`denied`)}getConsentMode(){return this.consentMode}isCookielessMode(){return this.options.cookieless||this.consentMode===`denied`?!0:this.consentMode===`pending`?this.cookielessWhilePending:!1}send(e,n={}){let r=t(this.isCookielessMode()),a=JSON.stringify({token:this.options.siteKey,...r?{userId:r}:{},sessionId:i(),data:{event:e,page:location.pathname,referrer:document.referrer||null,title:document.title||``,url:location.href,...f(),...n}});this.log(e),u({url:this.endpoint,data:a,contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] ${e}`})}enterPage(){this.pageEntryTime=Date.now(),this.pagePath=location.pathname,this.pageUrl=location.href,this.pageHash=location.hash,this.scrollDepth=0,this.hasLeftCurrentPage=!1}leavePage(){if(this.hasLeftCurrentPage)return;this.hasLeftCurrentPage=!0;let e=Date.now();this.send(`page_leave`,{page:this.pagePath,url:this.pageUrl,time_on_page:e-this.pageEntryTime,scroll_depth:this.scrollDepth,session_duration:e-s()})}trackScroll(){this.scrollHandler&&window.removeEventListener(`scroll`,this.scrollHandler);let e=()=>{let e=document.documentElement,t=document.body,n=window.innerHeight,r=Math.max(e.scrollHeight,t.scrollHeight);if(r<=n){this.scrollDepth=100;return}let i=Math.min(100,Math.round(((window.scrollY||e.scrollTop)+n)/r*100));i>this.scrollDepth&&(this.scrollDepth=i)};this.scrollHandler=e,e(),window.addEventListener(`scroll`,e,{passive:!0})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{if(document.visibilityState===`hidden`){clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;return}o()},300*1e3)}navigate(){this.navTimer&&clearTimeout(this.navTimer),this.navTimer=setTimeout(()=>{this.navTimer=null;let e=location.pathname!==this.pagePath,t=(this.options.trackHash??!1)&&location.hash!==this.pageHash;!e&&!t||(this.leavePage(),this.enterPage(),this.trackScroll(),this.pageview({trigger:`navigation`}))},300)}patch(){let e=()=>this.navigate();for(let t of[`pushState`,`replaceState`]){let n=history[t];history[t]=function(...t){let r=n.apply(this,t);return e(),r}}}links(){let e=e=>{let t=d(e.target);t&&t.host!==location.host&&this.track(`outbound_link`,{outbound_link:t.href})};document.addEventListener(`click`,e),document.addEventListener(`auxclick`,e)}};function m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1}function h(e){if(e==null||e.trim()===``)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(100,t))}function g(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`pending`)return`pending`;if(t===`granted`)return`granted`;if(t===`denied`)return`denied`}return typeof window<`u`&&(window.WebAnalytics=p,window.__FA_isTrackingDisabled=l,(()=>{let e=document.currentScript;if(!e)return;let t=e,n=e=>t.getAttribute(`data-${e}`),r=n(`sitekey`);if(!r)return;let i={siteKey:r},a=n(`endpoint`);a&&(i.endpoint=a);let o=n(`debug`);o&&(i.debug=o===`true`);let s=m(n(`trackErrors`));s!==void 0&&(i.trackErrors=s,i.errorTracking={enabled:s});let c=m(n(`webVitals`)),l=h(n(`web-vitals-sampling`));(c!==void 0||l!==void 0)&&(c!==void 0&&(i.trackWebVitals=c),i.webVitals={enabled:c,sampling:l===void 0?void 0:{percentage:l}});let u=m(n(`replay`)),d=h(n(`replay-sampling`));(u!==void 0||d!==void 0)&&(u!==void 0&&(i.trackReplay=u),i.sessionReplays={enabled:u,sampling:d===void 0?void 0:{percentage:d}});let f=m(n(`cookieless`));f!==void 0&&(i.cookieless=f);let _=g(n(`consent-mode`)),v=m(n(`cookieless-while-pending`));(_!==void 0||v!==void 0)&&(i.consent={mode:_,cookielessWhilePending:v}),new p(i)})()),e.WebAnalytics=p,e.isTrackingDisabled=l,e.sendData=u,e})({});
package/dist/script.js CHANGED
@@ -1 +1 @@
1
- var FA_Script=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e?``:n()}function n(){if(typeof localStorage>`u`)return``;let e=localStorage.getItem(`faststats_anon_id`);if(e)return e;let t=crypto.randomUUID();return localStorage.setItem(`faststats_anon_id`,t),t}function r(e){return e||typeof localStorage>`u`?``:(localStorage.removeItem(`faststats_anon_id`),n())}function i(){if(typeof sessionStorage>`u`)return``;let e=sessionStorage.getItem(`session_id`),t=sessionStorage.getItem(`session_timestamp`);if(e&&t){if(Date.now()-Number.parseInt(t,10)<18e5)return sessionStorage.setItem(`session_timestamp`,Date.now().toString()),e;sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`)}let n=Date.now().toString(),r=crypto.randomUUID();return sessionStorage.setItem(`session_id`,r),sessionStorage.setItem(`session_timestamp`,n),sessionStorage.setItem(`session_start`,n),r}function a(){return typeof sessionStorage>`u`?``:(sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`),i())}function o(){typeof sessionStorage>`u`||sessionStorage.getItem(`session_id`)&&sessionStorage.setItem(`session_timestamp`,Date.now().toString())}function s(){if(typeof sessionStorage>`u`)return Date.now();let e=sessionStorage.getItem(`session_start`);if(e)return Number.parseInt(e,10);let t=sessionStorage.getItem(`session_timestamp`);return t?Number.parseInt(t,10):Date.now()}function c(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}function l(){if(typeof localStorage>`u`)return!1;let e=localStorage.getItem(`disable-faststats`);return e===`true`||e===`1`}async function u(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`}=e,s=n instanceof Blob?n:new Blob([n],{type:r});if(navigator.sendBeacon?.(t,s))return a&&console.log(`${o} ✓ Sent via beacon`),!0;try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:!0}),s=e.ok;return a&&(s?console.log(`${o} ✓ Sent via fetch`):console.warn(`${o} ✗ Failed: ${e.status}`)),s}catch{return a&&console.warn(`${o} ✗ Failed to send`),!1}}function d(e){for(;e&&!(e.tagName===`A`&&e.href);)e=e.parentNode;return e}function f(){let e={};if(!location.search)return e;let t=new URLSearchParams(location.search);for(let n of[`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`]){let r=t.get(n);r&&(e[n]=r)}return e}var p=class{endpoint;debug;baseUrl;started=!1;pageKey=``;navTimer=null;heartbeatTimer=null;scrollDepth=0;pageEntryTime=0;pagePath=``;pageUrl=``;pageHash=``;hasLeftCurrentPage=!1;scrollHandler=null;consentMode;cookielessWhilePending;constructor(e){this.options=e,this.endpoint=e.endpoint??`https://metrics.faststats.dev/v1/web`,this.debug=e.debug??!1,this.consentMode=e.consent?.mode??`granted`,this.cookielessWhilePending=e.consent?.cookielessWhilePending??!0;let t=typeof document<`u`?document.currentScript:null,n=t?.src?t.src.substring(0,t.src.lastIndexOf(`/`)):``;this.baseUrl=(e.baseUrl??n)||(typeof window<`u`?window.location.origin:``),(e.autoTrack??!0)&&this.init()}log(e){this.debug&&console.log(`[Analytics] ${e}`)}init(){if(!(typeof window>`u`)){if(l()){this.log(`disabled`);return}`requestIdleCallback`in window?window.requestIdleCallback(()=>this.start()):setTimeout(()=>this.start(),1)}}start(){if(this.started||typeof window>`u`)return;if(window.__FA_webAnalyticsInstance&&window.__FA_webAnalyticsInstance!==this){this.log(`already started by another instance`);return}if(l()){this.log(`disabled`);return}this.started=!0,window.__FA_webAnalyticsInstance=this,window.__FA_getAnonymousId=()=>t(this.isCookielessMode()),window.__FA_getSessionId=i,window.__FA_sendData=u,window.__FA_identify=(e,t,n)=>this.identify(e,t,n),window.__FA_logout=e=>this.logout(e),window.__FA_setConsentMode=e=>this.setConsentMode(e),window.__FA_optIn=()=>this.optIn(),window.__FA_optOut=()=>this.optOut(),window.__FA_isTrackingDisabled=l;let e=this.options,n=e.webVitals?.sampling?.percentage!==void 0,r=e.replayOptions?.samplingPercentage!==void 0||e.sessionReplays?.sampling?.percentage!==void 0;if((e.errorTracking?.enabled??e.trackErrors)&&this.load(`error`,`__FA_ErrorTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,getCommonData:()=>({url:location.href,page:location.pathname,referrer:document.referrer||null})}),(e.webVitals?.enabled??e.trackWebVitals??n)&&this.load(`web-vitals`,`__FA_WebVitalsTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,samplingPercentage:c(e.webVitals?.sampling?.percentage)}),e.sessionReplays?.enabled??e.trackReplay??r){let t=e.replayOptions??{};this.load(`replay`,`__FA_ReplayTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,...t,samplingPercentage:c(t.samplingPercentage??e.sessionReplays?.sampling?.percentage)})}this.enterPage(),this.pageview({trigger:`load`}),this.links(),this.trackScroll(),this.startHeartbeat(),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.leavePage():this.startHeartbeat()}),window.addEventListener(`pagehide`,()=>this.leavePage()),window.addEventListener(`popstate`,()=>this.navigate()),e.trackHash&&window.addEventListener(`hashchange`,()=>this.navigate()),this.patch()}load(e,t,n){let r=document.createElement(`script`);r.src=`${this.baseUrl}/${e}.js`,r.async=!0,r.onload=()=>{let r=window[t];r&&(new r(n).start(),this.log(`${e} loaded`))},r.onerror=()=>{this.debug&&console.warn(`[Analytics] ${e} failed`)},document.head.appendChild(r)}pageview(e={}){let t=`${location.pathname}|${this.options.trackHash??!1?location.hash:``}`;t!==this.pageKey&&(this.pageKey=t,this.send(`pageview`,e))}track(e,t={}){this.send(e,t)}identify(e,n,r={}){if(l()||this.isCookielessMode())return;let i=e.trim(),a=n.trim();!i||!a||u({url:this.endpoint.replace(/\/v1\/web$/,`/v1/identify`),data:JSON.stringify({token:this.options.siteKey,identifier:t(!1),externalId:i,email:a,name:r.name?.trim()||void 0,phone:r.phone?.trim()||void 0,avatarUrl:r.avatarUrl?.trim()||void 0,traits:r.traits??{}}),contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] identify`})}logout(e=!0){l()||(e&&r(this.isCookielessMode()),a())}setConsentMode(e){this.consentMode=e}optIn(){this.setConsentMode(`granted`)}optOut(){this.setConsentMode(`denied`)}getConsentMode(){return this.consentMode}isCookielessMode(){return this.options.cookieless||this.consentMode===`denied`?!0:this.consentMode===`pending`?this.cookielessWhilePending:!1}send(e,n={}){let r=t(this.isCookielessMode()),a=JSON.stringify({token:this.options.siteKey,...r?{userId:r}:{},sessionId:i(),data:{event:e,page:location.pathname,referrer:document.referrer||null,title:document.title||``,url:location.href,...f(),...n}});this.log(e),u({url:this.endpoint,data:a,contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] ${e}`})}enterPage(){this.pageEntryTime=Date.now(),this.pagePath=location.pathname,this.pageUrl=location.href,this.pageHash=location.hash,this.scrollDepth=0,this.hasLeftCurrentPage=!1}leavePage(){if(this.hasLeftCurrentPage)return;this.hasLeftCurrentPage=!0;let e=Date.now();this.send(`page_leave`,{page:this.pagePath,url:this.pageUrl,time_on_page:e-this.pageEntryTime,scroll_depth:this.scrollDepth,session_duration:e-s()})}trackScroll(){this.scrollHandler&&window.removeEventListener(`scroll`,this.scrollHandler);let e=()=>{let e=document.documentElement,t=document.body,n=window.innerHeight,r=Math.max(e.scrollHeight,t.scrollHeight);if(r<=n){this.scrollDepth=100;return}let i=Math.min(100,Math.round(((window.scrollY||e.scrollTop)+n)/r*100));i>this.scrollDepth&&(this.scrollDepth=i)};this.scrollHandler=e,e(),window.addEventListener(`scroll`,e,{passive:!0})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{if(document.visibilityState===`hidden`){clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;return}o()},300*1e3)}navigate(){this.navTimer&&clearTimeout(this.navTimer),this.navTimer=setTimeout(()=>{this.navTimer=null;let e=location.pathname!==this.pagePath,t=(this.options.trackHash??!1)&&location.hash!==this.pageHash;!e&&!t||(this.leavePage(),this.enterPage(),this.trackScroll(),this.pageview({trigger:`navigation`}))},300)}patch(){let e=()=>this.navigate();for(let t of[`pushState`,`replaceState`]){let n=history[t];history[t]=function(...t){let r=n.apply(this,t);return e(),r}}}links(){let e=e=>{let t=d(e.target);t&&t.host!==location.host&&this.track(`outbound_link`,{outbound_link:t.href})};document.addEventListener(`click`,e),document.addEventListener(`auxclick`,e)}};function m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1}function h(e){if(e==null||e.trim()===``)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(100,t))}function g(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`pending`)return`pending`;if(t===`granted`)return`granted`;if(t===`denied`)return`denied`}return typeof window<`u`&&(window.WebAnalytics=p,window.__FA_isTrackingDisabled=l,(()=>{let e=document.currentScript;if(!e)return;let t=e,n=e=>t.getAttribute(`data-${e}`),r=n(`sitekey`);if(!r)return;let i={siteKey:r},a=n(`endpoint`);a&&(i.endpoint=a);let o=n(`debug`);o&&(i.debug=o===`true`);let s=m(n(`trackErrors`));s!==void 0&&(i.trackErrors=s,i.errorTracking={enabled:s});let c=m(n(`webVitals`)),l=h(n(`web-vitals-sampling`));(c!==void 0||l!==void 0)&&(c!==void 0&&(i.trackWebVitals=c),i.webVitals={enabled:c,sampling:l===void 0?void 0:{percentage:l}});let u=m(n(`replay`)),d=h(n(`replay-sampling`));(u!==void 0||d!==void 0)&&(u!==void 0&&(i.trackReplay=u),i.sessionReplays={enabled:u,sampling:d===void 0?void 0:{percentage:d}});let f=m(n(`cookieless`));f!==void 0&&(i.cookieless=f);let _=g(n(`consent-mode`)),v=m(n(`cookieless-while-pending`));(_!==void 0||v!==void 0)&&(i.consent={mode:_,cookielessWhilePending:v}),new p(i)})()),e.WebAnalytics=p,e.isTrackingDisabled=l,e.sendData=u,e})({});
1
+ var FA_Script=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e?``:n()}function n(){if(typeof localStorage>`u`)return``;let e=localStorage.getItem(`faststats_anon_id`);if(e)return e;let t=crypto.randomUUID();return localStorage.setItem(`faststats_anon_id`,t),t}function r(e){return e||typeof localStorage>`u`?``:(localStorage.removeItem(`faststats_anon_id`),n())}function i(){if(typeof sessionStorage>`u`)return``;let e=sessionStorage.getItem(`session_id`),t=sessionStorage.getItem(`session_timestamp`);if(e&&t){if(Date.now()-Number.parseInt(t,10)<18e5)return sessionStorage.setItem(`session_timestamp`,Date.now().toString()),e;sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`)}let n=Date.now().toString(),r=crypto.randomUUID();return sessionStorage.setItem(`session_id`,r),sessionStorage.setItem(`session_timestamp`,n),sessionStorage.setItem(`session_start`,n),r}function a(){return typeof sessionStorage>`u`?``:(sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`),i())}function o(){typeof sessionStorage>`u`||sessionStorage.getItem(`session_id`)&&sessionStorage.setItem(`session_timestamp`,Date.now().toString())}function s(){if(typeof sessionStorage>`u`)return Date.now();let e=sessionStorage.getItem(`session_start`);if(e)return Number.parseInt(e,10);let t=sessionStorage.getItem(`session_timestamp`);return t?Number.parseInt(t,10):Date.now()}function c(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}function l(){if(typeof localStorage>`u`)return!1;let e=localStorage.getItem(`disable-faststats`);return e===`true`||e===`1`}async function u(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`}=e,s=n instanceof Blob?n:new Blob([n],{type:r});if(navigator.sendBeacon?.(t,s))return a&&console.log(`${o} ✓ Sent via beacon`),!0;try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:!0}),s=e.ok;return a&&(s?console.log(`${o} ✓ Sent via fetch`):console.warn(`${o} ✗ Failed: ${e.status}`)),s}catch{return a&&console.warn(`${o} ✗ Failed to send`),!1}}function d(e){for(;e&&!(e.tagName===`A`&&e.href);)e=e.parentNode;return e}function f(){let e={};if(!location.search)return e;let t=new URLSearchParams(location.search);for(let n of[`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`]){let r=t.get(n);r&&(e[n]=r)}return e}var p=class{endpoint;debug;baseUrl;started=!1;pageKey=``;navTimer=null;heartbeatTimer=null;scrollDepth=0;pageEntryTime=0;pagePath=``;pageUrl=``;pageHash=``;hasLeftCurrentPage=!1;scrollHandler=null;consentMode;cookielessWhilePending;constructor(e){this.options=e,this.endpoint=e.endpoint??`https://metrics.faststats.dev/v1/web`,this.debug=e.debug??!1,this.consentMode=e.consent?.mode??`granted`,this.cookielessWhilePending=e.consent?.cookielessWhilePending??!0;let t=typeof document<`u`?document.currentScript:null,n=t?.src?t.src.substring(0,t.src.lastIndexOf(`/`)):``;this.baseUrl=(e.baseUrl??n)||(typeof window<`u`?window.location.origin:``),(e.autoTrack??!0)&&this.init()}log(e){this.debug&&console.log(`[Analytics] ${e}`)}init(){if(!(typeof window>`u`)){if(l()){this.log(`disabled`);return}`requestIdleCallback`in window?window.requestIdleCallback(()=>this.start()):setTimeout(()=>this.start(),1)}}start(){if(this.started||typeof window>`u`)return;if(window.__FA_webAnalyticsInstance&&window.__FA_webAnalyticsInstance!==this){this.log(`already started by another instance`);return}if(l()){this.log(`disabled`);return}this.started=!0,window.__FA_webAnalyticsInstance=this,window.__FA_getAnonymousId=()=>t(this.isCookielessMode()),window.__FA_getSessionId=i,window.__FA_sendData=u,window.__FA_identify=(e,t,n)=>this.identify(e,t,n),window.__FA_logout=e=>this.logout(e),window.__FA_setConsentMode=e=>this.setConsentMode(e),window.__FA_optIn=()=>this.optIn(),window.__FA_optOut=()=>this.optOut(),window.__FA_trackEvent=(e,t)=>this.track(e,t??{}),window.__FA_isTrackingDisabled=l;let e=this.options,n=e.webVitals?.sampling?.percentage!==void 0,r=e.replayOptions?.samplingPercentage!==void 0||e.sessionReplays?.sampling?.percentage!==void 0;if((e.errorTracking?.enabled??e.trackErrors)&&this.load(`error`,`__FA_ErrorTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,getCommonData:()=>({url:location.href,page:location.pathname,referrer:document.referrer||null})}),(e.webVitals?.enabled??e.trackWebVitals??n)&&this.load(`web-vitals`,`__FA_WebVitalsTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,samplingPercentage:c(e.webVitals?.sampling?.percentage)}),e.sessionReplays?.enabled??e.trackReplay??r){let t=e.replayOptions??{};this.load(`replay`,`__FA_ReplayTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,...t,samplingPercentage:c(t.samplingPercentage??e.sessionReplays?.sampling?.percentage)})}this.enterPage(),this.pageview({trigger:`load`}),this.links(),this.trackScroll(),this.startHeartbeat(),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.leavePage():this.startHeartbeat()}),window.addEventListener(`pagehide`,()=>this.leavePage()),window.addEventListener(`popstate`,()=>this.navigate()),e.trackHash&&window.addEventListener(`hashchange`,()=>this.navigate()),this.patch()}load(e,t,n){let r=document.createElement(`script`);r.src=`${this.baseUrl}/${e}.js`,r.async=!0,r.onload=()=>{let r=window[t];r&&(new r(n).start(),this.log(`${e} loaded`))},r.onerror=()=>{this.debug&&console.warn(`[Analytics] ${e} failed`)},document.head.appendChild(r)}pageview(e={}){let t=`${location.pathname}|${this.options.trackHash??!1?location.hash:``}`;t!==this.pageKey&&(this.pageKey=t,this.send(`pageview`,e))}track(e,t={}){this.send(e,t)}identify(e,n,r={}){if(l()||this.isCookielessMode())return;let i=e.trim(),a=n.trim();!i||!a||u({url:this.endpoint.replace(/\/v1\/web$/,`/v1/identify`),data:JSON.stringify({token:this.options.siteKey,identifier:t(!1),externalId:i,email:a,name:r.name?.trim()||void 0,phone:r.phone?.trim()||void 0,avatarUrl:r.avatarUrl?.trim()||void 0,traits:r.traits??{}}),contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] identify`})}logout(e=!0){l()||(e&&r(this.isCookielessMode()),a())}setConsentMode(e){this.consentMode=e}optIn(){this.setConsentMode(`granted`)}optOut(){this.setConsentMode(`denied`)}getConsentMode(){return this.consentMode}isCookielessMode(){return this.options.cookieless||this.consentMode===`denied`?!0:this.consentMode===`pending`?this.cookielessWhilePending:!1}send(e,n={}){let r=t(this.isCookielessMode()),a=JSON.stringify({token:this.options.siteKey,...r?{userId:r}:{},sessionId:i(),data:{event:e,page:location.pathname,referrer:document.referrer||null,title:document.title||``,url:location.href,...f(),...n}});this.log(e),u({url:this.endpoint,data:a,contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] ${e}`})}enterPage(){this.pageEntryTime=Date.now(),this.pagePath=location.pathname,this.pageUrl=location.href,this.pageHash=location.hash,this.scrollDepth=0,this.hasLeftCurrentPage=!1}leavePage(){if(this.hasLeftCurrentPage)return;this.hasLeftCurrentPage=!0;let e=Date.now();this.send(`page_leave`,{page:this.pagePath,url:this.pageUrl,time_on_page:e-this.pageEntryTime,scroll_depth:this.scrollDepth,session_duration:e-s()})}trackScroll(){this.scrollHandler&&window.removeEventListener(`scroll`,this.scrollHandler);let e=()=>{let e=document.documentElement,t=document.body,n=window.innerHeight,r=Math.max(e.scrollHeight,t.scrollHeight);if(r<=n){this.scrollDepth=100;return}let i=Math.min(100,Math.round(((window.scrollY||e.scrollTop)+n)/r*100));i>this.scrollDepth&&(this.scrollDepth=i)};this.scrollHandler=e,e(),window.addEventListener(`scroll`,e,{passive:!0})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{if(document.visibilityState===`hidden`){clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;return}o()},300*1e3)}navigate(){this.navTimer&&clearTimeout(this.navTimer),this.navTimer=setTimeout(()=>{this.navTimer=null;let e=location.pathname!==this.pagePath,t=(this.options.trackHash??!1)&&location.hash!==this.pageHash;!e&&!t||(this.leavePage(),this.enterPage(),this.trackScroll(),this.pageview({trigger:`navigation`}))},300)}patch(){let e=()=>this.navigate();for(let t of[`pushState`,`replaceState`]){let n=history[t];history[t]=function(...t){let r=n.apply(this,t);return e(),r}}}links(){let e=e=>{let t=d(e.target);t&&t.host!==location.host&&this.track(`outbound_link`,{outbound_link:t.href})};document.addEventListener(`click`,e),document.addEventListener(`auxclick`,e)}};function m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1}function h(e){if(e==null||e.trim()===``)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(100,t))}function g(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`pending`)return`pending`;if(t===`granted`)return`granted`;if(t===`denied`)return`denied`}return typeof window<`u`&&(window.WebAnalytics=p,window.__FA_isTrackingDisabled=l,(()=>{let e=document.currentScript;if(!e)return;let t=e,n=e=>t.getAttribute(`data-${e}`),r=n(`sitekey`);if(!r)return;let i={siteKey:r},a=n(`endpoint`);a&&(i.endpoint=a);let o=n(`debug`);o&&(i.debug=o===`true`);let s=m(n(`trackErrors`));s!==void 0&&(i.trackErrors=s,i.errorTracking={enabled:s});let c=m(n(`webVitals`)),l=h(n(`web-vitals-sampling`));(c!==void 0||l!==void 0)&&(c!==void 0&&(i.trackWebVitals=c),i.webVitals={enabled:c,sampling:l===void 0?void 0:{percentage:l}});let u=m(n(`replay`)),d=h(n(`replay-sampling`));(u!==void 0||d!==void 0)&&(u!==void 0&&(i.trackReplay=u),i.sessionReplays={enabled:u,sampling:d===void 0?void 0:{percentage:d}});let f=m(n(`cookieless`));f!==void 0&&(i.cookieless=f);let _=g(n(`consent-mode`)),v=m(n(`cookieless-while-pending`));(_!==void 0||v!==void 0)&&(i.consent={mode:_,cookielessWhilePending:v}),new p(i)})()),e.WebAnalytics=p,e.isTrackingDisabled=l,e.sendData=u,e})({});
package/package.json CHANGED
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "name": "@faststats/web",
3
+ "repository": "https://github.com/faststats-dev/web-analytics",
3
4
  "main": "dist/module.js",
4
5
  "module": "dist/module.js",
5
6
  "types": "dist/module.d.ts",
@@ -14,7 +15,7 @@
14
15
  "publishConfig": {
15
16
  "access": "public"
16
17
  },
17
- "version": "0.0.1",
18
+ "version": "0.0.2",
18
19
  "scripts": {
19
20
  "build": "tsdown && cp -f dist/script.iife.js dist/script.js && cp -f dist/error.iife.js dist/error.js && cp -f dist/web-vitals.iife.js dist/web-vitals.js && cp -f dist/replay.iife.js dist/replay.js",
20
21
  "sync:example-assets": "mkdir -p ../../examples/spa-test/public && cp -f dist/script.iife.js ../../examples/spa-test/public/script.js && cp -f dist/error.iife.js ../../examples/spa-test/public/error.js && cp -f dist/web-vitals.iife.js ../../examples/spa-test/public/web-vitals.js && cp -f dist/replay.iife.js ../../examples/spa-test/public/replay.js",
package/src/analytics.ts CHANGED
@@ -14,6 +14,14 @@ import {
14
14
 
15
15
  export type { SendDataOptions };
16
16
 
17
+ export function trackEvent(
18
+ eventName: string,
19
+ properties?: Record<string, unknown>,
20
+ ): void {
21
+ if (typeof window === "undefined" || isTrackingDisabled()) return;
22
+ window.__FA_webAnalyticsInstance?.track(eventName, properties ?? {});
23
+ }
24
+
17
25
  export function isTrackingDisabled(): boolean {
18
26
  if (typeof localStorage === "undefined") return false;
19
27
  const value = localStorage.getItem("disable-faststats");
@@ -162,6 +170,7 @@ declare global {
162
170
  __FA_optIn?: () => void;
163
171
  __FA_optOut?: () => void;
164
172
  __FA_isTrackingDisabled?: () => boolean;
173
+ __FA_trackEvent?: (eventName: string, properties?: Record<string, unknown>) => void;
165
174
  __FA_webAnalyticsInstance?: WebAnalytics;
166
175
  }
167
176
  }
@@ -244,6 +253,8 @@ export class WebAnalytics {
244
253
  window.__FA_setConsentMode = (mode) => this.setConsentMode(mode);
245
254
  window.__FA_optIn = () => this.optIn();
246
255
  window.__FA_optOut = () => this.optOut();
256
+ window.__FA_trackEvent = (eventName, props) =>
257
+ this.track(eventName, props ?? {});
247
258
  window.__FA_isTrackingDisabled = isTrackingDisabled;
248
259
 
249
260
  const opts = this.options;
package/src/module.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export {
2
2
  type ConsentMode,
3
3
  type IdentifyOptions,
4
+ trackEvent,
4
5
  WebAnalytics,
5
6
  type WebAnalyticsOptions,
6
7
  } from "./analytics";