@flareapp/core 2.2.0 → 2.2.1

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.
Files changed (54) hide show
  1. package/dist/index.cjs +806 -0
  2. package/dist/index.d.cts +411 -0
  3. package/dist/index.d.mts +411 -0
  4. package/dist/index.mjs +760 -0
  5. package/package.json +4 -1
  6. package/.oxlintrc.json +0 -7
  7. package/.release-it.json +0 -13
  8. package/CHANGELOG.md +0 -16
  9. package/src/Flare.ts +0 -543
  10. package/src/Scope.ts +0 -96
  11. package/src/api/Api.ts +0 -35
  12. package/src/api/index.ts +0 -1
  13. package/src/env/index.ts +0 -14
  14. package/src/index.ts +0 -41
  15. package/src/stacktrace/NullFileReader.ts +0 -28
  16. package/src/stacktrace/createStackTrace.ts +0 -74
  17. package/src/stacktrace/fileReader.ts +0 -96
  18. package/src/stacktrace/index.ts +0 -4
  19. package/src/types.ts +0 -81
  20. package/src/util/assert.ts +0 -9
  21. package/src/util/assertKey.ts +0 -11
  22. package/src/util/convertToError.ts +0 -22
  23. package/src/util/extractCode.ts +0 -11
  24. package/src/util/flatJsonStringify.ts +0 -45
  25. package/src/util/glowsToEvents.ts +0 -16
  26. package/src/util/index.ts +0 -8
  27. package/src/util/now.ts +0 -3
  28. package/src/util/redactUrl.ts +0 -83
  29. package/tests/api.test.ts +0 -95
  30. package/tests/configure.test.ts +0 -16
  31. package/tests/contextCollector.test.ts +0 -37
  32. package/tests/convertToError.test.ts +0 -95
  33. package/tests/createStackTrace.test.ts +0 -54
  34. package/tests/extractCode.test.ts +0 -30
  35. package/tests/fileReader.test.ts +0 -51
  36. package/tests/flatJsonStringify.test.ts +0 -31
  37. package/tests/flush.test.ts +0 -47
  38. package/tests/glows.test.ts +0 -47
  39. package/tests/glowsToEvents.test.ts +0 -41
  40. package/tests/helpers/FakeApi.ts +0 -20
  41. package/tests/helpers/index.ts +0 -1
  42. package/tests/hooks.test.ts +0 -123
  43. package/tests/light.test.ts +0 -25
  44. package/tests/nullFileReader.test.ts +0 -11
  45. package/tests/publicExports.test.ts +0 -17
  46. package/tests/redactUrl.test.ts +0 -151
  47. package/tests/report.test.ts +0 -146
  48. package/tests/sampleRate.test.ts +0 -88
  49. package/tests/scope.test.ts +0 -64
  50. package/tests/setEntryPoint.test.ts +0 -79
  51. package/tests/setFramework.test.ts +0 -48
  52. package/tests/setSdkInfo.test.ts +0 -62
  53. package/tsconfig.json +0 -4
  54. package/vitest.config.ts +0 -17
