@flareapp/js 1.2.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.js DELETED
@@ -1,640 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Flare: () => Flare,
34
- flare: () => flare
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
-
38
- // src/env/index.ts
39
- var CLIENT_VERSION = false ? "?" : "1.2.1";
40
- var KEY = typeof FLARE_JS_KEY === "undefined" ? "" : FLARE_JS_KEY;
41
- var SOURCEMAP_VERSION = typeof FLARE_SOURCEMAP_VERSION === "undefined" ? "" : FLARE_SOURCEMAP_VERSION;
42
-
43
- // src/util/assert.ts
44
- function assert(value, message, debug) {
45
- if (debug && !value) {
46
- console.error(`Flare JavaScript client v${CLIENT_VERSION}: ${message}`);
47
- }
48
- return !!value;
49
- }
50
-
51
- // src/util/assertKey.ts
52
- function assertKey(key, debug) {
53
- return assert(
54
- key,
55
- "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.",
56
- debug
57
- );
58
- }
59
-
60
- // src/util/assertSolutionProvider.ts
61
- function assertSolutionProvider(solutionProvider, debug) {
62
- return assert("canSolve" in solutionProvider, "A solution provider without a [canSolve] property was added.", debug) && assert(
63
- "getSolutions" in solutionProvider,
64
- "A solution provider without a [getSolutions] property was added.",
65
- debug
66
- );
67
- }
68
-
69
- // src/util/flatJsonStringify.ts
70
- function flatJsonStringify(json) {
71
- const ancestors = /* @__PURE__ */ new WeakSet();
72
- const path = [];
73
- return JSON.stringify(json, function(_key, value) {
74
- if (typeof value !== "object" || value === null) {
75
- return value;
76
- }
77
- while (path.length > 0 && path[path.length - 1] !== this) {
78
- const popped = path.pop();
79
- ancestors.delete(popped);
80
- }
81
- if (ancestors.has(value)) {
82
- return "[Circular]";
83
- }
84
- ancestors.add(value);
85
- path.push(value);
86
- return value;
87
- });
88
- }
89
-
90
- // src/util/flattenOnce.ts
91
- function flattenOnce(array) {
92
- return array.reduce((flat, toFlatten) => {
93
- return flat.concat(toFlatten);
94
- }, []);
95
- }
96
-
97
- // src/util/glowsToEvents.ts
98
- function glowsToEvents(glows) {
99
- return glows.map((glow) => ({
100
- type: "php_glow",
101
- startTimeUnixNano: Math.round(glow.microtime * 1e9),
102
- endTimeUnixNano: null,
103
- attributes: {
104
- "glow.name": String(glow.name),
105
- "glow.level": glow.message_level,
106
- "glow.context": glow.meta_data ?? {}
107
- }
108
- }));
109
- }
110
-
111
- // src/util/now.ts
112
- function now() {
113
- return Math.round(Date.now() / 1e3);
114
- }
115
-
116
- // src/api/mapToV2Wire.ts
117
- var KNOWN_CONTEXT_BUCKETS = /* @__PURE__ */ new Set(["request", "request_data", "cookies", "context"]);
118
- var NON_APPLICATION_FRAME_PATTERN = /node_modules|vendor|chunk-/;
119
- function mapToV2Wire(report, config) {
120
- const wire = {
121
- seenAtUnixNano: Math.round(report.seen_at * 1e9),
122
- stacktrace: report.stacktrace.map(mapStackFrame),
123
- events: glowsToEvents(report.glows),
124
- attributes: buildAttributes(report, config)
125
- };
126
- if (report.exception_class) {
127
- wire.exceptionClass = report.exception_class;
128
- }
129
- if (report.message != null) {
130
- wire.message = report.message;
131
- }
132
- if (report.sourcemap_version_id) {
133
- wire.sourcemapVersionId = report.sourcemap_version_id;
134
- }
135
- return wire;
136
- }
137
- function mapStackFrame(frame) {
138
- const out = {
139
- file: frame.file,
140
- lineNumber: frame.line_number,
141
- isApplicationFrame: !NON_APPLICATION_FRAME_PATTERN.test(frame.file)
142
- };
143
- if (frame.column_number != null) {
144
- out.columnNumber = frame.column_number;
145
- }
146
- if (frame.method) {
147
- out.method = frame.method;
148
- }
149
- if (frame.class) {
150
- out.class = frame.class;
151
- }
152
- if (frame.code_snippet) {
153
- out.codeSnippet = frame.code_snippet;
154
- }
155
- return out;
156
- }
157
- function buildAttributes(report, config) {
158
- const attrs = {
159
- "telemetry.sdk.language": "javascript",
160
- "telemetry.sdk.name": "@flareapp/js",
161
- "telemetry.sdk.version": CLIENT_VERSION,
162
- "flare.language.name": "javascript",
163
- "flare.entry_point.type": "web"
164
- };
165
- if (typeof window !== "undefined" && window.location && window.location.href) {
166
- attrs["flare.entry_point.value"] = window.location.href;
167
- }
168
- if (config.stage) {
169
- attrs["service.stage"] = config.stage;
170
- }
171
- if (config.version) {
172
- attrs["service.version"] = config.version;
173
- }
174
- const context = report.context ?? {};
175
- if (context.request?.url) attrs["url.full"] = String(context.request.url);
176
- if (context.request?.useragent) attrs["user_agent.original"] = String(context.request.useragent);
177
- if (context.request?.referrer) attrs["http.request.referrer"] = String(context.request.referrer);
178
- if (context.request?.readyState) attrs["document.ready_state"] = String(context.request.readyState);
179
- if (context.request_data?.queryString) {
180
- attrs["url.query"] = context.request_data.queryString;
181
- }
182
- if (context.cookies) {
183
- attrs["http.request.cookies"] = context.cookies;
184
- }
185
- const custom = buildCustomContext(context);
186
- if (Object.keys(custom).length > 0) {
187
- attrs["context.custom"] = custom;
188
- }
189
- return attrs;
190
- }
191
- function buildCustomContext(context) {
192
- const custom = {};
193
- for (const key of Object.keys(context)) {
194
- if (KNOWN_CONTEXT_BUCKETS.has(key)) continue;
195
- custom[key] = context[key];
196
- }
197
- const added = context.context;
198
- if (added && typeof added === "object") {
199
- for (const key of Object.keys(added)) {
200
- custom[key] = added[key];
201
- }
202
- }
203
- return custom;
204
- }
205
-
206
- // src/api/Api.ts
207
- var Api = class {
208
- report(report, config) {
209
- return fetch(config.reportingUrl, {
210
- method: "POST",
211
- headers: {
212
- "Accept": "application/json",
213
- "Content-Type": "application/json",
214
- "X-Api-Token": config.key ?? "",
215
- "X-Report-Browser-Extension-Errors": JSON.stringify(config.reportBrowserExtensionErrors),
216
- "X-Flare-Client-Version": "1"
217
- },
218
- body: flatJsonStringify(mapToV2Wire(report, config))
219
- }).then(
220
- (response) => {
221
- if (response.status !== 200 && response.status !== 201 && response.status !== 204) {
222
- console.error(`Received response with status ${response.status} from Flare`);
223
- }
224
- },
225
- (error) => console.error(error)
226
- );
227
- }
228
- };
229
-
230
- // src/context/cookie.ts
231
- function cookie() {
232
- if (!window.document.cookie) {
233
- return {};
234
- }
235
- const cookies = {};
236
- for (const raw of window.document.cookie.split("; ")) {
237
- const eq = raw.indexOf("=");
238
- if (eq === -1) {
239
- continue;
240
- }
241
- const name = raw.slice(0, eq);
242
- const value = raw.slice(eq + 1);
243
- cookies[name] = value;
244
- }
245
- if (Object.keys(cookies).length === 0) {
246
- return {};
247
- }
248
- return { cookies };
249
- }
250
-
251
- // src/context/request.ts
252
- function request() {
253
- return {
254
- request: {
255
- url: window.document.location.href,
256
- useragent: window.navigator.userAgent,
257
- referrer: window.document.referrer,
258
- readyState: window.document.readyState
259
- }
260
- };
261
- }
262
-
263
- // src/context/requestData.ts
264
- function requestData() {
265
- if (!window.location.search) {
266
- return {};
267
- }
268
- const queryString = {};
269
- new URLSearchParams(window.location.search).forEach((value, key) => {
270
- queryString[key] = value;
271
- });
272
- return { request_data: { queryString } };
273
- }
274
-
275
- // src/context/collectContext.ts
276
- function collectContext(additionalContext) {
277
- if (typeof window === "undefined") {
278
- return additionalContext;
279
- }
280
- return {
281
- ...cookie(),
282
- ...request(),
283
- ...requestData(),
284
- ...additionalContext
285
- };
286
- }
287
-
288
- // src/solutions/getSolutions.ts
289
- function getSolutions(solutionProviders, error, extraSolutionParameters = {}) {
290
- return new Promise((resolve) => {
291
- const canSolves = solutionProviders.reduce(
292
- (canSolves2, provider) => {
293
- canSolves2.push(Promise.resolve(provider.canSolve(error, extraSolutionParameters)));
294
- return canSolves2;
295
- },
296
- []
297
- );
298
- Promise.all(canSolves).then((resolvedCanSolves) => {
299
- const solutionPromises = [];
300
- resolvedCanSolves.forEach((canSolve, i) => {
301
- if (canSolve) {
302
- solutionPromises.push(
303
- Promise.resolve(solutionProviders[i].getSolutions(error, extraSolutionParameters))
304
- );
305
- }
306
- });
307
- Promise.all(solutionPromises).then((solutions) => {
308
- resolve(flattenOnce(solutions));
309
- });
310
- });
311
- });
312
- }
313
-
314
- // src/stacktrace/createStackTrace.ts
315
- var import_error_stack_parser = __toESM(require("error-stack-parser"));
316
-
317
- // src/stacktrace/fileReader.ts
318
- var cachedFiles = {};
319
- function getCodeSnippet(url, lineNumber, columnNumber) {
320
- return new Promise((resolve) => {
321
- if (!url || !lineNumber) {
322
- return resolve({
323
- codeSnippet: {
324
- 0: `Could not read from file: missing file URL or line number. URL: ${url} lineNumber: ${lineNumber}`
325
- },
326
- trimmedColumnNumber: null
327
- });
328
- }
329
- readFile(url).then((fileText) => {
330
- if (!fileText) {
331
- return resolve({
332
- codeSnippet: {
333
- 0: `Could not read from file: Error while opening file at URL ${url}`
334
- },
335
- trimmedColumnNumber: null
336
- });
337
- }
338
- return resolve(readLinesFromFile(fileText, lineNumber, columnNumber));
339
- });
340
- });
341
- }
342
- function readFile(url) {
343
- if (cachedFiles[url]) {
344
- return Promise.resolve(cachedFiles[url]);
345
- }
346
- return fetch(url).then((response) => {
347
- if (response.status !== 200) {
348
- return null;
349
- }
350
- return response.text();
351
- }).catch(() => null);
352
- }
353
- function readLinesFromFile(fileText, lineNumber, columnNumber, maxSnippetLineLength = 1e3, maxSnippetLines = 40) {
354
- const codeSnippet = {};
355
- let trimmedColumnNumber = null;
356
- const lines = fileText.split("\n");
357
- for (let i = -maxSnippetLines / 2; i <= maxSnippetLines / 2; i++) {
358
- const currentLineIndex = lineNumber + i;
359
- if (currentLineIndex >= 0 && lines[currentLineIndex]) {
360
- const displayLine = currentLineIndex + 1;
361
- if (lines[currentLineIndex].length > maxSnippetLineLength) {
362
- if (columnNumber && columnNumber + maxSnippetLineLength / 2 > maxSnippetLineLength) {
363
- codeSnippet[displayLine] = lines[currentLineIndex].substr(
364
- columnNumber - Math.round(maxSnippetLineLength / 2),
365
- maxSnippetLineLength
366
- );
367
- if (displayLine === lineNumber) {
368
- trimmedColumnNumber = Math.round(maxSnippetLineLength / 2);
369
- }
370
- continue;
371
- }
372
- codeSnippet[displayLine] = lines[currentLineIndex].substr(0, maxSnippetLineLength) + "\u2026";
373
- continue;
374
- }
375
- codeSnippet[displayLine] = lines[currentLineIndex];
376
- }
377
- }
378
- return { codeSnippet, trimmedColumnNumber };
379
- }
380
-
381
- // src/stacktrace/createStackTrace.ts
382
- function createStackTrace(error, debug) {
383
- return new Promise((resolve) => {
384
- if (!hasStack(error)) {
385
- assert(false, "Couldn't generate stacktrace of below error:", debug);
386
- if (debug) {
387
- console.error(error);
388
- }
389
- return resolve([fallbackFrame("stacktrace missing")]);
390
- }
391
- let parsed;
392
- try {
393
- parsed = import_error_stack_parser.default.parse(error);
394
- } catch (parseError) {
395
- if (debug) {
396
- console.error("Flare: failed to parse stacktrace", parseError);
397
- }
398
- return resolve([fallbackFrame("Could not parse stacktrace")]);
399
- }
400
- Promise.all(
401
- parsed.map((frame) => {
402
- return new Promise((resolve2) => {
403
- getCodeSnippet(frame.fileName, frame.lineNumber, frame.columnNumber).then((snippet) => {
404
- resolve2({
405
- line_number: frame.lineNumber || 1,
406
- column_number: frame.columnNumber || 1,
407
- method: frame.functionName || "Anonymous or unknown function",
408
- file: frame.fileName || "Unknown file",
409
- code_snippet: snippet.codeSnippet,
410
- trimmed_column_number: snippet.trimmedColumnNumber,
411
- class: ""
412
- });
413
- });
414
- });
415
- })
416
- ).then(resolve);
417
- });
418
- }
419
- function fallbackFrame(message) {
420
- return {
421
- line_number: 0,
422
- column_number: 0,
423
- method: "unknown",
424
- file: "unknown",
425
- code_snippet: { 0: message },
426
- trimmed_column_number: null,
427
- class: "unknown"
428
- };
429
- }
430
- function hasStack(err) {
431
- return !!err && (!!err.stack || !!err.stacktrace || !!err["opera#sourceloc"]) && typeof (err.stack || err.stacktrace || err["opera#sourceloc"]) === "string" && err.stack !== `${err.name}: ${err.message}`;
432
- }
433
-
434
- // src/Flare.ts
435
- var Flare = class {
436
- constructor(api = new Api()) {
437
- this.api = api;
438
- this.config = {
439
- key: null,
440
- version: CLIENT_VERSION,
441
- sourcemapVersion: SOURCEMAP_VERSION,
442
- stage: "",
443
- maxGlowsPerReport: 30,
444
- reportingUrl: "https://ingress.flareapp.io/v1/errors",
445
- reportBrowserExtensionErrors: false,
446
- debug: false,
447
- beforeEvaluate: (error) => error,
448
- beforeSubmit: (report) => report
449
- };
450
- this.glows = [];
451
- this.context = { context: {} };
452
- this.solutionProviders = [];
453
- }
454
- light(key = KEY, debug = false) {
455
- this.config.key = key;
456
- this.config.debug = debug;
457
- return this;
458
- }
459
- configure(config) {
460
- this.config = { ...this.config, ...config };
461
- return this;
462
- }
463
- test() {
464
- return this.report(new Error("The Flare client is set up correctly!"));
465
- }
466
- glow(name, level = "info", data = []) {
467
- const time = now();
468
- this.glows.push({
469
- name,
470
- message_level: level,
471
- meta_data: data,
472
- time,
473
- microtime: time
474
- });
475
- if (this.glows.length > this.config.maxGlowsPerReport) {
476
- this.glows = this.glows.slice(this.glows.length - this.config.maxGlowsPerReport);
477
- }
478
- return this;
479
- }
480
- clearGlows() {
481
- this.glows = [];
482
- return this;
483
- }
484
- addContext(name, value) {
485
- this.context.context[name] = value;
486
- return this;
487
- }
488
- addContextGroup(groupName, value) {
489
- this.context[groupName] = value;
490
- return this;
491
- }
492
- registerSolutionProvider(solutionProvider) {
493
- if (!assertSolutionProvider(solutionProvider, this.config.debug)) {
494
- return this;
495
- }
496
- this.solutionProviders.push(solutionProvider);
497
- return this;
498
- }
499
- async report(error, context = {}, extraSolutionParameters = {}) {
500
- const errorToReport = await this.config.beforeEvaluate(error);
501
- if (!errorToReport) {
502
- return;
503
- }
504
- const report = await this.createReportFromError(error, context, extraSolutionParameters);
505
- if (!report) {
506
- return;
507
- }
508
- return this.sendReport(report);
509
- }
510
- async reportMessage(message, context = {}, exceptionClass = "Log") {
511
- const stackTrace = await createStackTrace(Error(), this.config.debug);
512
- stackTrace.shift();
513
- this.sendReport({
514
- notifier: `Flare JavaScript client v${CLIENT_VERSION}`,
515
- exception_class: exceptionClass,
516
- seen_at: now(),
517
- message,
518
- language: "javascript",
519
- glows: this.glows,
520
- context: collectContext({ ...context, ...this.context }),
521
- stacktrace: stackTrace,
522
- sourcemap_version_id: this.config.sourcemapVersion,
523
- solutions: [],
524
- stage: this.config.stage
525
- });
526
- }
527
- createReportFromError(error, context = {}, extraSolutionParameters = {}) {
528
- if (!assert(error, "No error provided.", this.config.debug)) {
529
- return Promise.resolve(false);
530
- }
531
- const seenAt = now();
532
- return Promise.all([
533
- getSolutions(this.solutionProviders, error, extraSolutionParameters),
534
- createStackTrace(error, this.config.debug)
535
- ]).then((result) => {
536
- const [solutions, stacktrace] = result;
537
- assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this.config.debug);
538
- return {
539
- notifier: `Flare JavaScript client v${CLIENT_VERSION}`,
540
- exception_class: error.constructor && error.constructor.name ? error.constructor.name : "undefined",
541
- seen_at: seenAt,
542
- message: error.message,
543
- language: "javascript",
544
- glows: this.glows,
545
- context: collectContext({ ...context, ...this.context }),
546
- stacktrace,
547
- sourcemap_version_id: this.config.sourcemapVersion,
548
- solutions,
549
- stage: this.config.stage
550
- };
551
- });
552
- }
553
- async sendReport(report) {
554
- if (!assertKey(this.config.key, this.config.debug)) {
555
- return;
556
- }
557
- const reportToSubmit = await this.config.beforeSubmit(report);
558
- if (!reportToSubmit) {
559
- return;
560
- }
561
- return this.api.report(reportToSubmit, this.config);
562
- }
563
- // Deprecated, the following methods exist for backwards compatibility.
564
- set beforeEvaluate(beforeEvaluate) {
565
- this.config.beforeEvaluate = beforeEvaluate ?? "";
566
- }
567
- set beforeSubmit(beforeSubmit) {
568
- this.config.beforeSubmit = beforeSubmit ?? "";
569
- }
570
- set stage(stage) {
571
- this.config.stage = stage ?? "";
572
- }
573
- };
574
-
575
- // src/browser/catchWindowErrors.ts
576
- function catchWindowErrors() {
577
- if (typeof window === "undefined") {
578
- return;
579
- }
580
- const flare2 = window.flare;
581
- if (!window || !flare2) {
582
- return;
583
- }
584
- window.addEventListener("error", (event) => {
585
- if (event.error) {
586
- flare2.report(event.error);
587
- }
588
- });
589
- window.addEventListener("unhandledrejection", (event) => {
590
- const reason = event.reason;
591
- if (reason instanceof Error) {
592
- flare2.report(reason);
593
- return;
594
- }
595
- if (hasStack2(reason)) {
596
- const error = new Error(rejectionReasonToMessage(reason));
597
- error.stack = reason.stack;
598
- flare2.report(error);
599
- return;
600
- }
601
- flare2.reportMessage(rejectionReasonToMessage(reason), {}, "UnhandledPromiseRejection");
602
- });
603
- }
604
- function rejectionReasonToMessage(reason) {
605
- if (typeof reason === "string") {
606
- return reason;
607
- }
608
- if (reason == null) {
609
- return `Unhandled promise rejection (${reason})`;
610
- }
611
- if (typeof reason === "object") {
612
- if ("message" in reason && typeof reason.message === "string") {
613
- return reason.message;
614
- }
615
- try {
616
- const json = JSON.stringify(reason);
617
- if (json && json !== "{}") {
618
- return `Unhandled promise rejection: ${json}`;
619
- }
620
- } catch {
621
- }
622
- return "Unhandled promise rejection with non-serializable object";
623
- }
624
- return `Unhandled promise rejection: ${String(reason)}`;
625
- }
626
- function hasStack2(value) {
627
- return typeof value === "object" && value !== null && "stack" in value && typeof value.stack === "string";
628
- }
629
-
630
- // src/index.ts
631
- var flare = new Flare();
632
- if (typeof window !== "undefined" && window) {
633
- window.flare = flare;
634
- catchWindowErrors();
635
- }
636
- // Annotate the CommonJS export names for ESM import in node:
637
- 0 && (module.exports = {
638
- Flare,
639
- flare
640
- });