@flareapp/js 2.0.0-rc.1 → 2.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/dist/index.mjs CHANGED
@@ -1,466 +1,570 @@
1
- // src/env/index.ts
2
- var CLIENT_VERSION = false ? "?" : '"2.0.0-rc.1"';
3
- var KEY = typeof FLARE_JS_KEY === "undefined" ? "" : FLARE_JS_KEY;
4
- var SOURCEMAP_VERSION = typeof FLARE_SOURCEMAP_VERSION === "undefined" ? "" : FLARE_SOURCEMAP_VERSION;
1
+ import ErrorStackParser from "error-stack-parser";
2
+
3
+ //#region src/browser/catchWindowErrors.ts
4
+ function catchWindowErrors() {
5
+ if (typeof window === "undefined") return;
6
+ window.addEventListener("error", (event) => {
7
+ const flare = window.flare;
8
+ if (!flare) return;
9
+ if (event.error instanceof Error) Promise.resolve(flare.report(event.error)).catch(() => {});
10
+ });
11
+ window.addEventListener("unhandledrejection", (event) => {
12
+ const flare = window.flare;
13
+ if (!flare) return;
14
+ const reason = event.reason;
15
+ if (reason instanceof Error) {
16
+ Promise.resolve(flare.report(reason)).catch(() => {});
17
+ return;
18
+ }
19
+ if (hasStack$1(reason)) {
20
+ const error = new Error(describeRejectionReason(reason));
21
+ error.stack = reason.stack;
22
+ Promise.resolve(flare.report(error)).catch(() => {});
23
+ return;
24
+ }
25
+ Promise.resolve(flare.reportUnhandledRejection(describeRejectionReason(reason))).catch(() => {});
26
+ });
27
+ }
28
+ function describeRejectionReason(reason) {
29
+ if (typeof reason === "string") return reason;
30
+ if (reason && typeof reason === "object") {
31
+ const message = reason.message;
32
+ if (typeof message === "string") return message;
33
+ try {
34
+ return JSON.stringify(reason);
35
+ } catch {
36
+ return "Unhandled promise rejection (non-serializable reason)";
37
+ }
38
+ }
39
+ return String(reason);
40
+ }
41
+ function hasStack$1(value) {
42
+ return typeof value === "object" && value !== null && "stack" in value && typeof value.stack === "string";
43
+ }
44
+
45
+ //#endregion
46
+ //#region src/env/index.ts
47
+ const CLIENT_VERSION = typeof process !== "undefined" && true ? "2.0.0" : "?";
48
+ const KEY = typeof FLARE_JS_KEY === "undefined" ? "" : FLARE_JS_KEY;
49
+ const SOURCEMAP_VERSION = typeof FLARE_SOURCEMAP_VERSION === "undefined" ? "" : FLARE_SOURCEMAP_VERSION;
5
50
 
6
- // src/util/assert.ts
51
+ //#endregion
52
+ //#region src/util/assert.ts
7
53
  function assert(value, message, debug) {
8
- if (debug && !value) {
9
- console.error(`Flare JavaScript client v${CLIENT_VERSION}: ${message}`);
10
- }
11
- return !!value;
54
+ if (debug && !value) console.error(`Flare JavaScript client v${CLIENT_VERSION}: ${message}`);
55
+ return !!value;
12
56
  }
13
57
 
14
- // src/util/assertKey.ts
58
+ //#endregion
59
+ //#region src/util/assertKey.ts
15
60
  function assertKey(key, debug) {
16
- return assert(
17
- key,
18
- "The client was not yet initialised with an API key. Run client.light('<flare-project-key>') when you initialise your app. If you are running in dev mode and didn't run the light command on purpose, you can ignore this error.",
19
- debug
20
- );
61
+ return assert(key, "The client was not yet initialised with an API key. Run client.light('<flare-project-key>') when you initialise your app. If you are running in dev mode and didn't run the light command on purpose, you can ignore this error.", debug);
21
62
  }
22
63
 
