@honeybadger-io/js 5.1.5-alpha-3 → 5.2.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.
@@ -1,2209 +0,0 @@
1
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
-
3
- function getDefaultExportFromCjs (x) {
4
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5
- }
6
-
7
- function getAugmentedNamespace(n) {
8
- var f = n.default;
9
- if (typeof f == "function") {
10
- var a = function () {
11
- return f.apply(this, arguments);
12
- };
13
- a.prototype = f.prototype;
14
- } else a = {};
15
- Object.defineProperty(a, '__esModule', {value: true});
16
- Object.keys(n).forEach(function (k) {
17
- var d = Object.getOwnPropertyDescriptor(n, k);
18
- Object.defineProperty(a, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () {
21
- return n[k];
22
- }
23
- });
24
- });
25
- return a;
26
- }
27
-
28
- var browser$1 = {};
29
-
30
- var src = {};
31
-
32
- var client = {};
33
-
34
- var util$1 = {};
35
-
36
- var UNKNOWN_FUNCTION = '<unknown>';
37
- /**
38
- * This parses the different stack traces and puts them into one format
39
- * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)
40
- */
41
-
42
- function parse(stackString) {
43
- var lines = stackString.split('\n');
44
- return lines.reduce(function (stack, line) {
45
- var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
46
-
47
- if (parseResult) {
48
- stack.push(parseResult);
49
- }
50
-
51
- return stack;
52
- }, []);
53
- }
54
- var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
55
- var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
56
-
57
- function parseChrome(line) {
58
- var parts = chromeRe.exec(line);
59
-
60
- if (!parts) {
61
- return null;
62
- }
63
-
64
- var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
65
-
66
- var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
67
-
68
- var submatch = chromeEvalRe.exec(parts[2]);
69
-
70
- if (isEval && submatch != null) {
71
- // throw out eval line/column and use top-most line/column number
72
- parts[2] = submatch[1]; // url
73
-
74
- parts[3] = submatch[2]; // line
75
-
76
- parts[4] = submatch[3]; // column
77
- }
78
-
79
- return {
80
- file: !isNative ? parts[2] : null,
81
- methodName: parts[1] || UNKNOWN_FUNCTION,
82
- arguments: isNative ? [parts[2]] : [],
83
- lineNumber: parts[3] ? +parts[3] : null,
84
- column: parts[4] ? +parts[4] : null
85
- };
86
- }
87
-
88
- var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
89
-
90
- function parseWinjs(line) {
91
- var parts = winjsRe.exec(line);
92
-
93
- if (!parts) {
94
- return null;
95
- }
96
-
97
- return {
98
- file: parts[2],
99
- methodName: parts[1] || UNKNOWN_FUNCTION,
100
- arguments: [],
101
- lineNumber: +parts[3],
102
- column: parts[4] ? +parts[4] : null
103
- };
104
- }
105
-
106
- var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
107
- var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
108
-
109
- function parseGecko(line) {
110
- var parts = geckoRe.exec(line);
111
-
112
- if (!parts) {
113
- return null;
114
- }
115
-
116
- var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
117
- var submatch = geckoEvalRe.exec(parts[3]);
118
-
119
- if (isEval && submatch != null) {
120
- // throw out eval line/column and use top-most line number
121
- parts[3] = submatch[1];
122
- parts[4] = submatch[2];
123
- parts[5] = null; // no column when eval
124
- }
125
-
126
- return {
127
- file: parts[3],
128
- methodName: parts[1] || UNKNOWN_FUNCTION,
129
- arguments: parts[2] ? parts[2].split(',') : [],
130
- lineNumber: parts[4] ? +parts[4] : null,
131
- column: parts[5] ? +parts[5] : null
132
- };
133
- }
134
-
135
- var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
136
-
137
- function parseJSC(line) {
138
- var parts = javaScriptCoreRe.exec(line);
139
-
140
- if (!parts) {
141
- return null;
142
- }
143
-
144
- return {
145
- file: parts[3],
146
- methodName: parts[1] || UNKNOWN_FUNCTION,
147
- arguments: [],
148
- lineNumber: +parts[4],
149
- column: parts[5] ? +parts[5] : null
150
- };
151
- }
152
-
153
- var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
154
-
155
- function parseNode(line) {
156
- var parts = nodeRe.exec(line);
157
-
158
- if (!parts) {
159
- return null;
160
- }
161
-
162
- return {
163
- file: parts[2],
164
- methodName: parts[1] || UNKNOWN_FUNCTION,
165
- arguments: [],
166
- lineNumber: +parts[3],
167
- column: parts[4] ? +parts[4] : null
168
- };
169
- }
170
-
171
- var stackTraceParser_esm = /*#__PURE__*/Object.freeze({
172
- __proto__: null,
173
- parse: parse
174
- });
175
-
176
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(stackTraceParser_esm);
177
-
178
- (function (exports) {
179
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
180
- if (k2 === undefined) k2 = k;
181
- var desc = Object.getOwnPropertyDescriptor(m, k);
182
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
183
- desc = { enumerable: true, get: function() { return m[k]; } };
184
- }
185
- Object.defineProperty(o, k2, desc);
186
- }) : (function(o, m, k, k2) {
187
- if (k2 === undefined) k2 = k;
188
- o[k2] = m[k];
189
- }));
190
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
191
- Object.defineProperty(o, "default", { enumerable: true, value: v });
192
- }) : function(o, v) {
193
- o["default"] = v;
194
- });
195
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
196
- if (mod && mod.__esModule) return mod;
197
- var result = {};
198
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
199
- __setModuleDefault(result, mod);
200
- return result;
201
- };
202
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
203
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
204
- return new (P || (P = Promise))(function (resolve, reject) {
205
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
206
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
207
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
208
- step((generator = generator.apply(thisArg, _arguments || [])).next());
209
- });
210
- };
211
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
212
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
213
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
214
- function verb(n) { return function (v) { return step([n, v]); }; }
215
- function step(op) {
216
- if (f) throw new TypeError("Generator is already executing.");
217
- while (_) try {
218
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
219
- if (y = 0, t) op = [op[0] & 2, t.value];
220
- switch (op[0]) {
221
- case 0: case 1: t = op; break;
222
- case 4: _.label++; return { value: op[1], done: false };
223
- case 5: _.label++; y = op[1]; op = [0]; continue;
224
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
225
- default:
226
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
227
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
228
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
229
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
230
- if (t[2]) _.ops.pop();
231
- _.trys.pop(); continue;
232
- }
233
- op = body.call(thisArg, _);
234
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
235
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
236
- }
237
- };
238
- Object.defineProperty(exports, "__esModule", { value: true });
239
- exports.isBrowserConfig = exports.clone = exports.formatCGIData = exports.filterUrl = exports.filter = exports.generateStackTrace = exports.endpoint = exports.instrument = exports.isErrorObject = exports.makeNotice = exports.logger = exports.sanitize = exports.shallowClone = exports.runAfterNotifyHandlers = exports.runBeforeNotifyHandlers = exports.getSourceForBacktrace = exports.getCauses = exports.calculateBacktraceShift = exports.DEFAULT_BACKTRACE_SHIFT = exports.makeBacktrace = exports.objectIsExtensible = exports.objectIsEmpty = exports.mergeNotice = exports.merge = void 0;
240
- var stackTraceParser = __importStar(require$$0);
241
- function merge(obj1, obj2) {
242
- var result = {};
243
- for (var k in obj1) {
244
- result[k] = obj1[k];
245
- }
246
- for (var k in obj2) {
247
- result[k] = obj2[k];
248
- }
249
- return result;
250
- }
251
- exports.merge = merge;
252
- function mergeNotice(notice1, notice2) {
253
- var result = merge(notice1, notice2);
254
- if (notice1.context && notice2.context) {
255
- result.context = merge(notice1.context, notice2.context);
256
- }
257
- return result;
258
- }
259
- exports.mergeNotice = mergeNotice;
260
- function objectIsEmpty(obj) {
261
- for (var k in obj) {
262
- if (Object.prototype.hasOwnProperty.call(obj, k)) {
263
- return false;
264
- }
265
- }
266
- return true;
267
- }
268
- exports.objectIsEmpty = objectIsEmpty;
269
- function objectIsExtensible(obj) {
270
- if (typeof Object.isExtensible !== 'function') {
271
- return true;
272
- }
273
- return Object.isExtensible(obj);
274
- }
275
- exports.objectIsExtensible = objectIsExtensible;
276
- function makeBacktrace(stack, filterHbSourceCode, logger) {
277
- if (filterHbSourceCode === void 0) { filterHbSourceCode = false; }
278
- if (logger === void 0) { logger = console; }
279
- try {
280
- var backtrace = stackTraceParser
281
- .parse(stack)
282
- .map(function (line) {
283
- return {
284
- file: line.file,
285
- method: line.methodName,
286
- number: line.lineNumber,
287
- column: line.column
288
- };
289
- });
290
- if (filterHbSourceCode) {
291
- backtrace.splice(0, calculateBacktraceShift(backtrace));
292
- }
293
- return backtrace;
294
- }
295
- catch (err) {
296
- logger.debug(err);
297
- return [];
298
- }
299
- }
300
- exports.makeBacktrace = makeBacktrace;
301
- function isFrameFromHbSourceCode(frame) {
302
- var hasHbFile = false;
303
- var hasHbMethod = false;
304
- if (frame.file) {
305
- hasHbFile = frame.file.toLowerCase().indexOf('@honeybadger-io') > -1;
306
- }
307
- if (frame.method) {
308
- hasHbMethod = frame.method.toLowerCase().indexOf('@honeybadger-io') > -1;
309
- }
310
- return hasHbFile || hasHbMethod;
311
- }
312
- exports.DEFAULT_BACKTRACE_SHIFT = 3;
313
- /**
314
- * If {@link generateStackTrace} is used, we want to exclude frames that come from
315
- * Honeybadger's source code.
316
- *
317
- * Logic:
318
- * - For each frame, increment the shift if source code is from Honeybadger
319
- * - If a frame from an <anonymous> file is encountered increment the shift ONLY if between Honeybadger source code
320
- * (i.e. previous and next frames are from Honeybadger)
321
- * - Exit when frame encountered is not from Honeybadger source code
322
- *
323
- * Note: this will not always work, especially in browser versions where code
324
- * is minified, uglified and bundled.
325
- * For those cases we default to 3:
326
- * - generateStackTrace
327
- * - makeNotice
328
- * - notify
329
- */
330
- function calculateBacktraceShift(backtrace) {
331
- var shift = 0;
332
- for (var i = 0; i < backtrace.length; i++) {
333
- var frame = backtrace[i];
334
- if (isFrameFromHbSourceCode(frame)) {
335
- shift++;
336
- continue;
337
- }
338
- if (!frame.file || frame.file === '<anonymous>') {
339
- var nextFrame = backtrace[i + 1];
340
- if (nextFrame && isFrameFromHbSourceCode(nextFrame)) {
341
- shift++;
342
- continue;
343
- }
344
- }
345
- break;
346
- }
347
- return shift || exports.DEFAULT_BACKTRACE_SHIFT;
348
- }
349
- exports.calculateBacktraceShift = calculateBacktraceShift;
350
- function getCauses(notice, logger) {
351
- if (notice.cause) {
352
- var causes = [];
353
- var cause = notice;
354
- while (causes.length < 3 && (cause = cause.cause)) {
355
- causes.push({
356
- class: cause.name,
357
- message: cause.message,
358
- backtrace: typeof cause.stack == 'string' ? makeBacktrace(cause.stack, false, logger) : null
359
- });
360
- }
361
- return causes;
362
- }
363
- return [];
364
- }
365
- exports.getCauses = getCauses;
366
- function getSourceForBacktrace(backtrace, getSourceFileHandler) {
367
- return __awaiter(this, void 0, void 0, function () {
368
- var result, index, trace, fileContent;
369
- return __generator(this, function (_a) {
370
- switch (_a.label) {
371
- case 0:
372
- result = [];
373
- if (!getSourceFileHandler || !backtrace || !backtrace.length) {
374
- return [2 /*return*/, result];
375
- }
376
- index = 0;
377
- _a.label = 1;
378
- case 1:
379
- if (!backtrace.length) return [3 /*break*/, 3];
380
- trace = backtrace.splice(0)[index];
381
- return [4 /*yield*/, getSourceFileHandler(trace.file)];
382
- case 2:
383
- fileContent = _a.sent();
384
- result[index] = getSourceCodeSnippet(fileContent, trace.number);
385
- index++;
386
- return [3 /*break*/, 1];
387
- case 3: return [2 /*return*/, result];
388
- }
389
- });
390
- });
391
- }
392
- exports.getSourceForBacktrace = getSourceForBacktrace;
393
- function runBeforeNotifyHandlers(notice, handlers) {
394
- var result = true;
395
- for (var i = 0, len = handlers.length; i < len; i++) {
396
- var handler = handlers[i];
397
- if (handler(notice) === false) {
398
- result = false;
399
- }
400
- }
401
- return result;
402
- }
403
- exports.runBeforeNotifyHandlers = runBeforeNotifyHandlers;
404
- function runAfterNotifyHandlers(notice, handlers, error) {
405
- if (notice && notice.afterNotify) {
406
- notice.afterNotify(error, notice);
407
- }
408
- for (var i = 0, len = handlers.length; i < len; i++) {
409
- handlers[i](error, notice);
410
- }
411
- return true;
412
- }
413
- exports.runAfterNotifyHandlers = runAfterNotifyHandlers;
414
- // Returns a new object with properties from other object.
415
- function shallowClone(obj) {
416
- if (typeof (obj) !== 'object' || obj === null) {
417
- return {};
418
- }
419
- var result = {};
420
- for (var k in obj) {
421
- result[k] = obj[k];
422
- }
423
- return result;
424
- }
425
- exports.shallowClone = shallowClone;
426
- function sanitize(obj, maxDepth) {
427
- if (maxDepth === void 0) { maxDepth = 8; }
428
- var seenObjects = [];
429
- function seen(obj) {
430
- if (!obj || typeof (obj) !== 'object') {
431
- return false;
432
- }
433
- for (var i = 0; i < seenObjects.length; i++) {
434
- var value = seenObjects[i];
435
- if (value === obj) {
436
- return true;
437
- }
438
- }
439
- seenObjects.push(obj);
440
- return false;
441
- }
442
- function canSerialize(obj) {
443
- var typeOfObj = typeof obj;
444
- // Functions are TMI
445
- if (/function/.test(typeOfObj)) {
446
- // Let special toJSON method pass as it's used by JSON.stringify (#722)
447
- return obj.name === 'toJSON';
448
- }
449
- // Symbols can't convert to strings.
450
- if (/symbol/.test(typeOfObj)) {
451
- return false;
452
- }
453
- if (obj === null) {
454
- return false;
455
- }
456
- // No prototype, likely created with `Object.create(null)`.
457
- if (typeof obj === 'object' && typeof obj.hasOwnProperty === 'undefined') {
458
- return false;
459
- }
460
- return true;
461
- }
462
- function serialize(obj, depth) {
463
- if (depth === void 0) { depth = 0; }
464
- if (depth >= maxDepth) {
465
- return '[DEPTH]';
466
- }
467
- // Inspect invalid types
468
- if (!canSerialize(obj)) {
469
- return Object.prototype.toString.call(obj);
470
- }
471
- // Halt circular references
472
- if (seen(obj)) {
473
- return '[RECURSION]';
474
- }
475
- // Serialize inside arrays
476
- if (Array.isArray(obj)) {
477
- return obj.map(function (o) { return safeSerialize(o, depth + 1); });
478
- }
479
- // Serialize inside objects
480
- if (typeof (obj) === 'object') {
481
- var ret = {};
482
- for (var k in obj) {
483
- var v = obj[k];
484
- if (Object.prototype.hasOwnProperty.call(obj, k) && (k != null) && (v != null)) {
485
- ret[k] = safeSerialize(v, depth + 1);
486
- }
487
- }
488
- return ret;
489
- }
490
- // Return everything else untouched
491
- return obj;
492
- }
493
- function safeSerialize(obj, depth) {
494
- if (depth === void 0) { depth = 0; }
495
- try {
496
- return serialize(obj, depth);
497
- }
498
- catch (e) {
499
- return "[ERROR] ".concat(e);
500
- }
501
- }
502
- return safeSerialize(obj);
503
- }
504
- exports.sanitize = sanitize;
505
- function logger(client) {
506
- var log = function (method) {
507
- return function () {
508
- var _a;
509
- var args = [];
510
- for (var _i = 0; _i < arguments.length; _i++) {
511
- args[_i] = arguments[_i];
512
- }
513
- if (method === 'debug') {
514
- if (!client.config.debug) {
515
- return;
516
- }
517
- // Log at default level so that you don't need to also enable verbose
518
- // logging in Chrome.
519
- method = 'log';
520
- }
521
- args.unshift('[Honeybadger]');
522
- (_a = client.config.logger)[method].apply(_a, args);
523
- };
524
- };
525
- return {
526
- log: log('log'),
527
- info: log('info'),
528
- debug: log('debug'),
529
- warn: log('warn'),
530
- error: log('error')
531
- };
532
- }
533
- exports.logger = logger;
534
- /**
535
- * Converts any object into a notice object (which at minimum has the same
536
- * properties as Error, but supports additional Honeybadger properties.)
537
- */
538
- function makeNotice(thing) {
539
- var notice;
540
- if (!thing) {
541
- notice = {};
542
- }
543
- else if (isErrorObject(thing)) {
544
- var e = thing;
545
- notice = merge(thing, { name: e.name, message: e.message, stack: e.stack, cause: e.cause });
546
- }
547
- else if (typeof thing === 'object') {
548
- notice = shallowClone(thing);
549
- }
550
- else {
551
- var m = String(thing);
552
- notice = { message: m };
553
- }
554
- return notice;
555
- }
556
- exports.makeNotice = makeNotice;
557
- function isErrorObject(thing) {
558
- return thing instanceof Error
559
- || Object.prototype.toString.call(thing) === '[object Error]'; // Important for cross-realm objects
560
- }
561
- exports.isErrorObject = isErrorObject;
562
- /**
563
- * Instrument an existing function inside an object (usually global).
564
- * @param {!Object} object
565
- * @param {!String} name
566
- * @param {!Function} replacement
567
- */
568
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
569
- function instrument(object, name, replacement) {
570
- if (!object || !name || !replacement || !(name in object)) {
571
- return;
572
- }
573
- try {
574
- var original = object[name];
575
- while (original && original.__hb_original) {
576
- original = original.__hb_original;
577
- }
578
- object[name] = replacement(original);
579
- object[name].__hb_original = original;
580
- }
581
- catch (_e) {
582
- // Ignores errors where "original" is a restricted object (see #1001)
583
- // Uncaught Error: Permission denied to access property "__hb_original"
584
- // Also ignores:
585
- // Error: TypeError: Cannot set property onunhandledrejection of [object Object] which has only a getter
586
- // User-Agent: Mozilla/5.0 (Linux; Android 10; SAMSUNG SM-G960F) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/12.1 Chrome/79.0.3945.136 Mobile Safari/537.36
587
- }
588
- }
589
- exports.instrument = instrument;
590
- function endpoint(base, path) {
591
- var endpoint = base.trim().replace(/\/$/, '');
592
- path = path.trim().replace(/(^\/|\/$)/g, '');
593
- return "".concat(endpoint, "/").concat(path);
594
- }
595
- exports.endpoint = endpoint;
596
- function generateStackTrace() {
597
- try {
598
- throw new Error('');
599
- }
600
- catch (e) {
601
- if (e.stack) {
602
- return e.stack;
603
- }
604
- }
605
- var maxStackSize = 10;
606
- var stack = [];
607
- var curr = arguments.callee;
608
- while (curr && stack.length < maxStackSize) {
609
- if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
610
- stack.push(RegExp.$1 || '<anonymous>');
611
- }
612
- else {
613
- stack.push('<anonymous>');
614
- }
615
- try {
616
- curr = curr.caller;
617
- }
618
- catch (e) {
619
- break;
620
- }
621
- }
622
- return stack.join('\n');
623
- }
624
- exports.generateStackTrace = generateStackTrace;
625
- function filter(obj, filters) {
626
- if (!is('Object', obj)) {
627
- return;
628
- }
629
- if (!is('Array', filters)) {
630
- filters = [];
631
- }
632
- var seen = [];
633
- function filter(obj) {
634
- var k, newObj;
635
- if (is('Object', obj) || is('Array', obj)) {
636
- if (seen.indexOf(obj) !== -1) {
637
- return '[CIRCULAR DATA STRUCTURE]';
638
- }
639
- seen.push(obj);
640
- }
641
- if (is('Object', obj)) {
642
- newObj = {};
643
- for (k in obj) {
644
- if (filterMatch(k, filters)) {
645
- newObj[k] = '[FILTERED]';
646
- }
647
- else {
648
- newObj[k] = filter(obj[k]);
649
- }
650
- }
651
- return newObj;
652
- }
653
- if (is('Array', obj)) {
654
- return obj.map(function (v) {
655
- return filter(v);
656
- });
657
- }
658
- if (is('Function', obj)) {
659
- return '[FUNC]';
660
- }
661
- return obj;
662
- }
663
- return filter(obj);
664
- }
665
- exports.filter = filter;
666
- function filterMatch(key, filters) {
667
- for (var i = 0; i < filters.length; i++) {
668
- if (key.toLowerCase().indexOf(filters[i].toLowerCase()) !== -1) {
669
- return true;
670
- }
671
- }
672
- return false;
673
- }
674
- function is(type, obj) {
675
- var klass = Object.prototype.toString.call(obj).slice(8, -1);
676
- return obj !== undefined && obj !== null && klass === type;
677
- }
678
- function filterUrl(url, filters) {
679
- if (!filters) {
680
- return url;
681
- }
682
- if (typeof url !== 'string') {
683
- return url;
684
- }
685
- var query = url.split(/\?/, 2)[1];
686
- if (!query) {
687
- return url;
688
- }
689
- var result = url;
690
- query.split(/[&]\s?/).forEach(function (pair) {
691
- var _a = pair.split('=', 2), key = _a[0], value = _a[1];
692
- if (filterMatch(key, filters)) {
693
- result = result.replace("".concat(key, "=").concat(value), "".concat(key, "=[FILTERED]"));
694
- }
695
- });
696
- return result;
697
- }
698
- exports.filterUrl = filterUrl;
699
- function formatCGIData(vars, prefix) {
700
- if (prefix === void 0) { prefix = ''; }
701
- var formattedVars = {};
702
- Object.keys(vars).forEach(function (key) {
703
- var formattedKey = prefix + key.replace(/\W/g, '_').toUpperCase();
704
- formattedVars[formattedKey] = vars[key];
705
- });
706
- return formattedVars;
707
- }
708
- exports.formatCGIData = formatCGIData;
709
- function clone(obj) {
710
- return JSON.parse(JSON.stringify(obj));
711
- }
712
- exports.clone = clone;
713
- function getSourceCodeSnippet(fileData, lineNumber, sourceRadius) {
714
- if (sourceRadius === void 0) { sourceRadius = 2; }
715
- if (!fileData) {
716
- return null;
717
- }
718
- var lines = fileData.split('\n');
719
- // add one empty line because array index starts from 0, but error line number is counted from 1
720
- lines.unshift('');
721
- var start = lineNumber - sourceRadius;
722
- var end = lineNumber + sourceRadius;
723
- var result = {};
724
- for (var i = start; i <= end; i++) {
725
- var line = lines[i];
726
- if (typeof line === 'string') {
727
- result[i] = line;
728
- }
729
- }
730
- return result;
731
- }
732
- function isBrowserConfig(config) {
733
- return config.async !== undefined;
734
- }
735
- exports.isBrowserConfig = isBrowserConfig;
736
-
737
- } (util$1));
738
-
739
- var store = {};
740
-
741
- Object.defineProperty(store, "__esModule", { value: true });
742
- store.GlobalStore = void 0;
743
- var util_1$7 = util$1;
744
- var GlobalStore = /** @class */ (function () {
745
- function GlobalStore(contents, breadcrumbsLimit) {
746
- this.contents = contents;
747
- this.breadcrumbsLimit = breadcrumbsLimit;
748
- }
749
- GlobalStore.create = function (contents, breadcrumbsLimit) {
750
- return new GlobalStore(contents, breadcrumbsLimit);
751
- };
752
- GlobalStore.prototype.available = function () {
753
- return true;
754
- };
755
- GlobalStore.prototype.getContents = function (key) {
756
- var value = key ? this.contents[key] : this.contents;
757
- return JSON.parse(JSON.stringify(value));
758
- };
759
- GlobalStore.prototype.setContext = function (context) {
760
- this.contents.context = (0, util_1$7.merge)(this.contents.context, context || {});
761
- };
762
- GlobalStore.prototype.addBreadcrumb = function (breadcrumb) {
763
- if (this.contents.breadcrumbs.length == this.breadcrumbsLimit) {
764
- this.contents.breadcrumbs.shift();
765
- }
766
- this.contents.breadcrumbs.push(breadcrumb);
767
- };
768
- GlobalStore.prototype.clear = function () {
769
- this.contents.context = {};
770
- this.contents.breadcrumbs = [];
771
- };
772
- GlobalStore.prototype.run = function (callback) {
773
- return callback();
774
- };
775
- return GlobalStore;
776
- }());
777
- store.GlobalStore = GlobalStore;
778
-
779
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
780
- __assign = Object.assign || function(t) {
781
- for (var s, i = 1, n = arguments.length; i < n; i++) {
782
- s = arguments[i];
783
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
784
- t[p] = s[p];
785
- }
786
- return t;
787
- };
788
- return __assign.apply(this, arguments);
789
- };
790
- Object.defineProperty(client, "__esModule", { value: true });
791
- client.Client = void 0;
792
- var util_1$6 = util$1;
793
- var store_1 = store;
794
- var notifier = {
795
- name: 'honeybadger-js',
796
- url: 'https://github.com/honeybadger-io/honeybadger-js',
797
- version: '5.1.1'
798
- };
799
- // Split at commas and spaces
800
- var TAG_SEPARATOR = /,|\s+/;
801
- // Checks for non-blank characters
802
- var NOT_BLANK = /\S/;
803
- var Client = /** @class */ (function () {
804
- function Client(opts, transport) {
805
- if (opts === void 0) { opts = {}; }
806
- this.__pluginsExecuted = false;
807
- this.__store = null;
808
- this.__beforeNotifyHandlers = [];
809
- this.__afterNotifyHandlers = [];
810
- this.config = __assign({ apiKey: null, endpoint: 'https://api.honeybadger.io', environment: null, hostname: null, projectRoot: null, component: null, action: null, revision: null, reportData: null, breadcrumbsEnabled: true, maxBreadcrumbs: 40, maxObjectDepth: 8, logger: console, developmentEnvironments: ['dev', 'development', 'test'], debug: false, tags: null, enableUncaught: true, enableUnhandledRejection: true, afterUncaught: function () { return true; }, filters: ['creditcard', 'password'], __plugins: [] }, opts);
811
- this.__initStore();
812
- this.__transport = transport;
813
- this.logger = (0, util_1$6.logger)(this);
814
- }
815
- Client.prototype.getVersion = function () {
816
- return notifier.version;
817
- };
818
- Client.prototype.configure = function (opts) {
819
- var _this = this;
820
- if (opts === void 0) { opts = {}; }
821
- for (var k in opts) {
822
- this.config[k] = opts[k];
823
- }
824
- if (!this.__pluginsExecuted) {
825
- this.__pluginsExecuted = true;
826
- this.config.__plugins.forEach(function (plugin) { return plugin.load(_this); });
827
- }
828
- return this;
829
- };
830
- Client.prototype.__initStore = function () {
831
- this.__store = new store_1.GlobalStore({ context: {}, breadcrumbs: [] }, this.config.maxBreadcrumbs);
832
- };
833
- Client.prototype.beforeNotify = function (handler) {
834
- this.__beforeNotifyHandlers.push(handler);
835
- return this;
836
- };
837
- Client.prototype.afterNotify = function (handler) {
838
- this.__afterNotifyHandlers.push(handler);
839
- return this;
840
- };
841
- Client.prototype.setContext = function (context) {
842
- if (typeof context === 'object' && context != null) {
843
- this.__store.setContext(context);
844
- }
845
- return this;
846
- };
847
- Client.prototype.resetContext = function (context) {
848
- this.logger.warn('Deprecation warning: `Honeybadger.resetContext()` has been deprecated; please use `Honeybadger.clear()` instead.');
849
- this.__store.clear();
850
- if (typeof context === 'object' && context !== null) {
851
- this.__store.setContext(context);
852
- }
853
- return this;
854
- };
855
- Client.prototype.clear = function () {
856
- this.__store.clear();
857
- return this;
858
- };
859
- Client.prototype.notify = function (noticeable, name, extra) {
860
- var _this = this;
861
- if (name === void 0) { name = undefined; }
862
- if (extra === void 0) { extra = undefined; }
863
- var preConditionError = null;
864
- var notice = this.makeNotice(noticeable, name, extra);
865
- if (!notice) {
866
- this.logger.debug('failed to build error report');
867
- preConditionError = new Error('failed to build error report');
868
- }
869
- if (!preConditionError && this.config.reportData === false) {
870
- this.logger.debug('skipping error report: honeybadger.js is disabled', notice);
871
- preConditionError = new Error('honeybadger.js is disabled');
872
- }
873
- if (!preConditionError && this.__developmentMode()) {
874
- this.logger.log('honeybadger.js is in development mode; the following error report will be sent in production.', notice);
875
- preConditionError = new Error('honeybadger.js is in development mode');
876
- }
877
- if (!preConditionError && !this.config.apiKey) {
878
- this.logger.warn('could not send error report: no API key has been configured', notice);
879
- preConditionError = new Error('missing API key');
880
- }
881
- // we need to have the source file data before the beforeNotifyHandlers,
882
- // in case they modify them
883
- var sourceCodeData = notice && notice.backtrace ? notice.backtrace.map(function (trace) { return (0, util_1$6.shallowClone)(trace); }) : null;
884
- var beforeNotifyResult = (0, util_1$6.runBeforeNotifyHandlers)(notice, this.__beforeNotifyHandlers);
885
- if (!preConditionError && !beforeNotifyResult) {
886
- this.logger.debug('skipping error report: beforeNotify handlers returned false', notice);
887
- preConditionError = new Error('beforeNotify handlers returned false');
888
- }
889
- if (preConditionError) {
890
- (0, util_1$6.runAfterNotifyHandlers)(notice, this.__afterNotifyHandlers, preConditionError);
891
- return false;
892
- }
893
- this.addBreadcrumb('Honeybadger Notice', {
894
- category: 'notice',
895
- metadata: {
896
- message: notice.message,
897
- name: notice.name,
898
- stack: notice.stack
899
- }
900
- });
901
- var breadcrumbs = this.__store.getContents('breadcrumbs');
902
- notice.__breadcrumbs = this.config.breadcrumbsEnabled ? breadcrumbs : [];
903
- (0, util_1$6.getSourceForBacktrace)(sourceCodeData, this.__getSourceFileHandler)
904
- .then(function (sourcePerTrace) {
905
- sourcePerTrace.forEach(function (source, index) {
906
- notice.backtrace[index].source = source;
907
- });
908
- var payload = _this.__buildPayload(notice);
909
- _this.__transport
910
- .send({
911
- headers: {
912
- 'X-API-Key': _this.config.apiKey,
913
- 'Content-Type': 'application/json',
914
- 'Accept': 'text/json, application/json'
915
- },
916
- method: 'POST',
917
- endpoint: (0, util_1$6.endpoint)(_this.config.endpoint, '/v1/notices/js'),
918
- maxObjectDepth: _this.config.maxObjectDepth,
919
- logger: _this.logger,
920
- }, payload)
921
- .then(function (res) {
922
- if (res.statusCode !== 201) {
923
- (0, util_1$6.runAfterNotifyHandlers)(notice, _this.__afterNotifyHandlers, new Error("Bad HTTP response: ".concat(res.statusCode)));
924
- _this.logger.warn("Error report failed: unknown response from server. code=".concat(res.statusCode));
925
- return;
926
- }
927
- var uuid = JSON.parse(res.body).id;
928
- (0, util_1$6.runAfterNotifyHandlers)((0, util_1$6.merge)(notice, {
929
- id: uuid
930
- }), _this.__afterNotifyHandlers);
931
- _this.logger.info("Error report sent \u26A1 https://app.honeybadger.io/notice/".concat(uuid));
932
- })
933
- .catch(function (err) {
934
- _this.logger.error('Error report failed: an unknown error occurred.', "message=".concat(err.message));
935
- (0, util_1$6.runAfterNotifyHandlers)(notice, _this.__afterNotifyHandlers, err);
936
- });
937
- });
938
- return true;
939
- };
940
- /**
941
- * An async version of {@link notify} that resolves only after the notice has been reported to Honeybadger.
942
- * Implemented using the {@link afterNotify} hook.
943
- * Rejects if for any reason the report failed to be reported.
944
- * Useful in serverless environments (AWS Lambda).
945
- */
946
- Client.prototype.notifyAsync = function (noticeable, name, extra) {
947
- var _this = this;
948
- if (name === void 0) { name = undefined; }
949
- if (extra === void 0) { extra = undefined; }
950
- return new Promise(function (resolve, reject) {
951
- var applyAfterNotify = function (partialNotice) {
952
- var originalAfterNotify = partialNotice.afterNotify;
953
- partialNotice.afterNotify = function (err) {
954
- originalAfterNotify === null || originalAfterNotify === void 0 ? void 0 : originalAfterNotify.call(_this, err);
955
- if (err) {
956
- return reject(err);
957
- }
958
- resolve();
959
- };
960
- };
961
- // We have to respect any afterNotify hooks that come from the arguments
962
- var objectToOverride;
963
- if (noticeable.afterNotify) {
964
- objectToOverride = noticeable;
965
- }
966
- else if (name && name.afterNotify) {
967
- objectToOverride = name;
968
- }
969
- else if (extra && extra.afterNotify) {
970
- objectToOverride = extra;
971
- }
972
- else if (name && typeof name === 'object') {
973
- objectToOverride = name;
974
- }
975
- else if (extra) {
976
- objectToOverride = extra;
977
- }
978
- else {
979
- objectToOverride = name = {};
980
- }
981
- applyAfterNotify(objectToOverride);
982
- _this.notify(noticeable, name, extra);
983
- });
984
- };
985
- Client.prototype.makeNotice = function (noticeable, name, extra) {
986
- if (name === void 0) { name = undefined; }
987
- if (extra === void 0) { extra = undefined; }
988
- var notice = (0, util_1$6.makeNotice)(noticeable);
989
- if (name && !(typeof name === 'object')) {
990
- var n = String(name);
991
- name = { name: n };
992
- }
993
- if (name) {
994
- notice = (0, util_1$6.mergeNotice)(notice, name);
995
- }
996
- if (typeof extra === 'object' && extra !== null) {
997
- notice = (0, util_1$6.mergeNotice)(notice, extra);
998
- }
999
- if ((0, util_1$6.objectIsEmpty)(notice)) {
1000
- return null;
1001
- }
1002
- var context = this.__store.getContents('context');
1003
- var noticeTags = this.__constructTags(notice.tags);
1004
- var contextTags = this.__constructTags(context['tags']);
1005
- var configTags = this.__constructTags(this.config.tags);
1006
- // Turning into a Set will remove duplicates
1007
- var tags = noticeTags.concat(contextTags).concat(configTags);
1008
- var uniqueTags = tags.filter(function (item, index) { return tags.indexOf(item) === index; });
1009
- notice = (0, util_1$6.merge)(notice, {
1010
- name: notice.name || 'Error',
1011
- context: (0, util_1$6.merge)(context, notice.context),
1012
- projectRoot: notice.projectRoot || this.config.projectRoot,
1013
- environment: notice.environment || this.config.environment,
1014
- component: notice.component || this.config.component,
1015
- action: notice.action || this.config.action,
1016
- revision: notice.revision || this.config.revision,
1017
- tags: uniqueTags,
1018
- });
1019
- if (typeof notice.stack !== 'string' || !notice.stack.trim()) {
1020
- notice.stack = (0, util_1$6.generateStackTrace)();
1021
- notice.backtrace = (0, util_1$6.makeBacktrace)(notice.stack, true, this.logger);
1022
- }
1023
- else {
1024
- notice.backtrace = (0, util_1$6.makeBacktrace)(notice.stack, false, this.logger);
1025
- }
1026
- return notice;
1027
- };
1028
- Client.prototype.addBreadcrumb = function (message, opts) {
1029
- if (!this.config.breadcrumbsEnabled) {
1030
- return;
1031
- }
1032
- opts = opts || {};
1033
- var metadata = (0, util_1$6.shallowClone)(opts.metadata);
1034
- var category = opts.category || 'custom';
1035
- var timestamp = new Date().toISOString();
1036
- this.__store.addBreadcrumb({
1037
- category: category,
1038
- message: message,
1039
- metadata: metadata,
1040
- timestamp: timestamp
1041
- });
1042
- return this;
1043
- };
1044
- Client.prototype.__getBreadcrumbs = function () {
1045
- return this.__store.getContents('breadcrumbs').slice();
1046
- };
1047
- Client.prototype.__getContext = function () {
1048
- return this.__store.getContents('context');
1049
- };
1050
- Client.prototype.__developmentMode = function () {
1051
- if (this.config.reportData === true) {
1052
- return false;
1053
- }
1054
- return (this.config.environment && this.config.developmentEnvironments.includes(this.config.environment));
1055
- };
1056
- Client.prototype.__buildPayload = function (notice) {
1057
- var headers = (0, util_1$6.filter)(notice.headers, this.config.filters) || {};
1058
- var cgiData = (0, util_1$6.filter)(__assign(__assign({}, notice.cgiData), (0, util_1$6.formatCGIData)(headers, 'HTTP_')), this.config.filters);
1059
- return {
1060
- notifier: notifier,
1061
- breadcrumbs: {
1062
- enabled: !!this.config.breadcrumbsEnabled,
1063
- trail: notice.__breadcrumbs || []
1064
- },
1065
- error: {
1066
- class: notice.name,
1067
- message: notice.message,
1068
- backtrace: notice.backtrace,
1069
- fingerprint: notice.fingerprint,
1070
- tags: notice.tags,
1071
- causes: (0, util_1$6.getCauses)(notice, this.logger),
1072
- },
1073
- request: {
1074
- url: (0, util_1$6.filterUrl)(notice.url, this.config.filters),
1075
- component: notice.component,
1076
- action: notice.action,
1077
- context: notice.context,
1078
- cgi_data: cgiData,
1079
- params: (0, util_1$6.filter)(notice.params, this.config.filters) || {},
1080
- session: (0, util_1$6.filter)(notice.session, this.config.filters) || {}
1081
- },
1082
- server: {
1083
- project_root: notice.projectRoot,
1084
- environment_name: notice.environment,
1085
- revision: notice.revision,
1086
- hostname: this.config.hostname,
1087
- time: new Date().toUTCString()
1088
- },
1089
- details: notice.details || {}
1090
- };
1091
- };
1092
- Client.prototype.__constructTags = function (tags) {
1093
- if (!tags) {
1094
- return [];
1095
- }
1096
- return tags.toString().split(TAG_SEPARATOR).filter(function (tag) { return NOT_BLANK.test(tag); });
1097
- };
1098
- return Client;
1099
- }());
1100
- client.Client = Client;
1101
-
1102
- var types = {};
1103
-
1104
- Object.defineProperty(types, "__esModule", { value: true });
1105
-
1106
- (function (exports) {
1107
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
1108
- if (k2 === undefined) k2 = k;
1109
- var desc = Object.getOwnPropertyDescriptor(m, k);
1110
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1111
- desc = { enumerable: true, get: function() { return m[k]; } };
1112
- }
1113
- Object.defineProperty(o, k2, desc);
1114
- }) : (function(o, m, k, k2) {
1115
- if (k2 === undefined) k2 = k;
1116
- o[k2] = m[k];
1117
- }));
1118
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
1119
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1120
- }) : function(o, v) {
1121
- o["default"] = v;
1122
- });
1123
- var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
1124
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
1125
- };
1126
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
1127
- if (mod && mod.__esModule) return mod;
1128
- var result = {};
1129
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1130
- __setModuleDefault(result, mod);
1131
- return result;
1132
- };
1133
- Object.defineProperty(exports, "__esModule", { value: true });
1134
- exports.Util = exports.Types = exports.Client = void 0;
1135
- var client_1 = client;
1136
- Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } });
1137
- __exportStar(store, exports);
1138
- exports.Types = __importStar(types);
1139
- exports.Util = __importStar(util$1);
1140
-
1141
- } (src));
1142
-
1143
- var util = {};
1144
-
1145
- Object.defineProperty(util, "__esModule", { value: true });
1146
- util.globalThisOrWindow = util.preferCatch = util.encodeCookie = util.decodeCookie = util.localURLPathname = util.parseURL = util.nativeFetch = util.stringTextOfElement = util.stringSelectorOfElement = util.stringNameOfElement = void 0;
1147
- /**
1148
- * Converts an HTMLElement into a human-readable string.
1149
- * @param {!HTMLElement} element
1150
- * @return {string}
1151
- */
1152
- function stringNameOfElement(element) {
1153
- if (!element || !element.tagName) {
1154
- return '';
1155
- }
1156
- var name = element.tagName.toLowerCase();
1157
- // Ignore the root <html> element in selectors and events.
1158
- if (name === 'html') {
1159
- return '';
1160
- }
1161
- if (element.id) {
1162
- name += "#".concat(element.id);
1163
- }
1164
- var stringClassNames = element.getAttribute('class');
1165
- if (stringClassNames) {
1166
- stringClassNames.split(/\s+/).forEach(function (className) {
1167
- name += ".".concat(className);
1168
- });
1169
- }
1170
- ['alt', 'name', 'title', 'type'].forEach(function (attrName) {
1171
- var attr = element.getAttribute(attrName);
1172
- if (attr) {
1173
- name += "[".concat(attrName, "=\"").concat(attr, "\"]");
1174
- }
1175
- });
1176
- var siblings = getSiblings(element);
1177
- if (siblings.length > 1) {
1178
- name += ":nth-child(".concat(Array.prototype.indexOf.call(siblings, element) + 1, ")");
1179
- }
1180
- return name;
1181
- }
1182
- util.stringNameOfElement = stringNameOfElement;
1183
- function stringSelectorOfElement(element) {
1184
- var name = stringNameOfElement(element);
1185
- if (element.parentNode && element.parentNode.tagName) {
1186
- var parentName = stringSelectorOfElement(element.parentNode);
1187
- if (parentName.length > 0) {
1188
- return "".concat(parentName, " > ").concat(name);
1189
- }
1190
- }
1191
- return name;
1192
- }
1193
- util.stringSelectorOfElement = stringSelectorOfElement;
1194
- function stringTextOfElement(element) {
1195
- var text = element.textContent || element.innerText || '';
1196
- if (!text && (element.type === 'submit' || element.type === 'button')) {
1197
- text = element.value;
1198
- }
1199
- return truncate(text.trim(), 300);
1200
- }
1201
- util.stringTextOfElement = stringTextOfElement;
1202
- function nativeFetch() {
1203
- var global = globalThisOrWindow();
1204
- if (!global.fetch) {
1205
- return false;
1206
- }
1207
- if (isNative(global.fetch)) {
1208
- return true;
1209
- }
1210
- // If fetch isn't native, it may be wrapped by someone else. Try to get
1211
- // a pristine function from an iframe.
1212
- try {
1213
- var sandbox = document.createElement('iframe');
1214
- sandbox.style.display = 'none';
1215
- document.head.appendChild(sandbox);
1216
- var result = sandbox.contentWindow.fetch && isNative(sandbox.contentWindow.fetch);
1217
- document.head.removeChild(sandbox);
1218
- return result;
1219
- }
1220
- catch (err) {
1221
- if (console && console.warn) {
1222
- console.warn('failed to detect native fetch via iframe: ' + err);
1223
- }
1224
- }
1225
- return false;
1226
- }
1227
- util.nativeFetch = nativeFetch;
1228
- function isNative(func) {
1229
- return func.toString().indexOf('native') !== -1;
1230
- }
1231
- function parseURL(url) {
1232
- // Regexp: https://tools.ietf.org/html/rfc3986#appendix-B
1233
- var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/) || {};
1234
- return {
1235
- protocol: match[2],
1236
- host: match[4],
1237
- pathname: match[5]
1238
- };
1239
- }
1240
- util.parseURL = parseURL;
1241
- function localURLPathname(url) {
1242
- var parsed = parseURL(url);
1243
- var parsedDocURL = parseURL(document.URL);
1244
- // URL must be relative
1245
- if (!parsed.host || !parsed.protocol) {
1246
- return parsed.pathname;
1247
- }
1248
- // Same domain
1249
- if (parsed.protocol === parsedDocURL.protocol && parsed.host === parsedDocURL.host) {
1250
- return parsed.pathname;
1251
- }
1252
- // x-domain
1253
- return "".concat(parsed.protocol, "://").concat(parsed.host).concat(parsed.pathname);
1254
- }
1255
- util.localURLPathname = localURLPathname;
1256
- function decodeCookie(string) {
1257
- var result = {};
1258
- string.split(/[;,]\s?/).forEach(function (pair) {
1259
- var _a = pair.split('=', 2), key = _a[0], value = _a[1];
1260
- result[key] = value;
1261
- });
1262
- return result;
1263
- }
1264
- util.decodeCookie = decodeCookie;
1265
- function encodeCookie(object) {
1266
- if (typeof object !== 'object') {
1267
- return undefined;
1268
- }
1269
- var cookies = [];
1270
- for (var k in object) {
1271
- cookies.push(k + '=' + object[k]);
1272
- }
1273
- return cookies.join(';');
1274
- }
1275
- util.encodeCookie = encodeCookie;
1276
- // Helpers
1277
- function getSiblings(element) {
1278
- try {
1279
- var nodes = element.parentNode.childNodes;
1280
- var siblings_1 = [];
1281
- Array.prototype.forEach.call(nodes, function (node) {
1282
- if (node.tagName && node.tagName === element.tagName) {
1283
- siblings_1.push(node);
1284
- }
1285
- });
1286
- return siblings_1;
1287
- }
1288
- catch (e) {
1289
- return [];
1290
- }
1291
- }
1292
- function truncate(string, length) {
1293
- if (string.length > length) {
1294
- string = string.substr(0, length) + '...';
1295
- }
1296
- return string;
1297
- }
1298
- // Used to decide which error handling method to use when wrapping async
1299
- // handlers: try/catch, or `window.onerror`. When available, `window.onerror`
1300
- // will provide more information in modern browsers.
1301
- util.preferCatch = (function () {
1302
- var preferCatch = true;
1303
- // In case we're in an environment without access to "window", lets make sure theres a window.
1304
- if (typeof window === 'undefined')
1305
- return preferCatch;
1306
- // IE < 10
1307
- if (!window.atob) {
1308
- preferCatch = false;
1309
- }
1310
- // Modern browsers support the full ErrorEvent API
1311
- // See https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
1312
- if (window.ErrorEvent) {
1313
- try {
1314
- if ((new window.ErrorEvent('')).colno === 0) {
1315
- preferCatch = false;
1316
- }
1317
- // eslint-disable-next-line no-empty
1318
- }
1319
- catch (_e) { }
1320
- }
1321
- return preferCatch;
1322
- })();
1323
- /** globalThis has fairly good support. But just in case, lets check its defined.
1324
- * @see {https://caniuse.com/?search=globalThis}
1325
- */
1326
- function globalThisOrWindow() {
1327
- if (typeof globalThis !== 'undefined') {
1328
- return globalThis;
1329
- }
1330
- if (typeof self !== 'undefined') {
1331
- return self;
1332
- }
1333
- return window;
1334
- }
1335
- util.globalThisOrWindow = globalThisOrWindow;
1336
-
1337
- var onerror = {};
1338
-
1339
- Object.defineProperty(onerror, "__esModule", { value: true });
1340
- onerror.onError = onerror.ignoreNextOnError = void 0;
1341
- /* eslint-disable prefer-rest-params */
1342
- var core_1$5 = src;
1343
- var util_1$5 = util;
1344
- var instrument$4 = core_1$5.Util.instrument, makeNotice = core_1$5.Util.makeNotice;
1345
- var ignoreOnError = 0;
1346
- var currentTimeout;
1347
- function ignoreNextOnError() {
1348
- ignoreOnError += 1;
1349
- clearTimeout(currentTimeout);
1350
- currentTimeout = setTimeout(function () {
1351
- ignoreOnError = 0;
1352
- });
1353
- }
1354
- onerror.ignoreNextOnError = ignoreNextOnError;
1355
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1356
- function onError(_window) {
1357
- if (_window === void 0) { _window = (0, util_1$5.globalThisOrWindow)(); }
1358
- return {
1359
- load: function (client) {
1360
- instrument$4(_window, 'onerror', function (original) {
1361
- var onerror = function (msg, url, line, col, err) {
1362
- client.logger.debug('window.onerror callback invoked', arguments);
1363
- if (ignoreOnError > 0) {
1364
- client.logger.debug('Ignoring window.onerror (error likely reported earlier)', arguments);
1365
- ignoreOnError -= 1;
1366
- return;
1367
- }
1368
- // See https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onerror#Notes
1369
- if (line === 0 && /Script error\.?/.test(msg)) {
1370
- if (client.config.enableUncaught) {
1371
- // Log only if the user wants to report uncaught errors
1372
- client.logger.warn('Ignoring cross-domain script error: enable CORS to track these types of errors', arguments);
1373
- }
1374
- return;
1375
- }
1376
- var notice = makeNotice(err);
1377
- if (!notice.name) {
1378
- notice.name = 'window.onerror';
1379
- }
1380
- if (!notice.message) {
1381
- notice.message = msg;
1382
- }
1383
- if (!notice.stack) {
1384
- // Simulate v8 stack
1385
- notice.stack = [notice.message, '\n at ? (', url || 'unknown', ':', line || 0, ':', col || 0, ')'].join('');
1386
- }
1387
- client.addBreadcrumb((notice.name === 'window.onerror' || !notice.name) ? 'window.onerror' : "window.onerror: ".concat(notice.name), {
1388
- category: 'error',
1389
- metadata: {
1390
- name: notice.name,
1391
- message: notice.message,
1392
- stack: notice.stack
1393
- }
1394
- });
1395
- if (client.config.enableUncaught) {
1396
- client.notify(notice);
1397
- }
1398
- };
1399
- return function (msg, url, line, col, err) {
1400
- onerror(msg, url, line, col, err);
1401
- if (typeof original === 'function') {
1402
- return original.apply(_window, arguments);
1403
- }
1404
- return false;
1405
- };
1406
- });
1407
- }
1408
- };
1409
- }
1410
- onerror.onError = onError;
1411
-
1412
- var onunhandledrejection = {};
1413
-
1414
- Object.defineProperty(onunhandledrejection, "__esModule", { value: true });
1415
- /* eslint-disable prefer-rest-params */
1416
- var core_1$4 = src;
1417
- var util_1$4 = util;
1418
- var instrument$3 = core_1$4.Util.instrument;
1419
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1420
- function default_1$3(_window) {
1421
- if (_window === void 0) { _window = (0, util_1$4.globalThisOrWindow)(); }
1422
- return {
1423
- load: function (client) {
1424
- if (!client.config.enableUnhandledRejection) {
1425
- return;
1426
- }
1427
- instrument$3(_window, 'onunhandledrejection', function (original) {
1428
- // See https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
1429
- function onunhandledrejection(promiseRejectionEvent) {
1430
- var _a;
1431
- client.logger.debug('window.onunhandledrejection callback invoked', arguments);
1432
- if (!client.config.enableUnhandledRejection) {
1433
- return;
1434
- }
1435
- var reason = promiseRejectionEvent.reason;
1436
- if (reason instanceof Error) {
1437
- // simulate v8 stack
1438
- // const fileName = reason.fileName || 'unknown'
1439
- // const lineNumber = reason.lineNumber || 0
1440
- var fileName = 'unknown';
1441
- var lineNumber = 0;
1442
- var stackFallback = "".concat(reason.message, "\n at ? (").concat(fileName, ":").concat(lineNumber, ")");
1443
- var stack = reason.stack || stackFallback;
1444
- var err = {
1445
- name: reason.name,
1446
- message: "UnhandledPromiseRejectionWarning: ".concat(reason),
1447
- stack: stack
1448
- };
1449
- client.addBreadcrumb("window.onunhandledrejection: ".concat(err.name), {
1450
- category: 'error',
1451
- metadata: err
1452
- });
1453
- client.notify(err);
1454
- return;
1455
- }
1456
- var message = typeof reason === 'string' ? reason : ((_a = JSON.stringify(reason)) !== null && _a !== void 0 ? _a : 'Unspecified reason');
1457
- client.notify({
1458
- name: 'window.onunhandledrejection',
1459
- message: "UnhandledPromiseRejectionWarning: ".concat(message)
1460
- });
1461
- }
1462
- return function (promiseRejectionEvent) {
1463
- onunhandledrejection(promiseRejectionEvent);
1464
- if (typeof original === 'function') {
1465
- original.apply(this, arguments);
1466
- }
1467
- };
1468
- });
1469
- }
1470
- };
1471
- }
1472
- onunhandledrejection.default = default_1$3;
1473
-
1474
- var breadcrumbs = {};
1475
-
1476
- Object.defineProperty(breadcrumbs, "__esModule", { value: true });
1477
- /* eslint-disable prefer-rest-params */
1478
- var core_1$3 = src;
1479
- var util_1$3 = util;
1480
- var sanitize$1 = core_1$3.Util.sanitize, instrument$2 = core_1$3.Util.instrument;
1481
- function default_1$2(_window) {
1482
- if (_window === void 0) { _window = (0, util_1$3.globalThisOrWindow)(); }
1483
- return {
1484
- load: function (client) {
1485
- function breadcrumbsEnabled(type) {
1486
- if (client.config.breadcrumbsEnabled === true) {
1487
- return true;
1488
- }
1489
- if (type) {
1490
- return client.config.breadcrumbsEnabled[type] === true;
1491
- }
1492
- return client.config.breadcrumbsEnabled !== false;
1493
- }
1494
- // Breadcrumbs: instrument console
1495
- (function () {
1496
- if (!breadcrumbsEnabled('console')) {
1497
- return;
1498
- }
1499
- function inspectArray(obj) {
1500
- if (!Array.isArray(obj)) {
1501
- return '';
1502
- }
1503
- return obj.map(function (value) {
1504
- try {
1505
- return String(value);
1506
- }
1507
- catch (e) {
1508
- return '[unknown]';
1509
- }
1510
- }).join(' ');
1511
- }
1512
- ['debug', 'info', 'warn', 'error', 'log'].forEach(function (level) {
1513
- instrument$2(_window.console, level, function (original) {
1514
- return function () {
1515
- var args = Array.prototype.slice.call(arguments);
1516
- var message = inspectArray(args);
1517
- var opts = {
1518
- category: 'log',
1519
- metadata: {
1520
- level: level,
1521
- arguments: sanitize$1(args, 3)
1522
- }
1523
- };
1524
- client.addBreadcrumb(message, opts);
1525
- if (typeof original === 'function') {
1526
- Function.prototype.apply.call(original, _window.console, arguments);
1527
- }
1528
- };
1529
- });
1530
- });
1531
- })();
1532
- // Breadcrumbs: instrument click events
1533
- (function () {
1534
- if (!breadcrumbsEnabled('dom')) {
1535
- return;
1536
- }
1537
- _window.addEventListener('click', function (event) {
1538
- var message, selector, text;
1539
- try {
1540
- message = (0, util_1$3.stringNameOfElement)(event.target);
1541
- selector = (0, util_1$3.stringSelectorOfElement)(event.target);
1542
- text = (0, util_1$3.stringTextOfElement)(event.target);
1543
- }
1544
- catch (e) {
1545
- message = 'UI Click';
1546
- selector = '[unknown]';
1547
- text = '[unknown]';
1548
- }
1549
- // There's nothing to display
1550
- if (message.length === 0) {
1551
- return;
1552
- }
1553
- client.addBreadcrumb(message, {
1554
- category: 'ui.click',
1555
- metadata: {
1556
- selector: selector,
1557
- text: text,
1558
- event: event
1559
- }
1560
- });
1561
- }, _window.location ? true : false); // In CloudFlare workers useCapture must be false. window.locaiton is a hacky way to detect it.
1562
- })();
1563
- // Breadcrumbs: instrument XMLHttpRequest
1564
- (function () {
1565
- if (!breadcrumbsEnabled('network')) {
1566
- return;
1567
- }
1568
- // Some environments may not support XMLHttpRequest.
1569
- if (typeof XMLHttpRequest === 'undefined')
1570
- return;
1571
- // -- On xhr.open: capture initial metadata
1572
- instrument$2(XMLHttpRequest.prototype, 'open', function (original) {
1573
- return function () {
1574
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1575
- var xhr = this;
1576
- var url = arguments[1];
1577
- var method = typeof arguments[0] === 'string' ? arguments[0].toUpperCase() : arguments[0];
1578
- var message = "".concat(method, " ").concat((0, util_1$3.localURLPathname)(url));
1579
- this.__hb_xhr = {
1580
- type: 'xhr',
1581
- method: method,
1582
- url: url,
1583
- message: message
1584
- };
1585
- if (typeof original === 'function') {
1586
- original.apply(xhr, arguments);
1587
- }
1588
- };
1589
- });
1590
- // -- On xhr.send: set up xhr.onreadystatechange to report breadcrumb
1591
- instrument$2(XMLHttpRequest.prototype, 'send', function (original) {
1592
- return function () {
1593
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1594
- var xhr = this;
1595
- function onreadystatechangeHandler() {
1596
- if (xhr.readyState === 4) {
1597
- var message = void 0;
1598
- if (xhr.__hb_xhr) {
1599
- xhr.__hb_xhr.status_code = xhr.status;
1600
- message = xhr.__hb_xhr.message;
1601
- delete xhr.__hb_xhr.message;
1602
- }
1603
- client.addBreadcrumb(message || 'XMLHttpRequest', {
1604
- category: 'request',
1605
- metadata: xhr.__hb_xhr
1606
- });
1607
- }
1608
- }
1609
- if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {
1610
- instrument$2(xhr, 'onreadystatechange', function (original) {
1611
- return function () {
1612
- onreadystatechangeHandler();
1613
- if (typeof original === 'function') {
1614
- // eslint-disable-next-line prefer-rest-params
1615
- original.apply(this, arguments);
1616
- }
1617
- };
1618
- });
1619
- }
1620
- else {
1621
- xhr.onreadystatechange = onreadystatechangeHandler;
1622
- }
1623
- if (typeof original === 'function') {
1624
- // eslint-disable-next-line prefer-rest-params
1625
- original.apply(xhr, arguments);
1626
- }
1627
- };
1628
- });
1629
- })();
1630
- // Breadcrumbs: instrument fetch
1631
- (function () {
1632
- if (!breadcrumbsEnabled('network')) {
1633
- return;
1634
- }
1635
- if (!(0, util_1$3.nativeFetch)()) {
1636
- // Polyfills use XHR.
1637
- return;
1638
- }
1639
- instrument$2(_window, 'fetch', function (original) {
1640
- return function () {
1641
- // eslint-disable-next-line prefer-rest-params
1642
- var input = arguments[0];
1643
- var method = 'GET';
1644
- var url;
1645
- if (typeof input === 'string') {
1646
- url = input;
1647
- }
1648
- else if ('Request' in _window && input instanceof Request) {
1649
- url = input.url;
1650
- if (input.method) {
1651
- method = input.method;
1652
- }
1653
- }
1654
- else {
1655
- url = String(input);
1656
- }
1657
- if (arguments[1] && arguments[1].method) {
1658
- method = arguments[1].method;
1659
- }
1660
- if (typeof method === 'string') {
1661
- method = method.toUpperCase();
1662
- }
1663
- // localURLPathname cant be constructed for CF workers due to reliance on "document".
1664
- var message = "".concat(method, " ").concat(typeof document === 'undefined' ? url : (0, util_1$3.localURLPathname)(url));
1665
- var metadata = {
1666
- type: 'fetch',
1667
- method: method,
1668
- url: url
1669
- };
1670
- return original
1671
- .apply(this, arguments)
1672
- .then(function (response) {
1673
- metadata['status_code'] = response.status;
1674
- client.addBreadcrumb(message, {
1675
- category: 'request',
1676
- metadata: metadata
1677
- });
1678
- return response;
1679
- })
1680
- .catch(function (error) {
1681
- client.addBreadcrumb('fetch error', {
1682
- category: 'error',
1683
- metadata: metadata
1684
- });
1685
- throw error;
1686
- });
1687
- };
1688
- });
1689
- })();
1690
- // Breadcrumbs: instrument navigation
1691
- (function () {
1692
- if (!breadcrumbsEnabled('navigation')) {
1693
- return;
1694
- }
1695
- if (_window.location == null) {
1696
- // Most likely in a CF worker, we should be listening to fetch requests instead.
1697
- return;
1698
- }
1699
- // The last known href of the current page
1700
- var lastHref = _window.location.href;
1701
- function recordUrlChange(from, to) {
1702
- lastHref = to;
1703
- client.addBreadcrumb('Page changed', {
1704
- category: 'navigation',
1705
- metadata: {
1706
- from: from,
1707
- to: to
1708
- }
1709
- });
1710
- }
1711
- if (typeof addEventListener === 'function') {
1712
- addEventListener('popstate', function (_event) {
1713
- recordUrlChange(lastHref, _window.location.href);
1714
- });
1715
- }
1716
- // https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
1717
- // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
1718
- function historyWrapper(original) {
1719
- return function () {
1720
- var url = arguments.length > 2 ? arguments[2] : undefined;
1721
- if (url) {
1722
- recordUrlChange(lastHref, String(url));
1723
- }
1724
- return original.apply(this, arguments);
1725
- };
1726
- }
1727
- instrument$2(_window.history, 'pushState', historyWrapper);
1728
- instrument$2(_window.history, 'replaceState', historyWrapper);
1729
- })();
1730
- }
1731
- };
1732
- }
1733
- breadcrumbs.default = default_1$2;
1734
-
1735
- var timers = {};
1736
-
1737
- Object.defineProperty(timers, "__esModule", { value: true });
1738
- /* eslint-disable prefer-rest-params */
1739
- var core_1$2 = src;
1740
- var util_1$2 = util;
1741
- var instrument$1 = core_1$2.Util.instrument;
1742
- function default_1$1(_window) {
1743
- if (_window === void 0) { _window = (0, util_1$2.globalThisOrWindow)(); }
1744
- return {
1745
- load: function (client) {
1746
- // Wrap timers
1747
- (function () {
1748
- function instrumentTimer(wrapOpts) {
1749
- return function (original) {
1750
- // See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
1751
- return function (func, delay) {
1752
- if (typeof func === 'function') {
1753
- var args_1 = Array.prototype.slice.call(arguments, 2);
1754
- func = client.__wrap(func, wrapOpts);
1755
- return original(function () {
1756
- func.apply(void 0, args_1);
1757
- }, delay);
1758
- }
1759
- else {
1760
- return original(func, delay);
1761
- }
1762
- };
1763
- };
1764
- }
1765
- instrument$1(_window, 'setTimeout', instrumentTimer({ component: 'setTimeout' }));
1766
- instrument$1(_window, 'setInterval', instrumentTimer({ component: 'setInterval' }));
1767
- })();
1768
- }
1769
- };
1770
- }
1771
- timers.default = default_1$1;
1772
-
1773
- var event_listeners = {};
1774
-
1775
- Object.defineProperty(event_listeners, "__esModule", { value: true });
1776
- var core_1$1 = src;
1777
- var util_1$1 = util;
1778
- var instrument = core_1$1.Util.instrument;
1779
- function default_1(_window) {
1780
- if (_window === void 0) { _window = (0, util_1$1.globalThisOrWindow)(); }
1781
- return {
1782
- load: function (client) {
1783
- // Wrap event listeners
1784
- // Event targets borrowed from bugsnag-js:
1785
- // See https://github.com/bugsnag/bugsnag-js/blob/d55af916a4d3c7757f979d887f9533fe1a04cc93/src/bugsnag.js#L542
1786
- var targets = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload'];
1787
- targets.forEach(function (prop) {
1788
- var prototype = _window[prop] && _window[prop].prototype;
1789
- if (prototype && Object.prototype.hasOwnProperty.call(prototype, 'addEventListener')) {
1790
- instrument(prototype, 'addEventListener', function (original) {
1791
- var wrapOpts = { component: "".concat(prop, ".prototype.addEventListener") };
1792
- // See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
1793
- return function (type, listener, useCapture, wantsUntrusted) {
1794
- try {
1795
- if (listener && listener.handleEvent != null) {
1796
- listener.handleEvent = client.__wrap(listener.handleEvent, wrapOpts);
1797
- }
1798
- }
1799
- catch (e) {
1800
- // Ignore 'Permission denied to access property "handleEvent"' errors.
1801
- client.logger.error(e);
1802
- }
1803
- return original.call(this, type, client.__wrap(listener, wrapOpts), useCapture, wantsUntrusted);
1804
- };
1805
- });
1806
- instrument(prototype, 'removeEventListener', function (original) {
1807
- return function (type, listener, useCapture, wantsUntrusted) {
1808
- original.call(this, type, listener, useCapture, wantsUntrusted);
1809
- return original.call(this, type, client.__wrap(listener), useCapture, wantsUntrusted);
1810
- };
1811
- });
1812
- }
1813
- });
1814
- }
1815
- };
1816
- }
1817
- event_listeners.default = default_1;
1818
-
1819
- var transport = {};
1820
-
1821
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
1822
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1823
- return new (P || (P = Promise))(function (resolve, reject) {
1824
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1825
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1826
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1827
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1828
- });
1829
- };
1830
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
1831
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1832
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1833
- function verb(n) { return function (v) { return step([n, v]); }; }
1834
- function step(op) {
1835
- if (f) throw new TypeError("Generator is already executing.");
1836
- while (_) try {
1837
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1838
- if (y = 0, t) op = [op[0] & 2, t.value];
1839
- switch (op[0]) {
1840
- case 0: case 1: t = op; break;
1841
- case 4: _.label++; return { value: op[1], done: false };
1842
- case 5: _.label++; y = op[1]; op = [0]; continue;
1843
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1844
- default:
1845
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1846
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1847
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1848
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1849
- if (t[2]) _.ops.pop();
1850
- _.trys.pop(); continue;
1851
- }
1852
- op = body.call(thisArg, _);
1853
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1854
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1855
- }
1856
- };
1857
- Object.defineProperty(transport, "__esModule", { value: true });
1858
- transport.BrowserTransport = void 0;
1859
- var core_1 = src;
1860
- var util_1 = util;
1861
- var sanitize = core_1.Util.sanitize;
1862
- /**
1863
- * Helper function to get typesafe Object.entries()
1864
- * https://twitter.com/mattpocockuk/status/1502264005251018754?lang=en
1865
- */
1866
- function objectEntries(obj) {
1867
- return Object.entries(obj);
1868
- }
1869
- var BrowserTransport = /** @class */ (function () {
1870
- function BrowserTransport() {
1871
- }
1872
- BrowserTransport.prototype.send = function (options, payload) {
1873
- return __awaiter(this, void 0, void 0, function () {
1874
- var headerArray, headers, requestInit, response, body;
1875
- return __generator(this, function (_a) {
1876
- switch (_a.label) {
1877
- case 0:
1878
- headerArray = options.headers ? objectEntries(options.headers) : [];
1879
- headers = {};
1880
- headerArray.forEach(function (_a) {
1881
- var key = _a[0], value = _a[1];
1882
- if (key != null && value != null) {
1883
- headers[String(key)] = String(value);
1884
- }
1885
- });
1886
- requestInit = {
1887
- method: options.method,
1888
- headers: headers
1889
- };
1890
- // GET methods cannot have a body.
1891
- if (options.method === 'POST') {
1892
- requestInit.body = payload ? JSON.stringify(sanitize(payload, options.maxObjectDepth)) : undefined;
1893
- }
1894
- return [4 /*yield*/, (0, util_1.globalThisOrWindow)().fetch(options.endpoint, requestInit)];
1895
- case 1:
1896
- response = _a.sent();
1897
- return [4 /*yield*/, response.text()];
1898
- case 2:
1899
- body = _a.sent();
1900
- return [2 /*return*/, Promise.resolve({ statusCode: response.status, body: body })];
1901
- }
1902
- });
1903
- });
1904
- };
1905
- return BrowserTransport;
1906
- }());
1907
- transport.BrowserTransport = BrowserTransport;
1908
-
1909
- (function (exports) {
1910
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
1911
- var extendStatics = function (d, b) {
1912
- extendStatics = Object.setPrototypeOf ||
1913
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1914
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1915
- return extendStatics(d, b);
1916
- };
1917
- return function (d, b) {
1918
- if (typeof b !== "function" && b !== null)
1919
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1920
- extendStatics(d, b);
1921
- function __() { this.constructor = d; }
1922
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1923
- };
1924
- })();
1925
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1926
- __assign = Object.assign || function(t) {
1927
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1928
- s = arguments[i];
1929
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1930
- t[p] = s[p];
1931
- }
1932
- return t;
1933
- };
1934
- return __assign.apply(this, arguments);
1935
- };
1936
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
1937
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1938
- return new (P || (P = Promise))(function (resolve, reject) {
1939
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1940
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1941
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1942
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1943
- });
1944
- };
1945
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
1946
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1947
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1948
- function verb(n) { return function (v) { return step([n, v]); }; }
1949
- function step(op) {
1950
- if (f) throw new TypeError("Generator is already executing.");
1951
- while (_) try {
1952
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1953
- if (y = 0, t) op = [op[0] & 2, t.value];
1954
- switch (op[0]) {
1955
- case 0: case 1: t = op; break;
1956
- case 4: _.label++; return { value: op[1], done: false };
1957
- case 5: _.label++; y = op[1]; op = [0]; continue;
1958
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1959
- default:
1960
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1961
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1962
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1963
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1964
- if (t[2]) _.ops.pop();
1965
- _.trys.pop(); continue;
1966
- }
1967
- op = body.call(thisArg, _);
1968
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1969
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1970
- }
1971
- };
1972
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
1973
- return (mod && mod.__esModule) ? mod : { "default": mod };
1974
- };
1975
- Object.defineProperty(exports, "__esModule", { value: true });
1976
- exports.Types = exports.getUserFeedbackScriptUrl = void 0;
1977
- var core_1 = src;
1978
- var util_1 = util;
1979
- var onerror_1 = onerror;
1980
- var onunhandledrejection_1 = __importDefault(onunhandledrejection);
1981
- var breadcrumbs_1 = __importDefault(breadcrumbs);
1982
- var timers_1 = __importDefault(timers);
1983
- var event_listeners_1 = __importDefault(event_listeners);
1984
- var transport_1 = transport;
1985
- var merge = core_1.Util.merge, filter = core_1.Util.filter, objectIsExtensible = core_1.Util.objectIsExtensible;
1986
- var getProjectRoot = function () {
1987
- var global = (0, util_1.globalThisOrWindow)();
1988
- var projectRoot = '';
1989
- // Cloudflare workers do not have access to location API.
1990
- if (global.location != null) {
1991
- projectRoot = global.location.protocol + '//' + global.location.host;
1992
- }
1993
- return projectRoot;
1994
- };
1995
- var getUserFeedbackScriptUrl = function (version) {
1996
- var majorMinorVersion = version.split('.').slice(0, 2).join('.');
1997
- return "https://js.honeybadger.io/v".concat(majorMinorVersion, "/honeybadger-feedback-form.js");
1998
- };
1999
- exports.getUserFeedbackScriptUrl = getUserFeedbackScriptUrl;
2000
- var Honeybadger = /** @class */ (function (_super) {
2001
- __extends(Honeybadger, _super);
2002
- function Honeybadger(opts) {
2003
- if (opts === void 0) { opts = {}; }
2004
- var _this = _super.call(this, __assign({ userFeedbackEndpoint: 'https://api.honeybadger.io/v2/feedback', async: true, maxErrors: null, projectRoot: getProjectRoot() }, opts), new transport_1.BrowserTransport()) || this;
2005
- /** @internal */
2006
- _this.__errorsSent = 0;
2007
- /** @internal */
2008
- _this.__lastWrapErr = undefined;
2009
- /** @internal */
2010
- _this.__lastNoticeId = undefined;
2011
- /** @internal */
2012
- _this.__beforeNotifyHandlers = [
2013
- function (notice) {
2014
- if (_this.__exceedsMaxErrors()) {
2015
- _this.logger.debug('Dropping notice: max errors exceeded', notice);
2016
- return false;
2017
- }
2018
- if (notice && !notice.url && typeof document !== 'undefined') {
2019
- notice.url = document.URL;
2020
- }
2021
- _this.__incrementErrorsCount();
2022
- return true;
2023
- }
2024
- ];
2025
- _this.__afterNotifyHandlers = [
2026
- function (_error, notice) {
2027
- if (notice) {
2028
- _this.__lastNoticeId = notice.id;
2029
- }
2030
- return true;
2031
- }
2032
- ];
2033
- return _this;
2034
- }
2035
- Honeybadger.prototype.configure = function (opts) {
2036
- if (opts === void 0) { opts = {}; }
2037
- return _super.prototype.configure.call(this, opts);
2038
- };
2039
- Honeybadger.prototype.resetMaxErrors = function () {
2040
- return (this.__errorsSent = 0);
2041
- };
2042
- Honeybadger.prototype.factory = function (opts) {
2043
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2044
- return new Honeybadger(opts);
2045
- };
2046
- Honeybadger.prototype.checkIn = function (_id) {
2047
- throw new Error('Honeybadger.checkIn() is not supported on the browser');
2048
- };
2049
- Honeybadger.prototype.showUserFeedbackForm = function (options) {
2050
- if (options === void 0) { options = {}; }
2051
- return __awaiter(this, void 0, void 0, function () {
2052
- var global, script;
2053
- return __generator(this, function (_a) {
2054
- if (!this.config || !this.config.apiKey) {
2055
- this.logger.debug('Client not initialized');
2056
- return [2 /*return*/];
2057
- }
2058
- if (!this.__lastNoticeId) {
2059
- this.logger.debug("Can't show user feedback form without a notice already reported");
2060
- return [2 /*return*/];
2061
- }
2062
- global = (0, util_1.globalThisOrWindow)();
2063
- if (typeof global.document === 'undefined') {
2064
- this.logger.debug('global.document is undefined. Cannot attach script');
2065
- return [2 /*return*/];
2066
- }
2067
- if (this.isUserFeedbackScriptUrlAlreadyVisible()) {
2068
- this.logger.debug('User feedback form is already visible');
2069
- return [2 /*return*/];
2070
- }
2071
- global['honeybadgerUserFeedbackOptions'] = __assign(__assign({}, options), { apiKey: this.config.apiKey, endpoint: this.config.userFeedbackEndpoint, noticeId: this.__lastNoticeId });
2072
- script = global.document.createElement('script');
2073
- script.setAttribute('src', this.getUserFeedbackSubmitUrl());
2074
- script.setAttribute('async', 'true');
2075
- if (options.onLoad) {
2076
- script.onload = options.onLoad;
2077
- }
2078
- (global.document.head || global.document.body).appendChild(script);
2079
- return [2 /*return*/];
2080
- });
2081
- });
2082
- };
2083
- Honeybadger.prototype.isUserFeedbackScriptUrlAlreadyVisible = function () {
2084
- var global = (0, util_1.globalThisOrWindow)();
2085
- var feedbackScriptUrl = this.getUserFeedbackSubmitUrl();
2086
- for (var i = 0; i < global.document.scripts.length; i++) {
2087
- var script = global.document.scripts[i];
2088
- if (script.src === feedbackScriptUrl) {
2089
- return true;
2090
- }
2091
- }
2092
- return false;
2093
- };
2094
- Honeybadger.prototype.getUserFeedbackSubmitUrl = function () {
2095
- return (0, exports.getUserFeedbackScriptUrl)(this.getVersion());
2096
- };
2097
- /** @internal */
2098
- Honeybadger.prototype.__buildPayload = function (notice) {
2099
- var cgiData = {
2100
- HTTP_USER_AGENT: undefined,
2101
- HTTP_REFERER: undefined,
2102
- HTTP_COOKIE: undefined
2103
- };
2104
- cgiData.HTTP_USER_AGENT = navigator.userAgent;
2105
- if (typeof document !== 'undefined' && document.referrer.match(/\S/)) {
2106
- cgiData.HTTP_REFERER = document.referrer;
2107
- }
2108
- var cookiesObject;
2109
- if (typeof notice.cookies === 'string') {
2110
- cookiesObject = (0, util_1.decodeCookie)(notice.cookies);
2111
- }
2112
- else {
2113
- cookiesObject = notice.cookies;
2114
- }
2115
- if (cookiesObject) {
2116
- cgiData.HTTP_COOKIE = (0, util_1.encodeCookie)(filter(cookiesObject, this.config.filters));
2117
- }
2118
- var payload = _super.prototype.__buildPayload.call(this, notice);
2119
- payload.request.cgi_data = merge(cgiData, payload.request.cgi_data);
2120
- return payload;
2121
- };
2122
- /**
2123
- * wrap always returns the same function so that callbacks can be removed via
2124
- * removeEventListener.
2125
- * @internal
2126
- */
2127
- Honeybadger.prototype.__wrap = function (f, opts) {
2128
- if (opts === void 0) { opts = {}; }
2129
- var func = f;
2130
- if (!opts) {
2131
- opts = {};
2132
- }
2133
- try {
2134
- if (typeof func !== 'function') {
2135
- return func;
2136
- }
2137
- if (!objectIsExtensible(func)) {
2138
- return func;
2139
- }
2140
- if (!func.___hb) {
2141
- // eslint-disable-next-line @typescript-eslint/no-this-alias
2142
- var client_1 = this;
2143
- func.___hb = function () {
2144
- if (util_1.preferCatch) {
2145
- try {
2146
- // eslint-disable-next-line prefer-rest-params
2147
- return func.apply(this, arguments);
2148
- }
2149
- catch (err) {
2150
- if (client_1.__lastWrapErr === err) {
2151
- throw (err);
2152
- }
2153
- client_1.__lastWrapErr = err;
2154
- (0, onerror_1.ignoreNextOnError)();
2155
- client_1.addBreadcrumb(opts.component ? "".concat(opts.component, ": ").concat(err.name) : err.name, {
2156
- category: 'error',
2157
- metadata: {
2158
- message: err.message,
2159
- name: err.name,
2160
- stack: err.stack
2161
- }
2162
- });
2163
- if (client_1.config.enableUncaught) {
2164
- client_1.notify(err);
2165
- }
2166
- throw (err);
2167
- }
2168
- }
2169
- else {
2170
- // eslint-disable-next-line prefer-rest-params
2171
- return func.apply(this, arguments);
2172
- }
2173
- };
2174
- }
2175
- func.___hb.___hb = func.___hb;
2176
- return func.___hb;
2177
- }
2178
- catch (_e) {
2179
- return func;
2180
- }
2181
- };
2182
- /** @internal */
2183
- Honeybadger.prototype.__incrementErrorsCount = function () {
2184
- return this.__errorsSent++;
2185
- };
2186
- /** @internal */
2187
- Honeybadger.prototype.__exceedsMaxErrors = function () {
2188
- return this.config.maxErrors && this.__errorsSent >= this.config.maxErrors;
2189
- };
2190
- return Honeybadger;
2191
- }(core_1.Client));
2192
- var core_2 = src;
2193
- Object.defineProperty(exports, "Types", { enumerable: true, get: function () { return core_2.Types; } });
2194
- exports.default = new Honeybadger({
2195
- __plugins: [
2196
- (0, onerror_1.onError)(),
2197
- (0, onunhandledrejection_1.default)(),
2198
- (0, timers_1.default)(),
2199
- (0, event_listeners_1.default)(),
2200
- (0, breadcrumbs_1.default)()
2201
- ]
2202
- });
2203
-
2204
- } (browser$1));
2205
-
2206
- var browser = /*@__PURE__*/getDefaultExportFromCjs(browser$1);
2207
-
2208
- export { browser as default };
2209
- //# sourceMappingURL=honeybadger.esm.js.map