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!

(feature) Error tracking (#12)

Andrii Romasiun30cc11a85f5f
diff --git a/dist/esnext/Lib.d.ts b/dist/esnext/Lib.d.ts
index 039cfa42a..43f7578d2 100644
--- a/dist/esnext/Lib.d.ts
+++ b/dist/esnext/Lib.d.ts
@@ -35,6 +35,18 @@ export interface IPageViewPayload {
pg: string | null | undefined;
prev: string | null | undefined;
}
+export interface IErrorEventPayload {
+ name: string;
+ message: string | null | undefined;
+ lineno: number | null | undefined;
+ colno: number | null | undefined;
+ filename: string | null | undefined;
+}
+export interface IInternalErrorEventPayload extends IErrorEventPayload {
+ lc: string | undefined;
+ tz: string | undefined;
+ pg: string | null | undefined;
+}
interface IPerfPayload {
dns: number;
tls: number;
@@ -52,12 +64,36 @@ export interface PageActions {
/** Stops the tracking of pages. */
stop: () => void;
}
+/**
+ * The object returned by `trackErrors()`, used to stop tracking errors.
+ */
+export interface ErrorActions {
+ /** Stops the tracking of errors. */
+ stop: () => void;
+}
export interface PageData {
/** Current URL path. */
path: string;
/** The object returned by `trackPageViews()`, used to stop tracking pages. */
actions: PageActions;
}
+export interface ErrorOptions {
+ /**
+ * A number that indicates how many errors should be sent to the server.
+ * Accepts values between 0 and 1. For example, if set to 0.5 - only ~50% of errors will be sent to Swetrix.
+ * For testing, we recommend setting this value to 1. For production, you should configure it depending on your needs as each error event counts towards your plan.
+ *
+ * The default value for this option is 1.
+ */
+ sampleRate?: number;
+ /**
+ * Callback to edit / prevent sending errors.
+ *
+ * @param payload - The error payload.
+ * @returns The edited payload or `false` to prevent sending the error event. If `true` is returned, the payload will be sent as-is.
+ */
+ callback?: (payload: IInternalErrorEventPayload) => Partial<IInternalErrorEventPayload> | boolean;
+}
export interface PageViewsOptions {
/**
* If set to `true`, only unique events will be saved.
@@ -84,7 +120,7 @@ export interface PageViewsOptions {
*/
callback?: (payload: IPageViewPayload) => Partial<IPageViewPayload> | boolean;
}
-export declare const defaultPageActions: {
+export declare const defaultActions: {
stop(): void;
};
export declare class Lib {
@@ -92,9 +128,14 @@ export declare class Lib {
private options?;
private pageData;
private pageViewsOptions;
+ private errorsOptions;
private perfStatsCollected;
private activePage;
+ private errorListenerExists;
constructor(projectID: string, options?: LibOptions | undefined);
+ captureError(event: ErrorEvent): void;
+ trackErrors(options?: ErrorOptions): ErrorActions;
+ submitError(payload: IErrorEventPayload, evokeCallback?: boolean): void;
track(event: TrackEventOptions): void;
trackPageViews(options?: PageViewsOptions): PageActions;
getPerformanceStats(): IPerfPayload | {};
diff --git a/dist/esnext/Lib.js b/dist/esnext/Lib.js
index 3c730af0b..7ed25f614 100644
--- a/dist/esnext/Lib.js
+++ b/dist/esnext/Lib.js
@@ -1,5 +1,5 @@
import { isInBrowser, isLocalhost, isAutomated, getLocale, getTimezone, getReferrer, getUTMCampaign, getUTMMedium, getUTMSource, getPath, } from './utils';
-export const defaultPageActions = {
+export const defaultActions = {
stop() { },
};
const DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -9,10 +9,71 @@ export class Lib {
this.options = options;
this.pageData = null;
this.pageViewsOptions = null;
+ this.errorsOptions = null;
this.perfStatsCollected = false;
this.activePage = null;
+ this.errorListenerExists = false;
this.trackPathChange = this.trackPathChange.bind(this);
this.heartbeat = this.heartbeat.bind(this);
+ this.captureError = this.captureError.bind(this);
+ }
+ captureError(event) {
+ if (typeof this.errorsOptions?.sampleRate === 'number' && this.errorsOptions.sampleRate > Math.random()) {
+ return;
+ }
+ this.submitError({
+ // The file in which error occured.
+ filename: event.filename,
+ // The line of code error occured on.
+ lineno: event.lineno,
+ // The column of code error occured on.
+ colno: event.colno,
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
+ name: event.error?.name || 'Error',
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
+ // (we want to split error name and message so we could group them together later in dashboard).
+ // If message in error object does not exist - lets use a message from the Error event itself.
+ message: event.error?.message || event.message,
+ });
+ }
+ trackErrors(options) {
+ if (this.errorListenerExists || !this.canTrack()) {
+ return defaultActions;
+ }
+ this.errorsOptions = options;
+ window.addEventListener('error', this.captureError);
+ this.errorListenerExists = true;
+ return {
+ stop: () => {
+ window.removeEventListener('error', this.captureError);
+ },
+ };
+ }
+ submitError(payload, evokeCallback) {
+ const privateData = {
+ pid: this.projectID,
+ };
+ const errorPayload = {
+ pg: this.activePage ||
+ getPath({
+ hash: this.pageViewsOptions?.hash,
+ search: this.pageViewsOptions?.search,
+ }),
+ lc: getLocale(),
+ tz: getTimezone(),
+ ...payload,
+ };
+ if (evokeCallback && this.errorsOptions?.callback) {
+ const callbackResult = this.errorsOptions.callback(errorPayload);
+ if (callbackResult === false) {
+ return;
+ }
+ if (callbackResult && typeof callbackResult === 'object') {
+ Object.assign(errorPayload, callbackResult);
+ }
+ }
+ Object.assign(errorPayload, privateData);
+ this.sendRequest('error', errorPayload);
}
track(event) {
if (!this.canTrack()) {
@@ -33,7 +94,7 @@ export class Lib {
}
trackPageViews(options) {
if (!this.canTrack()) {
- return defaultPageActions;
+ return defaultActions;
}
if (this.pageData) {
return this.pageData.actions;
diff --git a/dist/esnext/Lib.js.map b/dist/esnext/Lib.js.map
index 2722a1888..e8469e9ef 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,EACX,WAAW,EACX,WAAW,EACX,SAAS,EACT,WAAW,EACX,WAAW,EACX,cAAc,EACd,YAAY,EACZ,YAAY,EACZ,OAAO,GACR,MAAM,SAAS,CAAA;AA0GhB,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,IAAI,KAAI,CAAC;CACV,CAAA;AAED,MAAM,gBAAgB,GAAG,6BAA6B,CAAA;AAEtD,MAAM,OAAO,GAAG;IAMd,YA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AC;QACH,CAAC;QAED,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAA;QAErC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,SAAS,CAAC,CAAA;IACjC,CAAC;IAEO,QAAQ;QACd,IACE,IAAI,CAAC,OAAO,EAAE,QAAQ;YACtB,CAAC,WAAW,EAAE;YACd,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,SAAS,EAAE,UAAU,KAAK,GAAG,CAAC;YAClE,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,CAAC;YACzC,WAAW,EAAE,EACb,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;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/index.d.ts b/dist/esnext/index.d.ts
index eb54f75d8..e5b8a1095 100644
--- a/dist/esnext/index.d.ts
+++ b/dist/esnext/index.d.ts
@@ -1,4 +1,4 @@
-import { Lib, LibOptions, TrackEventOptions, PageViewsOptions, PageActions } from './Lib';
+import { Lib, LibOptions, TrackEventOptions, PageViewsOptions, ErrorOptions, PageActions, ErrorActions, IErrorEventPayload } from './Lib';
export declare let LIB_INSTANCE: Lib | null;
/**
* Initialise the tracking library instance (other methods won't work if the library is not initialised).
@@ -16,6 +16,13 @@ export declare function init(pid: string, options?: LibOptions): Lib;
* @param {TrackEventOptions} event The options related to the custom event.
*/
export declare function track(event: TrackEventOptions): void;
+/**
+ * With this function you are able to automatically track pageviews across your application.
+ *
+ * @param {PageViewsOptions} options Pageviews tracking options.
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
+ */
+export declare function trackViews(options?: PageViewsOptions): Promise<PageActions>;
/**
* 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.
@@ -24,7 +31,15 @@ export declare function track(event: TrackEventOptions): void;
* @param {PageViewsOptions} options The options related to the custom event.
* @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
*/
-export declare function trackViews(options?: PageViewsOptions): Promise<PageActions>;
+export declare function trackErrors(options?: ErrorOptions): ErrorActions;
+/**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+export declare function trackError(payload: IErrorEventPayload): void;
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
diff --git a/dist/esnext/index.js b/dist/esnext/index.js
index 94faceb07..74ab24661 100644
--- a/dist/esnext/index.js
+++ b/dist/esnext/index.js
@@ -1,4 +1,4 @@
-import { Lib, defaultPageActions } from './Lib';
+import { Lib, defaultActions, } from './Lib';
export let LIB_INSTANCE = null;
/**
* Initialise the tracking library instance (other methods won't work if the library is not initialised).
@@ -26,17 +26,15 @@ export function track(event) {
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.
+ * With this function you are able to automatically track pageviews across your application.
*
- * @param {PageViewsOptions} options The options related to the custom event.
+ * @param {PageViewsOptions} options Pageviews tracking options.
* @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
*/
export function trackViews(options) {
return new Promise((resolve) => {
if (!LIB_INSTANCE) {
- resolve(defaultPageActions);
+ resolve(defaultActions);
return;
}
// We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -51,6 +49,32 @@ export function trackViews(options) {
}
});
}
+/**
+ * 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.
+ */
+export function trackErrors(options) {
+ if (!LIB_INSTANCE) {
+ return defaultActions;
+ }
+ return LIB_INSTANCE.trackErrors(options);
+}
+/**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+export function trackError(payload) {
+ if (!LIB_INSTANCE)
+ return;
+ LIB_INSTANCE.submitError(payload, false);
+}
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
diff --git a/dist/esnext/index.js.map b/dist/esnext/index.js.map
index 8b4d999d4..fe59bc725 100644
--- a/dist/esnext/index.js.map
+++ b/dist/esnext/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAgE,kBAAkB,EAAE,MAAM,OAAO,CAAA;AAE7G,MAAM,CAAC,IAAI,YAAY,GAAe,IAAI,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAAC,GAAW,EAAE,OAAoB;IACpD,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IACtC,CAAC;IAED,OAAO,YAAY,CAAA;AACrB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,KAAK,CAAC,KAAwB;IAC5C,IAAI,CAAC,YAAY;QAAE,OAAM;IAEz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C,IAAY,EAAE,IAAa,EAAE,MAAgB;IACzE,IAAI,CAAC,YAAY;QAAE,OAAM;IAEzB,YAAY,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,CAAA;AACtE,CAAC"}
\ No newline at end of file
diff --git a/dist/swetrix.cjs.js b/dist/swetrix.cjs.js
index 4dd29b721..4f9b11601 100644
--- a/dist/swetrix.cjs.js
+++ b/dist/swetrix.cjs.js
@@ -95,7 +95,7 @@ var getPath = function (options) {
return result;
};
-var defaultPageActions = {
+var defaultActions = {
stop: function () { },
};
var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -105,11 +105,70 @@ var Lib = /** @class */ (function () {
this.options = options;
this.pageData = null;
this.pageViewsOptions = null;
+ this.errorsOptions = null;
this.perfStatsCollected = false;
this.activePage = null;
+ this.errorListenerExists = false;
this.trackPathChange = this.trackPathChange.bind(this);
this.heartbeat = this.heartbeat.bind(this);
+ this.captureError = this.captureError.bind(this);
}
+ Lib.prototype.captureError = function (event) {
+ var _a, _b, _c;
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
+ return;
+ }
+ this.submitError({
+ // The file in which error occured.
+ filename: event.filename,
+ // The line of code error occured on.
+ lineno: event.lineno,
+ // The column of code error occured on.
+ colno: event.colno,
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
+ // (we want to split error name and message so we could group them together later in dashboard).
+ // If message in error object does not exist - lets use a message from the Error event itself.
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
+ });
+ };
+ Lib.prototype.trackErrors = function (options) {
+ var _this = this;
+ if (this.errorListenerExists || !this.canTrack()) {
+ return defaultActions;
+ }
+ this.errorsOptions = options;
+ window.addEventListener('error', this.captureError);
+ this.errorListenerExists = true;
+ return {
+ stop: function () {
+ window.removeEventListener('error', _this.captureError);
+ },
+ };
+ };
+ Lib.prototype.submitError = function (payload, evokeCallback) {
+ var _a, _b, _c;
+ var privateData = {
+ pid: this.projectID,
+ };
+ var errorPayload = __assign({ pg: this.activePage ||
+ getPath({
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
+ }), lc: getLocale(), tz: getTimezone() }, payload);
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
+ var callbackResult = this.errorsOptions.callback(errorPayload);
+ if (callbackResult === false) {
+ return;
+ }
+ if (callbackResult && typeof callbackResult === 'object') {
+ Object.assign(errorPayload, callbackResult);
+ }
+ }
+ Object.assign(errorPayload, privateData);
+ this.sendRequest('error', errorPayload);
+ };
Lib.prototype.track = function (event) {
if (!this.canTrack()) {
return;
@@ -119,7 +178,7 @@ var Lib = /** @class */ (function () {
};
Lib.prototype.trackPageViews = function (options) {
if (!this.canTrack()) {
- return defaultPageActions;
+ return defaultActions;
}
if (this.pageData) {
return this.pageData.actions;
@@ -313,17 +372,15 @@ function track(event) {
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.
+ * With this function you are able to automatically track pageviews across your application.
*
- * @param {PageViewsOptions} options The options related to the custom event.
+ * @param {PageViewsOptions} options Pageviews tracking options.
* @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);
+ resolve(defaultActions);
return;
}
// We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -338,6 +395,32 @@ function trackViews(options) {
}
});
}
+/**
+ * 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 trackErrors(options) {
+ if (!exports.LIB_INSTANCE) {
+ return defaultActions;
+ }
+ return exports.LIB_INSTANCE.trackErrors(options);
+}
+/**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+function trackError(payload) {
+ if (!exports.LIB_INSTANCE)
+ return;
+ exports.LIB_INSTANCE.submitError(payload, false);
+}
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -355,5 +438,7 @@ function trackPageview(path, prev, unique) {
exports.init = init;
exports.track = track;
+exports.trackError = trackError;
+exports.trackErrors = trackErrors;
exports.trackPageview = trackPageview;
exports.trackViews = trackViews;
diff --git a/dist/swetrix.es5.js b/dist/swetrix.es5.js
index 1c507f7aa..3c2cf93c6 100644
--- a/dist/swetrix.es5.js
+++ b/dist/swetrix.es5.js
@@ -91,7 +91,7 @@ var getPath = function (options) {
return result;
};
-var defaultPageActions = {
+var defaultActions = {
stop: function () { },
};
var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -101,11 +101,70 @@ var Lib = /** @class */ (function () {
this.options = options;
this.pageData = null;
this.pageViewsOptions = null;
+ this.errorsOptions = null;
this.perfStatsCollected = false;
this.activePage = null;
+ this.errorListenerExists = false;
this.trackPathChange = this.trackPathChange.bind(this);
this.heartbeat = this.heartbeat.bind(this);
+ this.captureError = this.captureError.bind(this);
}
+ Lib.prototype.captureError = function (event) {
+ var _a, _b, _c;
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
+ return;
+ }
+ this.submitError({
+ // The file in which error occured.
+ filename: event.filename,
+ // The line of code error occured on.
+ lineno: event.lineno,
+ // The column of code error occured on.
+ colno: event.colno,
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
+ // (we want to split error name and message so we could group them together later in dashboard).
+ // If message in error object does not exist - lets use a message from the Error event itself.
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
+ });
+ };
+ Lib.prototype.trackErrors = function (options) {
+ var _this = this;
+ if (this.errorListenerExists || !this.canTrack()) {
+ return defaultActions;
+ }
+ this.errorsOptions = options;
+ window.addEventListener('error', this.captureError);
+ this.errorListenerExists = true;
+ return {
+ stop: function () {
+ window.removeEventListener('error', _this.captureError);
+ },
+ };
+ };
+ Lib.prototype.submitError = function (payload, evokeCallback) {
+ var _a, _b, _c;
+ var privateData = {
+ pid: this.projectID,
+ };
+ var errorPayload = __assign({ pg: this.activePage ||
+ getPath({
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
+ }), lc: getLocale(), tz: getTimezone() }, payload);
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
+ var callbackResult = this.errorsOptions.callback(errorPayload);
+ if (callbackResult === false) {
+ return;
+ }
+ if (callbackResult && typeof callbackResult === 'object') {
+ Object.assign(errorPayload, callbackResult);
+ }
+ }
+ Object.assign(errorPayload, privateData);
+ this.sendRequest('error', errorPayload);
+ };
Lib.prototype.track = function (event) {
if (!this.canTrack()) {
return;
@@ -115,7 +174,7 @@ var Lib = /** @class */ (function () {
};
Lib.prototype.trackPageViews = function (options) {
if (!this.canTrack()) {
- return defaultPageActions;
+ return defaultActions;
}
if (this.pageData) {
return this.pageData.actions;
@@ -309,17 +368,15 @@ function track(event) {
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.
+ * With this function you are able to automatically track pageviews across your application.
*
- * @param {PageViewsOptions} options The options related to the custom event.
+ * @param {PageViewsOptions} options Pageviews tracking options.
* @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);
+ resolve(defaultActions);
return;
}
// We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -334,6 +391,32 @@ function trackViews(options) {
}
});
}
+/**
+ * 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 trackErrors(options) {
+ if (!LIB_INSTANCE) {
+ return defaultActions;
+ }
+ return LIB_INSTANCE.trackErrors(options);
+}
+/**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+function trackError(payload) {
+ if (!LIB_INSTANCE)
+ return;
+ LIB_INSTANCE.submitError(payload, false);
+}
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -349,4 +432,4 @@ function trackPageview(path, prev, unique) {
LIB_INSTANCE.submitPageView(path, prev || null, Boolean(unique), {});
}
-export { LIB_INSTANCE, init, track, trackPageview, trackViews };
+export { LIB_INSTANCE, init, track, trackError, trackErrors, trackPageview, trackViews };
diff --git a/dist/swetrix.js b/dist/swetrix.js
index d969bfd08..4d239e0ea 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(a){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function i(){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(n)}function u(){return t(p)}function l(){return t(h)}function o(t){var e,n=location.pathname||"";return t.hash&&(n+=-1<(e=location.hash.indexOf("?"))?location.hash.substring(0,e):location.hash),t.search&&(e=location.hash.indexOf("?"),n+=location.search||(-1<e?location.hash.substring(e):"")),n}var e=function(){return(e=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)},n=/[?&](ref|source|utm_source)=([^?&]+)/,h=/[?&](utm_campaign)=([^?&]+)/,p=/[?&](utm_medium)=([^?&]+)/,d={stop:function(){}},f=(g.prototype.track=function(t){this.canTrack()&&(t=e(e({},t),{pid:this.projectID,pg:this.activePage,lc:i(),tz:r(),ref:s(),so:c(),me:u(),ca:l()}),this.sendRequest("custom",t))},g.prototype.trackPageViews=function(t){var e,n,a;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(e=setInterval(this.trackPathChange,2e3)),setTimeout(this.heartbeat,3e3),n=setInterval(this.heartbeat,28e3),a=o({hash:null==t?void 0:t.hash,search:null==t?void 0:t.search}),this.pageData={path:a,actions:{stop:function(){clearInterval(e),clearInterval(n)}}},this.trackPage(a,null==t?void 0:t.unique)),this.pageData.actions):d},g.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}):{}},g.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},g.prototype.trackPathChange=function(){var t;this.pageData&&(t=o({hash:null==(t=this.pageViewsOptions)?void 0:t.hash,search:null==(t=this.pageViewsOptions)?void 0:t.search}),this.pageData.path!==t)&&this.trackPage(t,!1)},g.prototype.getPreviousPage=function(){if(this.activePage)return this.activePage;if("function"==typeof URL){var t=s();if(!t)return null;var e=location.host;try{var n=new URL(t),a=n.host,o=n.pathname;return e!==a?null:o}catch(t){}}return null},g.prototype.trackPage=function(t,e){var n,a;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,n=this.getPerformanceStats(),a=this.getPreviousPage(),this.activePage=t,this.submitPageView(t,a,e,n,!0))},g.prototype.submitPageView=function(t,e,n,a,o){a={pid:this.projectID,perf:a,unique:n},n={lc:i(),tz:r(),ref:s(),so:c(),me:u(),ca:l(),pg:t,prev:e};if(o&&null!=(t=this.pageViewsOptions)&&t.callback){e=this.pageViewsOptions.callback(n);if(!1===e)return;e&&"object"==typeof e&&Object.assign(n,e)}Object.assign(n,a),this.sendRequest("",n)},g.prototype.canTrack=function(){var t;return!(null!=(t=this.options)&&t.disabled||"undefined"==typeof window||null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)||(null==(t=this.options)||!t.devMode)&&("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)},g.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",a=new XMLHttpRequest;a.open("POST","".concat(n,"/").concat(t),!0),a.setRequestHeader("Content-Type","application/json"),a.send(JSON.stringify(e))},g);function g(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)}a.LIB_INSTANCE=null,a.init=function(t,e){return a.LIB_INSTANCE||(a.LIB_INSTANCE=new f(t,e)),a.LIB_INSTANCE},a.track=function(t){a.LIB_INSTANCE&&a.LIB_INSTANCE.track(t)},a.trackPageview=function(t,e,n){a.LIB_INSTANCE&&a.LIB_INSTANCE.submitPageView(t,e||null,Boolean(n),{})},a.trackViews=function(e){return new Promise(function(t){a.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(a.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(a.LIB_INSTANCE.trackPageViews(e))}):t(d)})},Object.defineProperty(a,"__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(o){"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 a(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function s(){return document.referrer||void 0}function c(){return t(e)}function u(){return t(p)}function l(){return t(n)}function i(t){var e,n=location.pathname||"";return t.hash&&(n+=-1<(e=location.hash.indexOf("?"))?location.hash.substring(0,e):location.hash),t.search&&(e=location.hash.indexOf("?"),n+=location.search||(-1<e?location.hash.substring(e):"")),n}var h=function(){return(h=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)},e=/[?&](ref|source|utm_source)=([^?&]+)/,n=/[?&](utm_campaign)=([^?&]+)/,p=/[?&](utm_medium)=([^?&]+)/,d={stop:function(){}},f=(g.prototype.captureError=function(t){var e;"number"==typeof(null==(e=this.errorsOptions)?void 0:e.sampleRate)&&this.errorsOptions.sampleRate>Math.random()||this.submitError({filename:t.filename,lineno:t.lineno,colno:t.colno,name:(null==(e=t.error)?void 0:e.name)||"Error",message:(null==(e=t.error)?void 0:e.message)||t.message})},g.prototype.trackErrors=function(t){var e=this;return this.errorListenerExists||!this.canTrack()?d:(this.errorsOptions=t,window.addEventListener("error",this.captureError),this.errorListenerExists=!0,{stop:function(){window.removeEventListener("error",e.captureError)}})},g.prototype.submitError=function(t,e){var n={pid:this.projectID},o=h({pg:this.activePage||i({hash:null==(o=this.pageViewsOptions)?void 0:o.hash,search:null==(o=this.pageViewsOptions)?void 0:o.search}),lc:r(),tz:a()},t);if(e&&null!=(t=this.errorsOptions)&&t.callback){e=this.errorsOptions.callback(o);if(!1===e)return;e&&"object"==typeof e&&Object.assign(o,e)}Object.assign(o,n),this.sendRequest("error",o)},g.prototype.track=function(t){this.canTrack()&&(t=h(h({},t),{pid:this.projectID,pg:this.activePage,lc:r(),tz:a(),ref:s(),so:c(),me:u(),ca:l()}),this.sendRequest("custom",t))},g.prototype.trackPageViews=function(t){var e,n,o;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(e=setInterval(this.trackPathChange,2e3)),setTimeout(this.heartbeat,3e3),n=setInterval(this.heartbeat,28e3),o=i({hash:null==t?void 0:t.hash,search:null==t?void 0:t.search}),this.pageData={path:o,actions:{stop:function(){clearInterval(e),clearInterval(n)}}},this.trackPage(o,null==t?void 0:t.unique)),this.pageData.actions):d},g.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}):{}},g.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},g.prototype.trackPathChange=function(){var t;this.pageData&&(t=i({hash:null==(t=this.pageViewsOptions)?void 0:t.hash,search:null==(t=this.pageViewsOptions)?void 0:t.search}),this.pageData.path!==t)&&this.trackPage(t,!1)},g.prototype.getPreviousPage=function(){if(this.activePage)return 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:i}catch(t){}}return null},g.prototype.trackPage=function(t,e){var n,o;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,n=this.getPerformanceStats(),o=this.getPreviousPage(),this.activePage=t,this.submitPageView(t,o,e,n,!0))},g.prototype.submitPageView=function(t,e,n,o,i){o={pid:this.projectID,perf:o,unique:n},n={lc:r(),tz:a(),ref:s(),so:c(),me:u(),ca:l(),pg:t,prev:e};if(i&&null!=(t=this.pageViewsOptions)&&t.callback){e=this.pageViewsOptions.callback(n);if(!1===e)return;e&&"object"==typeof e&&Object.assign(n,e)}Object.assign(n,o),this.sendRequest("",n)},g.prototype.canTrack=function(){var t;return!(null!=(t=this.options)&&t.disabled||"undefined"==typeof window||null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)||(null==(t=this.options)||!t.devMode)&&("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)},g.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))},g);function g(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.errorsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.errorListenerExists=!1,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this),this.captureError=this.captureError.bind(this)}o.LIB_INSTANCE=null,o.init=function(t,e){return o.LIB_INSTANCE||(o.LIB_INSTANCE=new f(t,e)),o.LIB_INSTANCE},o.track=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.track(t)},o.trackError=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.submitError(t,!1)},o.trackErrors=function(t){return o.LIB_INSTANCE?o.LIB_INSTANCE.trackErrors(t):d},o.trackPageview=function(t,e,n){o.LIB_INSTANCE&&o.LIB_INSTANCE.submitPageView(t,e||null,Boolean(n),{})},o.trackViews=function(e){return new Promise(function(t){o.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(o.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(o.LIB_INSTANCE.trackPageViews(e))}):t(d)})},Object.defineProperty(o,"__esModule",{value:!0})});
diff --git a/dist/swetrix.orig.js b/dist/swetrix.orig.js
index 4837f3129..efdcddf30 100644
--- a/dist/swetrix.orig.js
+++ b/dist/swetrix.orig.js
@@ -97,7 +97,7 @@
return result;
};
- var defaultPageActions = {
+ var defaultActions = {
stop: function () { },
};
var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -107,11 +107,70 @@
this.options = options;
this.pageData = null;
this.pageViewsOptions = null;
+ this.errorsOptions = null;
this.perfStatsCollected = false;
this.activePage = null;
+ this.errorListenerExists = false;
this.trackPathChange = this.trackPathChange.bind(this);
this.heartbeat = this.heartbeat.bind(this);
+ this.captureError = this.captureError.bind(this);
}
+ Lib.prototype.captureError = function (event) {
+ var _a, _b, _c;
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
+ return;
+ }
+ this.submitError({
+ // The file in which error occured.
+ filename: event.filename,
+ // The line of code error occured on.
+ lineno: event.lineno,
+ // The column of code error occured on.
+ colno: event.colno,
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
+ // (we want to split error name and message so we could group them together later in dashboard).
+ // If message in error object does not exist - lets use a message from the Error event itself.
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
+ });
+ };
+ Lib.prototype.trackErrors = function (options) {
+ var _this = this;
+ if (this.errorListenerExists || !this.canTrack()) {
+ return defaultActions;
+ }
+ this.errorsOptions = options;
+ window.addEventListener('error', this.captureError);
+ this.errorListenerExists = true;
+ return {
+ stop: function () {
+ window.removeEventListener('error', _this.captureError);
+ },
+ };
+ };
+ Lib.prototype.submitError = function (payload, evokeCallback) {
+ var _a, _b, _c;
+ var privateData = {
+ pid: this.projectID,
+ };
+ var errorPayload = __assign({ pg: this.activePage ||
+ getPath({
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
+ }), lc: getLocale(), tz: getTimezone() }, payload);
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
+ var callbackResult = this.errorsOptions.callback(errorPayload);
+ if (callbackResult === false) {
+ return;
+ }
+ if (callbackResult && typeof callbackResult === 'object') {
+ Object.assign(errorPayload, callbackResult);
+ }
+ }
+ Object.assign(errorPayload, privateData);
+ this.sendRequest('error', errorPayload);
+ };
Lib.prototype.track = function (event) {
if (!this.canTrack()) {
return;
@@ -121,7 +180,7 @@
};
Lib.prototype.trackPageViews = function (options) {
if (!this.canTrack()) {
- return defaultPageActions;
+ return defaultActions;
}
if (this.pageData) {
return this.pageData.actions;
@@ -315,17 +374,15 @@
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.
+ * With this function you are able to automatically track pageviews across your application.
*
- * @param {PageViewsOptions} options The options related to the custom event.
+ * @param {PageViewsOptions} options Pageviews tracking options.
* @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);
+ resolve(defaultActions);
return;
}
// We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -340,6 +397,32 @@
}
});
}
+ /**
+ * 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 trackErrors(options) {
+ if (!exports.LIB_INSTANCE) {
+ return defaultActions;
+ }
+ return exports.LIB_INSTANCE.trackErrors(options);
+ }
+ /**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+ function trackError(payload) {
+ if (!exports.LIB_INSTANCE)
+ return;
+ exports.LIB_INSTANCE.submitError(payload, false);
+ }
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -357,6 +440,8 @@
exports.init = init;
exports.track = track;
+ exports.trackError = trackError;
+ exports.trackErrors = trackErrors;
exports.trackPageview = trackPageview;
exports.trackViews = trackViews;
diff --git a/src/Lib.ts b/src/Lib.ts
index cf14fc53a..1aefeb277 100644
--- a/src/Lib.ts
+++ b/src/Lib.ts
@@ -57,6 +57,21 @@ export interface IPageViewPayload {
prev: string | null | undefined
}
+// Partial user-editable error payload
+export interface IErrorEventPayload {
+ name: string
+ message: string | null | undefined
+ lineno: number | null | undefined
+ colno: number | null | undefined
+ filename: string | null | undefined
+}
+
+export interface IInternalErrorEventPayload extends IErrorEventPayload {
+ lc: string | undefined
+ tz: string | undefined
+ pg: string | null | undefined
+}
+
interface IPerfPayload {
dns: number
tls: number
@@ -76,6 +91,14 @@ export interface PageActions {
stop: () => void
}
+/**
+ * The object returned by `trackErrors()`, used to stop tracking errors.
+ */
+export interface ErrorActions {
+ /** Stops the tracking of errors. */
+ stop: () => void
+}
+
export interface PageData {
/** Current URL path. */
path: string
@@ -84,6 +107,25 @@ export interface PageData {
actions: PageActions
}
+export interface ErrorOptions {
+ /**
+ * A number that indicates how many errors should be sent to the server.
+ * Accepts values between 0 and 1. For example, if set to 0.5 - only ~50% of errors will be sent to Swetrix.
+ * For testing, we recommend setting this value to 1. For production, you should configure it depending on your needs as each error event counts towards your plan.
+ *
+ * The default value for this option is 1.
+ */
+ sampleRate?: number
+
+ /**
+ * Callback to edit / prevent sending errors.
+ *
+ * @param payload - The error payload.
+ * @returns The edited payload or `false` to prevent sending the error event. If `true` is returned, the payload will be sent as-is.
+ */
+ callback?: (payload: IInternalErrorEventPayload) => Partial<IInternalErrorEventPayload> | boolean
+}
+
export interface PageViewsOptions {
/**
* If set to `true`, only unique events will be saved.
@@ -115,7 +157,7 @@ export interface PageViewsOptions {
callback?: (payload: IPageViewPayload) => Partial<IPageViewPayload> | boolean
}
-export const defaultPageActions = {
+export const defaultActions = {
stop() {},
}
@@ -124,12 +166,91 @@ const DEFAULT_API_HOST = 'https://api.swetrix.com/log'
export class Lib {
private pageData: PageData | null = null
private pageViewsOptions: PageViewsOptions | null | undefined = null
+ private errorsOptions: ErrorOptions | null | undefined = null
private perfStatsCollected: Boolean = false
private activePage: string | null = null
+ private errorListenerExists = false
constructor(private projectID: string, private options?: LibOptions) {
this.trackPathChange = this.trackPathChange.bind(this)
this.heartbeat = this.heartbeat.bind(this)
+ this.captureError = this.captureError.bind(this)
+ }
+
+ captureError(event: ErrorEvent): void {
+ if (typeof this.errorsOptions?.sampleRate === 'number' && this.errorsOptions.sampleRate > Math.random()) {
+ return
+ }
+
+ this.submitError({
+ // The file in which error occured.
+ filename: event.filename,
+
+ // The line of code error occured on.
+ lineno: event.lineno,
+
+ // The column of code error occured on.
+ colno: event.colno,
+
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
+ name: event.error?.name || 'Error',
+
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
+ // (we want to split error name and message so we could group them together later in dashboard).
+ // If message in error object does not exist - lets use a message from the Error event itself.
+ message: event.error?.message || event.message,
+ })
+ }
+
+ trackErrors(options?: ErrorOptions): ErrorActions {
+ if (this.errorListenerExists || !this.canTrack()) {
+ return defaultActions
+ }
+
+ this.errorsOptions = options
+
+ window.addEventListener('error', this.captureError)
+ this.errorListenerExists = true
+
+ return {
+ stop: () => {
+ window.removeEventListener('error', this.captureError)
+ },
+ }
+ }
+
+ submitError(payload: IErrorEventPayload, evokeCallback?: boolean): void {
+ const privateData = {
+ pid: this.projectID,
+ }
+
+ const errorPayload = {
+ pg:
+ this.activePage ||
+ getPath({
+ hash: this.pageViewsOptions?.hash,
+ search: this.pageViewsOptions?.search,
+ }),
+ lc: getLocale(),
+ tz: getTimezone(),
+ ...payload,
+ }
+
+ if (evokeCallback && this.errorsOptions?.callback) {
+ const callbackResult = this.errorsOptions.callback(errorPayload)
+
+ if (callbackResult === false) {
+ return
+ }
+
+ if (callbackResult && typeof callbackResult === 'object') {
+ Object.assign(errorPayload, callbackResult)
+ }
+ }
+
+ Object.assign(errorPayload, privateData)
+
+ this.sendRequest('error', errorPayload)
}
track(event: TrackEventOptions): void {
@@ -153,7 +274,7 @@ export class Lib {
trackPageViews(options?: PageViewsOptions): PageActions {
if (!this.canTrack()) {
- return defaultPageActions
+ return defaultActions
}
if (this.pageData) {
diff --git a/src/index.ts b/src/index.ts
index ddaee8568..4a570a09a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,14 @@
-import { Lib, LibOptions, TrackEventOptions, PageViewsOptions, PageActions, defaultPageActions } from './Lib'
+import {
+ Lib,
+ LibOptions,
+ TrackEventOptions,
+ PageViewsOptions,
+ ErrorOptions,
+ PageActions,
+ ErrorActions,
+ defaultActions,
+ IErrorEventPayload,
+} from './Lib'
export let LIB_INSTANCE: Lib | null = null
@@ -31,17 +41,15 @@ export function track(event: TrackEventOptions): void {
}
/**
- * 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.
+ * With this function you are able to automatically track pageviews across your application.
*
- * @param {PageViewsOptions} options The options related to the custom event.
+ * @param {PageViewsOptions} options Pageviews tracking options.
* @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
*/
export function trackViews(options?: PageViewsOptions): Promise<PageActions> {
return new Promise((resolve) => {
if (!LIB_INSTANCE) {
- resolve(defaultPageActions)
+ resolve(defaultActions)
return
}
@@ -57,6 +65,35 @@ export function trackViews(options?: PageViewsOptions): Promise<PageActions> {
})
}
+/**
+ * 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.
+ */
+export function trackErrors(options?: ErrorOptions): ErrorActions {
+ if (!LIB_INSTANCE) {
+ return defaultActions
+ }
+
+ return LIB_INSTANCE.trackErrors(options)
+}
+
+/**
+ * This function is used to manually track an error event.
+ * It's useful if you want to track specific errors in your application.
+ *
+ * @param payload Swetrix error object to send.
+ * @returns void
+ */
+export function trackError(payload: IErrorEventPayload): void {
+ if (!LIB_INSTANCE) return
+
+ LIB_INSTANCE.submitError(payload, false)
+}
+
/**
* This function is used to manually track a page view event.
* It's useful if your application uses esoteric routing which is not supported by Swetrix by default.