📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
build
Blue Mousea3e28c2a2bb1
diff --git a/dist/esnext/Lib.d.ts b/dist/esnext/Lib.d.tsindex 84f95a4fa..2d7dd2e7c 100644--- a/dist/esnext/Lib.d.ts+++ b/dist/esnext/Lib.d.ts@@ -42,6 +42,8 @@ export interface PageViewsOptions {unique?: boolean;/** A list of Regular Expressions or string pathes to ignore. */ignore?: Array<string | RegExp>;+ /** Do not send paths from ignore list to API. If set to `false`, the page view information will be sent to the Swetrix API, but the page will be displayed as a 'Redacted page' in the dashboard. */+ doNotAnonymise?: boolean;/** Do not send Heartbeat requests to the server. */noHeartbeat?: boolean;/** Send Heartbeat requests when the website tab is not active in the browser. */diff --git a/dist/esnext/Lib.js b/dist/esnext/Lib.jsindex 8ce32932f..55f9947f3 100644--- a/dist/esnext/Lib.js+++ b/dist/esnext/Lib.js@@ -127,10 +127,11 @@ export class Lib {// Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet// That method of getting previous page works for SPA websitesif (this.activePage) {- if (this.checkIgnore(this.activePage)) {+ const shouldIgnore = this.checkIgnore(this.activePage);+ if (shouldIgnore && this.pageViewsOptions?.doNotAnonymise) {return null;}- return this.activePage;+ return shouldIgnore ? null : this.activePage;}// Checking if URL is supported by the browser (for example, IE11 does not support it)if (typeof URL === 'function') {@@ -146,10 +147,11 @@ export class Lib {if (host !== refHost) {return null;}- if (this.checkIgnore(pathname)) {+ const shouldIgnore = this.checkIgnore(pathname);+ if (shouldIgnore && this.pageViewsOptions?.doNotAnonymise) {return null;}- return pathname;+ return shouldIgnore ? null : pathname;}catch {return null;@@ -161,7 +163,8 @@ export class Lib {if (!this.pageData)return;this.pageData.path = pg;- if (this.checkIgnore(pg))+ const shouldIgnore = this.checkIgnore(pg);+ if (shouldIgnore && this.pageViewsOptions?.doNotAnonymise)return;const perf = this.getPerformanceStats();let prev;@@ -177,7 +180,7 @@ export class Lib {me: getUTMMedium(),ca: getUTMCampaign(),unique,- pg,+ pg: shouldIgnore ? null : pg,perf,prev,};diff --git a/dist/esnext/Lib.js.map b/dist/esnext/Lib.js.mapindex eb0e3ab37..b22a2bb1a 100644--- a/dist/esnext/Lib.js.map+++ b/dist/esnext/Lib.js.map@@ -1 +1 @@-{"version":3,"file":"Lib.js","sourceRoot":"","sources":["../../src/Lib.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAC1E,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,OAAO,GACpD,MAAM,SAAS,CAAA;AAmEhB,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,IAAI,KAAI,CAAC;CACV,CAAA;AAED,MAAM,gBAAgB,GAAG,6BAA6B,CAAA;AAEtD,MAAM,OAAO,GAAG;IAMd,YAAoB,SAAiB,EAAU,OAAoB;QAA/C,cAAS,GAAT,SAAS,CAAQ;QAAU,YAAO,GAAP,OAAO,CAAa;QAL3D,aAAQ,GAAoB,IAAI,CAAA;QAChC,qBAAgB,GAAwC,IAAI,CAAA;QAC5D,uBAAkB,GAAY,KAAK,CAAA;QACnC,eAAU,GAAkB,IAAI,CAAA;QAGtC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACtD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC5C,CAAC;IAED,KAAK,CAAC,KAAwB;QAC5B,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE;YACpB,OAAM;SACP;QAED,MAAM,IAAI,GAAG;YACX,GAAG,EAAE,IAAI,CAAC,SAAS;YACnB,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ACzC,OAAO,KAAK,CAAA;SACb;QAED,IAAI,WAAW,EAAE,EAAE;YACjB,IAAI,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAA;YACtE,OAAO,KAAK,CAAA;SACb;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,WAAW,CAAC,IAAY,EAAE,IAAY;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,gBAAgB,CAAA;QACrD,MAAM,GAAG,GAAG,IAAI,cAAc,EAAE,CAAA;QAChC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,IAAI,IAAI,EAAE,EAAE,IAAI,CAAC,CAAA;QACzC,GAAG,CAAC,gBAAgB,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAA;QACxD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IAChC,CAAC;CACF"}\ No newline at end of filediff --git a/dist/swetrix.cjs.js b/dist/swetrix.cjs.jsindex c4c388849..a694e2a91 100644--- a/dist/swetrix.cjs.js+++ b/dist/swetrix.cjs.js@@ -26,317 +26,326 @@ var __assign = function() {return t;};return __assign.apply(this, arguments);+};++typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {+ var e = new Error(message);+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;};-var findInSearch = function (exp) {- var res = location.search.match(exp);- return (res && res[2]) || undefined;-};-var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;-var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;-var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;-var isInBrowser = function () {- return typeof window !== 'undefined';-};-var isLocalhost = function () {- return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';-};-var isAutomated = function () {- return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;-};-var getLocale = function () {- return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;-};-var getTimezone = function () {- try {- return Intl.DateTimeFormat().resolvedOptions().timeZone;- }- catch (e) {- return;- }-};-var getReferrer = function () {- return document.referrer || undefined;-};-var getUTMSource = function () { return findInSearch(utmSourceRegex); };-var getUTMMedium = function () { return findInSearch(utmMediumRegex); };-var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };-var getPath = function () {- // TODO: Maybe we should also include such data as location.hash or location.search- return location.pathname || '';+var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+};+var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+var isInBrowser = function () {+ return typeof window !== 'undefined';+};+var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+};+var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+};+var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+};+var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+};+var getReferrer = function () {+ return document.referrer || undefined;+};+var getUTMSource = function () { return findInSearch(utmSourceRegex); };+var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';};-var defaultPageActions = {- stop: function () { },-};-var DEFAULT_API_HOST = 'https://api.swetrix.com/log';-var Lib = /** @class */ (function () {- function Lib(projectID, options) {- this.projectID = projectID;- this.options = options;- this.pageData = null;- this.pageViewsOptions = null;- this.perfStatsCollected = false;- this.activePage = null;- this.trackPathChange = this.trackPathChange.bind(this);- this.heartbeat = this.heartbeat.bind(this);- }- Lib.prototype.track = function (event) {- if (!this.canTrack()) {- return;- }- var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);- this.sendRequest('custom', data);- };- Lib.prototype.trackPageViews = function (options) {- if (!this.canTrack()) {- return defaultPageActions;- }- if (this.pageData) {- return this.pageData.actions;- }- this.pageViewsOptions = options;- var hbInterval, interval;- if (!(options === null || options === void 0 ? void 0 : options.unique)) {- interval = setInterval(this.trackPathChange, 2000);- }- if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {- setTimeout(this.heartbeat, 3000);- hbInterval = setInterval(this.heartbeat, 28000);- }- var path = getPath();- this.pageData = {- path: path,- actions: {- stop: function () {- clearInterval(interval);- clearInterval(hbInterval);- },- },- };- this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);- return this.pageData.actions;- };- Lib.prototype.getPerformanceStats = function () {- var _a;- if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {- return {};- }- var perf = window.performance.getEntriesByType('navigation')[0];- if (!perf) {- return {};- }- this.perfStatsCollected = true;- return {- // Network- // @ts-ignore- dns: perf.domainLookupEnd - perf.domainLookupStart,- // @ts-ignore- tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,- // @ts-ignore- conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,- // @ts-ignore- response: perf.responseEnd - perf.responseStart,- // Frontend- // @ts-ignore- render: perf.domComplete - perf.domContentLoadedEventEnd,- // @ts-ignore- dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,- // @ts-ignore- page_load: perf.loadEventStart,- // Backend- // @ts-ignore- ttfb: perf.responseStart - perf.requestStart,- };- };- Lib.prototype.heartbeat = function () {- var _a;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {- return;- }- var data = {- pid: this.projectID,- };- this.sendRequest('hb', data);- };- Lib.prototype.checkIgnore = function (path) {- var _a;- var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;- if (Array.isArray(ignore)) {- for (var i = 0; i < ignore.length; ++i) {- if (ignore[i] === path)- return true;- // @ts-ignore- if (ignore[i] instanceof RegExp && ignore[i].test(path))- return true;- }- }- return false;- };- // Tracking path changes. If path changes -> calling this.trackPage method- Lib.prototype.trackPathChange = function () {- if (!this.pageData)- return;- var newPath = getPath();- var path = this.pageData.path;- if (path !== newPath) {- this.trackPage(newPath, false);- }- };- Lib.prototype.getPreviousPage = function () {- // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet- // That method of getting previous page works for SPA websites- if (this.activePage) {- if (this.checkIgnore(this.activePage)) {- return null;- }- return this.activePage;- }- // Checking if URL is supported by the browser (for example, IE11 does not support it)- if (typeof URL === 'function') {- // That method of getting previous page works for websites with page reloads- var referrer = getReferrer();- if (!referrer) {- return null;- }- var host = location.host;- try {- var url = new URL(referrer);- var refHost = url.host, pathname = url.pathname;- if (host !== refHost) {- return null;- }- if (this.checkIgnore(pathname)) {- return null;- }- return pathname;- }- catch (_a) {- return null;- }- }- return null;- };- Lib.prototype.trackPage = function (pg, unique) {- var _a;- if (unique === void 0) { unique = false; }- if (!this.pageData)- return;- this.pageData.path = pg;- if (this.checkIgnore(pg))- return;- var perf = this.getPerformanceStats();- var prev;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.noUserFlow)) {- prev = this.getPreviousPage();- }- var data = {- pid: this.projectID,- lc: getLocale(),- tz: getTimezone(),- ref: getReferrer(),- so: getUTMSource(),- me: getUTMMedium(),- ca: getUTMCampaign(),- unique: unique,- pg: pg,- perf: perf,- prev: prev,- };- this.activePage = pg;- this.sendRequest('', data);- };- Lib.prototype.debug = function (message) {- var _a;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {- console.log('[Swetrix]', message);- }- };- Lib.prototype.canTrack = function () {- var _a, _b, _c, _d;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {- this.debug('Tracking disabled: the \'disabled\' setting is set to true.');- return false;- }- if (!isInBrowser()) {- this.debug('Tracking disabled: script does not run in browser environment.');- return false;- }- if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {- this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');- return false;- }- if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {- return false;- }- if (isAutomated()) {- this.debug('Tracking disabled: navigation is automated by WebDriver.');- return false;- }- return true;- };- Lib.prototype.sendRequest = function (path, body) {- var _a;- var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;- var req = new XMLHttpRequest();- req.open('POST', "".concat(host, "/").concat(path), true);- req.setRequestHeader('Content-Type', 'application/json');- req.send(JSON.stringify(body));- };- return Lib;+var defaultPageActions = {+ stop: function () { },+};+var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.getPreviousPage = function () {+ var _a, _b;+ // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet+ // That method of getting previous page works for SPA websites+ if (this.activePage) {+ var shouldIgnore = this.checkIgnore(this.activePage);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : this.activePage;+ }+ // Checking if URL is supported by the browser (for example, IE11 does not support it)+ if (typeof URL === 'function') {+ // That method of getting previous page works for websites with page reloads+ var referrer = getReferrer();+ if (!referrer) {+ return null;+ }+ var host = location.host;+ try {+ var url = new URL(referrer);+ var refHost = url.host, pathname = url.pathname;+ if (host !== refHost) {+ return null;+ }+ var shouldIgnore = this.checkIgnore(pathname);+ if (shouldIgnore && ((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : pathname;+ }+ catch (_c) {+ return null;+ }+ }+ return null;+ };+ Lib.prototype.trackPage = function (pg, unique) {+ var _a, _b;+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ var shouldIgnore = this.checkIgnore(pg);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise))+ return;+ var perf = this.getPerformanceStats();+ var prev;+ if (!((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.noUserFlow)) {+ prev = this.getPreviousPage();+ }+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: shouldIgnore ? null : pg,+ perf: perf,+ prev: prev,+ };+ this.activePage = pg;+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;}());-exports.LIB_INSTANCE = null;-/**- * Initialise the tracking library instance (other methods won't work if the library is not initialised).- *- * @param {string} pid The Project ID to link the instance of Swetrix.js to.- * @param {LibOptions} options Options related to the tracking.- * @returns {Lib} Instance of the Swetrix.js.- */-function init(pid, options) {- if (!exports.LIB_INSTANCE) {- exports.LIB_INSTANCE = new Lib(pid, options);- }- return exports.LIB_INSTANCE;-}-/**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {TrackEventOptions} event The options related to the custom event.- */-function track(event) {- if (!exports.LIB_INSTANCE)- return;- exports.LIB_INSTANCE.track(event);-}-/**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {PageViewsOptions} options The options related to the custom event.- * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.- */-function trackViews(options) {- return new Promise(function (resolve) {- if (!exports.LIB_INSTANCE) {- resolve(defaultPageActions);- return;- }- // We need to verify that document.readyState is complete for the performance stats to be collected correctly.- if (typeof document === 'undefined' || document.readyState === 'complete') {- resolve(exports.LIB_INSTANCE.trackPageViews(options));- }- else {- window.addEventListener('load', function () {- // @ts-ignore- resolve(exports.LIB_INSTANCE.trackPageViews(options));- });- }- });+exports.LIB_INSTANCE = null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+function init(pid, options) {+ if (!exports.LIB_INSTANCE) {+ exports.LIB_INSTANCE = new Lib(pid, options);+ }+ return exports.LIB_INSTANCE;+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+function track(event) {+ if (!exports.LIB_INSTANCE)+ return;+ exports.LIB_INSTANCE.track(event);+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+function trackViews(options) {+ return new Promise(function (resolve) {+ if (!exports.LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ });+ }+ });}exports.init = init;diff --git a/dist/swetrix.es5.js b/dist/swetrix.es5.jsindex 94f28e2a6..25a5f893a 100644--- a/dist/swetrix.es5.js+++ b/dist/swetrix.es5.js@@ -22,317 +22,326 @@ var __assign = function() {return t;};return __assign.apply(this, arguments);+};++typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {+ var e = new Error(message);+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;};-var findInSearch = function (exp) {- var res = location.search.match(exp);- return (res && res[2]) || undefined;-};-var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;-var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;-var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;-var isInBrowser = function () {- return typeof window !== 'undefined';-};-var isLocalhost = function () {- return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';-};-var isAutomated = function () {- return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;-};-var getLocale = function () {- return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;-};-var getTimezone = function () {- try {- return Intl.DateTimeFormat().resolvedOptions().timeZone;- }- catch (e) {- return;- }-};-var getReferrer = function () {- return document.referrer || undefined;-};-var getUTMSource = function () { return findInSearch(utmSourceRegex); };-var getUTMMedium = function () { return findInSearch(utmMediumRegex); };-var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };-var getPath = function () {- // TODO: Maybe we should also include such data as location.hash or location.search- return location.pathname || '';+var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+};+var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+var isInBrowser = function () {+ return typeof window !== 'undefined';+};+var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+};+var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+};+var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+};+var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+};+var getReferrer = function () {+ return document.referrer || undefined;+};+var getUTMSource = function () { return findInSearch(utmSourceRegex); };+var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';};-var defaultPageActions = {- stop: function () { },-};-var DEFAULT_API_HOST = 'https://api.swetrix.com/log';-var Lib = /** @class */ (function () {- function Lib(projectID, options) {- this.projectID = projectID;- this.options = options;- this.pageData = null;- this.pageViewsOptions = null;- this.perfStatsCollected = false;- this.activePage = null;- this.trackPathChange = this.trackPathChange.bind(this);- this.heartbeat = this.heartbeat.bind(this);- }- Lib.prototype.track = function (event) {- if (!this.canTrack()) {- return;- }- var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);- this.sendRequest('custom', data);- };- Lib.prototype.trackPageViews = function (options) {- if (!this.canTrack()) {- return defaultPageActions;- }- if (this.pageData) {- return this.pageData.actions;- }- this.pageViewsOptions = options;- var hbInterval, interval;- if (!(options === null || options === void 0 ? void 0 : options.unique)) {- interval = setInterval(this.trackPathChange, 2000);- }- if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {- setTimeout(this.heartbeat, 3000);- hbInterval = setInterval(this.heartbeat, 28000);- }- var path = getPath();- this.pageData = {- path: path,- actions: {- stop: function () {- clearInterval(interval);- clearInterval(hbInterval);- },- },- };- this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);- return this.pageData.actions;- };- Lib.prototype.getPerformanceStats = function () {- var _a;- if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {- return {};- }- var perf = window.performance.getEntriesByType('navigation')[0];- if (!perf) {- return {};- }- this.perfStatsCollected = true;- return {- // Network- // @ts-ignore- dns: perf.domainLookupEnd - perf.domainLookupStart,- // @ts-ignore- tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,- // @ts-ignore- conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,- // @ts-ignore- response: perf.responseEnd - perf.responseStart,- // Frontend- // @ts-ignore- render: perf.domComplete - perf.domContentLoadedEventEnd,- // @ts-ignore- dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,- // @ts-ignore- page_load: perf.loadEventStart,- // Backend- // @ts-ignore- ttfb: perf.responseStart - perf.requestStart,- };- };- Lib.prototype.heartbeat = function () {- var _a;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {- return;- }- var data = {- pid: this.projectID,- };- this.sendRequest('hb', data);- };- Lib.prototype.checkIgnore = function (path) {- var _a;- var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;- if (Array.isArray(ignore)) {- for (var i = 0; i < ignore.length; ++i) {- if (ignore[i] === path)- return true;- // @ts-ignore- if (ignore[i] instanceof RegExp && ignore[i].test(path))- return true;- }- }- return false;- };- // Tracking path changes. If path changes -> calling this.trackPage method- Lib.prototype.trackPathChange = function () {- if (!this.pageData)- return;- var newPath = getPath();- var path = this.pageData.path;- if (path !== newPath) {- this.trackPage(newPath, false);- }- };- Lib.prototype.getPreviousPage = function () {- // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet- // That method of getting previous page works for SPA websites- if (this.activePage) {- if (this.checkIgnore(this.activePage)) {- return null;- }- return this.activePage;- }- // Checking if URL is supported by the browser (for example, IE11 does not support it)- if (typeof URL === 'function') {- // That method of getting previous page works for websites with page reloads- var referrer = getReferrer();- if (!referrer) {- return null;- }- var host = location.host;- try {- var url = new URL(referrer);- var refHost = url.host, pathname = url.pathname;- if (host !== refHost) {- return null;- }- if (this.checkIgnore(pathname)) {- return null;- }- return pathname;- }- catch (_a) {- return null;- }- }- return null;- };- Lib.prototype.trackPage = function (pg, unique) {- var _a;- if (unique === void 0) { unique = false; }- if (!this.pageData)- return;- this.pageData.path = pg;- if (this.checkIgnore(pg))- return;- var perf = this.getPerformanceStats();- var prev;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.noUserFlow)) {- prev = this.getPreviousPage();- }- var data = {- pid: this.projectID,- lc: getLocale(),- tz: getTimezone(),- ref: getReferrer(),- so: getUTMSource(),- me: getUTMMedium(),- ca: getUTMCampaign(),- unique: unique,- pg: pg,- perf: perf,- prev: prev,- };- this.activePage = pg;- this.sendRequest('', data);- };- Lib.prototype.debug = function (message) {- var _a;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {- console.log('[Swetrix]', message);- }- };- Lib.prototype.canTrack = function () {- var _a, _b, _c, _d;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {- this.debug('Tracking disabled: the \'disabled\' setting is set to true.');- return false;- }- if (!isInBrowser()) {- this.debug('Tracking disabled: script does not run in browser environment.');- return false;- }- if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {- this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');- return false;- }- if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {- return false;- }- if (isAutomated()) {- this.debug('Tracking disabled: navigation is automated by WebDriver.');- return false;- }- return true;- };- Lib.prototype.sendRequest = function (path, body) {- var _a;- var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;- var req = new XMLHttpRequest();- req.open('POST', "".concat(host, "/").concat(path), true);- req.setRequestHeader('Content-Type', 'application/json');- req.send(JSON.stringify(body));- };- return Lib;+var defaultPageActions = {+ stop: function () { },+};+var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.getPreviousPage = function () {+ var _a, _b;+ // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet+ // That method of getting previous page works for SPA websites+ if (this.activePage) {+ var shouldIgnore = this.checkIgnore(this.activePage);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : this.activePage;+ }+ // Checking if URL is supported by the browser (for example, IE11 does not support it)+ if (typeof URL === 'function') {+ // That method of getting previous page works for websites with page reloads+ var referrer = getReferrer();+ if (!referrer) {+ return null;+ }+ var host = location.host;+ try {+ var url = new URL(referrer);+ var refHost = url.host, pathname = url.pathname;+ if (host !== refHost) {+ return null;+ }+ var shouldIgnore = this.checkIgnore(pathname);+ if (shouldIgnore && ((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : pathname;+ }+ catch (_c) {+ return null;+ }+ }+ return null;+ };+ Lib.prototype.trackPage = function (pg, unique) {+ var _a, _b;+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ var shouldIgnore = this.checkIgnore(pg);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise))+ return;+ var perf = this.getPerformanceStats();+ var prev;+ if (!((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.noUserFlow)) {+ prev = this.getPreviousPage();+ }+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: shouldIgnore ? null : pg,+ perf: perf,+ prev: prev,+ };+ this.activePage = pg;+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;}());-var LIB_INSTANCE = null;-/**- * Initialise the tracking library instance (other methods won't work if the library is not initialised).- *- * @param {string} pid The Project ID to link the instance of Swetrix.js to.- * @param {LibOptions} options Options related to the tracking.- * @returns {Lib} Instance of the Swetrix.js.- */-function init(pid, options) {- if (!LIB_INSTANCE) {- LIB_INSTANCE = new Lib(pid, options);- }- return LIB_INSTANCE;-}-/**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {TrackEventOptions} event The options related to the custom event.- */-function track(event) {- if (!LIB_INSTANCE)- return;- LIB_INSTANCE.track(event);-}-/**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {PageViewsOptions} options The options related to the custom event.- * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.- */-function trackViews(options) {- return new Promise(function (resolve) {- if (!LIB_INSTANCE) {- resolve(defaultPageActions);- return;- }- // We need to verify that document.readyState is complete for the performance stats to be collected correctly.- if (typeof document === 'undefined' || document.readyState === 'complete') {- resolve(LIB_INSTANCE.trackPageViews(options));- }- else {- window.addEventListener('load', function () {- // @ts-ignore- resolve(LIB_INSTANCE.trackPageViews(options));- });- }- });+var LIB_INSTANCE = null;+/**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+function init(pid, options) {+ if (!LIB_INSTANCE) {+ LIB_INSTANCE = new Lib(pid, options);+ }+ return LIB_INSTANCE;+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+function track(event) {+ if (!LIB_INSTANCE)+ return;+ LIB_INSTANCE.track(event);+}+/**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+function trackViews(options) {+ return new Promise(function (resolve) {+ if (!LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(LIB_INSTANCE.trackPageViews(options));+ });+ }+ });}export { LIB_INSTANCE, init, track, trackViews };diff --git a/dist/swetrix.js b/dist/swetrix.jsindex e3c49a3a5..55ec4db23 100644--- a/dist/swetrix.js+++ b/dist/swetrix.js@@ -1 +1 @@-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(n){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function a(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function r(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function s(){return document.referrer||void 0}function c(){return t(o)}function u(){return t(d)}function l(){return t(p)}function i(){return location.pathname||""}var e=function(){return(e=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},o=/[?&](ref|source|utm_source)=([^?&]+)/,p=/[?&](utm_campaign)=([^?&]+)/,d=/[?&](utm_medium)=([^?&]+)/,h={stop:function(){}},g=(f.prototype.track=function(t){this.canTrack()&&(t=e({pid:this.projectID,pg:this.activePage,lc:a(),tz:r(),ref:s(),so:c(),me:u(),ca:l()},t),this.sendRequest("custom",t))},f.prototype.trackPageViews=function(t){var e,n,o;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(n=setInterval(this.trackPathChange,2e3)),null!=t&&t.noHeartbeat||(setTimeout(this.heartbeat,3e3),e=setInterval(this.heartbeat,28e3)),o=i(),this.pageData={path:o,actions:{stop:function(){clearInterval(n),clearInterval(e)}}},this.trackPage(o,null==t?void 0:t.unique)),this.pageData.actions):h},f.prototype.getPerformanceStats=function(){var t;return this.canTrack()&&!this.perfStatsCollected&&null!=(t=window.performance)&&t.getEntriesByType&&(t=window.performance.getEntriesByType("navigation")[0])?(this.perfStatsCollected=!0,{dns:t.domainLookupEnd-t.domainLookupStart,tls:t.secureConnectionStart?t.requestStart-t.secureConnectionStart:0,conn:t.secureConnectionStart?t.secureConnectionStart-t.connectStart:t.connectEnd-t.connectStart,response:t.responseEnd-t.responseStart,render:t.domComplete-t.domContentLoadedEventEnd,dom_load:t.domContentLoadedEventEnd-t.responseEnd,page_load:t.loadEventStart,ttfb:t.responseStart-t.requestStart}):{}},f.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},f.prototype.checkIgnore=function(t){var e,n=null==(e=this.pageViewsOptions)?void 0:e.ignore;if(Array.isArray(n))for(var o=0;o<n.length;++o){if(n[o]===t)return!0;if(n[o]instanceof RegExp&&n[o].test(t))return!0}return!1},f.prototype.trackPathChange=function(){var t;this.pageData&&(t=i(),this.pageData.path!==t)&&this.trackPage(t,!1)},f.prototype.getPreviousPage=function(){if(this.activePage)return this.checkIgnore(this.activePage)?null:this.activePage;if("function"==typeof URL){var t=s();if(!t)return null;var e=location.host;try{var n=new URL(t),o=n.host,i=n.pathname;return e!==o?null:this.checkIgnore(i)?null:i}catch(t){}}return null},f.prototype.trackPage=function(t,e){var n,o,i;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,this.checkIgnore(t)||(n=this.getPerformanceStats(),null!=(i=this.pageViewsOptions)&&i.noUserFlow||(o=this.getPreviousPage()),i={pid:this.projectID,lc:a(),tz:r(),ref:s(),so:c(),me:u(),ca:l(),unique:e,pg:t,perf:n,prev:o},this.activePage=t,this.sendRequest("",i)))},f.prototype.debug=function(t){var e;null!=(e=this.options)&&e.debug&&console.log("[Swetrix]",t)},f.prototype.canTrack=function(){var t;return null!=(t=this.options)&&t.disabled?(this.debug("Tracking disabled: the 'disabled' setting is set to true."),!1):"undefined"==typeof window?(this.debug("Tracking disabled: script does not run in browser environment."),!1):null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)?(this.debug("Tracking disabled: respecting user's 'Do Not Track' preference."),!1):!(!(null!=(t=this.options)&&t.debug||"localhost"!==(null===location||void 0===location?void 0:location.hostname)&&"127.0.0.1"!==(null===location||void 0===location?void 0:location.hostname)&&""!==(null===location||void 0===location?void 0:location.hostname))||null!==navigator&&void 0!==navigator&&navigator.webdriver&&(this.debug("Tracking disabled: navigation is automated by WebDriver."),1))},f.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",o=new XMLHttpRequest;o.open("POST","".concat(n,"/").concat(t),!0),o.setRequestHeader("Content-Type","application/json"),o.send(JSON.stringify(e))},f);function f(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this)}n.LIB_INSTANCE=null,n.init=function(t,e){return n.LIB_INSTANCE||(n.LIB_INSTANCE=new g(t,e)),n.LIB_INSTANCE},n.track=function(t){n.LIB_INSTANCE&&n.LIB_INSTANCE.track(t)},n.trackViews=function(e){return new Promise(function(t){n.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(n.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(n.LIB_INSTANCE.trackPageViews(e))}):t(h)})},Object.defineProperty(n,"__esModule",{value:!0})});+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(n){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function r(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function s(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function c(){return document.referrer||void 0}function u(){return t(o)}function l(){return t(d)}function p(){return t(a)}function i(){return location.pathname||""}var e=function(){return(e=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},o=/[?&](ref|source|utm_source)=([^?&]+)/,a=/[?&](utm_campaign)=([^?&]+)/,d=/[?&](utm_medium)=([^?&]+)/,h={stop:function(){}},g=(f.prototype.track=function(t){this.canTrack()&&(t=e({pid:this.projectID,pg:this.activePage,lc:r(),tz:s(),ref:c(),so:u(),me:l(),ca:p()},t),this.sendRequest("custom",t))},f.prototype.trackPageViews=function(t){var e,n,o;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(n=setInterval(this.trackPathChange,2e3)),null!=t&&t.noHeartbeat||(setTimeout(this.heartbeat,3e3),e=setInterval(this.heartbeat,28e3)),o=i(),this.pageData={path:o,actions:{stop:function(){clearInterval(n),clearInterval(e)}}},this.trackPage(o,null==t?void 0:t.unique)),this.pageData.actions):h},f.prototype.getPerformanceStats=function(){var t;return this.canTrack()&&!this.perfStatsCollected&&null!=(t=window.performance)&&t.getEntriesByType&&(t=window.performance.getEntriesByType("navigation")[0])?(this.perfStatsCollected=!0,{dns:t.domainLookupEnd-t.domainLookupStart,tls:t.secureConnectionStart?t.requestStart-t.secureConnectionStart:0,conn:t.secureConnectionStart?t.secureConnectionStart-t.connectStart:t.connectEnd-t.connectStart,response:t.responseEnd-t.responseStart,render:t.domComplete-t.domContentLoadedEventEnd,dom_load:t.domContentLoadedEventEnd-t.responseEnd,page_load:t.loadEventStart,ttfb:t.responseStart-t.requestStart}):{}},f.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},f.prototype.checkIgnore=function(t){var e,n=null==(e=this.pageViewsOptions)?void 0:e.ignore;if(Array.isArray(n))for(var o=0;o<n.length;++o){if(n[o]===t)return!0;if(n[o]instanceof RegExp&&n[o].test(t))return!0}return!1},f.prototype.trackPathChange=function(){var t;this.pageData&&(t=i(),this.pageData.path!==t)&&this.trackPage(t,!1)},f.prototype.getPreviousPage=function(){var t;if(this.activePage)return(o=this.checkIgnore(this.activePage))&&null!=(e=this.pageViewsOptions)&&e.doNotAnonymise||o?null:this.activePage;if("function"==typeof URL){var e=c();if(!e)return null;var n=location.host;try{var o,i=new URL(e),a=i.host,r=i.pathname;return n!==a?null:(o=this.checkIgnore(r))&&null!=(t=this.pageViewsOptions)&&t.doNotAnonymise||o?null:r}catch(t){}}return null},f.prototype.trackPage=function(t,e){var n,o,i,a;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,(n=this.checkIgnore(t))&&null!=(o=this.pageViewsOptions)&&o.doNotAnonymise||(o=this.getPerformanceStats(),null!=(a=this.pageViewsOptions)&&a.noUserFlow||(i=this.getPreviousPage()),a={pid:this.projectID,lc:r(),tz:s(),ref:c(),so:u(),me:l(),ca:p(),unique:e,pg:n?null:t,perf:o,prev:i},this.activePage=t,this.sendRequest("",a)))},f.prototype.debug=function(t){var e;null!=(e=this.options)&&e.debug&&console.log("[Swetrix]",t)},f.prototype.canTrack=function(){var t;return null!=(t=this.options)&&t.disabled?(this.debug("Tracking disabled: the 'disabled' setting is set to true."),!1):"undefined"==typeof window?(this.debug("Tracking disabled: script does not run in browser environment."),!1):null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)?(this.debug("Tracking disabled: respecting user's 'Do Not Track' preference."),!1):!(!(null!=(t=this.options)&&t.debug||"localhost"!==(null===location||void 0===location?void 0:location.hostname)&&"127.0.0.1"!==(null===location||void 0===location?void 0:location.hostname)&&""!==(null===location||void 0===location?void 0:location.hostname))||null!==navigator&&void 0!==navigator&&navigator.webdriver&&(this.debug("Tracking disabled: navigation is automated by WebDriver."),1))},f.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",o=new XMLHttpRequest;o.open("POST","".concat(n,"/").concat(t),!0),o.setRequestHeader("Content-Type","application/json"),o.send(JSON.stringify(e))},f);function f(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this)}n.LIB_INSTANCE=null,n.init=function(t,e){return n.LIB_INSTANCE||(n.LIB_INSTANCE=new g(t,e)),n.LIB_INSTANCE},n.track=function(t){n.LIB_INSTANCE&&n.LIB_INSTANCE.track(t)},n.trackViews=function(e){return new Promise(function(t){n.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(n.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(n.LIB_INSTANCE.trackPageViews(e))}):t(h)})},Object.defineProperty(n,"__esModule",{value:!0})});diff --git a/dist/swetrix.orig.js b/dist/swetrix.orig.jsindex 45ec83d68..762158ac7 100644--- a/dist/swetrix.orig.js+++ b/dist/swetrix.orig.js@@ -28,317 +28,326 @@return t;};return __assign.apply(this, arguments);+ };++ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {+ var e = new Error(message);+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;};- var findInSearch = function (exp) {- var res = location.search.match(exp);- return (res && res[2]) || undefined;- };- var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;- var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;- var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;- var isInBrowser = function () {- return typeof window !== 'undefined';- };- var isLocalhost = function () {- return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';- };- var isAutomated = function () {- return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;- };- var getLocale = function () {- return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;- };- var getTimezone = function () {- try {- return Intl.DateTimeFormat().resolvedOptions().timeZone;- }- catch (e) {- return;- }- };- var getReferrer = function () {- return document.referrer || undefined;- };- var getUTMSource = function () { return findInSearch(utmSourceRegex); };- var getUTMMedium = function () { return findInSearch(utmMediumRegex); };- var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };- var getPath = function () {- // TODO: Maybe we should also include such data as location.hash or location.search- return location.pathname || '';+ var findInSearch = function (exp) {+ var res = location.search.match(exp);+ return (res && res[2]) || undefined;+ };+ var utmSourceRegex = /[?&](ref|source|utm_source)=([^?&]+)/;+ var utmCampaignRegex = /[?&](utm_campaign)=([^?&]+)/;+ var utmMediumRegex = /[?&](utm_medium)=([^?&]+)/;+ var isInBrowser = function () {+ return typeof window !== 'undefined';+ };+ var isLocalhost = function () {+ return (location === null || location === void 0 ? void 0 : location.hostname) === 'localhost' || (location === null || location === void 0 ? void 0 : location.hostname) === '127.0.0.1' || (location === null || location === void 0 ? void 0 : location.hostname) === '';+ };+ var isAutomated = function () {+ return navigator === null || navigator === void 0 ? void 0 : navigator.webdriver;+ };+ var getLocale = function () {+ return typeof navigator.languages !== 'undefined' ? navigator.languages[0] : navigator.language;+ };+ var getTimezone = function () {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ }+ catch (e) {+ return;+ }+ };+ var getReferrer = function () {+ return document.referrer || undefined;+ };+ var getUTMSource = function () { return findInSearch(utmSourceRegex); };+ var getUTMMedium = function () { return findInSearch(utmMediumRegex); };+ var getUTMCampaign = function () { return findInSearch(utmCampaignRegex); };+ var getPath = function () {+ // TODO: Maybe we should also include such data as location.hash or location.search+ return location.pathname || '';};- var defaultPageActions = {- stop: function () { },- };- var DEFAULT_API_HOST = 'https://api.swetrix.com/log';- var Lib = /** @class */ (function () {- function Lib(projectID, options) {- this.projectID = projectID;- this.options = options;- this.pageData = null;- this.pageViewsOptions = null;- this.perfStatsCollected = false;- this.activePage = null;- this.trackPathChange = this.trackPathChange.bind(this);- this.heartbeat = this.heartbeat.bind(this);- }- Lib.prototype.track = function (event) {- if (!this.canTrack()) {- return;- }- var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);- this.sendRequest('custom', data);- };- Lib.prototype.trackPageViews = function (options) {- if (!this.canTrack()) {- return defaultPageActions;- }- if (this.pageData) {- return this.pageData.actions;- }- this.pageViewsOptions = options;- var hbInterval, interval;- if (!(options === null || options === void 0 ? void 0 : options.unique)) {- interval = setInterval(this.trackPathChange, 2000);- }- if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {- setTimeout(this.heartbeat, 3000);- hbInterval = setInterval(this.heartbeat, 28000);- }- var path = getPath();- this.pageData = {- path: path,- actions: {- stop: function () {- clearInterval(interval);- clearInterval(hbInterval);- },- },- };- this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);- return this.pageData.actions;- };- Lib.prototype.getPerformanceStats = function () {- var _a;- if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {- return {};- }- var perf = window.performance.getEntriesByType('navigation')[0];- if (!perf) {- return {};- }- this.perfStatsCollected = true;- return {- // Network- // @ts-ignore- dns: perf.domainLookupEnd - perf.domainLookupStart,- // @ts-ignore- tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,- // @ts-ignore- conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,- // @ts-ignore- response: perf.responseEnd - perf.responseStart,- // Frontend- // @ts-ignore- render: perf.domComplete - perf.domContentLoadedEventEnd,- // @ts-ignore- dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,- // @ts-ignore- page_load: perf.loadEventStart,- // Backend- // @ts-ignore- ttfb: perf.responseStart - perf.requestStart,- };- };- Lib.prototype.heartbeat = function () {- var _a;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {- return;- }- var data = {- pid: this.projectID,- };- this.sendRequest('hb', data);- };- Lib.prototype.checkIgnore = function (path) {- var _a;- var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;- if (Array.isArray(ignore)) {- for (var i = 0; i < ignore.length; ++i) {- if (ignore[i] === path)- return true;- // @ts-ignore- if (ignore[i] instanceof RegExp && ignore[i].test(path))- return true;- }- }- return false;- };- // Tracking path changes. If path changes -> calling this.trackPage method- Lib.prototype.trackPathChange = function () {- if (!this.pageData)- return;- var newPath = getPath();- var path = this.pageData.path;- if (path !== newPath) {- this.trackPage(newPath, false);- }- };- Lib.prototype.getPreviousPage = function () {- // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet- // That method of getting previous page works for SPA websites- if (this.activePage) {- if (this.checkIgnore(this.activePage)) {- return null;- }- return this.activePage;- }- // Checking if URL is supported by the browser (for example, IE11 does not support it)- if (typeof URL === 'function') {- // That method of getting previous page works for websites with page reloads- var referrer = getReferrer();- if (!referrer) {- return null;- }- var host = location.host;- try {- var url = new URL(referrer);- var refHost = url.host, pathname = url.pathname;- if (host !== refHost) {- return null;- }- if (this.checkIgnore(pathname)) {- return null;- }- return pathname;- }- catch (_a) {- return null;- }- }- return null;- };- Lib.prototype.trackPage = function (pg, unique) {- var _a;- if (unique === void 0) { unique = false; }- if (!this.pageData)- return;- this.pageData.path = pg;- if (this.checkIgnore(pg))- return;- var perf = this.getPerformanceStats();- var prev;- if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.noUserFlow)) {- prev = this.getPreviousPage();- }- var data = {- pid: this.projectID,- lc: getLocale(),- tz: getTimezone(),- ref: getReferrer(),- so: getUTMSource(),- me: getUTMMedium(),- ca: getUTMCampaign(),- unique: unique,- pg: pg,- perf: perf,- prev: prev,- };- this.activePage = pg;- this.sendRequest('', data);- };- Lib.prototype.debug = function (message) {- var _a;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {- console.log('[Swetrix]', message);- }- };- Lib.prototype.canTrack = function () {- var _a, _b, _c, _d;- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {- this.debug('Tracking disabled: the \'disabled\' setting is set to true.');- return false;- }- if (!isInBrowser()) {- this.debug('Tracking disabled: script does not run in browser environment.');- return false;- }- if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {- this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');- return false;- }- if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {- return false;- }- if (isAutomated()) {- this.debug('Tracking disabled: navigation is automated by WebDriver.');- return false;- }- return true;- };- Lib.prototype.sendRequest = function (path, body) {- var _a;- var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;- var req = new XMLHttpRequest();- req.open('POST', "".concat(host, "/").concat(path), true);- req.setRequestHeader('Content-Type', 'application/json');- req.send(JSON.stringify(body));- };- return Lib;+ var defaultPageActions = {+ stop: function () { },+ };+ var DEFAULT_API_HOST = 'https://api.swetrix.com/log';+ var Lib = /** @class */ (function () {+ function Lib(projectID, options) {+ this.projectID = projectID;+ this.options = options;+ this.pageData = null;+ this.pageViewsOptions = null;+ this.perfStatsCollected = false;+ this.activePage = null;+ this.trackPathChange = this.trackPathChange.bind(this);+ this.heartbeat = this.heartbeat.bind(this);+ }+ Lib.prototype.track = function (event) {+ if (!this.canTrack()) {+ return;+ }+ var data = __assign({ pid: this.projectID, pg: this.activePage, lc: getLocale(), tz: getTimezone(), ref: getReferrer(), so: getUTMSource(), me: getUTMMedium(), ca: getUTMCampaign() }, event);+ this.sendRequest('custom', data);+ };+ Lib.prototype.trackPageViews = function (options) {+ if (!this.canTrack()) {+ return defaultPageActions;+ }+ if (this.pageData) {+ return this.pageData.actions;+ }+ this.pageViewsOptions = options;+ var hbInterval, interval;+ if (!(options === null || options === void 0 ? void 0 : options.unique)) {+ interval = setInterval(this.trackPathChange, 2000);+ }+ if (!(options === null || options === void 0 ? void 0 : options.noHeartbeat)) {+ setTimeout(this.heartbeat, 3000);+ hbInterval = setInterval(this.heartbeat, 28000);+ }+ var path = getPath();+ this.pageData = {+ path: path,+ actions: {+ stop: function () {+ clearInterval(interval);+ clearInterval(hbInterval);+ },+ },+ };+ this.trackPage(path, options === null || options === void 0 ? void 0 : options.unique);+ return this.pageData.actions;+ };+ Lib.prototype.getPerformanceStats = function () {+ var _a;+ if (!this.canTrack() || this.perfStatsCollected || !((_a = window.performance) === null || _a === void 0 ? void 0 : _a.getEntriesByType)) {+ return {};+ }+ var perf = window.performance.getEntriesByType('navigation')[0];+ if (!perf) {+ return {};+ }+ this.perfStatsCollected = true;+ return {+ // Network+ // @ts-ignore+ dns: perf.domainLookupEnd - perf.domainLookupStart,+ // @ts-ignore+ tls: perf.secureConnectionStart ? perf.requestStart - perf.secureConnectionStart : 0,+ // @ts-ignore+ conn: perf.secureConnectionStart ? perf.secureConnectionStart - perf.connectStart : perf.connectEnd - perf.connectStart,+ // @ts-ignore+ response: perf.responseEnd - perf.responseStart,+ // Frontend+ // @ts-ignore+ render: perf.domComplete - perf.domContentLoadedEventEnd,+ // @ts-ignore+ dom_load: perf.domContentLoadedEventEnd - perf.responseEnd,+ // @ts-ignore+ page_load: perf.loadEventStart,+ // Backend+ // @ts-ignore+ ttfb: perf.responseStart - perf.requestStart,+ };+ };+ Lib.prototype.heartbeat = function () {+ var _a;+ if (!((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.heartbeatOnBackground) && document.visibilityState === 'hidden') {+ return;+ }+ var data = {+ pid: this.projectID,+ };+ this.sendRequest('hb', data);+ };+ Lib.prototype.checkIgnore = function (path) {+ var _a;+ var ignore = (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.ignore;+ if (Array.isArray(ignore)) {+ for (var i = 0; i < ignore.length; ++i) {+ if (ignore[i] === path)+ return true;+ // @ts-ignore+ if (ignore[i] instanceof RegExp && ignore[i].test(path))+ return true;+ }+ }+ return false;+ };+ // Tracking path changes. If path changes -> calling this.trackPage method+ Lib.prototype.trackPathChange = function () {+ if (!this.pageData)+ return;+ var newPath = getPath();+ var path = this.pageData.path;+ if (path !== newPath) {+ this.trackPage(newPath, false);+ }+ };+ Lib.prototype.getPreviousPage = function () {+ var _a, _b;+ // Assuming that this function is called in trackPage and this.activePage is not overwritten by new value yet+ // That method of getting previous page works for SPA websites+ if (this.activePage) {+ var shouldIgnore = this.checkIgnore(this.activePage);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : this.activePage;+ }+ // Checking if URL is supported by the browser (for example, IE11 does not support it)+ if (typeof URL === 'function') {+ // That method of getting previous page works for websites with page reloads+ var referrer = getReferrer();+ if (!referrer) {+ return null;+ }+ var host = location.host;+ try {+ var url = new URL(referrer);+ var refHost = url.host, pathname = url.pathname;+ if (host !== refHost) {+ return null;+ }+ var shouldIgnore = this.checkIgnore(pathname);+ if (shouldIgnore && ((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.doNotAnonymise)) {+ return null;+ }+ return shouldIgnore ? null : pathname;+ }+ catch (_c) {+ return null;+ }+ }+ return null;+ };+ Lib.prototype.trackPage = function (pg, unique) {+ var _a, _b;+ if (unique === void 0) { unique = false; }+ if (!this.pageData)+ return;+ this.pageData.path = pg;+ var shouldIgnore = this.checkIgnore(pg);+ if (shouldIgnore && ((_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.doNotAnonymise))+ return;+ var perf = this.getPerformanceStats();+ var prev;+ if (!((_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.noUserFlow)) {+ prev = this.getPreviousPage();+ }+ var data = {+ pid: this.projectID,+ lc: getLocale(),+ tz: getTimezone(),+ ref: getReferrer(),+ so: getUTMSource(),+ me: getUTMMedium(),+ ca: getUTMCampaign(),+ unique: unique,+ pg: shouldIgnore ? null : pg,+ perf: perf,+ prev: prev,+ };+ this.activePage = pg;+ this.sendRequest('', data);+ };+ Lib.prototype.debug = function (message) {+ var _a;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.debug) {+ console.log('[Swetrix]', message);+ }+ };+ Lib.prototype.canTrack = function () {+ var _a, _b, _c, _d;+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.disabled) {+ this.debug('Tracking disabled: the \'disabled\' setting is set to true.');+ return false;+ }+ if (!isInBrowser()) {+ this.debug('Tracking disabled: script does not run in browser environment.');+ return false;+ }+ if (((_b = this.options) === null || _b === void 0 ? void 0 : _b.respectDNT) && ((_c = window.navigator) === null || _c === void 0 ? void 0 : _c.doNotTrack) === '1') {+ this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');+ return false;+ }+ if (!((_d = this.options) === null || _d === void 0 ? void 0 : _d.debug) && isLocalhost()) {+ return false;+ }+ if (isAutomated()) {+ this.debug('Tracking disabled: navigation is automated by WebDriver.');+ return false;+ }+ return true;+ };+ Lib.prototype.sendRequest = function (path, body) {+ var _a;+ var host = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.apiURL) || DEFAULT_API_HOST;+ var req = new XMLHttpRequest();+ req.open('POST', "".concat(host, "/").concat(path), true);+ req.setRequestHeader('Content-Type', 'application/json');+ req.send(JSON.stringify(body));+ };+ return Lib;}());- exports.LIB_INSTANCE = null;- /**- * Initialise the tracking library instance (other methods won't work if the library is not initialised).- *- * @param {string} pid The Project ID to link the instance of Swetrix.js to.- * @param {LibOptions} options Options related to the tracking.- * @returns {Lib} Instance of the Swetrix.js.- */- function init(pid, options) {- if (!exports.LIB_INSTANCE) {- exports.LIB_INSTANCE = new Lib(pid, options);- }- return exports.LIB_INSTANCE;- }- /**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {TrackEventOptions} event The options related to the custom event.- */- function track(event) {- if (!exports.LIB_INSTANCE)- return;- exports.LIB_INSTANCE.track(event);- }- /**- * With this function you are able to track any custom events you want.- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.- * The total number of track calls and their conversion rate will be saved.- *- * @param {PageViewsOptions} options The options related to the custom event.- * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.- */- function trackViews(options) {- return new Promise(function (resolve) {- if (!exports.LIB_INSTANCE) {- resolve(defaultPageActions);- return;- }- // We need to verify that document.readyState is complete for the performance stats to be collected correctly.- if (typeof document === 'undefined' || document.readyState === 'complete') {- resolve(exports.LIB_INSTANCE.trackPageViews(options));- }- else {- window.addEventListener('load', function () {- // @ts-ignore- resolve(exports.LIB_INSTANCE.trackPageViews(options));- });- }- });+ exports.LIB_INSTANCE = null;+ /**+ * Initialise the tracking library instance (other methods won't work if the library is not initialised).+ *+ * @param {string} pid The Project ID to link the instance of Swetrix.js to.+ * @param {LibOptions} options Options related to the tracking.+ * @returns {Lib} Instance of the Swetrix.js.+ */+ function init(pid, options) {+ if (!exports.LIB_INSTANCE) {+ exports.LIB_INSTANCE = new Lib(pid, options);+ }+ return exports.LIB_INSTANCE;+ }+ /**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {TrackEventOptions} event The options related to the custom event.+ */+ function track(event) {+ if (!exports.LIB_INSTANCE)+ return;+ exports.LIB_INSTANCE.track(event);+ }+ /**+ * With this function you are able to track any custom events you want.+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.+ * The total number of track calls and their conversion rate will be saved.+ *+ * @param {PageViewsOptions} options The options related to the custom event.+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.+ */+ function trackViews(options) {+ return new Promise(function (resolve) {+ if (!exports.LIB_INSTANCE) {+ resolve(defaultPageActions);+ return;+ }+ // We need to verify that document.readyState is complete for the performance stats to be collected correctly.+ if (typeof document === 'undefined' || document.readyState === 'complete') {+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ }+ else {+ window.addEventListener('load', function () {+ // @ts-ignore+ resolve(exports.LIB_INSTANCE.trackPageViews(options));+ });+ }+ });}exports.init = init;