23
- // src/util/assertSolutionProvider.ts
24
- function assertSolutionProvider(solutionProvider, debug) {
25
- return assert("canSolve" in solutionProvider, "A solution provider without a [canSolve] property was added.", debug) && assert(
26
- "getSolutions" in solutionProvider,
27
- "A solution provider without a [getSolutions] property was added.",
28
- debug
29
- );
64
+ //#endregion
65
+ //#region src/util/extractCode.ts
66
+ const MAX_CODE_LENGTH = 64;
67
+ function extractCode(error) {
68
+ const code = error.code;
69
+ if (typeof code !== "string" || code.length === 0) return;
70
+ return code.slice(0, MAX_CODE_LENGTH);
30
71
  }
31
72
 
32
- // src/util/flatJsonStringify.ts
73
+ //#endregion
74
+ //#region src/util/flatJsonStringify.ts
33
75
  function flatJsonStringify(json) {
34
- let cache = [];
35
- const flattenedStringifiedJson = JSON.stringify(json, function(_, value) {
36
- if (typeof value === "object" && value !== null) {
37
- if (cache.indexOf(value) !== -1) {
38
- try {
39
- return JSON.parse(JSON.stringify(value));
40
- } catch (error) {
41
- return;
42
- }
43
- }
44
- cache.push(value);
45
- }
46
- return value;
47
- });
48
- cache = null;
49
- return flattenedStringifiedJson;
76
+ return JSON.stringify(decycle(json));
77
+ }
78
+ function isPlainObject(value) {
79
+ if (typeof value !== "object" || value === null) return false;
80
+ const proto = Object.getPrototypeOf(value);
81
+ return proto === Object.prototype || proto === null;
82
+ }
83
+ function decycle(root) {
84
+ const inPath = /* @__PURE__ */ new WeakSet();
85
+ function clone(node) {
86
+ if (Array.isArray(node)) {
87
+ if (inPath.has(node)) return "[Circular]";
88
+ inPath.add(node);
89
+ const result = node.map(clone);
90
+ inPath.delete(node);
91
+ return result;
92
+ }
93
+ if (isPlainObject(node)) {
94
+ if (inPath.has(node)) return "[Circular]";
95
+ inPath.add(node);
96
+ const result = {};
97
+ for (const [k, v] of Object.entries(node)) result[k] = clone(v);
98
+ inPath.delete(node);
99
+ return result;
100
+ }
101
+ return node;
102
+ }
103
+ return clone(root);
50
104
  }
51
105
 
52
- // src/util/flattenOnce.ts
53
- function flattenOnce(array) {
54
- return array.reduce((flat, toFlatten) => {
55
- return flat.concat(toFlatten);
56
- }, []);
106
+ //#endregion
107
+ //#region src/util/glowsToEvents.ts
108
+ function glowsToEvents(glows) {
109
+ return glows.map((glow) => ({
110
+ type: "php_glow",
111
+ startTimeUnixNano: Math.round(glow.microtime * 1e9),
112
+ endTimeUnixNano: null,
113
+ attributes: {
114
+ "glow.name": String(glow.name),
115
+ "glow.level": glow.messageLevel,
116
+ "glow.context": glow.metaData ?? {}
117
+ }
118
+ }));
57
119
  }
58
120
 
59
- // src/util/now.ts
121
+ //#endregion
122
+ //#region src/util/now.ts
60
123
  function now() {
61
- return Math.round(Date.now() / 1e3);
124
+ return Math.round(Date.now() / 1e3);
125
+ }
126
+
127
+ //#endregion
128
+ //#region src/util/redactUrl.ts
129
+ const DEFAULT_URL_DENYLIST = /password|passwd|pwd|token|secret|authorization|\bauth\b|bearer|oauth|credentials?|cookie|api[-_]?key|private[-_]?key|session|csrf|xsrf|\bpin\b|\bssn\b|card[-_]?number|\bcvv\b/i;
130
+ function resolveDenylist(custom, replaceDefault = false, defaultDenylist = DEFAULT_URL_DENYLIST) {
131
+ if (!custom) return defaultDenylist;
132
+ if (replaceDefault) {
133
+ const safeFlags = custom.flags.replace(/[gy]/g, "");
134
+ return new RegExp(custom.source, safeFlags);
135
+ }
136
+ const flags = unionFlags(defaultDenylist.flags, custom.flags);
137
+ return new RegExp(`(?:${defaultDenylist.source})|(?:${custom.source})`, flags);
138
+ }
139
+ function unionFlags(a, b) {
140
+ const merged = /* @__PURE__ */ new Set();
141
+ for (const flag of a + b) {
142
+ if (flag === "g" || flag === "y") continue;
143
+ merged.add(flag);
144
+ }
145
+ return [...merged].join("");
146
+ }
147
+ function redactFullPath(fullPath, denylist = DEFAULT_URL_DENYLIST) {
148
+ const queryStart = fullPath.indexOf("?");
149
+ if (queryStart === -1) return fullPath;
150
+ const hashStart = fullPath.indexOf("#", queryStart);
151
+ const queryEnd = hashStart === -1 ? fullPath.length : hashStart;
152
+ const prefix = fullPath.slice(0, queryStart + 1);
153
+ const queryString = fullPath.slice(queryStart + 1, queryEnd);
154
+ const suffix = fullPath.slice(queryEnd);
155
+ return `${prefix}${queryString.split("&").map((pair) => {
156
+ if (pair === "") return pair;
157
+ const eq = pair.indexOf("=");
158
+ const rawKey = eq === -1 ? pair : pair.slice(0, eq);
159
+ const decodedKey = safeDecode(rawKey);
160
+ if (!denylist.test(decodedKey)) return pair;
161
+ return eq === -1 ? rawKey : `${rawKey}=[redacted]`;
162
+ }).join("&")}${suffix}`;
163
+ }
164
+ function safeDecode(value) {
165
+ try {
166
+ return decodeURIComponent(value);
167
+ } catch {
168
+ return value;
169
+ }
62
170
  }
63
171
 
64
- // src/api/Api.ts
172
+ //#endregion
173
+ //#region src/api/Api.ts
65
174
  var Api = class {
66
- report(report, url, key, reportBrowserExtensionErrors) {
67
- return fetch(url, {
68
- method: "POST",
69
- headers: {
70
- "Content-Type": "application/json",
71
- "X-Api-Token": key,
72
- "X-Requested-With": "XMLHttpRequest",
73
- "X-Report-Browser-Extension-Errors": JSON.stringify(reportBrowserExtensionErrors)
74
- },
75
- body: flatJsonStringify({
76
- ...report,
77
- key
78
- })
79
- }).then(
80
- (response) => {
81
- if (response.status !== 204) {
82
- console.error(`Received response with status ${response.status} from Flare`);
83
- }
84
- },
85
- (error) => console.error(error)
86
- );
87
- }
175
+ report(report, url, key, reportBrowserExtensionErrors, debug = false) {
176
+ return fetch(url, {
177
+ method: "POST",
178
+ headers: {
179
+ "Accept": "application/json",
180
+ "Content-Type": "application/json",
181
+ "X-Api-Token": key ?? "",
182
+ "X-Report-Browser-Extension-Errors": JSON.stringify(reportBrowserExtensionErrors),
183
+ "X-Flare-Client-Version": "2"
184
+ },
185
+ body: flatJsonStringify(report)
186
+ }).then((response) => {
187
+ if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from Flare`);
188
+ }, (error) => {
189
+ if (debug) console.error(error);
190
+ });
191
+ }
88
192
  };
89
193
 
90
- // src/context/cookie.ts
194
+ //#endregion
195
+ //#region src/context/cookie.ts
91
196
  function cookie() {
92
- if (!window.document.cookie) {
93
- return {};
94
- }
95
- return {
96
- cookies: window.document.cookie.split("; ").reduce(
97
- (cookies, cookie2) => {
98
- const [cookieName, cookieValue] = cookie2.split(/=/);
99
- cookies[cookieName] = cookieValue;
100
- return cookies;
101
- },
102
- {}
103
- )
104
- };
105
- }
106
-
107
- // src/context/request.ts
108
- function request() {
109
- return {
110
- request: {
111
- url: window.document.location.href,
112
- useragent: window.navigator.userAgent,
113
- referrer: window.document.referrer,
114
- readyState: window.document.readyState
115
- }
116
- };
197
+ if (!window.document.cookie) return {};
198
+ const cookies = {};
199
+ window.document.cookie.split("; ").forEach((rawCookie) => {
200
+ const idx = rawCookie.indexOf("=");
201
+ if (idx === -1) {
202
+ cookies[rawCookie] = "";
203
+ return;
204
+ }
205
+ const name = rawCookie.slice(0, idx);
206
+ cookies[name] = rawCookie.slice(idx + 1);
207
+ });
208
+ return { "http.request.cookies": cookies };
117
209
  }
118
210
 
119
- // src/context/requestData.ts
120
- function requestData() {
121
- if (!window.location.search) {
122
- return {};
123
- }
124
- const queryString = {};
125
- new URLSearchParams(window.location.search).forEach((value, key) => {
126
- queryString[key] = value;
127
- });
128
- return { request_data: { queryString } };
211
+ //#endregion
212
+ //#region src/context/request.ts
213
+ function request(urlDenylist) {
214
+ return {
215
+ "url.full": redactFullPath(window.location.href, urlDenylist),
216
+ "user_agent.original": window.navigator.userAgent,
217
+ "http.request.referrer": redactFullPath(window.document.referrer, urlDenylist),
218
+ "document.ready_state": window.document.readyState
219
+ };
129
220
  }
130
221
 
131
- // src/context/collectContext.ts
132
- function collectContext(additionalContext) {
133
- if (typeof window === "undefined") {
134
- return additionalContext;
135
- }
136
- return {
137
- ...cookie(),
138
- ...request(),
139
- ...requestData(),
140
- ...additionalContext
141
- };
222
+ //#endregion
223
+ //#region src/context/requestData.ts
224
+ function requestData(urlDenylist) {
225
+ if (!window.location.search) return {};
226
+ return { "url.query": redactFullPath(window.location.search, urlDenylist).replace(/^\?/, "") };
142
227
  }
143
228
 
144
- // src/solutions/getSolutions.ts
145
- function getSolutions(solutionProviders, error, extraSolutionParameters = {}) {
146
- return new Promise((resolve) => {
147
- const canSolves = solutionProviders.reduce(
148
- (canSolves2, provider) => {
149
- canSolves2.push(Promise.resolve(provider.canSolve(error, extraSolutionParameters)));
150
- return canSolves2;
151
- },
152
- []
153
- );
154
- Promise.all(canSolves).then((resolvedCanSolves) => {
155
- const solutionPromises = [];
156
- resolvedCanSolves.forEach((canSolve, i) => {
157
- if (canSolve) {
158
- solutionPromises.push(
159
- Promise.resolve(solutionProviders[i].getSolutions(error, extraSolutionParameters))
160
- );
161
- }
162
- });
163
- Promise.all(solutionPromises).then((solutions) => {
164
- resolve(flattenOnce(solutions));
165
- });
166
- });
167
- });
229
+ //#endregion
230
+ //#region src/context/collectAttributes.ts
231
+ function collectAttributes(urlDenylist) {
232
+ if (typeof window === "undefined") return {};
233
+ return {
234
+ ...request(urlDenylist),
235
+ ...requestData(urlDenylist),
236
+ ...cookie()
237
+ };
168
238
  }
169
239
 
170
- // src/stacktrace/createStackTrace.ts
171
- import ErrorStackParser from "error-stack-parser";
172
-
173
- // src/stacktrace/fileReader.ts
174
- var cachedFiles = {};
240
+ //#endregion
241
+ //#region src/stacktrace/fileReader.ts
242
+ const cachedFiles = {};
175
243
  function getCodeSnippet(url, lineNumber, columnNumber) {
176
- return new Promise((resolve) => {
177
- if (!url || !lineNumber) {
178
- return resolve({
179
- codeSnippet: {
180
- 0: `Could not read from file: missing file URL or line number. URL: ${url} lineNumber: ${lineNumber}`
181
- },
182
- trimmedColumnNumber: null
183
- });
184
- }
185
- readFile(url).then((fileText) => {
186
- if (!fileText) {
187
- return resolve({
188
- codeSnippet: {
189
- 0: `Could not read from file: Error while opening file at URL ${url}`
190
- },
191
- trimmedColumnNumber: null
192
- });
193
- }
194
- return resolve(readLinesFromFile(fileText, lineNumber, columnNumber));
195
- });
196
- });
244
+ return new Promise((resolve) => {
245
+ if (!url || !lineNumber) return resolve({
246
+ codeSnippet: { 0: `Could not read from file: missing file URL or line number. URL: ${url} lineNumber: ${lineNumber}` },
247
+ trimmedColumnNumber: null
248
+ });
249
+ if (!isFetchableUrl(url)) return resolve({
250
+ codeSnippet: { 0: `Could not read from file: unsupported URL scheme. URL: ${url}` },
251
+ trimmedColumnNumber: null
252
+ });
253
+ readFile(url).then((fileText) => {
254
+ if (!fileText) return resolve({
255
+ codeSnippet: { 0: `Could not read from file: Error while opening file at URL ${url}` },
256
+ trimmedColumnNumber: null
257
+ });
258
+ return resolve(readLinesFromFile(fileText, lineNumber, columnNumber));
259
+ });
260
+ });
261
+ }
262
+ function isFetchableUrl(url) {
263
+ return /^https?:\/\//i.test(url);
197
264
  }
198
265
  function readFile(url) {
199
- if (cachedFiles[url]) {
200
- return Promise.resolve(cachedFiles[url]);
201
- }
202
- return fetch(url).then((response) => {
203
- if (response.status !== 200) {
204
- return null;
205
- }
206
- return response.text();
207
- }).catch(() => null);
266
+ if (cachedFiles[url] !== void 0) return Promise.resolve(cachedFiles[url]);
267
+ return fetch(url).then((response) => {
268
+ if (response.status !== 200) return null;
269
+ return response.text();
270
+ }).then((text) => {
271
+ if (text !== null) cachedFiles[url] = text;
272
+ return text;
273
+ }).catch(() => null);
208
274
  }
209
275
  function readLinesFromFile(fileText, lineNumber, columnNumber, maxSnippetLineLength = 1e3, maxSnippetLines = 40) {
210
- const codeSnippet = {};
211
- let trimmedColumnNumber = null;
212
- const lines = fileText.split("\n");
213
- for (let i = -maxSnippetLines / 2; i <= maxSnippetLines / 2; i++) {
214
- const currentLineIndex = lineNumber + i;
215
- if (currentLineIndex >= 0 && lines[currentLineIndex]) {
216
- const displayLine = currentLineIndex + 1;
217
- if (lines[currentLineIndex].length > maxSnippetLineLength) {
218
- if (columnNumber && columnNumber + maxSnippetLineLength / 2 > maxSnippetLineLength) {
219
- codeSnippet[displayLine] = lines[currentLineIndex].substr(
220
- columnNumber - Math.round(maxSnippetLineLength / 2),
221
- maxSnippetLineLength
222
- );
223
- if (displayLine === lineNumber) {
224
- trimmedColumnNumber = Math.round(maxSnippetLineLength / 2);
225
- }
226
- continue;
227
- }
228
- codeSnippet[displayLine] = lines[currentLineIndex].substr(0, maxSnippetLineLength) + "\u2026";
229
- continue;
230
- }
231
- codeSnippet[displayLine] = lines[currentLineIndex];
232
- }
233
- }
234
- return { codeSnippet, trimmedColumnNumber };
276
+ const codeSnippet = {};
277
+ let trimmedColumnNumber = null;
278
+ const lines = fileText.split("\n");
279
+ const errorLineIndex = lineNumber - 1;
280
+ const half = Math.floor(maxSnippetLines / 2);
281
+ for (let i = -half; i <= half; i++) {
282
+ const currentLineIndex = errorLineIndex + i;
283
+ if (currentLineIndex < 0 || !lines[currentLineIndex]) continue;
284
+ const displayLine = currentLineIndex + 1;
285
+ const line = lines[currentLineIndex];
286
+ if (line.length > maxSnippetLineLength) {
287
+ if (columnNumber && columnNumber > maxSnippetLineLength / 2) {
288
+ const start = columnNumber - Math.round(maxSnippetLineLength / 2);
289
+ codeSnippet[displayLine] = line.slice(start, start + maxSnippetLineLength);
290
+ if (displayLine === lineNumber) trimmedColumnNumber = Math.round(maxSnippetLineLength / 2);
291
+ continue;
292
+ }
293
+ codeSnippet[displayLine] = line.slice(0, maxSnippetLineLength) + "…";
294
+ continue;
295
+ }
296
+ codeSnippet[displayLine] = line;
297
+ }
298
+ return {
299
+ codeSnippet,
300
+ trimmedColumnNumber
301
+ };
235
302
  }
236
303
 
237
- // src/stacktrace/createStackTrace.ts
304
+ //#endregion
305
+ //#region src/stacktrace/createStackTrace.ts
238
306
  function createStackTrace(error, debug) {
239
- return new Promise((resolve) => {
240
- if (!hasStack(error)) {
241
- assert(false, "Couldn't generate stacktrace of below error:", debug);
242
- if (debug) {
243
- console.error(error);
244
- }
245
- return resolve([
246
- {
247
- line_number: 0,
248
- column_number: 0,
249
- method: "unknown",
250
- file: "unknown",
251
- code_snippet: {
252
- 0: "Could not read from file: stacktrace missing"
253
- },
254
- trimmed_column_number: null,
255
- class: "unknown"
256
- }
257
- ]);
258
- }
259
- Promise.all(
260
- ErrorStackParser.parse(error).map((frame) => {
261
- return new Promise((resolve2) => {
262
- getCodeSnippet(frame.fileName, frame.lineNumber, frame.columnNumber).then((snippet) => {
263
- resolve2({
264
- line_number: frame.lineNumber || 1,
265
- column_number: frame.columnNumber || 1,
266
- method: frame.functionName || "Anonymous or unknown function",
267
- file: frame.fileName || "Unknown file",
268
- code_snippet: snippet.codeSnippet,
269
- trimmed_column_number: snippet.trimmedColumnNumber,
270
- class: ""
271
- });
272
- });
273
- });
274
- })
275
- ).then(resolve);
276
- });
307
+ return new Promise((resolve) => {
308
+ if (!hasStack(error)) return resolve([fallbackFrame("stacktrace missing")]);
309
+ let parsedFrames;
310
+ try {
311
+ parsedFrames = ErrorStackParser.parse(error);
312
+ } catch (parseError) {
313
+ assert(false, "Couldn't parse stacktrace of below error:", debug);
314
+ if (debug) {
315
+ console.error(parseError);
316
+ console.error(error);
317
+ }
318
+ return resolve([fallbackFrame("stacktrace could not be parsed")]);
319
+ }
320
+ Promise.all(parsedFrames.map((frame) => {
321
+ return getCodeSnippet(frame.fileName, frame.lineNumber, frame.columnNumber).then((snippet) => ({
322
+ lineNumber: frame.lineNumber || 1,
323
+ columnNumber: frame.columnNumber || 1,
324
+ method: frame.functionName || "Anonymous or unknown function",
325
+ file: frame.fileName || "Unknown file",
326
+ codeSnippet: snippet.codeSnippet,
327
+ class: "",
328
+ isApplicationFrame: isApplicationFrame(frame.fileName)
329
+ }));
330
+ })).then(resolve);
331
+ });
332
+ }
333
+ function fallbackFrame(reason) {
334
+ return {
335
+ lineNumber: 0,
336
+ columnNumber: 0,
337
+ method: "unknown",
338
+ file: "unknown",
339
+ codeSnippet: { 0: `Could not read from file: ${reason}` },
340
+ class: "unknown"
341
+ };
277
342
  }
278
343
  function hasStack(err) {
279
- return !!err && (!!err.stack || !!err.stacktrace || !!err["opera#sourceloc"]) && typeof (err.stack || err.stacktrace || err["opera#sourceloc"]) === "string" && err.stack !== `${err.name}: ${err.message}`;
344
+ if (!err || typeof err !== "object") return false;
345
+ const e = err;
346
+ const stack = e.stack ?? e.stacktrace ?? e["opera#sourceloc"];
347
+ return typeof stack === "string" && stack !== `${e.name}: ${e.message}`;
348
+ }
349
+ function isApplicationFrame(fileName) {
350
+ if (!fileName) return true;
351
+ if (/[/\\]node_modules[/\\]/.test(fileName)) return false;
352
+ if (/(^|[/\\])(vendor|vendors)[.~-][^/\\]*\.js/i.test(fileName)) return false;
353
+ return true;
280
354
  }
281
355
 
282
- // src/Flare.ts
356
+ //#endregion
357
+ //#region src/Flare.ts
358
+ const DEFAULT_SDK_NAME = "@flareapp/js";
283
359
  var Flare = class {
284
- constructor(http = new Api()) {
285
- this.http = http;
286
- this.config = {
287
- key: KEY,
288
- version: CLIENT_VERSION,
289
- sourcemapVersion: SOURCEMAP_VERSION,
290
- stage: "",
291
- maxGlowsPerReport: 30,
292
- reportingUrl: "https://reporting.flareapp.io/api/reports",
293
- reportBrowserExtensionErrors: false,
294
- debug: false,
295
- beforeEvaluate: (error) => error,
296
- beforeSubmit: (report) => report
297
- };
298
- this.glows = [];
299
- this.context = { context: {} };
300
- this.solutionProviders = [];
301
- }
302
- light(key = KEY, debug = false) {
303
- this.config.key = key;
304
- this.config.debug = debug;
305
- return this;
306
- }
307
- configure(config) {
308
- this.config = { ...this.config, ...config };
309
- return this;
310
- }
311
- test() {
312
- return this.report(new Error("The Flare client is set up correctly!"));
313
- }
314
- glow(name, level = "info", data = []) {
315
- const time = now();
316
- this.glows.push({
317
- name,
318
- message_level: level,
319
- meta_data: data,
320
- time,
321
- microtime: time
322
- });
323
- if (this.glows.length > this.config.maxGlowsPerReport) {
324
- this.glows = this.glows.slice(this.glows.length - this.config.maxGlowsPerReport);
325
- }
326
- return this;
327
- }
328
- clearGlows() {
329
- this.glows = [];
330
- return this;
331
- }
332
- addContext(name, value) {
333
- this.context.context[name] = value;
334
- return this;
335
- }
336
- addContextGroup(groupName, value) {
337
- this.context[groupName] = value;
338
- return this;
339
- }
340
- registerSolutionProvider(solutionProvider) {
341
- if (!assertSolutionProvider(solutionProvider, this.config.debug)) {
342
- return this;
343
- }
344
- this.solutionProviders.push(solutionProvider);
345
- return this;
346
- }
347
- async report(error, context = {}, extraSolutionParameters = {}) {
348
- const errorToReport = await this.config.beforeEvaluate(error);
349
- if (!errorToReport) {
350
- return;
351
- }
352
- const report = await this.createReportFromError(error, context, extraSolutionParameters);
353
- if (!report) {
354
- return;
355
- }
356
- return this.sendReport(report);
357
- }
358
- async reportMessage(message, context = {}, exceptionClass = "Log") {
359
- const stackTrace = await createStackTrace(Error(), this.config.debug);
360
- stackTrace.shift();
361
- this.sendReport({
362
- notifier: `Flare JavaScript client v${CLIENT_VERSION}`,
363
- exception_class: exceptionClass,
364
- seen_at: now(),
365
- message,
366
- language: "javascript",
367
- glows: this.glows,
368
- context: collectContext({ ...context, ...this.context }),
369
- stacktrace: stackTrace,
370
- sourcemap_version_id: this.config.sourcemapVersion,
371
- solutions: [],
372
- stage: this.config.stage
373
- });
374
- }
375
- createReportFromError(error, context = {}, extraSolutionParameters = {}) {
376
- if (!assert(error, "No error provided.", this.config.debug)) {
377
- return Promise.resolve(false);
378
- }
379
- const seenAt = now();
380
- return Promise.all([
381
- getSolutions(this.solutionProviders, error, extraSolutionParameters),
382
- createStackTrace(error, this.config.debug)
383
- ]).then((result) => {
384
- const [solutions, stacktrace] = result;
385
- assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this.config.debug);
386
- return {
387
- notifier: `Flare JavaScript client v${CLIENT_VERSION}`,
388
- exception_class: error.constructor && error.constructor.name ? error.constructor.name : "undefined",
389
- seen_at: seenAt,
390
- message: error.message,
391
- language: "javascript",
392
- glows: this.glows,
393
- context: collectContext({ ...context, ...this.context }),
394
- stacktrace,
395
- sourcemap_version_id: this.config.sourcemapVersion,
396
- solutions,
397
- stage: this.config.stage
398
- };
399
- });
400
- }
401
- async sendReport(report) {
402
- if (!assertKey(this.config.key, this.config.debug)) {
403
- return;
404
- }
405
- const reportToSubmit = await this.config.beforeSubmit(report);
406
- if (!reportToSubmit) {
407
- return;
408
- }
409
- return this.http.report(
410
- reportToSubmit,
411
- this.config.reportingUrl,
412
- this.config.key,
413
- this.config.reportBrowserExtensionErrors
414
- );
415
- }
416
- // Deprecated, the following methods exist for backwards compatibility.
417
- set beforeEvaluate(beforeEvaluate) {
418
- this.config.beforeEvaluate = beforeEvaluate ?? "";
419
- }
420
- set beforeSubmit(beforeSubmit) {
421
- this.config.beforeSubmit = beforeSubmit ?? "";
422
- }
423
- set stage(stage) {
424
- this.config.stage = stage ?? "";
425
- }
360
+ _config = {
361
+ key: null,
362
+ version: "",
363
+ sourcemapVersionId: SOURCEMAP_VERSION,
364
+ stage: "",
365
+ maxGlowsPerReport: 30,
366
+ ingestUrl: "https://ingress.flareapp.io/v1/errors",
367
+ reportBrowserExtensionErrors: false,
368
+ debug: false,
369
+ urlDenylist: DEFAULT_URL_DENYLIST,
370
+ replaceDefaultUrlDenylist: false,
371
+ sampleRate: 1,
372
+ beforeEvaluate: (error) => error,
373
+ beforeSubmit: (report) => report
374
+ };
375
+ _glows = [];
376
+ pendingAttributes = {};
377
+ entryPoint = null;
378
+ sdkInfo = {
379
+ name: DEFAULT_SDK_NAME,
380
+ version: CLIENT_VERSION
381
+ };
382
+ framework = null;
383
+ constructor(api = new Api()) {
384
+ this.api = api;
385
+ }
386
+ get config() {
387
+ return this._config;
388
+ }
389
+ get glows() {
390
+ return this._glows;
391
+ }
392
+ light(key = KEY, debug) {
393
+ this._config.key = key;
394
+ if (debug !== void 0) this._config.debug = debug;
395
+ return this;
396
+ }
397
+ configure(config) {
398
+ this._config = {
399
+ ...this._config,
400
+ ...config
401
+ };
402
+ if (config.sampleRate !== void 0) this._config.sampleRate = Math.max(0, Math.min(1, config.sampleRate));
403
+ this._config.urlDenylist = resolveDenylist(config.urlDenylist, config.replaceDefaultUrlDenylist ?? this._config.replaceDefaultUrlDenylist);
404
+ return this;
405
+ }
406
+ async test() {
407
+ const report = await this.createReportFromError(/* @__PURE__ */ new Error("The Flare client is set up correctly!"));
408
+ if (!report) return;
409
+ return this.sendReport(report);
410
+ }
411
+ glow(name, level = "info", data = []) {
412
+ const time = now();
413
+ this._glows.push({
414
+ name,
415
+ messageLevel: level,
416
+ metaData: data,
417
+ time,
418
+ microtime: time
419
+ });
420
+ if (this._glows.length > this._config.maxGlowsPerReport) this._glows = this._glows.slice(this._glows.length - this._config.maxGlowsPerReport);
421
+ return this;
422
+ }
423
+ clearGlows() {
424
+ this._glows = [];
425
+ return this;
426
+ }
427
+ addContext(name, value) {
428
+ const existing = this.pendingAttributes["context.custom"] ?? {};
429
+ this.pendingAttributes["context.custom"] = {
430
+ ...existing,
431
+ [name]: value
432
+ };
433
+ return this;
434
+ }
435
+ addContextGroup(groupName, value) {
436
+ this.pendingAttributes[`context.${groupName}`] = value;
437
+ return this;
438
+ }
439
+ setEntryPoint(handler) {
440
+ this.entryPoint = handler;
441
+ return this;
442
+ }
443
+ setSdkInfo(info) {
444
+ this.sdkInfo = info;
445
+ return this;
446
+ }
447
+ setFramework(framework) {
448
+ this.framework = framework;
449
+ return this;
450
+ }
451
+ async report(error, attributes = {}) {
452
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
453
+ const seenAtUnixNano = Date.now() * 1e6;
454
+ const coerced = error instanceof Error ? error : new Error(typeof error === "string" ? error : String(error));
455
+ const errorToReport = await this._config.beforeEvaluate(coerced);
456
+ if (!errorToReport) return;
457
+ const report = await this.createReportFromError(errorToReport, attributes, seenAtUnixNano);
458
+ if (!report) return;
459
+ return this.sendReport(report);
460
+ }
461
+ async reportUnhandledRejection(message, attributes = {}) {
462
+ if (Math.random() >= this._config.sampleRate) return;
463
+ const seenAtUnixNano = Date.now() * 1e6;
464
+ const report = this.buildReport({
465
+ exceptionClass: "UnhandledRejection",
466
+ message,
467
+ stacktrace: [],
468
+ isLog: false,
469
+ level: void 0,
470
+ extraAttributes: attributes,
471
+ code: void 0,
472
+ seenAtUnixNano
473
+ });
474
+ return this.sendReport(report);
475
+ }
476
+ async reportMessage(message, level, attributes = {}) {
477
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
478
+ const seenAtUnixNano = Date.now() * 1e6;
479
+ const stackTrace = await createStackTrace(/* @__PURE__ */ new Error(), this._config.debug);
480
+ stackTrace.shift();
481
+ const report = this.buildReport({
482
+ exceptionClass: "Log",
483
+ message,
484
+ stacktrace: stackTrace,
485
+ isLog: true,
486
+ level,
487
+ extraAttributes: attributes,
488
+ code: void 0,
489
+ seenAtUnixNano
490
+ });
491
+ return this.sendReport(report);
492
+ }
493
+ async createReportFromError(error, attributes = {}, seenAtUnixNano = Date.now() * 1e6) {
494
+ if (!assert(error, "No error provided.", this._config.debug)) return false;
495
+ const stacktrace = await createStackTrace(error, this._config.debug);
496
+ assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this._config.debug);
497
+ const exceptionClass = error.constructor && error.constructor.name ? error.constructor.name : "undefined";
498
+ return this.buildReport({
499
+ exceptionClass,
500
+ message: error.message,
501
+ stacktrace,
502
+ isLog: false,
503
+ level: void 0,
504
+ extraAttributes: attributes,
505
+ code: extractCode(error),
506
+ seenAtUnixNano
507
+ });
508
+ }
509
+ buildReport(input) {
510
+ const baseAttributes = {
511
+ "telemetry.sdk.language": "javascript",
512
+ "telemetry.sdk.name": this.sdkInfo.name,
513
+ "telemetry.sdk.version": this.sdkInfo.version,
514
+ "flare.language.name": "javascript",
515
+ "flare.entry_point.type": "web"
516
+ };
517
+ if (typeof window !== "undefined" && window?.location?.href) baseAttributes["flare.entry_point.value"] = redactFullPath(window.location.href, this._config.urlDenylist);
518
+ const handlerIdentifier = this.entryPoint?.identifier ?? (typeof window !== "undefined" && window?.location?.pathname ? window.location.pathname : void 0);
519
+ const handlerType = this.entryPoint?.type ?? (typeof window !== "undefined" && window ? "browser" : void 0);
520
+ if (handlerIdentifier !== void 0) baseAttributes["flare.entry_point.handler.identifier"] = handlerIdentifier;
521
+ if (handlerType !== void 0) baseAttributes["flare.entry_point.handler.type"] = handlerType;
522
+ if (this.entryPoint?.name !== void 0) baseAttributes["flare.entry_point.handler.name"] = this.entryPoint.name;
523
+ if (this.framework?.name) baseAttributes["flare.framework.name"] = this.framework.name;
524
+ if (this.framework?.version) baseAttributes["flare.framework.version"] = this.framework.version;
525
+ if (this._config.stage) baseAttributes["service.stage"] = this._config.stage;
526
+ if (this._config.version) baseAttributes["service.version"] = this._config.version;
527
+ const attributes = {
528
+ ...baseAttributes,
529
+ ...collectAttributes(this._config.urlDenylist),
530
+ ...this.pendingAttributes,
531
+ ...input.extraAttributes
532
+ };
533
+ const pendingCustom = this.pendingAttributes["context.custom"];
534
+ const extraCustom = input.extraAttributes["context.custom"];
535
+ if (pendingCustom && extraCustom && typeof pendingCustom === "object" && typeof extraCustom === "object" && !Array.isArray(pendingCustom) && !Array.isArray(extraCustom)) attributes["context.custom"] = {
536
+ ...pendingCustom,
537
+ ...extraCustom
538
+ };
539
+ const report = {
540
+ exceptionClass: input.exceptionClass,
541
+ message: input.message,
542
+ seenAtUnixNano: input.seenAtUnixNano,
543
+ stacktrace: input.stacktrace,
544
+ events: glowsToEvents(this._glows),
545
+ attributes
546
+ };
547
+ if (input.isLog) report.isLog = true;
548
+ if (input.level !== void 0) report.level = input.level;
549
+ if (this._config.sourcemapVersionId) report.sourcemapVersionId = this._config.sourcemapVersionId;
550
+ if (input.code !== void 0) report.code = input.code;
551
+ return report;
552
+ }
553
+ async sendReport(report) {
554
+ if (!assertKey(this._config.key, this._config.debug)) return;
555
+ const reportToSubmit = await this._config.beforeSubmit(report);
556
+ if (!reportToSubmit) return;
557
+ return this.api.report(reportToSubmit, this._config.ingestUrl, this._config.key, this._config.reportBrowserExtensionErrors, this._config.debug);
558
+ }
426
559
  };
427
560
 
428
- // src/browser/catchWindowErrors.ts
429
- function catchWindowErrors() {
430
- if (typeof window === "undefined") {
431
- return;
432
- }
433
- const flare2 = window.flare;
434
- if (!window || !flare2) {
435
- return;
436
- }
437
- const originalOnerrorHandler = window.onerror;
438
- const originalOnunhandledrejectionHandler = window.onunhandledrejection;
439
- window.onerror = (_1, _2, _3, _4, error) => {
440
- if (error) {
441
- flare2.report(error);
442
- }
443
- if (typeof originalOnerrorHandler === "function") {
444
- originalOnerrorHandler(_1, _2, _3, _4, error);
445
- }
446
- };
447
- window.onunhandledrejection = (error) => {
448
- if (error.reason instanceof Error) {
449
- flare2.report(error.reason);
450
- }
451
- if (typeof originalOnunhandledrejectionHandler === "function") {
452
- originalOnunhandledrejectionHandler(error);
453
- }
454
- };
455
- }
456
-
457
- // src/index.ts
458
- var flare = new Flare();
561
+ //#endregion
562
+ //#region src/index.ts
563
+ const flare = new Flare();
459
564
  if (typeof window !== "undefined" && window) {
460
- window.flare = flare;
461
- catchWindowErrors();
565
+ window.flare = flare;
566
+ catchWindowErrors();
462
567
  }
463
- export {
464
- Flare,
465
- flare
466
- };
568
+
569
+ //#endregion
570
+ export { DEFAULT_URL_DENYLIST, Flare, flare, redactFullPath, resolveDenylist };