package/dist/index.cjs ADDED
@@ -0,0 +1,806 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+
28
+ //#endregion
29
+ let error_stack_parser = require("error-stack-parser");
30
+ error_stack_parser = __toESM(error_stack_parser);
31
+
32
+ //#region src/env/index.ts
33
+ const CLIENT_VERSION = typeof process !== "undefined" && true ? "2.2.1" : "?";
34
+ const KEY = typeof FLARE_JS_KEY === "undefined" ? "" : FLARE_JS_KEY;
35
+ const SOURCEMAP_VERSION = typeof FLARE_SOURCEMAP_VERSION === "undefined" ? "" : FLARE_SOURCEMAP_VERSION;
36
+
37
+ //#endregion
38
+ //#region src/util/assert.ts
39
+ function assert(value, message, debug) {
40
+ if (debug && !value) console.error(`Flare JavaScript client v${CLIENT_VERSION}: ${message}`);
41
+ return !!value;
42
+ }
43
+
44
+ //#endregion
45
+ //#region src/util/assertKey.ts
46
+ function assertKey(key, debug) {
47
+ return assert(key, "The client was not yet initialised with an API key. Run client.light('<flare-project-key>') when you initialise your app. If you are running in dev mode and didn't run the light command on purpose, you can ignore this error.", debug);
48
+ }
49
+
50
+ //#endregion
51
+ //#region src/util/convertToError.ts
52
+ function convertToError(error) {
53
+ if (error instanceof Error) return error;
54
+ if (typeof error === "string") return new Error(error);
55
+ if (typeof error === "object" && error !== null) {
56
+ const obj = error;
57
+ const message = typeof obj.message === "string" ? obj.message : String(error);
58
+ const converted = new Error(message);
59
+ if (typeof obj.stack === "string") converted.stack = obj.stack;
60
+ if (typeof obj.name === "string") converted.name = obj.name;
61
+ return converted;
62
+ }
63
+ return new Error(String(error));
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/util/extractCode.ts
68
+ const MAX_CODE_LENGTH = 64;
69
+ function extractCode(error) {
70
+ const code = error.code;
71
+ if (typeof code !== "string" || code.length === 0) return;
72
+ return code.slice(0, MAX_CODE_LENGTH);
73
+ }
74
+
75
+ //#endregion
76
+ //#region src/util/flatJsonStringify.ts
77
+ function flatJsonStringify(json) {
78
+ return JSON.stringify(decycle(json));
79
+ }
80
+ function isPlainObject(value) {
81
+ if (typeof value !== "object" || value === null) return false;
82
+ const proto = Object.getPrototypeOf(value);
83
+ return proto === Object.prototype || proto === null;
84
+ }
85
+ function decycle(root) {
86
+ const inPath = /* @__PURE__ */ new WeakSet();
87
+ function clone(node) {
88
+ if (Array.isArray(node)) {
89
+ if (inPath.has(node)) return "[Circular]";
90
+ inPath.add(node);
91
+ const result = node.map(clone);
92
+ inPath.delete(node);
93
+ return result;
94
+ }
95
+ if (isPlainObject(node)) {
96
+ if (inPath.has(node)) return "[Circular]";
97
+ inPath.add(node);
98
+ const result = {};
99
+ for (const [k, v] of Object.entries(node)) result[k] = clone(v);
100
+ inPath.delete(node);
101
+ return result;
102
+ }
103
+ return node;
104
+ }
105
+ return clone(root);
106
+ }
107
+
108
+ //#endregion
109
+ //#region src/util/glowsToEvents.ts
110
+ function glowsToEvents(glows) {
111
+ return glows.map((glow) => ({
112
+ type: "php_glow",
113
+ startTimeUnixNano: Math.round(glow.microtime * 1e9),
114
+ endTimeUnixNano: null,
115
+ attributes: {
116
+ "glow.name": String(glow.name),
117
+ "glow.level": glow.messageLevel,
118
+ "glow.context": glow.metaData ?? {}
119
+ }
120
+ }));
121
+ }
122
+
123
+ //#endregion
124
+ //#region src/util/now.ts
125
+ function now() {
126
+ return Math.round(Date.now() / 1e3);
127
+ }
128
+
129
+ //#endregion
130
+ //#region src/util/redactUrl.ts
131
+ const DEFAULT_URL_DENYLIST = /password|passwd|pwd|token|secret|authorization|\bauth\b|bearer|oauth|credentials?|cookie|api[-_]?key|private[-_]?key|session|csrf|xsrf|\bpin\b|\bssn\b|card[-_]?number|\bcvv\b/i;
132
+ function resolveDenylist(custom, replaceDefault = false, defaultDenylist = DEFAULT_URL_DENYLIST) {
133
+ if (!custom) return defaultDenylist;
134
+ if (replaceDefault) {
135
+ const safeFlags = custom.flags.replace(/[gy]/g, "");
136
+ return new RegExp(custom.source, safeFlags);
137
+ }
138
+ const flags = unionFlags(defaultDenylist.flags, custom.flags);
139
+ return new RegExp(`(?:${defaultDenylist.source})|(?:${custom.source})`, flags);
140
+ }
141
+ function unionFlags(a, b) {
142
+ const merged = /* @__PURE__ */ new Set();
143
+ for (const flag of a + b) {
144
+ if (flag === "g" || flag === "y") continue;
145
+ merged.add(flag);
146
+ }
147
+ return [...merged].join("");
148
+ }
149
+ function redactUrlQuery(fullPath, denylist = DEFAULT_URL_DENYLIST) {
150
+ const queryStart = fullPath.indexOf("?");
151
+ if (queryStart === -1) return fullPath;
152
+ const hashStart = fullPath.indexOf("#", queryStart);
153
+ const queryEnd = hashStart === -1 ? fullPath.length : hashStart;
154
+ const prefix = fullPath.slice(0, queryStart + 1);
155
+ const queryString = fullPath.slice(queryStart + 1, queryEnd);
156
+ const suffix = fullPath.slice(queryEnd);
157
+ return `${prefix}${queryString.split("&").map((pair) => {
158
+ if (pair === "") return pair;
159
+ const eq = pair.indexOf("=");
160
+ const rawKey = eq === -1 ? pair : pair.slice(0, eq);
161
+ const decodedKey = safeDecode(rawKey);
162
+ if (!denylist.test(decodedKey)) return pair;
163
+ return eq === -1 ? rawKey : `${rawKey}=[redacted]`;
164
+ }).join("&")}${suffix}`;
165
+ }
166
+ function safeDecode(value) {
167
+ try {
168
+ return decodeURIComponent(value);
169
+ } catch {
170
+ return value;
171
+ }
172
+ }
173
+
174
+ //#endregion
175
+ //#region src/api/Api.ts
176
+ var Api = class {
177
+ report(report, url, key, reportBrowserExtensionErrors, debug = false) {
178
+ return fetch(url, {
179
+ method: "POST",
180
+ headers: {
181
+ "Accept": "application/json",
182
+ "Content-Type": "application/json",
183
+ "X-Api-Token": key ?? "",
184
+ "X-Report-Browser-Extension-Errors": JSON.stringify(reportBrowserExtensionErrors),
185
+ "X-Flare-Client-Version": "2"
186
+ },
187
+ body: flatJsonStringify(report)
188
+ }).then((response) => {
189
+ if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from Flare`);
190
+ }, (error) => {
191
+ if (debug) console.error(error);
192
+ });
193
+ }
194
+ };
195
+
196
+ //#endregion
197
+ //#region src/Scope.ts
198
+ /**
199
+ * Holds the per-call mutable state that used to live on the `Flare` instance:
200
+ * breadcrumbs (`glows`), custom attributes (`pendingAttributes`), and the
201
+ * current entry-point handler.
202
+ *
203
+ * Why this exists as its own class: in the browser there is one `Flare` per
204
+ * page and one user at a time, so a single shared bag of state is fine. In
205
+ * Node, a single `Flare` instance serves many concurrent requests, and each
206
+ * request wants its own breadcrumbs and its own custom context that do NOT
207
+ * leak into other requests. Splitting this state out of `Flare` lets the
208
+ * consumer choose: one global `Scope` (browser) or one `Scope` per request
209
+ * via AsyncLocalStorage (Node).
210
+ *
211
+ * `Flare` reads and writes this through `scopeProvider.active()` instead of
212
+ * holding the state directly, so the per-request behavior comes from the
213
+ * provider, not from the class itself.
214
+ *
215
+ * `NodeScope` (in `@flareapp/node`) extends this with two more buckets:
216
+ * `request` (HTTP method, path, headers) and `user` (id, email, ...). Browser
217
+ * does not need those.
218
+ */
219
+ var Scope = class {
220
+ glows = [];
221
+ pendingAttributes = {};
222
+ entryPoint = null;
223
+ /**
224
+ * Append a breadcrumb. Caps the list at `maxGlowsPerReport` by dropping the
225
+ * OLDEST entries when the limit is exceeded; this keeps reports below a
226
+ * payload-size threshold while preserving the most recent events leading
227
+ * up to an error.
228
+ *
229
+ * `slice(length - max)` returns the trailing `max` items, which is the
230
+ * shortest way to drop from the front and keep insertion order.
231
+ */
232
+ addGlow(glow, maxGlowsPerReport) {
233
+ this.glows.push(glow);
234
+ if (this.glows.length > maxGlowsPerReport) this.glows = this.glows.slice(this.glows.length - maxGlowsPerReport);
235
+ }
236
+ clearGlows() {
237
+ this.glows = [];
238
+ }
239
+ /**
240
+ * Set a single attribute on this scope. Called from `Flare.addContext` and
241
+ * `Flare.addContextGroup`. Last write wins.
242
+ */
243
+ setAttribute(key, value) {
244
+ this.pendingAttributes[key] = value;
245
+ }
246
+ /**
247
+ * Shallow-merge a bag of attributes into this scope. Used by Node's
248
+ * AsyncLocalStorage provider when patching the live request context via
249
+ * `flare.mergeContext({ ... })`. Last write wins per key; nested objects
250
+ * are NOT deep-merged.
251
+ */
252
+ mergeAttributes(partial) {
253
+ Object.assign(this.pendingAttributes, partial);
254
+ }
255
+ };
256
+ /**
257
+ * The simplest provider: one `Scope` for the lifetime of the provider, shared
258
+ * by every caller. This is the right default for environments with a single
259
+ * logical context (browser tab, CLI script, etc.) and is the default that
260
+ * `Flare`'s constructor falls back to when no provider is supplied.
261
+ */
262
+ var GlobalScopeProvider = class {
263
+ scope = new Scope();
264
+ active() {
265
+ return this.scope;
266
+ }
267
+ };
268
+
269
+ //#endregion
270
+ //#region src/stacktrace/fileReader.ts
271
+ const cachedFiles = {};
272
+ function getCodeSnippet(fileReader, url, lineNumber, columnNumber) {
273
+ return new Promise((resolve) => {
274
+ if (!url || !lineNumber) return resolve({
275
+ codeSnippet: { 0: `Could not read from file: missing file URL or line number. URL: ${url} lineNumber: ${lineNumber}` },
276
+ trimmedColumnNumber: null
277
+ });
278
+ readFile(fileReader, url).then((fileText) => {
279
+ if (!fileText) return resolve({
280
+ codeSnippet: { 0: `Could not read from file: Error while opening file at URL ${url}` },
281
+ trimmedColumnNumber: null
282
+ });
283
+ return resolve(readLinesFromFile(fileText, lineNumber, columnNumber));
284
+ });
285
+ });
286
+ }
287
+ function readFile(fileReader, url) {
288
+ if (cachedFiles[url] !== void 0) return Promise.resolve(cachedFiles[url]);
289
+ return fileReader.read(url).then((text) => {
290
+ if (text !== null) cachedFiles[url] = text;
291
+ return text;
292
+ });
293
+ }
294
+ function readLinesFromFile(fileText, lineNumber, columnNumber, maxSnippetLineLength = 1e3, maxSnippetLines = 40) {
295
+ const codeSnippet = {};
296
+ let trimmedColumnNumber = null;
297
+ const lines = fileText.split("\n");
298
+ const errorLineIndex = lineNumber - 1;
299
+ const half = Math.floor(maxSnippetLines / 2);
300
+ for (let i = -half; i <= half; i++) {
301
+ const currentLineIndex = errorLineIndex + i;
302
+ if (currentLineIndex < 0 || !lines[currentLineIndex]) continue;
303
+ const displayLine = currentLineIndex + 1;
304
+ const line = lines[currentLineIndex];
305
+ if (line.length > maxSnippetLineLength) {
306
+ if (columnNumber && columnNumber > maxSnippetLineLength / 2) {
307
+ const start = columnNumber - Math.round(maxSnippetLineLength / 2);
308
+ codeSnippet[displayLine] = line.slice(start, start + maxSnippetLineLength);
309
+ if (displayLine === lineNumber) trimmedColumnNumber = Math.round(maxSnippetLineLength / 2);
310
+ continue;
311
+ }
312
+ codeSnippet[displayLine] = line.slice(0, maxSnippetLineLength) + "…";
313
+ continue;
314
+ }
315
+ codeSnippet[displayLine] = line;
316
+ }
317
+ return {
318
+ codeSnippet,
319
+ trimmedColumnNumber
320
+ };
321
+ }
322
+
323
+ //#endregion
324
+ //#region src/stacktrace/createStackTrace.ts
325
+ function createStackTrace(error, debug, fileReader) {
326
+ return new Promise((resolve) => {
327
+ if (!hasStack(error)) return resolve([fallbackFrame("stacktrace missing")]);
328
+ let parsedFrames;
329
+ try {
330
+ parsedFrames = error_stack_parser.default.parse(error);
331
+ } catch (parseError) {
332
+ assert(false, "Couldn't parse stacktrace of below error:", debug);
333
+ if (debug) {
334
+ console.error(parseError);
335
+ console.error(error);
336
+ }
337
+ return resolve([fallbackFrame("stacktrace could not be parsed")]);
338
+ }
339
+ Promise.all(parsedFrames.map((frame) => {
340
+ return getCodeSnippet(fileReader, frame.fileName, frame.lineNumber, frame.columnNumber).then((snippet) => ({
341
+ lineNumber: frame.lineNumber || 1,
342
+ columnNumber: frame.columnNumber || 1,
343
+ method: frame.functionName || "Anonymous or unknown function",
344
+ file: frame.fileName || "Unknown file",
345
+ codeSnippet: snippet.codeSnippet,
346
+ class: "",
347
+ isApplicationFrame: isApplicationFrame(frame.fileName)
348
+ }));
349
+ })).then(resolve);
350
+ });
351
+ }
352
+ function fallbackFrame(reason) {
353
+ return {
354
+ lineNumber: 0,
355
+ columnNumber: 0,
356
+ method: "unknown",
357
+ file: "unknown",
358
+ codeSnippet: { 0: `Could not read from file: ${reason}` },
359
+ class: "unknown"
360
+ };
361
+ }
362
+ function hasStack(err) {
363
+ if (!err || typeof err !== "object") return false;
364
+ const e = err;
365
+ const stack = e.stack ?? e.stacktrace ?? e["opera#sourceloc"];
366
+ return typeof stack === "string" && stack !== `${e.name}: ${e.message}`;
367
+ }
368
+ function isApplicationFrame(fileName) {
369
+ if (!fileName) return true;
370
+ if (/[/\\]node_modules[/\\]/.test(fileName)) return false;
371
+ if (/(^|[/\\])(vendor|vendors)[.~-][^/\\]*\.js/i.test(fileName)) return false;
372
+ return true;
373
+ }
374
+
375
+ //#endregion
376
+ //#region src/stacktrace/NullFileReader.ts
377
+ /**
378
+ * No-op `FileReader` that returns `null` for every URL it is asked to read.
379
+ *
380
+ * Used as the default for `Flare`'s `fileReader` constructor parameter so the
381
+ * class is usable without picking a side: instantiated bare (`new Flare()`),
382
+ * reports still build, but stack frames omit source-code snippets — which is
383
+ * the correct, safe behavior in an environment we know nothing about.
384
+ *
385
+ * The two real implementations live in the consumer packages and take their
386
+ * place once the right environment is established:
387
+ *
388
+ * - `@flareapp/js` injects `FetchFileReader`, which `fetch()`s source maps
389
+ * and original files over HTTP for browser stack frames.
390
+ * - `@flareapp/node` injects `DiskFileReader`, which reads files from disk
391
+ * via `node:fs/promises` for server stack frames.
392
+ *
393
+ * The interface (`read(url) -> Promise<string | null>`) lets the stack-trace
394
+ * builder treat all three the same way: ask for a URL, render the snippet
395
+ * when text comes back, gracefully skip it when `null` does. No environment
396
+ * checks anywhere in core.
397
+ */
398
+ var NullFileReader = class {
399
+ read(_url) {
400
+ return Promise.resolve(null);
401
+ }
402
+ };
403
+
404
+ //#endregion
405
+ //#region src/Flare.ts
406
+ const DEFAULT_SDK_NAME = "@flareapp/core";
407
+ var Flare = class {
408
+ inflight = /* @__PURE__ */ new Set();
409
+ _config = {
410
+ key: null,
411
+ version: "",
412
+ sourcemapVersionId: SOURCEMAP_VERSION,
413
+ stage: "",
414
+ maxGlowsPerReport: 30,
415
+ ingestUrl: "https://ingress.flareapp.io/v1/errors",
416
+ reportBrowserExtensionErrors: false,
417
+ debug: false,
418
+ urlDenylist: DEFAULT_URL_DENYLIST,
419
+ replaceDefaultUrlDenylist: false,
420
+ sampleRate: 1,
421
+ beforeEvaluate: (error) => error,
422
+ beforeSubmit: (report) => report
423
+ };
424
+ sdkInfo = {
425
+ name: DEFAULT_SDK_NAME,
426
+ version: CLIENT_VERSION
427
+ };
428
+ framework = null;
429
+ /**
430
+ * @param api sends the report over HTTP.
431
+ * @param contextCollector returns per-report attributes (browser DOM info, Node
432
+ * process info, etc). Default is a no-op.
433
+ * @param fileReader reads source files for stack-trace snippets. Default
434
+ * returns null (no snippets); `@flareapp/js` injects a
435
+ * fetch-based reader, `@flareapp/node` injects a disk reader.
436
+ * @param scopeProvider returns the current `Scope` (per-call mutable state:
437
+ * glows, pendingAttributes, entryPoint). Browser uses a
438
+ * single global scope; Node uses an AsyncLocalStorage-
439
+ * backed provider so each request gets its own.
440
+ */
441
+ constructor(api = new Api(), contextCollector = () => ({}), fileReader = new NullFileReader(), scopeProvider = new GlobalScopeProvider()) {
442
+ this.api = api;
443
+ this.contextCollector = contextCollector;
444
+ this.fileReader = fileReader;
445
+ this.scopeProvider = scopeProvider;
446
+ }
447
+ /**
448
+ * Register an in-flight report so `flush()` can wait for it. Called by
449
+ * every public report entry point (`report`, `reportSilently`,
450
+ * `reportMessage`, `reportUnhandledRejection`, `test`); each wraps its
451
+ * full async pipeline (beforeEvaluate -> stack trace + source snippets ->
452
+ * beforeSubmit -> `api.report()`) so the entire roundtrip is what's
453
+ * tracked, not just the HTTP send at the end.
454
+ *
455
+ * Two problems this method solves at once.
456
+ *
457
+ * Problem 1: hold a reference to the work without leaking rejections.
458
+ *
459
+ * `p` is the real report pipeline; it can reject (network failure,
460
+ * `beforeSubmit` throws, etc). If we stored `p` directly in `inflight`
461
+ * and no caller attached a `.catch` (the global error listeners use
462
+ * `reportSilently` which DOES catch, but the path is still subtle), an
463
+ * eventual rejection would surface as an unhandled-rejection warning
464
+ * on Node and a console error in the browser. Bad citizen.
465
+ *
466
+ * So we build a SHADOW promise that mirrors `p`'s timing but cannot
467
+ * reject:
468
+ *
469
+ * p.then(
470
+ * () => undefined, // on fulfilment, value is undefined
471
+ * () => undefined, // on rejection, ALSO resolve with undefined
472
+ * )
473
+ *
474
+ * Providing the second argument means we have "handled" any rejection
475
+ * from `p`. The shadow always resolves with `undefined`, and `p`'s
476
+ * rejection is consumed at the boundary. From the runtime's point of
477
+ * view, the shadow is well-behaved.
478
+ *
479
+ * Problem 2: self-cleaning entry.
480
+ *
481
+ * `tracked.finally(() => this.inflight.delete(tracked))`. `finally`
482
+ * fires whether the shadow resolves or rejects, but the shadow can no
483
+ * longer reject (problem 1 normalized it), so this is effectively
484
+ * "when the underlying report has settled, remove me from the Set."
485
+ * No GC magic, no external cleanup, no race window.
486
+ *
487
+ * Note that `.finally` itself returns a new promise that we drop on
488
+ * the floor. If the cleanup callback ever throws, that would surface
489
+ * as an unhandled rejection on the dropped promise; `delete` does not
490
+ * throw so we are safe today, but anything more elaborate added here
491
+ * should be wrapped in try/catch.
492
+ *
493
+ * The return value is the ORIGINAL `p`. The caller awaits real success
494
+ * or failure; the tracking is completely invisible to them. This is why
495
+ * `await flare.report(err)` inside a fatal handler observes network
496
+ * errors the same as before tracking was added.
497
+ */
498
+ track(p) {
499
+ const tracked = p.then(() => void 0, () => void 0);
500
+ this.inflight.add(tracked);
501
+ tracked.finally(() => this.inflight.delete(tracked));
502
+ return p;
503
+ }
504
+ /**
505
+ * Wait until every in-flight report settles, or until `timeoutMs`
506
+ * elapses, whichever comes first. Always resolves; never rejects.
507
+ *
508
+ * The main consumer is `@flareapp/node`'s fatal handler:
509
+ *
510
+ * process.on('uncaughtException', async (err) => {
511
+ * process.exitCode = 1;
512
+ * try { await flare.report(err); } catch {}
513
+ * await flare.flush(shutdownTimeoutMs);
514
+ * process.exit(1);
515
+ * });
516
+ *
517
+ * The fatal `report` is awaited explicitly; `flush` then drains any
518
+ * OTHER reports that were already in flight (a request handler that
519
+ * fired `flare.report(...)` concurrently with the crash). The timeout
520
+ * caps the wait so a hung HTTP request cannot indefinitely block
521
+ * shutdown.
522
+ *
523
+ * Walking the implementation:
524
+ *
525
+ * const pending = [...this.inflight];
526
+ *
527
+ * Spread takes a SNAPSHOT of the Set at this instant. Reports that
528
+ * start AFTER this line are not included in `pending`, so they are
529
+ * not awaited by THIS flush call. This is intentional: it bounds
530
+ * the wait. Without the snapshot, a handler that kept emitting
531
+ * reports during shutdown could keep flush alive forever and block
532
+ * the process from exiting.
533
+ *
534
+ * if (pending.length === 0) return Promise.resolve();
535
+ *
536
+ * Fast path. No timer scheduled, no promise constructor needed.
537
+ * Resolves on the microtask queue. Cheap.
538
+ *
539
+ * return new Promise<void>((resolve) => {
540
+ * const timer = setTimeout(resolve, timeoutMs);
541
+ * Promise.allSettled(pending).then(() => {
542
+ * clearTimeout(timer);
543
+ * resolve();
544
+ * });
545
+ * });
546
+ *
547
+ * The race between two outcomes, both calling the same `resolve`:
548
+ *
549
+ * 1. `setTimeout(resolve, timeoutMs)` schedules a "give up" call.
550
+ * After `timeoutMs` it fires, calling `resolve()` from the
551
+ * timer-queue side. The outer promise resolves immediately,
552
+ * even if reports are still pending. Those reports are abandoned
553
+ * (they continue running but the process is about to die).
554
+ *
555
+ * 2. `Promise.allSettled(pending)` returns a promise that resolves
556
+ * when every promise in `pending` has either fulfilled or
557
+ * rejected. It NEVER rejects on its own. We use `allSettled`
558
+ * rather than `Promise.all` because `all` short-circuits on the
559
+ * first rejection -- we want to wait for everyone regardless of
560
+ * whether their HTTP calls succeed or fail. (Our shadows cannot
561
+ * reject anyway because `track` normalized them, but using
562
+ * `allSettled` documents the intent and survives future changes
563
+ * to shadow construction.) When it resolves, we call
564
+ * `clearTimeout(timer)` to cancel the pending timer (so it does
565
+ * not fire later and call `resolve` a second time -- a no-op,
566
+ * but wasted work) and then `resolve()` ourselves.
567
+ *
568
+ * Resolve can only meaningfully fire once. Subsequent calls to the
569
+ * same `resolve` are silently ignored by the Promise spec, so the
570
+ * race is safe even if for some reason both branches fired together.
571
+ *
572
+ * Things flush() deliberately does NOT do:
573
+ *
574
+ * - It does not reject. Even if every report failed, allSettled
575
+ * resolves. Callers do not need a `.catch`.
576
+ * - It does not retry. One pipeline attempt per report, then move on.
577
+ * - It does not stop new reports from starting. The Flare instance
578
+ * is still usable after flush resolves. flush is "wait for what is
579
+ * in flight," not "freeze the SDK."
580
+ * - It does not drain reports started after the snapshot. Call flush
581
+ * again if you need to wait for those too.
582
+ */
583
+ flush(timeoutMs = 2e3) {
584
+ const pending = [...this.inflight];
585
+ if (pending.length === 0) return Promise.resolve();
586
+ return new Promise((resolve) => {
587
+ const timer = setTimeout(resolve, timeoutMs);
588
+ Promise.allSettled(pending).then(() => {
589
+ clearTimeout(timer);
590
+ resolve();
591
+ });
592
+ });
593
+ }
594
+ get config() {
595
+ return this._config;
596
+ }
597
+ get glows() {
598
+ return this.scopeProvider.active().glows;
599
+ }
600
+ light(key = KEY, debug) {
601
+ this._config.key = key;
602
+ if (debug !== void 0) this._config.debug = debug;
603
+ return this;
604
+ }
605
+ configure(config) {
606
+ this._config = {
607
+ ...this._config,
608
+ ...config
609
+ };
610
+ if (config.sampleRate !== void 0) this._config.sampleRate = Math.max(0, Math.min(1, config.sampleRate));
611
+ this._config.urlDenylist = resolveDenylist(config.urlDenylist, config.replaceDefaultUrlDenylist ?? this._config.replaceDefaultUrlDenylist);
612
+ return this;
613
+ }
614
+ test() {
615
+ return this.track(this.testInternal());
616
+ }
617
+ async testInternal() {
618
+ const report = await this.createReportFromError(/* @__PURE__ */ new Error("The Flare client is set up correctly!"));
619
+ if (!report) return;
620
+ return this.sendReport(report);
621
+ }
622
+ glow(name, level = "info", data = []) {
623
+ const time = now();
624
+ this.scopeProvider.active().addGlow({
625
+ name,
626
+ messageLevel: level,
627
+ metaData: data,
628
+ time,
629
+ microtime: time
630
+ }, this._config.maxGlowsPerReport);
631
+ return this;
632
+ }
633
+ clearGlows() {
634
+ this.scopeProvider.active().clearGlows();
635
+ return this;
636
+ }
637
+ addContext(name, value) {
638
+ const scope = this.scopeProvider.active();
639
+ const existing = scope.pendingAttributes["context.custom"] ?? {};
640
+ scope.setAttribute("context.custom", {
641
+ ...existing,
642
+ [name]: value
643
+ });
644
+ return this;
645
+ }
646
+ addContextGroup(groupName, value) {
647
+ this.scopeProvider.active().setAttribute(`context.${groupName}`, value);
648
+ return this;
649
+ }
650
+ setEntryPoint(handler) {
651
+ this.scopeProvider.active().entryPoint = handler;
652
+ return this;
653
+ }
654
+ setSdkInfo(info) {
655
+ this.sdkInfo = info;
656
+ return this;
657
+ }
658
+ setFramework(framework) {
659
+ this.framework = framework;
660
+ return this;
661
+ }
662
+ report(error, attributes = {}) {
663
+ return this.track(this.reportInternal(error, attributes));
664
+ }
665
+ async reportInternal(error, attributes = {}) {
666
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
667
+ const seenAtUnixNano = Date.now() * 1e6;
668
+ const coerced = error instanceof Error ? error : new Error(typeof error === "string" ? error : String(error));
669
+ const errorToReport = await this._config.beforeEvaluate(coerced);
670
+ if (!errorToReport) return;
671
+ const report = await this.createReportFromError(errorToReport, attributes, seenAtUnixNano);
672
+ if (!report) return;
673
+ return this.sendReport(report);
674
+ }
675
+ reportSilently(error, attributes = {}) {
676
+ this.track(this.reportInternal(error, attributes).catch(() => {}));
677
+ }
678
+ reportUnhandledRejection(message, attributes = {}) {
679
+ return this.track(this.reportUnhandledRejectionInternal(message, attributes));
680
+ }
681
+ async reportUnhandledRejectionInternal(message, attributes = {}) {
682
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
683
+ const seenAtUnixNano = Date.now() * 1e6;
684
+ const report = this.buildReport({
685
+ exceptionClass: "UnhandledRejection",
686
+ message,
687
+ stacktrace: [],
688
+ isLog: false,
689
+ level: void 0,
690
+ extraAttributes: attributes,
691
+ code: void 0,
692
+ seenAtUnixNano
693
+ });
694
+ return this.sendReport(report);
695
+ }
696
+ reportMessage(message, level, attributes = {}) {
697
+ return this.track(this.reportMessageInternal(message, level, attributes));
698
+ }
699
+ async reportMessageInternal(message, level, attributes = {}) {
700
+ if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
701
+ const seenAtUnixNano = Date.now() * 1e6;
702
+ const stackTrace = await createStackTrace(/* @__PURE__ */ new Error(), this._config.debug, this.fileReader);
703
+ stackTrace.shift();
704
+ const report = this.buildReport({
705
+ exceptionClass: "Log",
706
+ message,
707
+ stacktrace: stackTrace,
708
+ isLog: true,
709
+ level,
710
+ extraAttributes: attributes,
711
+ code: void 0,
712
+ seenAtUnixNano
713
+ });
714
+ return this.sendReport(report);
715
+ }
716
+ async createReportFromError(error, attributes = {}, seenAtUnixNano = Date.now() * 1e6) {
717
+ if (!assert(error, "No error provided.", this._config.debug)) return false;
718
+ const stacktrace = await createStackTrace(error, this._config.debug, this.fileReader);
719
+ assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this._config.debug);
720
+ const exceptionClass = error.constructor && error.constructor.name ? error.constructor.name : "undefined";
721
+ return this.buildReport({
722
+ exceptionClass,
723
+ message: error.message,
724
+ stacktrace,
725
+ isLog: false,
726
+ level: void 0,
727
+ extraAttributes: attributes,
728
+ code: extractCode(error),
729
+ seenAtUnixNano
730
+ });
731
+ }
732
+ buildReport(input) {
733
+ const activeScope = this.scopeProvider.active();
734
+ const baseAttributes = {
735
+ "telemetry.sdk.language": "javascript",
736
+ "telemetry.sdk.name": this.sdkInfo.name,
737
+ "telemetry.sdk.version": this.sdkInfo.version,
738
+ "flare.language.name": "javascript"
739
+ };
740
+ if (this._config.stage) baseAttributes["service.stage"] = this._config.stage;
741
+ if (this._config.version) baseAttributes["service.version"] = this._config.version;
742
+ if (this.framework?.name) baseAttributes["flare.framework.name"] = this.framework.name;
743
+ if (this.framework?.version) baseAttributes["flare.framework.version"] = this.framework.version;
744
+ const entryPoint = activeScope.entryPoint;
745
+ const entryPointOverrides = {};
746
+ if (entryPoint?.identifier !== void 0) entryPointOverrides["flare.entry_point.handler.identifier"] = entryPoint.identifier;
747
+ if (entryPoint?.type !== void 0) entryPointOverrides["flare.entry_point.handler.type"] = entryPoint.type;
748
+ if (entryPoint?.name !== void 0) entryPointOverrides["flare.entry_point.handler.name"] = entryPoint.name;
749
+ const attributes = {
750
+ ...baseAttributes,
751
+ ...this.contextCollector(this._config),
752
+ ...entryPointOverrides,
753
+ ...activeScope.pendingAttributes,
754
+ ...input.extraAttributes
755
+ };
756
+ const pendingCustom = activeScope.pendingAttributes["context.custom"];
757
+ const extraCustom = input.extraAttributes["context.custom"];
758
+ if (pendingCustom && extraCustom && typeof pendingCustom === "object" && typeof extraCustom === "object" && !Array.isArray(pendingCustom) && !Array.isArray(extraCustom)) attributes["context.custom"] = {
759
+ ...pendingCustom,
760
+ ...extraCustom
761
+ };
762
+ if (this.framework?.name) attributes["context.custom"] = {
763
+ ...attributes["context.custom"] ?? {},
764
+ framework: this.framework.name.toLowerCase()
765
+ };
766
+ const report = {
767
+ exceptionClass: input.exceptionClass,
768
+ message: input.message,
769
+ seenAtUnixNano: input.seenAtUnixNano,
770
+ stacktrace: input.stacktrace,
771
+ events: glowsToEvents(activeScope.glows),
772
+ attributes
773
+ };
774
+ if (input.isLog) report.isLog = true;
775
+ if (input.level !== void 0) report.level = input.level;
776
+ if (this._config.sourcemapVersionId) report.sourcemapVersionId = this._config.sourcemapVersionId;
777
+ if (input.code !== void 0) report.code = input.code;
778
+ return report;
779
+ }
780
+ async sendReport(report) {
781
+ if (!assertKey(this._config.key, this._config.debug)) return;
782
+ const reportToSubmit = await this._config.beforeSubmit(report);
783
+ if (!reportToSubmit) return;
784
+ return this.api.report(reportToSubmit, this._config.ingestUrl, this._config.key, this._config.reportBrowserExtensionErrors, this._config.debug);
785
+ }
786
+ };
787
+
788
+ //#endregion
789
+ exports.Api = Api;
790
+ exports.DEFAULT_URL_DENYLIST = DEFAULT_URL_DENYLIST;
791
+ exports.Flare = Flare;
792
+ exports.GlobalScopeProvider = GlobalScopeProvider;
793
+ exports.NullFileReader = NullFileReader;
794
+ exports.Scope = Scope;
795
+ exports.assert = assert;
796
+ exports.assertKey = assertKey;
797
+ exports.convertToError = convertToError;
798
+ exports.createStackTrace = createStackTrace;
799
+ exports.extractCode = extractCode;
800
+ exports.flatJsonStringify = flatJsonStringify;
801
+ exports.getCodeSnippet = getCodeSnippet;
802
+ exports.glowsToEvents = glowsToEvents;
803
+ exports.now = now;
804
+ exports.readLinesFromFile = readLinesFromFile;
805
+ exports.redactUrlQuery = redactUrlQuery;
806
+ exports.resolveDenylist = resolveDenylist;