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