Skip to content

📈 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!

new build

Blue Mouse2b0409766fed
diff --git a/dist/captcha-validator.cjs.js b/dist/captcha-validator.cjs.js
index 80a65bb13..490ac9d33 100644
--- a/dist/captcha-validator.cjs.js
+++ b/dist/captcha-validator.cjs.js
@@ -2,6 +2,12 @@
Object.defineProperty(exports, '__esModule', { value: true });
+var https = require('https');
+
+function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
+
+var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
+
/******************************************************************************
Copyright (c) Microsoft Corporation.
@@ -60,27 +66,48 @@ var ENDPOINTS = {
VALIDATE: '/validate',
};
var makeAPIRequest = function (path, method, body, apiURL) { return __awaiter(void 0, void 0, void 0, function () {
- var res, e_1;
+ var options;
return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2, , 3]);
- return [4 /*yield*/, fetch("".concat(apiURL || DEFAULT_API_HOST).concat(path), {
- method: method,
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- })];
- case 1:
- res = _a.sent();
- return [3 /*break*/, 3];
- case 2:
- e_1 = _a.sent();
- throw "Unable to make API request, error: ".concat(e_1);
- case 3: return [4 /*yield*/, res.json()];
- case 4: return [2 /*return*/, _a.sent()];
+ options = {
+ method: method,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ };
+ if (body) {
+ // @ts-ignore
+ options.body = JSON.stringify(body);
}
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var url = "".concat(apiURL || DEFAULT_API_HOST).concat(path);
+ var req = https__default["default"].request(url, options, function (res) {
+ var data = '';
+ res.on('data', function (chunk) {
+ data += chunk;
+ });
+ res.on('end', function () {
+ if (res.statusCode >= 400) {
+ reject("Request failed with status code ".concat(res.statusCode, ": ").concat(data));
+ }
+ else {
+ try {
+ resolve(JSON.parse(data));
+ }
+ catch (e) {
+ reject("Unable to parse JSON response: ".concat(data));
+ }
+ }
+ });
+ });
+ req.on('error', function (e) {
+ reject("Unable to make API request, error: ".concat(e));
+ });
+ if (body) {
+ // @ts-ignore
+ req.write(options.body);
+ }
+ req.end();
+ })];
});
}); };
diff --git a/dist/captcha-validator.es5.js b/dist/captcha-validator.es5.js
index 1ab359dd5..e4efa61ed 100644
--- a/dist/captcha-validator.es5.js
+++ b/dist/captcha-validator.es5.js
@@ -1,3 +1,5 @@
+import https from 'https';
+
/******************************************************************************
Copyright (c) Microsoft Corporation.
@@ -56,27 +58,48 @@ var ENDPOINTS = {
VALIDATE: '/validate',
};
var makeAPIRequest = function (path, method, body, apiURL) { return __awaiter(void 0, void 0, void 0, function () {
- var res, e_1;
+ var options;
return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2, , 3]);
- return [4 /*yield*/, fetch("".concat(apiURL || DEFAULT_API_HOST).concat(path), {
- method: method,
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- })];
- case 1:
- res = _a.sent();
- return [3 /*break*/, 3];
- case 2:
- e_1 = _a.sent();
- throw "Unable to make API request, error: ".concat(e_1);
- case 3: return [4 /*yield*/, res.json()];
- case 4: return [2 /*return*/, _a.sent()];
+ options = {
+ method: method,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ };
+ if (body) {
+ // @ts-ignore
+ options.body = JSON.stringify(body);
}
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var url = "".concat(apiURL || DEFAULT_API_HOST).concat(path);
+ var req = https.request(url, options, function (res) {
+ var data = '';
+ res.on('data', function (chunk) {
+ data += chunk;
+ });
+ res.on('end', function () {
+ if (res.statusCode >= 400) {
+ reject("Request failed with status code ".concat(res.statusCode, ": ").concat(data));
+ }
+ else {
+ try {
+ resolve(JSON.parse(data));
+ }
+ catch (e) {
+ reject("Unable to parse JSON response: ".concat(data));
+ }
+ }
+ });
+ });
+ req.on('error', function (e) {
+ reject("Unable to make API request, error: ".concat(e));
+ });
+ if (body) {
+ // @ts-ignore
+ req.write(options.body);
+ }
+ req.end();
+ })];
});
}); };
diff --git a/dist/captcha-validator.js b/dist/captcha-validator.js
index dc0ac17f0..cdee3b473 100644
--- a/dist/captcha-validator.js
+++ b/dist/captcha-validator.js
@@ -1 +1 @@
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["captcha-validator"]={})}(this,function(e){"use strict";function h(e,i,c,s){return new(c=c||Promise)(function(n,t){function r(e){try{a(s.next(e))}catch(e){t(e)}}function o(e){try{a(s.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?n(e.value):((t=e.value)instanceof c?t:new c(function(e){e(t)})).then(r,o)}a((s=s.apply(e,i||[])).next())})}function d(r,o){var a,i,c,s={label:0,sent:function(){if(1&c[0])throw c[1];return c[1]},trys:[],ops:[]},u={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(u[Symbol.iterator]=function(){return this}),u;function e(n){return function(e){var t=[n,e];if(a)throw new TypeError("Generator is already executing.");for(;s=u&&t[u=0]?0:s;)try{if(a=1,i&&(c=2&t[0]?i.return:t[0]?i.throw||((c=i.return)&&c.call(i),0):i.next)&&!(c=c.call(i,t[1])).done)return c;switch(i=0,(t=c?[2&t[0],c.value]:t)[0]){case 0:case 1:c=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,i=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(c=0<(c=s.trys).length&&c[c.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!c||t[1]>c[0]&&t[1]<c[3]))s.label=t[1];else if(6===t[0]&&s.label<c[1])s.label=c[1],c=t;else{if(!(c&&s.label<c[2])){c[2]&&s.ops.pop(),s.trys.pop();continue}s.label=c[2],s.ops.push(t)}}t=o.call(r,s)}catch(e){t=[6,e],i=0}finally{a=c=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}var y="https://api.swetrix.com/captcha",v="/validate";e.validateToken=function(s,u,l,f,p){return h(this,void 0,void 0,function(){var t,n,c;return d(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,(r=v,o="POST",a={token:s,secret:u,timestamp:l,hash:f},i=p,h(void 0,void 0,void 0,function(){var t,n;return d(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,fetch("".concat(i||y).concat(r),{method:o,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})];case 1:return t=e.sent(),[3,3];case 2:throw n=e.sent(),"Unable to make API request, error: ".concat(n);case 3:return[4,t.json()];case 4:return[2,e.sent()]}})}))];case 1:return t=e.sent(),[3,3];case 2:return[2,[!1,e.sent()]];case 3:return(n=t.success,c=t.data,n)?[2,[!0,c]]:[2,[!1,"CAPTCHA validation failed"]]}var r,o,a,i})})},Object.defineProperty(e,"__esModule",{value:!0})});
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("https")):"function"==typeof define&&define.amd?define(["exports","https"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["captcha-validator"]={},e.https)}(this,function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=n(t);function h(e,i,c,u){return new(c=c||Promise)(function(n,t){function o(e){try{a(u.next(e))}catch(e){t(e)}}function r(e){try{a(u.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?n(e.value):((t=e.value)instanceof c?t:new c(function(e){e(t)})).then(o,r)}a((u=u.apply(e,i||[])).next())})}function v(o,r){var a,i,c,u={label:0,sent:function(){if(1&c[0])throw c[1];return c[1]},trys:[],ops:[]},s={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function e(n){return function(e){var t=[n,e];if(a)throw new TypeError("Generator is already executing.");for(;u=s&&t[s=0]?0:u;)try{if(a=1,i&&(c=2&t[0]?i.return:t[0]?i.throw||((c=i.return)&&c.call(i),0):i.next)&&!(c=c.call(i,t[1])).done)return c;switch(i=0,(t=c?[2&t[0],c.value]:t)[0]){case 0:case 1:c=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,i=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(c=0<(c=u.trys).length&&c[c.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!c||t[1]>c[0]&&t[1]<c[3]))u.label=t[1];else if(6===t[0]&&u.label<c[1])u.label=c[1],c=t;else{if(!(c&&u.label<c[2])){c[2]&&u.ops.pop(),u.trys.pop();continue}u.label=c[2],u.ops.push(t)}}t=r.call(o,u)}catch(e){t=[6,e],i=0}finally{a=c=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}var y="https://api.swetrix.com/captcha",b="/validate";e.validateToken=function(u,s,l,f,d){return h(this,void 0,void 0,function(){var t,o,c;return v(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,(r=b,n="POST",a={token:u,secret:s,timestamp:l,hash:f},i=d,h(void 0,void 0,void 0,function(){var t;return v(this,function(e){return t={method:n,headers:{"Content-Type":"application/json"}},a&&(t.body=JSON.stringify(a)),[2,new Promise(function(n,o){var e="".concat(i||y).concat(r),e=p.default.request(e,t,function(e){var t="";e.on("data",function(e){t+=e}),e.on("end",function(){if(400<=e.statusCode)o("Request failed with status code ".concat(e.statusCode,": ").concat(t));else try{n(JSON.parse(t))}catch(e){o("Unable to parse JSON response: ".concat(t))}})});e.on("error",function(e){o("Unable to make API request, error: ".concat(e))}),a&&e.write(t.body),e.end()})]})}))];case 1:return t=e.sent(),[3,3];case 2:return[2,[!1,e.sent()]];case 3:return(o=t.success,c=t.data,o)?[2,[!0,c]]:[2,[!1,"CAPTCHA validation failed"]]}var r,n,a,i})})},Object.defineProperty(e,"__esModule",{value:!0})});
diff --git a/dist/captcha-validator.orig.js b/dist/captcha-validator.orig.js
index a6c696750..7dbb6d122 100644
--- a/dist/captcha-validator.orig.js
+++ b/dist/captcha-validator.orig.js
@@ -1,8 +1,12 @@
(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["captcha-validator"] = {}));
-})(this, (function (exports) { 'use strict';
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('https')) :
+ typeof define === 'function' && define.amd ? define(['exports', 'https'], factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["captcha-validator"] = {}, global.https));
+})(this, (function (exports, https) { 'use strict';
+
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
+
+ var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
/******************************************************************************
Copyright (c) Microsoft Corporation.
@@ -62,27 +66,48 @@
VALIDATE: '/validate',
};
var makeAPIRequest = function (path, method, body, apiURL) { return __awaiter(void 0, void 0, void 0, function () {
- var res, e_1;
+ var options;
return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 2, , 3]);
- return [4 /*yield*/, fetch("".concat(apiURL || DEFAULT_API_HOST).concat(path), {
- method: method,
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- })];
- case 1:
- res = _a.sent();
- return [3 /*break*/, 3];
- case 2:
- e_1 = _a.sent();
- throw "Unable to make API request, error: ".concat(e_1);
- case 3: return [4 /*yield*/, res.json()];
- case 4: return [2 /*return*/, _a.sent()];
+ options = {
+ method: method,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ };
+ if (body) {
+ // @ts-ignore
+ options.body = JSON.stringify(body);
}
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var url = "".concat(apiURL || DEFAULT_API_HOST).concat(path);
+ var req = https__default["default"].request(url, options, function (res) {
+ var data = '';
+ res.on('data', function (chunk) {
+ data += chunk;
+ });
+ res.on('end', function () {
+ if (res.statusCode >= 400) {
+ reject("Request failed with status code ".concat(res.statusCode, ": ").concat(data));
+ }
+ else {
+ try {
+ resolve(JSON.parse(data));
+ }
+ catch (e) {
+ reject("Unable to parse JSON response: ".concat(data));
+ }
+ }
+ });
+ });
+ req.on('error', function (e) {
+ reject("Unable to make API request, error: ".concat(e));
+ });
+ if (body) {
+ // @ts-ignore
+ req.write(options.body);
+ }
+ req.end();
+ })];
});
}); };
diff --git a/dist/esnext/Lib.d.ts b/dist/esnext/Lib.d.ts
deleted file mode 100644
index a3d4c332f..000000000
--- a/dist/esnext/Lib.d.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-export interface LibOptions {
- /**
- * When set to `true`, all tracking logs will be printed to console and localhost events will be sent to server.
- */
- debug?: boolean;
- /**
- * When set to `true`, the tracking library won't send any data to server.
- * Useful for development purposes when this value is set based on `.env` var.
- */
- disabled?: boolean;
- /**
- * By setting this flag to `true`, we will not collect ANY kind of data about the user with the DNT setting.
- */
- respectDNT?: boolean;
- /** Set a custom URL of the API server (for selfhosted variants of Swetrix). */
- apiURL?: string;
-}
-export interface TrackEventOptions {
- /** The custom event name. */
- ev: string;
- /** If set to `true`, only 1 event with the same ID will be saved per user session. */
- unique?: boolean;
-}
-/**
- * The object returned by `trackPageViews()`, used to stop tracking pages.
- */
-export interface PageActions {
- /** Stops the tracking of pages. */
- stop: () => void;
-}
-export interface PageData {
- /** Current URL path. */
- path: string;
- /** The object returned by `trackPageViews()`, used to stop tracking pages. */
- actions: PageActions;
-}
-export interface PageViewsOptions {
- /**
- * If set to `true`, only unique events will be saved.
- * This param is useful when tracking single-page landing websites.
- */
- unique?: boolean;
- /** A list of Regular Expressions or string pathes to ignore. */
- ignore?: Array<string | RegExp>;
- /** Do not send Heartbeat requests to the server. */
- noHeartbeat?: boolean;
- /** Send Heartbeat requests when the website tab is not active in the browser. */
- heartbeatOnBackground?: boolean;
-}
-export declare const defaultPageActions: {
- stop(): void;
-};
-export declare class Lib {
- private projectID;
- private options?;
- private pageData;
- private pageViewsOptions;
- private perfStatsCollected;
- private activePage;
- constructor(projectID: string, options?: LibOptions | undefined);
- track(event: TrackEventOptions): void;
- trackPageViews(options?: PageViewsOptions): PageActions;
- getPerformanceStats(): object;
- private heartbeat;
- private checkIgnore;
- private trackPathChange;
- private trackPage;
- private debug;
- private canTrack;
- private sendRequest;
-}
diff --git a/dist/esnext/Lib.js b/dist/esnext/Lib.js
deleted file mode 100644
index 3fccb9d79..000000000
--- a/dist/esnext/Lib.js
+++ /dev/null
@@ -1,183 +0,0 @@
-import { isInBrowser, isLocalhost, isAutomated, getLocale, getTimezone, getReferrer, getUTMCampaign, getUTMMedium, getUTMSource, getPath, } from './utils';
-export const defaultPageActions = {
- stop() { },
-};
-const DEFAULT_API_HOST = 'https://api.swetrix.com/log';
-export class Lib {
- constructor(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);
- }
- track(event) {
- if (!this.canTrack()) {
- return;
- }
- const data = {
- pid: this.projectID,
- pg: this.activePage,
- lc: getLocale(),
- tz: getTimezone(),
- ref: getReferrer(),
- so: getUTMSource(),
- me: getUTMMedium(),
- ca: getUTMCampaign(),
- ...event,
- };
- this.sendRequest('custom', data);
- }
- trackPageViews(options) {
- if (!this.canTrack()) {
- return defaultPageActions;
- }
- if (this.pageData) {
- return this.pageData.actions;
- }
- this.pageViewsOptions = options;
- let hbInterval, interval;
- if (!options?.unique) {
- interval = setInterval(this.trackPathChange, 2000);
- }
- if (!options?.noHeartbeat) {
- setTimeout(this.heartbeat, 3000);
- hbInterval = setInterval(this.heartbeat, 28000);
- }
- const path = getPath();
- this.pageData = {
- path,
- actions: {
- stop: () => {
- clearInterval(interval);
- clearInterval(hbInterval);
- },
- },
- };
- this.trackPage(path, options?.unique);
- return this.pageData.actions;
- }
- getPerformanceStats() {
- if (!this.canTrack() || this.perfStatsCollected || !window.performance?.getEntriesByType) {
- return {};
- }
- const 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,
- };
- }
- heartbeat() {
- if (!this.pageViewsOptions?.heartbeatOnBackground && document.visibilityState === 'hidden') {
- return;
- }
- const data = {
- pid: this.projectID,
- };
- this.sendRequest('hb', data);
- }
- checkIgnore(path) {
- const ignore = this.pageViewsOptions?.ignore;
- if (Array.isArray(ignore)) {
- for (let 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
- trackPathChange() {
- if (!this.pageData)
- return;
- const newPath = getPath();
- const { path } = this.pageData;
- if (path !== newPath) {
- this.trackPage(newPath, false);
- }
- }
- trackPage(pg, unique = false) {
- if (!this.pageData)
- return;
- this.pageData.path = pg;
- if (this.checkIgnore(pg))
- return;
- this.activePage = pg;
- const perf = this.getPerformanceStats();
- const data = {
- pid: this.projectID,
- lc: getLocale(),
- tz: getTimezone(),
- ref: getReferrer(),
- so: getUTMSource(),
- me: getUTMMedium(),
- ca: getUTMCampaign(),
- unique,
- pg,
- perf,
- };
- this.sendRequest('', data);
- }
- debug(message) {
- if (this.options?.debug) {
- console.log('[Swetrix]', message);
- }
- }
- canTrack() {
- if (this.options?.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 (this.options?.respectDNT && window.navigator?.doNotTrack === '1') {
- this.debug('Tracking disabled: respecting user\'s \'Do Not Track\' preference.');
- return false;
- }
- if (!this.options?.debug && isLocalhost()) {
- return false;
- }
- if (isAutomated()) {
- this.debug('Tracking disabled: navigation is automated by WebDriver.');
- return false;
- }
- return true;
- }
- sendRequest(path, body) {
- const host = this.options?.apiURL || DEFAULT_API_HOST;
- const req = new XMLHttpRequest();
- req.open('POST', `${host}/${path}`, true);
- req.setRequestHeader('Content-Type', 'application/json');
- req.send(JSON.stringify(body));
- }
-}
-//# sourceMappingURL=Lib.js.map
\ No newline at end of file
diff --git a/dist/esnext/Lib.js.map b/dist/esnext/Lib.js.map
deleted file mode 100644
index 55469a4a5..000000000
--- a/dist/esnext/Lib.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"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;AAgEhB,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,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,IAAI,CAAC,KAAK,CAAC,gEAAgE,CAAC,CAAA;YAC5E,OAAO,KAAK,CAAA;SACb;QAED,IAAI,IAAI,CAAC,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,SAAS,EAAE,UAAU,KAAK,GAAG,EAAE;YACpE,IAAI,CAAC,KAAK,CAAC,oEAAoE,CAAC,CAAA;YAChF,OAAO,KAAK,CAAA;SACb;QAED,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,EAAE;YACzC,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 file
diff --git a/dist/esnext/utils.js b/dist/esnext/utils.js
index 1eb172dee..09c07bdd2 100644
--- a/dist/esnext/utils.js
+++ b/dist/esnext/utils.js
@@ -1,21 +1,48 @@
+import https from 'https';
const DEFAULT_API_HOST = 'https://api.swetrix.com/captcha';
export const ENDPOINTS = {
VALIDATE: '/validate',
};
export const makeAPIRequest = async (path, method, body, apiURL) => {
- let res;
- try {
- res = await fetch(`${apiURL || DEFAULT_API_HOST}${path}`, {
- method,
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- });
- }
- catch (e) {
- throw `Unable to make API request, error: ${e}`;
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ };
+ if (body) {
+ // @ts-ignore
+ options.body = JSON.stringify(body);
}
- return await res.json();
+ return new Promise((resolve, reject) => {
+ const url = `${apiURL || DEFAULT_API_HOST}${path}`;
+ const req = https.request(url, options, (res) => {
+ let data = '';
+ res.on('data', (chunk) => {
+ data += chunk;
+ });
+ res.on('end', () => {
+ if (res.statusCode >= 400) {
+ reject(`Request failed with status code ${res.statusCode}: ${data}`);
+ }
+ else {
+ try {
+ resolve(JSON.parse(data));
+ }
+ catch (e) {
+ reject(`Unable to parse JSON response: ${data}`);
+ }
+ }
+ });
+ });
+ req.on('error', (e) => {
+ reject(`Unable to make API request, error: ${e}`);
+ });
+ if (body) {
+ // @ts-ignore
+ req.write(options.body);
+ }
+ req.end();
+ });
};
//# sourceMappingURL=utils.js.map
\ No newline at end of file
diff --git a/dist/esnext/utils.js.map b/dist/esnext/utils.js.map
index a102aa324..7200f1610 100644
--- a/dist/esnext/utils.js.map
+++ b/dist/esnext/utils.js.map
@@ -1 +1 @@
-{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,iCAAiC,CAAA;AAE1D,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,QAAQ,EAAE,WAAW;CACtB,CAAA;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,EAAE,IAAY,EAAE,MAAc,EAAE,IAAY,EAAE,MAAe,EAAgB,EAAE;IAChH,IAAI,GAAG,CAAA;IAEP,IAAI;QACF,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,IAAI,gBAAgB,GAAG,IAAI,EAAE,EAAE;YACxD,MAAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;aACnC;YACD,IAAI,EAAE,IAAI,CAAC,SA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CAAmC,GAAG,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC,CAAA;iBACrE;qBAAM;oBACL,IAAI;wBACF,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;qBAC1B;oBAAC,OAAO,CAAC,EAAE;wBACV,MAAM,CAAC,kCAAkC,IAAI,EAAE,CAAC,CAAA;qBACjD;iBACF;YACH,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACpB,MAAM,CAAC,sCAAsC,CAAC,EAAE,CAAC,CAAA;QACnD,CAAC,CAAC,CAAA;QAEF,IAAI,IAAI,EAAE;YACR,aAAa;YACb,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;SACxB;QAED,GAAG,CAAC,GAAG,EAAE,CAAA;IACX,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}
\ No newline at end of file
diff --git a/dist/swetrix.cjs.js b/dist/swetrix.cjs.js
deleted file mode 100644
index 353ee1d56..000000000
--- a/dist/swetrix.cjs.js
+++ /dev/null
@@ -1,304 +0,0 @@
-'use strict';
-
-Object.defineProperty(exports, '__esModule', { value: true });
-
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-
-var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-
-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.trackPage = function (pg, unique) {
- if (unique === void 0) { unique = false; }
- if (!this.pageData)
- return;
- this.pageData.path = pg;
- if (this.checkIgnore(pg))
- return;
- this.activePage = pg;
- var perf = this.getPerformanceStats();
- var data = {
- pid: this.projectID,
- lc: getLocale(),
- tz: getTimezone(),
- ref: getReferrer(),
- so: getUTMSource(),
- me: getUTMMedium(),
- ca: getUTMCampaign(),
- unique: unique,
- pg: pg,
- perf: perf,
- };
- 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.init = init;
-exports.track = track;
-exports.trackViews = trackViews;
diff --git a/dist/swetrix.es5.js b/dist/swetrix.es5.js
deleted file mode 100644
index 6757b9e6f..000000000
--- a/dist/swetrix.es5.js
+++ /dev/null
@@ -1,298 +0,0 @@
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-
-var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-
-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.trackPage = function (pg, unique) {
- if (unique === void 0) { unique = false; }
- if (!this.pageData)
- return;
- this.pageData.path = pg;
- if (this.checkIgnore(pg))
- return;
- this.activePage = pg;
- var perf = this.getPerformanceStats();
- var data = {
- pid: this.projectID,
- lc: getLocale(),
- tz: getTimezone(),
- ref: getReferrer(),
- so: getUTMSource(),
- me: getUTMMedium(),
- ca: getUTMCampaign(),
- unique: unique,
- pg: pg,
- perf: perf,
- };
- 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));
- });
- }
- });
-}
-
-export { LIB_INSTANCE, init, track, trackViews };
diff --git a/dist/swetrix.js b/dist/swetrix.js
deleted file mode 100644
index e479524d5..000000000
--- a/dist/swetrix.js
+++ /dev/null
@@ -1 +0,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 o(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function i(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function a(){return document.referrer||void 0}function r(){return t(d)}function s(){return t(l)}function c(){return t(p)}function u(){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)},d=/[?&](ref|source|utm_source)=([^?&]+)/,p=/[?&](utm_campaign)=([^?&]+)/,l=/[?&](utm_medium)=([^?&]+)/,h={stop:function(){}},g=(f.prototype.track=function(t){this.canTrack()&&(t=e({pid:this.projectID,pg:this.activePage,lc:o(),tz:i(),ref:a(),so:r(),me:s(),ca:c()},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=u(),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=u(),this.pageData.path!==t)&&this.trackPage(t,!1)},f.prototype.trackPage=function(t,e){var n;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,this.checkIgnore(t)||(this.activePage=t,n=this.getPerformanceStats(),e={pid:this.projectID,lc:o(),tz:i(),ref:a(),so:r(),me:s(),ca:c(),unique:e,pg:t,perf:n},this.sendRequest("",e)))},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.js
deleted file mode 100644
index f53f97d0b..000000000
--- a/dist/swetrix.orig.js
+++ /dev/null
@@ -1,310 +0,0 @@
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.swetrix = {}));
-})(this, (function (exports) { 'use strict';
-
- /******************************************************************************
- Copyright (c) Microsoft Corporation.
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
-
- var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
-
- 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.trackPage = function (pg, unique) {
- if (unique === void 0) { unique = false; }
- if (!this.pageData)
- return;
- this.pageData.path = pg;
- if (this.checkIgnore(pg))
- return;
- this.activePage = pg;
- var perf = this.getPerformanceStats();
- var data = {
- pid: this.projectID,
- lc: getLocale(),
- tz: getTimezone(),
- ref: getReferrer(),
- so: getUTMSource(),
- me: getUTMMedium(),
- ca: getUTMCampaign(),
- unique: unique,
- pg: pg,
- perf: perf,
- };
- 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.init = init;
- exports.track = track;
- exports.trackViews = trackViews;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-}));