app-tracker 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,78 +1,83 @@
1
-
2
-
3
- # App Tracker for Web & Node.js
4
-
5
- App Tracker is a TypeScript/JavaScript library for logging and tracking events in web and Node.js applications. It supports batching, flexible configuration, and sending logs to a central endpoint.
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm i app-tracker
11
- ```
12
-
13
- ## Registration & API Key
14
-
15
- - Register at [App Tracker](https://www.app-tracker.cloud/) and create an application to get your API key.
16
-
17
- ## Quick Start
18
-
19
- ```typescript
20
- import { AppTracker, AppTrackerService } from "app-tracker";
21
-
22
- const config = {
23
- userAgentOrOs: typeof window !== 'undefined' ? navigator.userAgent : require('os'),
24
- logInConsole: true,
25
- sendLogsInDevelopment: true,
26
- // more options below
27
- };
28
- const tracker: AppTrackerService = AppTracker.init("API_KEY", config);
29
-
30
- tracker.debug("Debug message", { foo: "bar" });
31
- tracker.error("An error occurred", errorObj);
32
- ```
33
-
34
- ## Configuration
35
-
36
- | Property | Type | Default | Description |
37
- |-----------------------------|--------------|--------------------------------|-------------|
38
- | sendLogsInDevelopment | boolean | false | Send logs during development |
39
- | logInConsole | boolean | false | Also log to the console |
40
- | endpointUrl | string | https://app-tracker-api.azurewebsites.net/ | Target endpoint for logs |
41
- | maxSendTries | number | 5 | Max. send attempts on error |
42
- | maxLogsCount | number | 10 | Batch size for sending logs |
43
- | logLevel | LogType[] | [LogType.error] | Which log types are sent |
44
- | sendLogsByTypesImmediately | LogType[] | [LogType.error, LogType.critical] | Types sent immediately |
45
- | userAgentOrOs | any | | Browser: navigator.userAgent, Node: require('os') |
46
-
47
- **LogType:** `debug`, `info`, `log`, `warn`, `error`, `critical`
48
-
49
- ## Architecture & Features
50
-
51
- - **Singleton Service:** Always access via `AppTracker.init()` or `AppTracker.getService()`
52
- - **Batching:** Logs are collected and sent after `maxLogsCount` or immediately for critical errors
53
- - **Environment Awareness:** Automatically adapts for browser/Node.js
54
- - **Secure Sending:** API key required, retry mechanism on errors
55
- - **External Dependency:** Uses `cross-fetch` for HTTP requests
56
-
57
- ## Build & Development
58
-
59
- - **Build:** `npm run build` (TypeScript compile & copy to `lib/`)
60
- - **Minify:** `npm run terser` (Terser minification of JS files)
61
- - **Lint:** `npm run lint` (TSLint)
62
- - **Format:** `npm run format` (Prettier)
63
-
64
- ## FAQ
65
-
66
- **Where do I get my API key?**
67
- > Register at https://www.app-tracker.cloud/ and create an application.
68
-
69
- **How can I suppress logs in development?**
70
- > Set `sendLogsInDevelopment: false` in the configuration.
71
-
72
- **How do I send custom log types?**
73
- > Use the `debug`, `info`, `warn`, `error`, `critical` methods of the service object.
74
-
75
- ## Further Information
76
- - See `src/app-tracker.service.ts` for service logic
77
- - See `src/log.ts` for configuration and log types
78
- - See `.github/copilot-instructions.md` for developer guidelines
1
+
2
+
3
+ # App Tracker for Web & Node.js
4
+
5
+ App Tracker is a TypeScript/JavaScript library for logging and tracking events in web and Node.js applications. It supports batching, flexible configuration, and sending logs to a central endpoint.
6
+
7
+ Runtime support: Node.js 16 or newer and modern browsers with `fetch`/XHR, `Promise`, and `WeakSet`. Missing browser storage or `sendBeacon` support is handled with fallbacks.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm i app-tracker
13
+ ```
14
+
15
+ ## Registration & API Key
16
+
17
+ - Register at [App Tracker](https://www.app-tracker.cloud/) and create an application to get your API key.
18
+
19
+ ## Quick Start
20
+
21
+ ```typescript
22
+ import { AppTracker, AppTrackerService } from "app-tracker";
23
+
24
+ const config = {
25
+ userAgentOrOs: typeof window !== 'undefined' ? navigator.userAgent : require('os'),
26
+ logInConsole: true,
27
+ sendLogsInDevelopment: true,
28
+ // more options below
29
+ };
30
+ const tracker: AppTrackerService = AppTracker.init("API_KEY", config);
31
+
32
+ tracker.debug("Debug message", { foo: "bar" });
33
+ tracker.error("An error occurred", errorObj);
34
+ ```
35
+
36
+ ## Configuration
37
+
38
+ | Property | Type | Default | Description |
39
+ |-----------------------------|--------------|--------------------------------|-------------|
40
+ | sendLogsInDevelopment | boolean | false | Send logs during development |
41
+ | logInConsole | boolean | false | Also log to the console |
42
+ | endpointUrl | string | https://app-tracker-api.azurewebsites.net/ | Target endpoint for logs |
43
+ | maxSendTries | number | 5 | Max. send attempts on error |
44
+ | retryDelayMs | number | 10000 | Delay between send attempts in milliseconds |
45
+ | requestTimeoutMs | number | 10000 | Timeout for each HTTP attempt in milliseconds |
46
+ | maxLogsCount | number | 10 | Batch size for sending logs |
47
+ | logLevel | LogType[] | [LogType.error] | Which log types are sent |
48
+ | sendLogsByTypesImmediately | LogType[] | [LogType.error, LogType.critical] | Types sent immediately |
49
+ | userAgentOrOs | any | | Browser: navigator.userAgent, Node: require('os') |
50
+
51
+ **LogType:** `debug`, `info`, `log`, `warn`, `error`, `critical`
52
+
53
+ ## Architecture & Features
54
+
55
+ - **Singleton Service:** Always access via `AppTracker.init()` or `AppTracker.getService()`
56
+ - **Batching:** Logs are collected and sent after `maxLogsCount` or immediately for critical errors
57
+ - **Explicit flush:** Call and await `tracker.flush()` before a controlled Node.js shutdown
58
+ - **Environment Awareness:** Automatically adapts for browser/Node.js
59
+ - **Secure Sending:** API key required, retry mechanism on errors
60
+ - **External Dependency:** Uses `cross-fetch` for HTTP requests
61
+
62
+ ## Build & Development
63
+
64
+ - **Build:** `npm run build` (TypeScript compile & copy to `lib/`)
65
+ - **Minify:** `npm run terser` (Terser minification of JS files)
66
+ - **Lint:** `npm run lint` (TSLint)
67
+ - **Format:** `npm run format` (Prettier)
68
+
69
+ ## FAQ
70
+
71
+ **Where do I get my API key?**
72
+ > Register at https://www.app-tracker.cloud/ and create an application.
73
+
74
+ **How can I suppress logs in development?**
75
+ > Set `sendLogsInDevelopment: false` in the configuration.
76
+
77
+ **How do I send custom log types?**
78
+ > Use the `debug`, `info`, `warn`, `error`, `critical` methods of the service object.
79
+
80
+ ## Further Information
81
+ - See `src/app-tracker.service.ts` for service logic
82
+ - See `src/log.ts` for configuration and log types
83
+ - See `.github/copilot-instructions.md` for developer guidelines
@@ -1,40 +1,48 @@
1
- import { AppTrackerConfig } from './log';
2
- export declare class AppTrackerService {
3
- private sendLogsInDevelopment;
4
- private logInConsole;
5
- private endpointUrl;
6
- private apiKey;
7
- private logs;
8
- private sendTries;
9
- private maxSendTries;
10
- private isSending;
11
- private maxLogsCount;
12
- private userAgent;
13
- private logLevel;
14
- private sendLogsByTypesImmediately;
15
- private isNode;
16
- private os;
17
- private isRunningLocal;
18
- private ident;
19
- private eventListenerAdded;
20
- private _boundBeforeUnloadHandler?;
21
- init(apiKey: string, config?: AppTrackerConfig): void;
22
- private addEventListener;
23
- private removeEventListener;
24
- private beforeunloadHandler;
25
- private setRunningSystem;
26
- getIdent(): string;
27
- debug(message?: string, ...optionalParams: any[]): void;
28
- info(message?: string, ...optionalParams: any[]): void;
29
- log(message?: string, ...optionalParams: any[]): void;
30
- warn(message?: string, ...optionalParams: any[]): void;
31
- error(message?: string, ...optionalParams: any[]): void;
32
- critical(message?: string, ...optionalParams: any[]): void;
33
- private addLog;
34
- private logToConsole;
35
- private sendLogsToServer;
36
- private checkLogType;
37
- private sendLogsToServerCore;
38
- private setUserAgentFromOs;
39
- private createUUID;
40
- }
1
+ import { AppTrackerConfig } from './log';
2
+ export declare class AppTrackerService {
3
+ private sendLogsInDevelopment;
4
+ private logInConsole;
5
+ private endpointUrl;
6
+ private apiKey;
7
+ private logs;
8
+ private maxSendTries;
9
+ private retryDelayMs;
10
+ private requestTimeoutMs;
11
+ private isSending;
12
+ private activeSend?;
13
+ private maxLogsCount;
14
+ private userAgent;
15
+ private logLevel;
16
+ private sendLogsByTypesImmediately;
17
+ private isNode;
18
+ private nodeProcess;
19
+ private os;
20
+ private isRunningLocal;
21
+ private ident;
22
+ private eventListenerAdded;
23
+ private _boundBeforeUnloadHandler?;
24
+ init(apiKey: string, config?: AppTrackerConfig): void;
25
+ private addEventListener;
26
+ private removeEventListener;
27
+ private beforeunloadHandler;
28
+ private setRunningSystem;
29
+ getIdent(): string;
30
+ debug(message?: string, ...optionalParams: any[]): void;
31
+ info(message?: string, ...optionalParams: any[]): void;
32
+ log(message?: string, ...optionalParams: any[]): void;
33
+ warn(message?: string, ...optionalParams: any[]): void;
34
+ error(message?: string, ...optionalParams: any[]): void;
35
+ critical(message?: string, ...optionalParams: any[]): void;
36
+ private addLog;
37
+ private logToConsole;
38
+ private sendLogsToServer;
39
+ private checkLogType;
40
+ /** Sends all currently queued logs and any logs added while sending. */
41
+ flush(): Promise<void>;
42
+ private runSendLoop;
43
+ private sendLogsToServerCore;
44
+ private getLogsEndpoint;
45
+ private serializePayload;
46
+ private setUserAgentFromOs;
47
+ private createUUID;
48
+ }
@@ -1,247 +1,332 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const log_1 = require("./log");
13
- const cross_fetch_1 = require("cross-fetch");
14
- const safeFetch = typeof window !== 'undefined' ? cross_fetch_1.default.bind(window) : cross_fetch_1.default;
15
- class AppTrackerService {
16
- constructor() {
17
- this.sendLogsInDevelopment = false;
18
- this.logInConsole = false;
19
- this.endpointUrl = 'https://app-tracker-api.azurewebsites.net/';
20
- this.apiKey = '';
21
- this.logs = [];
22
- this.sendTries = 0;
23
- this.maxSendTries = 5;
24
- this.isSending = false;
25
- this.maxLogsCount = 10;
26
- this.userAgent = '';
27
- this.logLevel = [log_1.LogType.error];
28
- this.sendLogsByTypesImmediately = [log_1.LogType.error, log_1.LogType.critical];
29
- this.isNode = false;
30
- this.isRunningLocal = true;
31
- this.ident = '';
32
- this.eventListenerAdded = false;
33
- }
34
- init(apiKey, config) {
35
- this.apiKey = apiKey;
36
- if (config) {
37
- if (typeof config.endpointUrl !== 'undefined')
38
- this.endpointUrl = config.endpointUrl;
39
- if (typeof config.maxLogsCount !== 'undefined')
40
- this.maxLogsCount = config.maxLogsCount;
41
- if (typeof config.maxSendTries !== 'undefined')
42
- this.maxSendTries = config.maxSendTries;
43
- if (typeof config.sendLogsInDevelopment !== 'undefined')
44
- this.sendLogsInDevelopment = config.sendLogsInDevelopment;
45
- if (typeof config.logInConsole !== 'undefined')
46
- this.logInConsole = config.logInConsole;
47
- if (typeof config.logLevel !== 'undefined')
48
- this.logLevel = config.logLevel;
49
- if (typeof config.sendLogsByTypesImmediately !== 'undefined')
50
- this.sendLogsByTypesImmediately = config.sendLogsByTypesImmediately;
51
- }
52
- this.setRunningSystem(config);
53
- }
54
- addEventListener(apiKey) {
55
- if (apiKey != '' && !this.isNode && !this.isRunningLocal && !this.eventListenerAdded) {
56
- this._boundBeforeUnloadHandler = this._boundBeforeUnloadHandler || ((e) => this.beforeunloadHandler(e));
57
- window.addEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
58
- this.eventListenerAdded = true;
59
- }
60
- }
61
- removeEventListener(apiKey) {
62
- if (apiKey != '' && !this.isNode && !this.isRunningLocal && this.eventListenerAdded) {
63
- if (this._boundBeforeUnloadHandler) {
64
- window.removeEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
65
- }
66
- this.eventListenerAdded = false;
67
- }
68
- }
69
- beforeunloadHandler(event) {
70
- event.preventDefault();
71
- event.returnValue = '';
72
- if (!this.isSending) {
73
- const logsToSend = this.logs;
74
- this.isSending = true;
75
- this.logs = [];
76
- this.sendLogsToServerCore(logsToSend);
77
- }
78
- }
79
- setRunningSystem(config) {
80
- var _a, _b, _c;
81
- this.isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
82
- if (!this.isNode) {
83
- this.userAgent = (_a = config) === null || _a === void 0 ? void 0 : _a.userAgentOrOs;
84
- this.ident = this.getIdent();
85
- }
86
- else {
87
- this.os = (_b = config) === null || _b === void 0 ? void 0 : _b.userAgentOrOs;
88
- this.userAgent = this.setUserAgentFromOs();
89
- }
90
- this.isRunningLocal = this.isNode ? (_c = process.env.NODE_ENV, (_c !== null && _c !== void 0 ? _c : '')).indexOf("development") > -1 : window.location.href.indexOf('localhost') > -1;
91
- }
92
- getIdent() {
93
- var _a;
94
- let ident = (_a = localStorage) === null || _a === void 0 ? void 0 : _a.getItem('App-Tracker.device-ident');
95
- if (!ident) {
96
- ident = this.createUUID();
97
- localStorage.setItem('App-Tracker.device-ident', ident);
98
- }
99
- return ident;
100
- }
101
- debug(message, ...optionalParams) {
102
- this.addLog(log_1.LogType.debug, message, ...optionalParams);
103
- }
104
- info(message, ...optionalParams) {
105
- this.addLog(log_1.LogType.info, message, ...optionalParams);
106
- }
107
- log(message, ...optionalParams) {
108
- this.addLog(log_1.LogType.log, message, ...optionalParams);
109
- }
110
- warn(message, ...optionalParams) {
111
- this.addLog(log_1.LogType.warn, message, ...optionalParams);
112
- }
113
- error(message, ...optionalParams) {
114
- this.addLog(log_1.LogType.error, message, ...optionalParams);
115
- }
116
- critical(message, ...optionalParams) {
117
- this.addLog(log_1.LogType.critical, message, ...optionalParams);
118
- }
119
- addLog(type, message, ...optionalParams) {
120
- if (this.checkLogType(type)) {
121
- if (this.isRunningLocal && !this.sendLogsInDevelopment) {
122
- this.logToConsole(type, message, ...optionalParams);
123
- }
124
- else {
125
- this.sendLogsToServer(type, message, ...optionalParams);
126
- }
127
- }
128
- else {
129
- this.logToConsole(type, message, ...optionalParams);
130
- }
131
- }
132
- logToConsole(type, message, ...optionalParams) {
133
- if (this.logInConsole) {
134
- switch (type) {
135
- case log_1.LogType.debug:
136
- console.debug(message, ...optionalParams);
137
- break;
138
- case log_1.LogType.critical:
139
- case log_1.LogType.error:
140
- console.error(message, ...optionalParams);
141
- break;
142
- case log_1.LogType.info:
143
- console.info(message, ...optionalParams);
144
- break;
145
- case log_1.LogType.log:
146
- console.log(message, ...optionalParams);
147
- break;
148
- case log_1.LogType.warn:
149
- console.warn(message, ...optionalParams);
150
- break;
151
- default:
152
- console.warn("Unkown LogType: ", type);
153
- break;
154
- }
155
- }
156
- }
157
- sendLogsToServer(type, message, ...optionalParams) {
158
- var _a, _b;
159
- const log = { logType: type, message: message, optionalParams: [], createdAt: new Date(), ident: this.ident };
160
- optionalParams.forEach((op) => {
161
- if (Array.isArray(op))
162
- op.forEach(o => log.optionalParams.push(o));
163
- else
164
- log.optionalParams.push(op);
165
- });
166
- this.logs.push(log);
167
- if ((this.logs.length >= this.maxLogsCount && !this.isSending) ||
168
- ((((_a = this.sendLogsByTypesImmediately) === null || _a === void 0 ? void 0 : _a.find(l => l == type)) || type == log_1.LogType.critical) != null && !this.isSending)) {
169
- const logsToSend = this.logs;
170
- this.logs = [];
171
- this.isSending = true;
172
- this.sendLogsToServerCore(logsToSend);
173
- this.removeEventListener(this.apiKey);
174
- }
175
- if (((_b = this.logs) === null || _b === void 0 ? void 0 : _b.length) > 0 && !this.eventListenerAdded) {
176
- this.addEventListener(this.apiKey);
177
- }
178
- }
179
- checkLogType(type) {
180
- if (this.logLevel.find(l => l === type) != null || type === log_1.LogType.critical) {
181
- return true;
182
- }
183
- else {
184
- return false;
185
- }
186
- }
187
- sendLogsToServerCore(logsToSend) {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- if (this.sendTries < this.maxSendTries) {
190
- try {
191
- const last = this.endpointUrl.charAt(this.endpointUrl.length - 1);
192
- const response = yield safeFetch(`${this.endpointUrl}${last === '/' ? 'logs/createLog' : '/logs/createLog'}`, {
193
- method: 'POST',
194
- headers: {
195
- 'Accept': 'application/json',
196
- 'Content-Type': 'application/json',
197
- 'X-Auth-Key': this.apiKey
198
- },
199
- body: JSON.stringify({ logs: logsToSend, userAgent: this.userAgent }, (key, value) => {
200
- if (value instanceof Error) {
201
- let error = {};
202
- Object.getOwnPropertyNames(value).forEach(function (key) {
203
- error[key] = value[key];
204
- });
205
- return error;
206
- }
207
- return value;
208
- })
209
- });
210
- logsToSend = [];
211
- this.isSending = false;
212
- this.sendTries = 0; // Reset sendTries after successful send
213
- }
214
- catch (error) {
215
- console.error(`AppLogger: Could not send Logs to Server try ${this.sendTries}`, error);
216
- this.sendTries++;
217
- // Warten, bevor der nächste asynchrone Versuch gestartet wird
218
- yield new Promise(resolve => setTimeout(resolve, 10000));
219
- yield this.sendLogsToServerCore(logsToSend);
220
- }
221
- }
222
- else {
223
- this.sendTries = 0;
224
- this.isSending = false;
225
- console.error('AppLogger: Could not send Logs to Server finally');
226
- }
227
- });
228
- }
229
- setUserAgentFromOs() {
230
- const osInfo = {
231
- arch: this.os.arch(),
232
- platform: this.os.platform(),
233
- release: this.os.release(),
234
- type: this.os.type(),
235
- version: this.os.version(),
236
- hostname: this.os.hostname()
237
- };
238
- return JSON.stringify(osInfo);
239
- }
240
- createUUID() {
241
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
242
- const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
243
- return v.toString(16);
244
- });
245
- }
246
- }
247
- exports.AppTrackerService = AppTrackerService;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const log_1 = require("./log");
13
+ const cross_fetch_1 = require("cross-fetch");
14
+ const version_1 = require("./version");
15
+ const safeFetch = typeof window !== 'undefined' ? cross_fetch_1.default.bind(window) : cross_fetch_1.default;
16
+ class AppTrackerService {
17
+ constructor() {
18
+ this.sendLogsInDevelopment = false;
19
+ this.logInConsole = false;
20
+ this.endpointUrl = 'https://app-tracker-api.azurewebsites.net/';
21
+ this.apiKey = '';
22
+ this.logs = [];
23
+ this.maxSendTries = 5;
24
+ this.retryDelayMs = 10000;
25
+ this.requestTimeoutMs = 10000;
26
+ this.isSending = false;
27
+ this.maxLogsCount = 10;
28
+ this.userAgent = '';
29
+ this.logLevel = [log_1.LogType.error];
30
+ this.sendLogsByTypesImmediately = [log_1.LogType.error, log_1.LogType.critical];
31
+ this.isNode = false;
32
+ this.isRunningLocal = true;
33
+ this.ident = '';
34
+ this.eventListenerAdded = false;
35
+ }
36
+ init(apiKey, config) {
37
+ this.apiKey = apiKey;
38
+ if (config) {
39
+ if (typeof config.endpointUrl !== 'undefined')
40
+ this.endpointUrl = config.endpointUrl;
41
+ if (typeof config.maxLogsCount !== 'undefined')
42
+ this.maxLogsCount = config.maxLogsCount;
43
+ if (typeof config.maxSendTries !== 'undefined')
44
+ this.maxSendTries = Math.max(1, config.maxSendTries);
45
+ if (typeof config.retryDelayMs !== 'undefined')
46
+ this.retryDelayMs = Math.max(0, config.retryDelayMs);
47
+ if (typeof config.requestTimeoutMs !== 'undefined')
48
+ this.requestTimeoutMs = Math.max(1, config.requestTimeoutMs);
49
+ if (typeof config.sendLogsInDevelopment !== 'undefined')
50
+ this.sendLogsInDevelopment = config.sendLogsInDevelopment;
51
+ if (typeof config.logInConsole !== 'undefined')
52
+ this.logInConsole = config.logInConsole;
53
+ if (typeof config.logLevel !== 'undefined')
54
+ this.logLevel = config.logLevel;
55
+ if (typeof config.sendLogsByTypesImmediately !== 'undefined')
56
+ this.sendLogsByTypesImmediately = config.sendLogsByTypesImmediately;
57
+ }
58
+ this.setRunningSystem(config);
59
+ }
60
+ addEventListener(apiKey) {
61
+ if (apiKey != '' && !this.isNode && !this.isRunningLocal && !this.eventListenerAdded) {
62
+ this._boundBeforeUnloadHandler = this._boundBeforeUnloadHandler || ((e) => this.beforeunloadHandler(e));
63
+ window.addEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
64
+ this.eventListenerAdded = true;
65
+ }
66
+ }
67
+ removeEventListener(apiKey) {
68
+ if (apiKey != '' && !this.isNode && !this.isRunningLocal && this.eventListenerAdded) {
69
+ if (this._boundBeforeUnloadHandler) {
70
+ window.removeEventListener('beforeunload', this._boundBeforeUnloadHandler, true);
71
+ }
72
+ this.eventListenerAdded = false;
73
+ }
74
+ }
75
+ beforeunloadHandler(_event) {
76
+ if (this.logs.length === 0)
77
+ return;
78
+ const logsToSend = this.logs.splice(0);
79
+ const body = this.serializePayload(logsToSend, true);
80
+ const url = this.getLogsEndpoint();
81
+ // sendBeacon is specifically designed to survive page termination. The API
82
+ // key is also accepted in the request body by the server's ApiKeyGuard.
83
+ // text/plain keeps a cross-origin beacon CORS-safelisted; the API explicitly
84
+ // enables JSON parsing for this content type.
85
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
86
+ const accepted = navigator.sendBeacon(url, new Blob([body], { type: 'text/plain;charset=UTF-8' }));
87
+ if (accepted)
88
+ return;
89
+ }
90
+ // Keep the logs queued if the browser could not schedule the beacon. A
91
+ // keepalive fetch is the best available fallback during page termination.
92
+ this.logs.unshift(...logsToSend);
93
+ void this.flush();
94
+ }
95
+ setRunningSystem(config) {
96
+ var _a, _b, _c, _d, _e;
97
+ this.nodeProcess = typeof globalThis !== 'undefined' ? globalThis.process : undefined;
98
+ this.isNode = Object.prototype.toString.call(this.nodeProcess || 0) === '[object process]';
99
+ if (!this.isNode) {
100
+ this.userAgent = (_a = config) === null || _a === void 0 ? void 0 : _a.userAgentOrOs;
101
+ this.ident = this.getIdent();
102
+ }
103
+ else {
104
+ this.os = (_b = config) === null || _b === void 0 ? void 0 : _b.userAgentOrOs;
105
+ this.userAgent = this.setUserAgentFromOs();
106
+ }
107
+ this.isRunningLocal = this.isNode
108
+ ? (_e = (_d = (_c = this.nodeProcess) === null || _c === void 0 ? void 0 : _c.env) === null || _d === void 0 ? void 0 : _d.NODE_ENV, (_e !== null && _e !== void 0 ? _e : '')).indexOf("development") > -1
109
+ : window.location.href.indexOf('localhost') > -1;
110
+ }
111
+ getIdent() {
112
+ try {
113
+ let ident = localStorage.getItem('App-Tracker.device-ident');
114
+ if (!ident) {
115
+ ident = this.createUUID();
116
+ localStorage.setItem('App-Tracker.device-ident', ident);
117
+ }
118
+ return ident;
119
+ }
120
+ catch (_) {
121
+ // Storage can be unavailable in sandboxed iframes or privacy modes.
122
+ return this.createUUID();
123
+ }
124
+ }
125
+ debug(message, ...optionalParams) {
126
+ this.addLog(log_1.LogType.debug, message, ...optionalParams);
127
+ }
128
+ info(message, ...optionalParams) {
129
+ this.addLog(log_1.LogType.info, message, ...optionalParams);
130
+ }
131
+ log(message, ...optionalParams) {
132
+ this.addLog(log_1.LogType.log, message, ...optionalParams);
133
+ }
134
+ warn(message, ...optionalParams) {
135
+ this.addLog(log_1.LogType.warn, message, ...optionalParams);
136
+ }
137
+ error(message, ...optionalParams) {
138
+ this.addLog(log_1.LogType.error, message, ...optionalParams);
139
+ }
140
+ critical(message, ...optionalParams) {
141
+ this.addLog(log_1.LogType.critical, message, ...optionalParams);
142
+ }
143
+ addLog(type, message, ...optionalParams) {
144
+ if (this.checkLogType(type)) {
145
+ if (this.isRunningLocal && !this.sendLogsInDevelopment) {
146
+ this.logToConsole(type, message, ...optionalParams);
147
+ }
148
+ else {
149
+ this.sendLogsToServer(type, message, ...optionalParams);
150
+ }
151
+ }
152
+ else {
153
+ this.logToConsole(type, message, ...optionalParams);
154
+ }
155
+ }
156
+ logToConsole(type, message, ...optionalParams) {
157
+ if (this.logInConsole) {
158
+ switch (type) {
159
+ case log_1.LogType.debug:
160
+ console.debug(message, ...optionalParams);
161
+ break;
162
+ case log_1.LogType.critical:
163
+ case log_1.LogType.error:
164
+ console.error(message, ...optionalParams);
165
+ break;
166
+ case log_1.LogType.info:
167
+ console.info(message, ...optionalParams);
168
+ break;
169
+ case log_1.LogType.log:
170
+ console.log(message, ...optionalParams);
171
+ break;
172
+ case log_1.LogType.warn:
173
+ console.warn(message, ...optionalParams);
174
+ break;
175
+ default:
176
+ console.warn("Unkown LogType: ", type);
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ sendLogsToServer(type, message, ...optionalParams) {
182
+ var _a, _b;
183
+ const log = { logType: type, message: message, optionalParams: [], createdAt: new Date(), ident: this.ident };
184
+ optionalParams.forEach((op) => {
185
+ if (Array.isArray(op))
186
+ op.forEach(o => log.optionalParams.push(o));
187
+ else
188
+ log.optionalParams.push(op);
189
+ });
190
+ this.logs.push(log);
191
+ const sendImmediately = type === log_1.LogType.critical || ((_a = this.sendLogsByTypesImmediately) === null || _a === void 0 ? void 0 : _a.includes(type)) === true;
192
+ if (this.logs.length >= this.maxLogsCount || sendImmediately)
193
+ void this.flush();
194
+ if (((_b = this.logs) === null || _b === void 0 ? void 0 : _b.length) > 0 && !this.eventListenerAdded) {
195
+ this.addEventListener(this.apiKey);
196
+ }
197
+ }
198
+ checkLogType(type) {
199
+ if (this.logLevel.find(l => l === type) != null || type === log_1.LogType.critical) {
200
+ return true;
201
+ }
202
+ else {
203
+ return false;
204
+ }
205
+ }
206
+ /** Sends all currently queued logs and any logs added while sending. */
207
+ flush() {
208
+ if (this.activeSend)
209
+ return this.activeSend;
210
+ if (this.logs.length === 0)
211
+ return Promise.resolve();
212
+ this.isSending = true;
213
+ this.removeEventListener(this.apiKey);
214
+ this.activeSend = this.runSendLoop();
215
+ return this.activeSend;
216
+ }
217
+ runSendLoop() {
218
+ return __awaiter(this, void 0, void 0, function* () {
219
+ try {
220
+ while (this.logs.length > 0) {
221
+ const logsToSend = this.logs.splice(0);
222
+ const sent = yield this.sendLogsToServerCore(logsToSend);
223
+ if (!sent) {
224
+ // Preserve the failed batch for a later explicit flush or log event.
225
+ this.logs.unshift(...logsToSend);
226
+ return;
227
+ }
228
+ }
229
+ }
230
+ finally {
231
+ this.isSending = false;
232
+ this.activeSend = undefined;
233
+ if (this.logs.length > 0)
234
+ this.addEventListener(this.apiKey);
235
+ }
236
+ });
237
+ }
238
+ sendLogsToServerCore(logsToSend) {
239
+ var _a;
240
+ return __awaiter(this, void 0, void 0, function* () {
241
+ for (let sendTry = 1; sendTry <= this.maxSendTries; sendTry++) {
242
+ const abortController = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
243
+ const timeout = abortController ? setTimeout(() => abortController.abort(), this.requestTimeoutMs) : undefined;
244
+ try {
245
+ const body = this.serializePayload(logsToSend);
246
+ const response = yield safeFetch(this.getLogsEndpoint(), {
247
+ method: 'POST',
248
+ headers: {
249
+ 'Accept': 'application/json',
250
+ 'Content-Type': 'application/json',
251
+ 'X-Auth-Key': this.apiKey
252
+ },
253
+ body,
254
+ signal: (_a = abortController) === null || _a === void 0 ? void 0 : _a.signal,
255
+ // Browsers impose a small quota on keepalive requests.
256
+ keepalive: body.length <= 60000
257
+ });
258
+ if (!response.ok)
259
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
260
+ return true;
261
+ }
262
+ catch (error) {
263
+ console.error(`AppLogger: Could not send logs to server (attempt ${sendTry}/${this.maxSendTries})`, error);
264
+ if (sendTry < this.maxSendTries)
265
+ yield new Promise(resolve => setTimeout(resolve, this.retryDelayMs));
266
+ }
267
+ finally {
268
+ if (timeout !== undefined)
269
+ clearTimeout(timeout);
270
+ }
271
+ }
272
+ console.error('AppLogger: Could not send logs to server finally; batch remains queued');
273
+ return false;
274
+ });
275
+ }
276
+ getLogsEndpoint() {
277
+ const last = this.endpointUrl.charAt(this.endpointUrl.length - 1);
278
+ return `${this.endpointUrl}${last === '/' ? 'logs/createLog' : '/logs/createLog'}`;
279
+ }
280
+ serializePayload(logsToSend, includeApiKey = false) {
281
+ const seen = new WeakSet();
282
+ const payload = {
283
+ ident: this.ident,
284
+ logs: logsToSend,
285
+ osType: this.isNode ? 'node' : 'web',
286
+ packageVersion: version_1.APP_TRACKER_VERSION,
287
+ userAgent: this.userAgent
288
+ };
289
+ if (includeApiKey)
290
+ payload.apiKey = this.apiKey;
291
+ return JSON.stringify(payload, (_key, value) => {
292
+ if (value instanceof Error) {
293
+ if (seen.has(value))
294
+ return '[Circular]';
295
+ seen.add(value);
296
+ const serializedError = {};
297
+ Object.getOwnPropertyNames(value).forEach(key => serializedError[key] = value[key]);
298
+ return serializedError;
299
+ }
300
+ if (typeof value === 'bigint')
301
+ return value.toString();
302
+ if (value && typeof value === 'object') {
303
+ if (seen.has(value))
304
+ return '[Circular]';
305
+ seen.add(value);
306
+ }
307
+ return value;
308
+ });
309
+ }
310
+ setUserAgentFromOs() {
311
+ var _a, _b;
312
+ if (!this.os) {
313
+ return JSON.stringify({ platform: (_a = this.nodeProcess) === null || _a === void 0 ? void 0 : _a.platform, version: (_b = this.nodeProcess) === null || _b === void 0 ? void 0 : _b.version });
314
+ }
315
+ const osInfo = {
316
+ arch: this.os.arch(),
317
+ platform: this.os.platform(),
318
+ release: this.os.release(),
319
+ type: this.os.type(),
320
+ version: this.os.version(),
321
+ hostname: this.os.hostname()
322
+ };
323
+ return JSON.stringify(osInfo);
324
+ }
325
+ createUUID() {
326
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
327
+ const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
328
+ return v.toString(16);
329
+ });
330
+ }
331
+ }
332
+ exports.AppTrackerService = AppTrackerService;
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export * from './main';
2
- export * from './app-tracker.service';
3
- export * from './log';
1
+ export * from './main';
2
+ export * from './app-tracker.service';
3
+ export * from './log';
4
+ export * from './version';
package/index.js CHANGED
@@ -1,8 +1,9 @@
1
- "use strict";
2
- function __export(m) {
3
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
- }
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- __export(require("./main"));
7
- __export(require("./app-tracker.service"));
8
- __export(require("./log"));
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ __export(require("./main"));
7
+ __export(require("./app-tracker.service"));
8
+ __export(require("./log"));
9
+ __export(require("./version"));
package/log.d.ts CHANGED
@@ -1,32 +1,36 @@
1
- export declare class AppTrackerConfig {
2
- /** Should logs in the development environment be sent to the server. For Node enviroment process.env.NODE_ENV must be set to 'development' */
3
- sendLogsInDevelopment?: boolean;
4
- logInConsole?: boolean;
5
- endpointUrl?: string;
6
- maxSendTries?: number;
7
- maxLogsCount?: number;
8
- /** Defines which log types should be sent to the server */
9
- logLevel?: LogType[];
10
- sendLogsByTypesImmediately?: LogType[];
11
- /**
12
- * Please pass:
13
- * Web -> navigator.userAgent,
14
- * Node -> os (from require('os'))
15
- */
16
- userAgentOrOs: any;
17
- }
18
- export declare class Log {
19
- logType: LogType;
20
- message: any;
21
- optionalParams: any[];
22
- createdAt: Date;
23
- ident: string;
24
- }
25
- export declare enum LogType {
26
- debug = 0,
27
- info = 1,
28
- log = 2,
29
- warn = 3,
30
- error = 4,
31
- critical = 5
32
- }
1
+ export declare class AppTrackerConfig {
2
+ /** Should logs in the development environment be sent to the server. For Node enviroment process.env.NODE_ENV must be set to 'development' */
3
+ sendLogsInDevelopment?: boolean;
4
+ logInConsole?: boolean;
5
+ endpointUrl?: string;
6
+ maxSendTries?: number;
7
+ /** Delay between send attempts. */
8
+ retryDelayMs?: number;
9
+ /** Maximum duration of a single request before it is aborted. */
10
+ requestTimeoutMs?: number;
11
+ maxLogsCount?: number;
12
+ /** Defines which log types should be sent to the server */
13
+ logLevel?: LogType[];
14
+ sendLogsByTypesImmediately?: LogType[];
15
+ /**
16
+ * Please pass:
17
+ * Web -> navigator.userAgent,
18
+ * Node -> os (from require('os'))
19
+ */
20
+ userAgentOrOs: any;
21
+ }
22
+ export declare class Log {
23
+ logType: LogType;
24
+ message: any;
25
+ optionalParams: any[];
26
+ createdAt: Date;
27
+ ident: string;
28
+ }
29
+ export declare enum LogType {
30
+ debug = 0,
31
+ info = 1,
32
+ log = 2,
33
+ warn = 3,
34
+ error = 4,
35
+ critical = 5
36
+ }
package/log.js CHANGED
@@ -1,27 +1,31 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class AppTrackerConfig {
4
- constructor() {
5
- this.maxLogsCount = 5;
6
- this.sendLogsByTypesImmediately = [LogType.error];
7
- }
8
- }
9
- exports.AppTrackerConfig = AppTrackerConfig;
10
- class Log {
11
- constructor() {
12
- this.logType = LogType.log;
13
- this.optionalParams = [];
14
- this.createdAt = new Date();
15
- this.ident = '';
16
- }
17
- }
18
- exports.Log = Log;
19
- var LogType;
20
- (function (LogType) {
21
- LogType[LogType["debug"] = 0] = "debug";
22
- LogType[LogType["info"] = 1] = "info";
23
- LogType[LogType["log"] = 2] = "log";
24
- LogType[LogType["warn"] = 3] = "warn";
25
- LogType[LogType["error"] = 4] = "error";
26
- LogType[LogType["critical"] = 5] = "critical";
27
- })(LogType = exports.LogType || (exports.LogType = {}));
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class AppTrackerConfig {
4
+ constructor() {
5
+ /** Delay between send attempts. */
6
+ this.retryDelayMs = 10000;
7
+ /** Maximum duration of a single request before it is aborted. */
8
+ this.requestTimeoutMs = 10000;
9
+ this.maxLogsCount = 5;
10
+ this.sendLogsByTypesImmediately = [LogType.error];
11
+ }
12
+ }
13
+ exports.AppTrackerConfig = AppTrackerConfig;
14
+ class Log {
15
+ constructor() {
16
+ this.logType = LogType.log;
17
+ this.optionalParams = [];
18
+ this.createdAt = new Date();
19
+ this.ident = '';
20
+ }
21
+ }
22
+ exports.Log = Log;
23
+ var LogType;
24
+ (function (LogType) {
25
+ LogType[LogType["debug"] = 0] = "debug";
26
+ LogType[LogType["info"] = 1] = "info";
27
+ LogType[LogType["log"] = 2] = "log";
28
+ LogType[LogType["warn"] = 3] = "warn";
29
+ LogType[LogType["error"] = 4] = "error";
30
+ LogType[LogType["critical"] = 5] = "critical";
31
+ })(LogType = exports.LogType || (exports.LogType = {}));
package/main.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { AppTrackerService } from './app-tracker.service';
2
- import { AppTrackerConfig } from './log';
3
- export declare class AppTracker {
4
- private static _service;
5
- private static get service();
6
- static init(apiKey: string, config?: AppTrackerConfig): AppTrackerService;
7
- static getService(): AppTrackerService;
8
- }
1
+ import { AppTrackerService } from './app-tracker.service';
2
+ import { AppTrackerConfig } from './log';
3
+ export declare class AppTracker {
4
+ private static _service;
5
+ private static get service();
6
+ static init(apiKey: string, config?: AppTrackerConfig): AppTrackerService;
7
+ static getService(): AppTrackerService;
8
+ }
package/main.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const app_tracker_service_1 = require("./app-tracker.service");
4
- class AppTracker {
5
- static get service() {
6
- if (!this._service)
7
- this._service = new app_tracker_service_1.AppTrackerService();
8
- return this._service;
9
- }
10
- static init(apiKey, config) {
11
- AppTracker.service.init(apiKey, config);
12
- return AppTracker.service;
13
- }
14
- static getService() {
15
- return AppTracker.service;
16
- }
17
- }
18
- exports.AppTracker = AppTracker;
19
- AppTracker._service = null;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const app_tracker_service_1 = require("./app-tracker.service");
4
+ class AppTracker {
5
+ static get service() {
6
+ if (!this._service)
7
+ this._service = new app_tracker_service_1.AppTrackerService();
8
+ return this._service;
9
+ }
10
+ static init(apiKey, config) {
11
+ AppTracker.service.init(apiKey, config);
12
+ return AppTracker.service;
13
+ }
14
+ static getService() {
15
+ return AppTracker.service;
16
+ }
17
+ }
18
+ exports.AppTracker = AppTracker;
19
+ AppTracker._service = null;
package/package.json CHANGED
@@ -1,46 +1,54 @@
1
- {
2
- "name": "app-tracker",
3
- "version": "2.2.2",
4
- "description": "App Tracker for Web-Applications",
5
- "main": "index.js",
6
- "scripts": {
7
- "build": "tsc && npm run copyFile",
8
- "copyFile": "xcopy package.json lib && xcopy README.md lib",
9
- "terser": "terser lib/main.js -c -m -o lib/main.js && terser lib/log.js -c -m -o lib/log.js && terser lib/app-tracker.service.js -c -m -o lib/app-tracker.service.js",
10
- "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
11
- "lint": "tslint -p tsconfig.json"
12
- },
13
- "keywords": [
14
- "logging",
15
- "protocol",
16
- "event logging",
17
- "monitoring",
18
- "tracking",
19
- "recording",
20
- "debugging",
21
- "iroubleshooting",
22
- "user activity",
23
- "data analysis",
24
- "system events",
25
- "performance monitoring",
26
- "processing",
27
- "archiving",
28
- "alerting",
29
- "notification",
30
- "integration",
31
- "interfaces"
32
- ],
33
- "author": "Wigtertainment Ltd",
34
- "license": "ISC",
35
- "devDependencies": {
36
- "@types/node": "^17.0.10",
37
- "parcel": "^2.7.0",
38
- "prettier": "^1.19.1",
39
- "tslint": "^5.20.1",
40
- "tslint-config-prettier": "^1.18.0",
41
- "typescript": "^3.7.3"
42
- },
43
- "dependencies": {
44
- "cross-fetch": "^3.1.5"
45
- }
46
- }
1
+ {
2
+ "name": "app-tracker",
3
+ "version": "3.0.0",
4
+ "description": "App Tracker for Web-Applications",
5
+ "main": "index.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Wigtertainment-Ltd/App-Tracker-PKG.git"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc && npm run copyFile",
12
+ "copyFile": "node scripts/copy-package-files.js",
13
+ "terser": "terser lib/main.js -c -m -o lib/main.js && terser lib/log.js -c -m -o lib/log.js && terser lib/app-tracker.service.js -c -m -o lib/app-tracker.service.js",
14
+ "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
15
+ "lint": "tslint -p tsconfig.json",
16
+ "test": "npm run build && node test/logging.integration.js && node test/browser-build.js"
17
+ },
18
+ "keywords": [
19
+ "logging",
20
+ "protocol",
21
+ "event logging",
22
+ "monitoring",
23
+ "tracking",
24
+ "recording",
25
+ "debugging",
26
+ "iroubleshooting",
27
+ "user activity",
28
+ "data analysis",
29
+ "system events",
30
+ "performance monitoring",
31
+ "processing",
32
+ "archiving",
33
+ "alerting",
34
+ "notification",
35
+ "integration",
36
+ "interfaces"
37
+ ],
38
+ "author": "Wigtertainment Ltd",
39
+ "license": "ISC",
40
+ "engines": {
41
+ "node": ">=16"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^17.0.10",
45
+ "parcel": "^2.7.0",
46
+ "prettier": "^1.19.1",
47
+ "tslint": "^5.20.1",
48
+ "tslint-config-prettier": "^1.18.0",
49
+ "typescript": "^3.7.3"
50
+ },
51
+ "dependencies": {
52
+ "cross-fetch": "^3.1.5"
53
+ }
54
+ }
package/version.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Replaced with the package.json version by the build script. */
2
+ export declare const APP_TRACKER_VERSION: string;
package/version.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /** Replaced with the package.json version by the build script. */
4
+ exports.APP_TRACKER_VERSION = '3.0.0';