@utk09/ui-observability 0.1.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.
Files changed (62) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +217 -0
  3. package/dist/bus/bus.d.ts +134 -0
  4. package/dist/bus/links.d.ts +106 -0
  5. package/dist/capture/errors.d.ts +34 -0
  6. package/dist/capture/interactions.d.ts +29 -0
  7. package/dist/capture/network.d.ts +40 -0
  8. package/dist/capture/types.d.ts +78 -0
  9. package/dist/capture/web-vitals.d.ts +21 -0
  10. package/dist/constants-D8-4Ged5.cjs +2 -0
  11. package/dist/constants-D8-4Ged5.cjs.map +1 -0
  12. package/dist/constants-DbvMIryP.js +110 -0
  13. package/dist/constants-DbvMIryP.js.map +1 -0
  14. package/dist/constants.d.ts +339 -0
  15. package/dist/core/breadcrumbs.d.ts +48 -0
  16. package/dist/core/config.d.ts +16 -0
  17. package/dist/core/context.d.ts +35 -0
  18. package/dist/core/diagnostics.d.ts +76 -0
  19. package/dist/core/journey.d.ts +112 -0
  20. package/dist/core/logger.d.ts +117 -0
  21. package/dist/core/pipeline.d.ts +75 -0
  22. package/dist/core/record.d.ts +72 -0
  23. package/dist/core/runtime.d.ts +146 -0
  24. package/dist/core/sampling.d.ts +9 -0
  25. package/dist/index.cjs +4 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.ts +167 -0
  28. package/dist/index.js +2577 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/indexeddb-storage-DvsvCUlO.cjs +2 -0
  31. package/dist/indexeddb-storage-DvsvCUlO.cjs.map +1 -0
  32. package/dist/indexeddb-storage-DwpCDRnX.js +88 -0
  33. package/dist/indexeddb-storage-DwpCDRnX.js.map +1 -0
  34. package/dist/models/batch.d.ts +22 -0
  35. package/dist/models/bus.d.ts +97 -0
  36. package/dist/models/config.d.ts +528 -0
  37. package/dist/models/log-record.d.ts +54 -0
  38. package/dist/models/serializer.d.ts +23 -0
  39. package/dist/models/storage.d.ts +62 -0
  40. package/dist/storage/emergency-queue.d.ts +16 -0
  41. package/dist/storage/factory.d.ts +13 -0
  42. package/dist/storage/indexeddb-storage.d.ts +69 -0
  43. package/dist/storage/keys.d.ts +8 -0
  44. package/dist/storage/local-storage.d.ts +80 -0
  45. package/dist/storage/memory-storage.d.ts +52 -0
  46. package/dist/transport/compression.d.ts +7 -0
  47. package/dist/transport/errors.d.ts +29 -0
  48. package/dist/transport/exit-flush.d.ts +63 -0
  49. package/dist/transport/http-transport.d.ts +63 -0
  50. package/dist/transport/retry-engine.d.ts +69 -0
  51. package/dist/transport/serializers/ecs.d.ts +3 -0
  52. package/dist/transport/serializers/otlp.d.ts +3 -0
  53. package/dist/utils/console.d.ts +24 -0
  54. package/dist/utils/identity.d.ts +36 -0
  55. package/dist/utils/lock.d.ts +15 -0
  56. package/dist/utils/platform.d.ts +36 -0
  57. package/dist/utils/sanitize.d.ts +47 -0
  58. package/dist/utils/sequence.d.ts +15 -0
  59. package/dist/utils/timer.d.ts +19 -0
  60. package/dist/utils/tracing.d.ts +55 -0
  61. package/dist/utils/unref.d.ts +9 -0
  62. package/package.json +106 -0
package/dist/index.js ADDED
@@ -0,0 +1,2577 @@
1
+ import { $ as e, At as t, B as n, C as r, Ct as i, D as a, E as o, Et as s, F as c, Ft as l, H as u, I as d, It as f, J as p, K as m, L as h, Lt as ee, Mt as te, N as g, Nt as ne, O as re, Ot as ie, P as ae, Pt as oe, Q as se, Rt as ce, S as le, T as ue, Tt as de, U as fe, V as pe, X as me, Y as he, Z as ge, _ as _e, _t as ve, a as ye, b as be, c as xe, ct as Se, d as Ce, dt as we, et as Te, ft as _, g as Ee, gt as De, h as Oe, ht as ke, i as Ae, it as je, j as Me, jt as Ne, k as Pe, kt as Fe, l as v, lt as Ie, m as Le, mt as Re, n as y, nt as ze, o as Be, ot as Ve, p as He, pt as Ue, q as b, r as We, rt as Ge, s as Ke, st as qe, t as Je, tt as Ye, u as Xe, ut as Ze, v as Qe, vt as $e, w as et, x as tt, xt as nt, yt as rt, z as it, zt as at } from "./constants-DbvMIryP.js";
2
+ import { context as ot, isSpanContextValid as st, propagation as ct, trace as lt } from "@opentelemetry/api";
3
+ import { EMPTY as ut, Subject as dt, asapScheduler as ft, bufferTime as pt, catchError as x, filter as mt, from as ht, map as gt, merge as _t, mergeMap as vt, observeOn as yt, partition as bt, tap as xt } from "rxjs";
4
+ //#region src/utils/timer.ts
5
+ function St(e) {
6
+ return Math.round((performance.now() - e) * Me) / Me;
7
+ }
8
+ function Ct(e, t, n, r, i) {
9
+ e.logMetric(`${t}.duration`, St(n), "ms", "histogram", {
10
+ status: r,
11
+ ...i
12
+ });
13
+ }
14
+ function wt(e, t, n, r, i) {
15
+ e.error(`${t} failed`, r, {
16
+ "action.duration_ms": St(n),
17
+ status: "FAILURE",
18
+ ...i
19
+ });
20
+ }
21
+ function Tt(e, t, n, r) {
22
+ let i = performance.now();
23
+ try {
24
+ let a = n();
25
+ return Ct(e, t, i, "SUCCESS", r), a;
26
+ } catch (n) {
27
+ throw wt(e, t, i, n, r), n;
28
+ }
29
+ }
30
+ async function Et(e, t, n, r) {
31
+ let i = performance.now();
32
+ try {
33
+ let a = await n();
34
+ return Ct(e, t, i, "SUCCESS", r), a;
35
+ } catch (n) {
36
+ throw wt(e, t, i, n, r), n;
37
+ }
38
+ }
39
+ //#endregion
40
+ //#region src/core/logger.ts
41
+ function Dt(e) {
42
+ return e instanceof Error ? e : Error(String(e));
43
+ }
44
+ var S = class e {
45
+ runtime;
46
+ namespace;
47
+ options;
48
+ constructor(e, t, n = {}) {
49
+ this.runtime = e, this.namespace = t, this.options = n;
50
+ }
51
+ child(t, n = {}) {
52
+ return new e(this.runtime, `${this.namespace}.${t}`, { scopedContext: {
53
+ ...this.options.scopedContext,
54
+ ...n.scopedContext
55
+ } });
56
+ }
57
+ trace = (e, t) => {
58
+ this.write("TRACE", "system", e, t);
59
+ };
60
+ debug = (e, t) => {
61
+ this.write("DEBUG", "system", e, t);
62
+ };
63
+ info = (e, t) => {
64
+ this.write("INFO", "system", e, t);
65
+ };
66
+ warn = (e, t) => {
67
+ this.write("WARN", "system", e, t);
68
+ };
69
+ error = (e, t, n) => {
70
+ this.writeError("ERROR", e, t, n);
71
+ };
72
+ fatal = (e, t, n) => {
73
+ this.writeError("FATAL", e, t, n);
74
+ };
75
+ logAction = (e, t) => {
76
+ this.write("INFO", "action", e, t);
77
+ };
78
+ logEvent = (e, t) => {
79
+ this.write("INFO", "event", e, t);
80
+ };
81
+ logMetric = (e, t, n = re, r = "gauge", i) => {
82
+ this.write("INFO", "metric", e, {
83
+ "metric.name": e,
84
+ "metric.value": t,
85
+ "metric.unit": n,
86
+ "metric.type": r,
87
+ ...i
88
+ });
89
+ };
90
+ timeSync = (e, t, n) => Tt(this, e, t, n);
91
+ timeAsync = (e, t, n) => Et(this, e, t, n);
92
+ write(e, t, n, r) {
93
+ if (!this.runtime.builder.isEnabled(e)) return;
94
+ let i = this.runtime.builder.build({
95
+ level: e,
96
+ type: t,
97
+ body: n,
98
+ namespace: this.namespace,
99
+ scoped: this.options.scopedContext,
100
+ payload: r
101
+ });
102
+ i && t !== "metric" && this.runtime.breadcrumbs.push({
103
+ t: Date.now(),
104
+ category: t === "action" ? "action" : t === "event" ? "event" : "log",
105
+ message: n
106
+ }), this.runtime.console.write(e, n, i?.attributes), this.runtime.emit(i);
107
+ }
108
+ writeError(e, t, n, r) {
109
+ if (!this.runtime.builder.isEnabled(e)) return;
110
+ let i = n === void 0 ? void 0 : Dt(n), a = this.runtime.builder.build({
111
+ level: e,
112
+ type: "system",
113
+ body: t,
114
+ namespace: this.namespace,
115
+ scoped: this.options.scopedContext,
116
+ payload: {
117
+ ...r,
118
+ ...i ? {
119
+ "error.type": i.name,
120
+ "error.message": i.message,
121
+ "error.stack_trace": i.stack
122
+ } : {},
123
+ breadcrumbs: this.runtime.breadcrumbs.snapshot()
124
+ }
125
+ });
126
+ this.runtime.console.write(e, t, i ?? a?.attributes), this.runtime.emit(a);
127
+ }
128
+ };
129
+ //#endregion
130
+ //#region src/utils/unref.ts
131
+ function C(e) {
132
+ typeof e != "number" && e.unref?.();
133
+ }
134
+ //#endregion
135
+ //#region src/models/bus.ts
136
+ function w(e) {
137
+ return {
138
+ p: be,
139
+ m: e
140
+ };
141
+ }
142
+ function T(e) {
143
+ if (typeof e != "object" || !e) return null;
144
+ let t = e;
145
+ if (t.p !== "ui-observability/1" || typeof t.m != "object" || t.m === null) return null;
146
+ let n = t.m;
147
+ return typeof n.t == "string" ? n : null;
148
+ }
149
+ //#endregion
150
+ //#region src/bus/links.ts
151
+ var Ot = Symbol.for(rt);
152
+ function kt(e, t) {
153
+ if (typeof window > "u" || window.parent === window) return null;
154
+ let n;
155
+ try {
156
+ n = window.parent[Ot];
157
+ } catch {
158
+ return null;
159
+ }
160
+ if (typeof n?.busAccept != "function") return null;
161
+ let r = n, i = !0;
162
+ return {
163
+ kind: "direct",
164
+ post(n) {
165
+ i && t.guard("bus.send_failed", "direct call into the parent runtime", () => {
166
+ r.busAccept(n, e);
167
+ });
168
+ },
169
+ close() {
170
+ i = !1;
171
+ }
172
+ };
173
+ }
174
+ function At(e, t) {
175
+ if (typeof window > "u" || window.parent === window) return null;
176
+ let n = (t) => {
177
+ let n = T(t.data);
178
+ n && t.source === window.parent && e(n, {
179
+ link: "parent",
180
+ origin: t.origin
181
+ });
182
+ };
183
+ return addEventListener("message", n), {
184
+ kind: "parent",
185
+ post(e) {
186
+ t.guard("bus.send_failed", "postMessage to parent", () => {
187
+ window.parent.postMessage(w(e), "*");
188
+ });
189
+ },
190
+ close() {
191
+ removeEventListener("message", n);
192
+ }
193
+ };
194
+ }
195
+ function jt(e, t, n) {
196
+ if (typeof window > "u") return null;
197
+ let r = /* @__PURE__ */ new Set([window.location.origin, ...t]), i = /* @__PURE__ */ new Set(), a = (t) => {
198
+ let a = T(t.data);
199
+ if (a) {
200
+ if (!r.has(t.origin)) {
201
+ n.report("bus.untrusted_origin", `ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`, {
202
+ origin: t.origin,
203
+ type: a.t
204
+ });
205
+ return;
206
+ }
207
+ t.source && i.add(t.source), e(a, {
208
+ link: "children",
209
+ origin: t.origin
210
+ });
211
+ }
212
+ };
213
+ return addEventListener("message", a), {
214
+ kind: "children",
215
+ post(e) {
216
+ for (let t of i) {
217
+ let r = t;
218
+ if (r.closed) {
219
+ i.delete(t);
220
+ continue;
221
+ }
222
+ n.guard("bus.send_failed", "postMessage to child", () => {
223
+ r.postMessage(w(e), "*");
224
+ });
225
+ }
226
+ },
227
+ close() {
228
+ removeEventListener("message", a), i.clear();
229
+ }
230
+ };
231
+ }
232
+ function Mt(e, t, n) {
233
+ let r = globalThis.BroadcastChannel;
234
+ if (r === void 0) return null;
235
+ let i = n.guard("bus.send_failed", "opening BroadcastChannel", () => new r(e));
236
+ return i ? (i.onmessage = (e) => {
237
+ let n = T(e.data);
238
+ n && t(n, {
239
+ link: "broadcast",
240
+ origin: "same-origin"
241
+ });
242
+ }, {
243
+ kind: "broadcast",
244
+ post(e) {
245
+ n.guard("bus.send_failed", "BroadcastChannel.postMessage", () => {
246
+ i.postMessage(w(e));
247
+ });
248
+ },
249
+ close() {
250
+ n.guard("bus.send_failed", "closing BroadcastChannel", () => {
251
+ i.close();
252
+ });
253
+ }
254
+ }) : null;
255
+ }
256
+ function Nt(e, t, n) {
257
+ let r = globalThis.fin?.InterApplicationBus;
258
+ return r ? (n.guardAsync("bus.send_failed", "InterApplicationBus.subscribe", () => r.subscribe({ uuid: "*" }, e, (e) => {
259
+ let n = T(e);
260
+ n && t(n, {
261
+ link: "openfin",
262
+ origin: "openfin"
263
+ });
264
+ })), {
265
+ kind: "openfin",
266
+ post(t) {
267
+ n.guardAsync("bus.send_failed", "InterApplicationBus.publish", () => r.publish(e, w(t)));
268
+ },
269
+ close() {}
270
+ }) : null;
271
+ }
272
+ function Pt(e, t) {
273
+ let n = globalThis, r = n.postMessage;
274
+ return n.WorkerGlobalScope === void 0 || !r ? null : (n.addEventListener?.("message", (t) => {
275
+ let n = T(t.data);
276
+ n && e(n, {
277
+ link: "owner",
278
+ origin: "same-origin"
279
+ });
280
+ }), {
281
+ kind: "owner",
282
+ post(e) {
283
+ t.guard("bus.send_failed", "worker postMessage", () => {
284
+ r(w(e));
285
+ });
286
+ },
287
+ close() {}
288
+ });
289
+ }
290
+ function Ft(e, t, n) {
291
+ let r = (e) => {
292
+ let n = T(e.data);
293
+ n && t(n, {
294
+ link: "worker",
295
+ origin: "same-origin"
296
+ });
297
+ };
298
+ return e.addEventListener("message", r), e.start?.(), {
299
+ kind: "worker",
300
+ post(t) {
301
+ n.guard("bus.send_failed", "postMessage to a worker", () => {
302
+ e.postMessage(w(t));
303
+ });
304
+ },
305
+ close() {
306
+ e.removeEventListener("message", r);
307
+ }
308
+ };
309
+ }
310
+ //#endregion
311
+ //#region src/bus/bus.ts
312
+ var It = [
313
+ "children",
314
+ "direct",
315
+ "worker"
316
+ ], Lt = class {
317
+ config;
318
+ diagnostics;
319
+ platform;
320
+ contextId;
321
+ tabId;
322
+ handlers;
323
+ role = "sender";
324
+ upstream = null;
325
+ links = [];
326
+ openFinLink = null;
327
+ isOpenFinProvider = !1;
328
+ resolved = !1;
329
+ awaitingWelcome = null;
330
+ constructor(e, t, n, r, i, a) {
331
+ this.config = e, this.diagnostics = t, this.platform = n, this.contextId = r, this.tabId = i, this.handlers = a;
332
+ }
333
+ getRole() {
334
+ return this.role;
335
+ }
336
+ isResolved() {
337
+ return this.resolved;
338
+ }
339
+ async start() {
340
+ let { bus: e } = this.config;
341
+ if (e.mode === "off") return this.role = "sender", this.resolved = !0, this.role;
342
+ if (this.isOpenFinProvider = this.resolveOpenFinProvider(), e.mode === "sender" || e.mode === "forwarder") return this.role = e.mode, this.openControlLinks(), this.role === "forwarder" && (this.upstream = this.candidateUpstream(), this.upstream || this.diagnostics.report("bus.no_owner", "bus.mode is \"forwarder\" but there is no owner to forward to. Records will be dropped.")), this.resolved = !0, this.announce(), this.role;
343
+ this.openControlLinks();
344
+ let t = kt(this.receive, this.diagnostics);
345
+ if (t) return this.role = "forwarder", this.upstream = t, this.resolved = !0, this.diagnostics.report("bus.role_resolved", "attached directly to the same-origin parent runtime", {
346
+ role: "forwarder",
347
+ via: "direct"
348
+ }), this.announce(), this.role;
349
+ let n = this.candidateUpstream();
350
+ if (!n) return this.role = "sender", this.resolved = !0, this.diagnostics.report("bus.role_resolved", "no owner to forward to, sending directly", { role: "sender" }), this.announce(), this.role;
351
+ let r = this.orphanPolicy() === "retry" ? this.config.bus.maxHandshakeAttempts : 1, i = !1;
352
+ for (let e = 0; e < r && !i; e++) i = await this.handshake(n);
353
+ return this.role = i ? "forwarder" : "sender", this.upstream = i ? n : null, i || (n !== this.openFinLink && n.close(), this.diagnostics.report("bus.handshake_timeout", `no owner answered after ${String(r)} attempt(s) of ${String(this.config.bus.handshakeTimeoutMs)}ms, promoting to sender`, {
354
+ via: n.kind,
355
+ crossOrigin: this.isCrossOriginFrame()
356
+ })), this.diagnostics.report("bus.role_resolved", `role is ${this.role}`, {
357
+ role: this.role,
358
+ via: i ? n.kind : "none"
359
+ }), this.resolved = !0, this.announce(), this.role;
360
+ }
361
+ sendRecords(e) {
362
+ this.upstream?.post({
363
+ t: "records",
364
+ from: this.contextId,
365
+ records: e
366
+ });
367
+ }
368
+ acceptDirect(e, t) {
369
+ if (e.from === this.contextId) return;
370
+ let n = {
371
+ link: "direct",
372
+ origin: "same-origin"
373
+ };
374
+ if (e.t === "hello") {
375
+ this.canOwn("direct") && t({
376
+ t: "welcome",
377
+ from: this.contextId,
378
+ to: e.from,
379
+ tabId: this.tabId
380
+ }, n);
381
+ return;
382
+ }
383
+ if (e.t === "journey?") {
384
+ let e = this.handlers.onJourneyRequest();
385
+ e && t({
386
+ t: "journey",
387
+ from: this.contextId,
388
+ journey: e
389
+ }, n);
390
+ return;
391
+ }
392
+ this.receive(e, n);
393
+ }
394
+ attachWorker(e) {
395
+ this.links.push(Ft(e, this.receive, this.diagnostics));
396
+ }
397
+ broadcastJourney(e) {
398
+ this.post({
399
+ t: "journey",
400
+ from: this.contextId,
401
+ journey: e
402
+ });
403
+ }
404
+ destroy() {
405
+ for (let e of this.allLinks()) e.close();
406
+ this.links.length = 0, this.upstream = null, this.openFinLink = null;
407
+ }
408
+ allLinks() {
409
+ return !this.upstream || this.links.includes(this.upstream) ? this.links : [...this.links, this.upstream];
410
+ }
411
+ post(e) {
412
+ for (let t of this.allLinks()) t.post(e);
413
+ }
414
+ postOver(e, t) {
415
+ for (let n of this.allLinks()) n.kind === e && n.post(t);
416
+ }
417
+ receive = (e, t) => {
418
+ if (e.from !== this.contextId) switch (e.t) {
419
+ case "hello":
420
+ this.canOwn(t.link) && this.postOver(t.link, {
421
+ t: "welcome",
422
+ from: this.contextId,
423
+ to: e.from,
424
+ tabId: this.tabId
425
+ });
426
+ break;
427
+ case "welcome":
428
+ if (e.to !== this.contextId) break;
429
+ this.awaitingWelcome?.link === t.link && this.awaitingWelcome.settle(!0);
430
+ break;
431
+ case "records":
432
+ this.role === "sender" ? this.handlers.onRecords(e.records) : this.upstream && t.link !== this.upstream.kind && this.upstream.post(e);
433
+ break;
434
+ case "journey":
435
+ this.handlers.onJourney(e.journey);
436
+ break;
437
+ case "journey?": {
438
+ let e = this.handlers.onJourneyRequest();
439
+ e && this.postOver(t.link, {
440
+ t: "journey",
441
+ from: this.contextId,
442
+ journey: e
443
+ });
444
+ break;
445
+ }
446
+ case "tab": t.link === "broadcast" && e.tabId === this.tabId && this.contextId > e.from && this.handlers.onTabConflict();
447
+ }
448
+ };
449
+ canOwn(e) {
450
+ return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : It.includes(e) : !1;
451
+ }
452
+ resolveOpenFinProvider() {
453
+ let e = this.config.bus.openFinRole;
454
+ if (e !== "auto") return e === "provider";
455
+ if (this.platform.platform !== "openfin" && this.platform.platform !== "openfin_web") return !1;
456
+ let t = globalThis.fin?.me;
457
+ return !t?.identity || t.isView ? !1 : !!(t.identity.name && t.identity.name === t.identity.uuid);
458
+ }
459
+ orphanPolicy() {
460
+ let e = this.config.bus.orphanPolicy;
461
+ return e === "auto" ? this.isCrossOriginFrame() ? "retry" : "promote" : e;
462
+ }
463
+ isCrossOriginFrame() {
464
+ if (typeof window > "u" || window.parent === window) return !1;
465
+ try {
466
+ return window.parent.location, !1;
467
+ } catch {
468
+ return !0;
469
+ }
470
+ }
471
+ candidateUpstream() {
472
+ return this.platform.isWorker ? Pt(this.receive, this.diagnostics) : this.platform.isTopLevelDocument ? this.platform.platform === "openfin" && this.config.bus.openFinHost === "provider" && !this.isOpenFinProvider ? this.ensureOpenFinLink() : null : At(this.receive, this.diagnostics);
473
+ }
474
+ openControlLinks() {
475
+ let e = (e) => {
476
+ e && this.links.push(e);
477
+ };
478
+ this.platform.isTopLevelDocument && (e(jt(this.receive, this.config.bus.trustedOrigins, this.diagnostics)), e(Mt(this.config.bus.channelName, this.receive, this.diagnostics))), (this.platform.platform === "openfin" || this.platform.platform === "openfin_web") && e(this.ensureOpenFinLink());
479
+ }
480
+ ensureOpenFinLink() {
481
+ return this.openFinLink ??= Nt(this.config.bus.channelName, this.receive, this.diagnostics), this.openFinLink;
482
+ }
483
+ handshake(e) {
484
+ return new Promise((t) => {
485
+ let n = !1, r = (e) => {
486
+ n || (n = !0, this.awaitingWelcome = null, clearTimeout(i), t(e));
487
+ };
488
+ this.awaitingWelcome = {
489
+ link: e.kind,
490
+ settle: r
491
+ };
492
+ let i = setTimeout(() => {
493
+ r(!1);
494
+ }, this.config.bus.handshakeTimeoutMs);
495
+ C(i), e.post({
496
+ t: "hello",
497
+ from: this.contextId,
498
+ tabId: this.tabId
499
+ });
500
+ });
501
+ }
502
+ announce() {
503
+ this.postOver("broadcast", {
504
+ t: "tab",
505
+ from: this.contextId,
506
+ tabId: this.tabId
507
+ }), this.post({
508
+ t: "journey?",
509
+ from: this.contextId
510
+ });
511
+ }
512
+ }, Rt = class {
513
+ ctx;
514
+ name = "errors";
515
+ installed = !1;
516
+ seen = /* @__PURE__ */ new Map();
517
+ windowStart = 0;
518
+ windowCount = 0;
519
+ constructor(e) {
520
+ this.ctx = e;
521
+ }
522
+ install() {
523
+ this.installed || typeof addEventListener > "u" || (this.installed = !0, addEventListener("error", this.onError, !0), addEventListener("unhandledrejection", this.onRejection));
524
+ }
525
+ uninstall() {
526
+ this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
527
+ }
528
+ onError = (e) => {
529
+ let t = e.target, n = t?.src ?? t?.href ?? "";
530
+ if (t !== null && t !== globalThis && n !== "") {
531
+ if (!this.ctx.config.capture.resourceErrors) return;
532
+ this.ctx.breadcrumbs.push({
533
+ t: Date.now(),
534
+ category: "http",
535
+ message: `resource failed: ${n}`
536
+ }), this.ctx.logger.warn("resource failed to load", {
537
+ "error.type": "resource",
538
+ "resource.url": n,
539
+ "resource.tag": t.tagName.toLowerCase()
540
+ });
541
+ return;
542
+ }
543
+ if (!this.ctx.config.capture.errors) return;
544
+ let r = e, i = r.message === "" ? "unknown error" : r.message, a = r.error ?? Error(i);
545
+ this.report("window.onerror", a, {
546
+ "error.source": r.filename,
547
+ "error.line": r.lineno,
548
+ "error.column": r.colno
549
+ });
550
+ };
551
+ onRejection = (e) => {
552
+ this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
553
+ };
554
+ report(e, t, n) {
555
+ let r = Date.now();
556
+ if (r - this.windowStart > 1e4 && (this.windowStart = r, this.windowCount = 0), this.windowCount++, this.windowCount > 20) {
557
+ this.ctx.diagnostics.report("capture.rate_limited", `more than 20 errors in ${String(c)}ms, suppressing the rest of this window`);
558
+ return;
559
+ }
560
+ let i = t instanceof Error ? t : Error(String(t)), a = (i.stack ?? "").split("\n")[1] ?? "", o = `${i.name}|${i.message}|${a}`, s = this.seen.get(o);
561
+ if (s && r - s.at < this.ctx.config.capture.errorDedupeMs) {
562
+ s.count++, s.at = r;
563
+ return;
564
+ }
565
+ let l = s ? s.count - 1 : 0;
566
+ if (this.seen.delete(o), this.seen.set(o, {
567
+ at: r,
568
+ count: 1
569
+ }), this.seen.size > 200) {
570
+ let [e] = this.seen.keys();
571
+ this.seen.delete(e);
572
+ }
573
+ this.ctx.logger.error(i.message === "" ? e : i.message, i, {
574
+ ...n,
575
+ "error.captured_by": e,
576
+ "error.suppressed_count": l
577
+ });
578
+ }
579
+ };
580
+ //#endregion
581
+ //#region src/capture/interactions.ts
582
+ function zt(e) {
583
+ if (e === null) return "unknown";
584
+ let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
585
+ if (n !== null) return `[data-testid="${n}"]`;
586
+ if (e.id !== "") return `#${e.id}`;
587
+ let r = e.getAttribute("aria-label");
588
+ if (r !== null) return `${t}[aria-label="${r.slice(0, 40)}"]`;
589
+ let i = e.getAttribute("class")?.trim() ?? "";
590
+ return i === "" ? t : `${t}.${i.split(/\s+/).slice(0, 2).join(".")}`;
591
+ }
592
+ function E() {
593
+ return history;
594
+ }
595
+ var Bt = class {
596
+ ctx;
597
+ name = "interactions";
598
+ installed = !1;
599
+ originalPushState = null;
600
+ originalReplaceState = null;
601
+ lastUrl = "";
602
+ constructor(e) {
603
+ this.ctx = e;
604
+ }
605
+ install() {
606
+ this.installed || typeof document > "u" || (this.installed = !0, this.lastUrl = location.href, this.ctx.config.capture.interactions && addEventListener("click", this.onClick, !0), this.ctx.config.capture.navigation && (this.installHistory(), addEventListener("popstate", this.onNavigate), addEventListener("hashchange", this.onNavigate)));
607
+ }
608
+ uninstall() {
609
+ this.installed && (this.installed = !1, removeEventListener("click", this.onClick, !0), removeEventListener("popstate", this.onNavigate), removeEventListener("hashchange", this.onNavigate), this.originalPushState && (E().pushState = this.originalPushState), this.originalReplaceState && (E().replaceState = this.originalReplaceState), this.originalPushState = null, this.originalReplaceState = null);
610
+ }
611
+ onClick = (e) => {
612
+ let t = e.target, n = zt(t instanceof Element ? t : null), r = t instanceof HTMLElement ? t.innerText.trim().slice(0, 50) : "";
613
+ this.ctx.tracing.rotate("interaction"), this.ctx.breadcrumbs.push({
614
+ t: Date.now(),
615
+ category: "click",
616
+ message: n,
617
+ data: r === "" ? void 0 : { text: r }
618
+ });
619
+ };
620
+ onNavigate = () => {
621
+ let e = this.lastUrl, t = location.href;
622
+ e !== t && (this.lastUrl = t, this.ctx.tracing.rotate("navigation"), this.ctx.breadcrumbs.push({
623
+ t: Date.now(),
624
+ category: "navigation",
625
+ message: `${e} -> ${t}`
626
+ }), this.ctx.logger.logEvent("NAVIGATION", { "page.url.previous": e }));
627
+ };
628
+ installHistory() {
629
+ if (typeof history > "u" || this.originalPushState) return;
630
+ let e = E(), t = e.pushState, n = e.replaceState;
631
+ this.originalPushState = t, this.originalReplaceState = n;
632
+ let r = this.onNavigate;
633
+ e.pushState = function(...e) {
634
+ t.apply(this, e), queueMicrotask(r);
635
+ }, e.replaceState = function(...e) {
636
+ n.apply(this, e), queueMicrotask(r);
637
+ };
638
+ }
639
+ };
640
+ //#endregion
641
+ //#region src/capture/types.ts
642
+ function Vt(e, t) {
643
+ return t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
644
+ }
645
+ //#endregion
646
+ //#region src/capture/network.ts
647
+ function D() {
648
+ return XMLHttpRequest.prototype;
649
+ }
650
+ var Ht = class {
651
+ ctx;
652
+ name = "network";
653
+ originalFetch = null;
654
+ originalOpen = null;
655
+ originalSend = null;
656
+ constructor(e) {
657
+ this.ctx = e;
658
+ }
659
+ install() {
660
+ this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr();
661
+ }
662
+ uninstall() {
663
+ this.originalFetch &&= (globalThis.fetch = this.originalFetch, null), this.originalOpen &&= (D().open = this.originalOpen, null), this.originalSend &&= (D().send = this.originalSend, null);
664
+ }
665
+ ignored(e) {
666
+ return Vt(e, this.ctx.config.capture.ignoreUrls);
667
+ }
668
+ installFetch() {
669
+ if (typeof globalThis.fetch != "function" || this.originalFetch) return;
670
+ let e = globalThis.fetch.bind(globalThis);
671
+ this.originalFetch = globalThis.fetch;
672
+ let t = this.ctx, n = (e) => this.ignored(e), r = (e, t, n, r, i) => {
673
+ this.record(e, t, n, r, i);
674
+ };
675
+ globalThis.fetch = async function(i, a) {
676
+ let o = typeof i == "string" ? i : i instanceof URL ? i.href : i.url, s = (a?.method ?? (i instanceof Request ? i.method : "GET")).toUpperCase();
677
+ if (n(o)) return e(i, a);
678
+ let c = i, l = a;
679
+ if (Vt(o, t.config.capture.propagateTraceHeaderTo)) try {
680
+ let e = Object.entries(t.tracing.headers());
681
+ if (i instanceof Request) {
682
+ let t = new Headers(i.headers);
683
+ for (let [n, r] of e) t.set(n, r);
684
+ c = new Request(i, { headers: t });
685
+ } else {
686
+ let t = new Headers(a?.headers);
687
+ for (let [n, r] of e) t.set(n, r);
688
+ l = {
689
+ ...a,
690
+ headers: t
691
+ };
692
+ }
693
+ } catch (e) {
694
+ c = i, l = a, t.diagnostics.report("capture.header_failed", "could not attach traceparent, sending the request unchanged", { url: o }, e);
695
+ }
696
+ let u = performance.now();
697
+ try {
698
+ let t = await e(c, l);
699
+ return r(s, o, t.status, performance.now() - u, void 0), t;
700
+ } catch (e) {
701
+ throw r(s, o, 0, performance.now() - u, e), e;
702
+ }
703
+ };
704
+ }
705
+ installXhr() {
706
+ if (typeof XMLHttpRequest > "u" || this.originalOpen) return;
707
+ let e = (e) => this.ignored(e), t = (e, t, n, r) => {
708
+ this.record(e, t, n, r, void 0);
709
+ }, n = D(), r = n.open, i = n.send;
710
+ this.originalOpen = r, this.originalSend = i, n.open = function(e, t, ...n) {
711
+ this.__uiobs = {
712
+ method: e.toUpperCase(),
713
+ url: String(t),
714
+ startedAt: 0
715
+ }, r.apply(this, [
716
+ e,
717
+ t,
718
+ ...n
719
+ ]);
720
+ }, n.send = function(...n) {
721
+ let r = this.__uiobs;
722
+ r && !e(r.url) && (r.startedAt = performance.now(), this.addEventListener("loadend", () => {
723
+ t(r.method, r.url, this.status, performance.now() - r.startedAt);
724
+ })), i.apply(this, n);
725
+ };
726
+ }
727
+ record(e, t, n, r, i) {
728
+ this.ctx.diagnostics.guard("capture.record_failed", `recording ${e} ${t}`, () => {
729
+ let a = Math.round(r);
730
+ this.ctx.breadcrumbs.push({
731
+ t: Date.now(),
732
+ category: "http",
733
+ message: `${e} ${t} ${n === 0 ? "failed" : String(n)}`,
734
+ data: { durationMs: a }
735
+ });
736
+ let o = {
737
+ "http.request.method": e,
738
+ "url.full": t,
739
+ "http.response.status_code": n,
740
+ "http.duration_ms": a
741
+ };
742
+ if (n === 0) {
743
+ this.ctx.logger.error(`${e} ${t} failed`, i, o);
744
+ return;
745
+ }
746
+ if (n >= 400) {
747
+ this.ctx.logger.warn(`${e} ${t} returned ${String(n)}`, o);
748
+ return;
749
+ }
750
+ this.ctx.logger.debug(`${e} ${t}`, o);
751
+ });
752
+ }
753
+ };
754
+ //#endregion
755
+ //#region src/capture/web-vitals.ts
756
+ function Ut() {
757
+ return import(
758
+ /* @vite-ignore */
759
+ "web-vitals"
760
+ );
761
+ }
762
+ var Wt = class {
763
+ ctx;
764
+ name = "web-vitals";
765
+ installed = !1;
766
+ constructor(e) {
767
+ this.ctx = e;
768
+ }
769
+ install() {
770
+ this.installed || (this.installed = !0, this.reportNavigationTiming(), this.loadWebVitals());
771
+ }
772
+ uninstall() {
773
+ this.installed = !1;
774
+ }
775
+ async loadWebVitals() {
776
+ let e = this.ctx.config.capture.webVitalsLoader ?? Ut, t = await this.ctx.diagnostics.guardAsync("capture.install_failed", "loading web-vitals", e);
777
+ if (!t) {
778
+ this.ctx.diagnostics.report("capture.install_failed", "web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.");
779
+ return;
780
+ }
781
+ let n = (e, t) => (n) => {
782
+ this.ctx.logger.logMetric(`web_vitals.${e}`, Math.round(n.value * 1e3) / 1e3, t, "gauge", {
783
+ "metric.rating": n.rating,
784
+ "metric.id": n.id
785
+ });
786
+ };
787
+ t.onLCP(n("lcp", "ms")), t.onCLS(n("cls", "1")), t.onINP(n("inp", "ms")), t.onFCP(n("fcp", "ms")), t.onTTFB(n("ttfb", "ms"));
788
+ }
789
+ reportNavigationTiming() {
790
+ this.ctx.diagnostics.guard("capture.install_failed", "reading navigation timing", () => {
791
+ let e = performance.getEntriesByType("navigation")[0];
792
+ if (!e) return;
793
+ let t = {
794
+ "navigation.dns_ms": e.domainLookupEnd - e.domainLookupStart,
795
+ "navigation.tcp_ms": e.connectEnd - e.connectStart,
796
+ "navigation.ttfb_ms": e.responseStart - e.requestStart,
797
+ "navigation.response_ms": e.responseEnd - e.responseStart,
798
+ "navigation.dom_interactive_ms": e.domInteractive,
799
+ "navigation.dom_complete_ms": e.domComplete,
800
+ "navigation.load_ms": e.loadEventEnd
801
+ };
802
+ for (let [n, r] of Object.entries(t)) Number.isFinite(r) && r >= 0 && this.ctx.logger.logMetric(n, Math.round(r), "ms", "gauge", { "navigation.type": e.type });
803
+ });
804
+ }
805
+ };
806
+ //#endregion
807
+ //#region src/models/log-record.ts
808
+ function O() {
809
+ return `${String(Date.now())}000000`;
810
+ }
811
+ function k(e) {
812
+ if (typeof e != "object" || !e) return !1;
813
+ let t = e;
814
+ return typeof t.body == "string" && typeof t.severityText == "string" && typeof t.timeUnixNano == "string" && typeof t.attributes == "object" && t.attributes !== null && typeof t.resource == "object" && t.resource !== null;
815
+ }
816
+ //#endregion
817
+ //#region src/utils/lock.ts
818
+ function A(e, t, n, { skipIfBusy: r = !0 } = {}) {
819
+ let i = globalThis.navigator?.locks;
820
+ return i?.request ? t.guardAsync("storage.degraded", `acquiring lock ${e}`, () => i.request(e, { ifAvailable: r }, (e) => e ? n() : Promise.resolve(void 0))) : n();
821
+ }
822
+ //#endregion
823
+ //#region src/storage/keys.ts
824
+ function j(e, t) {
825
+ let n = [];
826
+ return t.guard("storage.unavailable", "enumerating localStorage", () => {
827
+ for (let t = 0; t < localStorage.length; t++) {
828
+ let r = String(localStorage.key(t));
829
+ r.startsWith(e) && n.push(r);
830
+ }
831
+ }), n.sort();
832
+ }
833
+ //#endregion
834
+ //#region src/storage/emergency-queue.ts
835
+ function Gt(e) {
836
+ let t = String(e.createdAt).padStart(14, "0");
837
+ return `${g}${t}.${e.id}`;
838
+ }
839
+ function Kt(e, t) {
840
+ let n = t.guard("storage.degraded", "an emergency entry was not JSON and was dropped", () => JSON.parse(e));
841
+ if (typeof n != "object" || !n) return null;
842
+ let r = Reflect.get(n, "createdAt"), i = Reflect.get(n, "records");
843
+ return typeof r != "number" || !Array.isArray(i) ? (t.report("storage.degraded", "an emergency entry was not a batch and was dropped"), null) : n;
844
+ }
845
+ async function qt(e, t) {
846
+ let n = 0;
847
+ for (let r of j(g, t)) {
848
+ let i = t.guard("storage.unavailable", "reading the emergency queue", () => {
849
+ let e = localStorage.getItem(r);
850
+ return localStorage.removeItem(r), e;
851
+ });
852
+ if (!i) continue;
853
+ let a = Kt(i, t);
854
+ if (a !== null) try {
855
+ await e.save(a), n++;
856
+ } catch (e) {
857
+ t.report("storage.degraded", "an emergency batch could not be recovered", { key: r }, e);
858
+ }
859
+ }
860
+ return n;
861
+ }
862
+ function Jt(e, t) {
863
+ t.guard("storage.quota_exceeded", "writing the emergency queue", () => {
864
+ let n = j(g, t);
865
+ for (let e of n.slice(0, Math.max(0, n.length - 20 + 1))) localStorage.removeItem(e);
866
+ localStorage.setItem(Gt(e), JSON.stringify(e));
867
+ });
868
+ }
869
+ async function Yt(e, t) {
870
+ return await A("ui-observability.emergency", t, () => qt(e, t), { skipIfBusy: !1 }) ?? 0;
871
+ }
872
+ //#endregion
873
+ //#region src/storage/local-storage.ts
874
+ function Xt(e) {
875
+ let t = String(e.createdAt).padStart(14, "0");
876
+ return `${Qe}${t}.${e.id}`;
877
+ }
878
+ var Zt = class {
879
+ limits;
880
+ diagnostics;
881
+ onGap;
882
+ name = ie;
883
+ constructor(e, t, n) {
884
+ this.limits = e, this.diagnostics = t, this.onGap = n;
885
+ }
886
+ async save(e) {
887
+ if (this.diagnostics.guard("storage.quota_exceeded", "localStorage refused a batch, evicting the oldest", () => (localStorage.setItem(Xt(e), JSON.stringify(e)), !0)) !== !0) {
888
+ let e = this.keys();
889
+ this.evict(e.slice(0, Math.ceil(e.length / 4)));
890
+ return;
891
+ }
892
+ await this.prune();
893
+ }
894
+ take(e) {
895
+ let t = [];
896
+ for (let n of this.keys().slice(0, e)) {
897
+ let e = this.read(n);
898
+ if (e === null) {
899
+ this.removeKey(n);
900
+ continue;
901
+ }
902
+ t.push(e);
903
+ }
904
+ return Promise.resolve(t);
905
+ }
906
+ remove(e) {
907
+ let t = this.keyOf(e);
908
+ return t !== null && this.removeKey(t), Promise.resolve();
909
+ }
910
+ bumpAttempts(e, t) {
911
+ let n = this.keyOf(e);
912
+ if (n === null) return Promise.resolve();
913
+ let r = this.read(n);
914
+ return r === null ? Promise.resolve() : (r.attempts = t, this.diagnostics.guard("storage.degraded", "updating attempts", () => {
915
+ localStorage.setItem(n, JSON.stringify(r));
916
+ }), Promise.resolve());
917
+ }
918
+ prune() {
919
+ let e = Date.now() - this.limits.maxAgeMs, t = {
920
+ batches: 0,
921
+ records: 0,
922
+ reason: "expired"
923
+ }, n = (e, n) => {
924
+ this.removeKey(e), t.batches++, t.records += n;
925
+ }, r = [];
926
+ for (let t of this.keys()) {
927
+ let i = this.read(t);
928
+ if (i === null) {
929
+ n(t, 0);
930
+ continue;
931
+ }
932
+ if (i.createdAt < e) {
933
+ n(t, i.records.length);
934
+ continue;
935
+ }
936
+ r.push({
937
+ key: t,
938
+ records: i.records.length
939
+ });
940
+ }
941
+ let i = r.length - this.limits.maxBatches;
942
+ if (i > 0) {
943
+ t.reason = "over_capacity";
944
+ for (let e of r.slice(0, i)) n(e.key, e.records);
945
+ }
946
+ return t.batches > 0 && (this.diagnostics.report("storage.evicted", `dropped ${String(t.batches)} stored batches (${String(t.records)} records)`, { ...t }), this.onGap?.(t)), Promise.resolve(t);
947
+ }
948
+ count() {
949
+ return Promise.resolve(this.keys().length);
950
+ }
951
+ clear() {
952
+ return this.evict(this.keys()), Promise.resolve();
953
+ }
954
+ close() {
955
+ return Promise.resolve();
956
+ }
957
+ read(e) {
958
+ let t = this.diagnostics.guard("storage.unavailable", "reading a stored batch", () => localStorage.getItem(e));
959
+ if (!t) return null;
960
+ let n = this.diagnostics.guard("storage.degraded", "a stored batch was corrupt and was removed", () => JSON.parse(t));
961
+ if (typeof n != "object" || !n) return null;
962
+ let r = Reflect.get(n, "createdAt"), i = Reflect.get(n, "records");
963
+ return typeof r != "number" || !Array.isArray(i) ? null : n;
964
+ }
965
+ keyOf(e) {
966
+ return this.keys().find((t) => t.endsWith(`.${e}`)) ?? null;
967
+ }
968
+ evict(e) {
969
+ for (let t of e) this.removeKey(t);
970
+ }
971
+ removeKey(e) {
972
+ this.diagnostics.guard("storage.degraded", "removing a stored batch", () => {
973
+ localStorage.removeItem(e);
974
+ });
975
+ }
976
+ keys() {
977
+ return j(Qe, this.diagnostics);
978
+ }
979
+ };
980
+ //#endregion
981
+ //#region src/storage/memory-storage.ts
982
+ function Qt(e) {
983
+ return e.reduce((e, t) => e + t.records.length, 0);
984
+ }
985
+ var M = class {
986
+ limits;
987
+ onGap;
988
+ name = Fe;
989
+ batches = [];
990
+ constructor(e, t) {
991
+ this.limits = e, this.onGap = t;
992
+ }
993
+ async save(e) {
994
+ this.batches.push(e), await this.prune();
995
+ }
996
+ take(e) {
997
+ return Promise.resolve(this.batches.slice(0, e));
998
+ }
999
+ remove(e) {
1000
+ return this.batches = this.batches.filter((t) => t.id !== e), Promise.resolve();
1001
+ }
1002
+ bumpAttempts(e, t) {
1003
+ let n = this.batches.find((t) => t.id === e);
1004
+ return n && (n.attempts = t), Promise.resolve();
1005
+ }
1006
+ prune() {
1007
+ let e = Date.now() - this.limits.maxAgeMs, t = {
1008
+ batches: 0,
1009
+ records: 0,
1010
+ reason: "expired"
1011
+ }, n = this.batches.filter((t) => t.createdAt < e);
1012
+ this.batches = this.batches.filter((t) => t.createdAt >= e), t.batches += n.length, t.records += Qt(n);
1013
+ let r = this.batches.length - this.limits.maxBatches;
1014
+ if (r > 0) {
1015
+ t.reason = "over_capacity";
1016
+ let e = this.batches.slice(0, r);
1017
+ this.batches = this.batches.slice(r), t.batches += e.length, t.records += Qt(e);
1018
+ }
1019
+ return t.batches > 0 && this.onGap?.(t), Promise.resolve(t);
1020
+ }
1021
+ count() {
1022
+ return Promise.resolve(this.batches.length);
1023
+ }
1024
+ clear() {
1025
+ return this.batches = [], Promise.resolve();
1026
+ }
1027
+ close() {
1028
+ return this.batches = [], Promise.resolve();
1029
+ }
1030
+ }, $t = {
1031
+ name: t,
1032
+ save: () => Promise.resolve(),
1033
+ take: () => Promise.resolve([]),
1034
+ remove: () => Promise.resolve(),
1035
+ bumpAttempts: () => Promise.resolve(),
1036
+ prune: () => Promise.resolve({
1037
+ batches: 0,
1038
+ records: 0,
1039
+ reason: "expired"
1040
+ }),
1041
+ count: () => Promise.resolve(0),
1042
+ clear: () => Promise.resolve(),
1043
+ close: () => Promise.resolve()
1044
+ };
1045
+ function en(e) {
1046
+ return e.guard("storage.unavailable", "reading indexedDB", () => globalThis.indexedDB != null) === !0;
1047
+ }
1048
+ function tn(e) {
1049
+ return e.guard("storage.unavailable", "probing localStorage", () => (localStorage.setItem(Ne, "1"), localStorage.removeItem(Ne), !0)) === !0;
1050
+ }
1051
+ async function nn(e, t, n, r, i) {
1052
+ if (e === "none") return $t;
1053
+ if (e === "memory") return new M(n, i);
1054
+ if (e === "indexeddb" || e === "auto") {
1055
+ if (en(r)) {
1056
+ let e = await r.guardAsync("storage.unavailable", "opening IndexedDB", async () => {
1057
+ let { IndexedDbStorage: e } = await import("./indexeddb-storage-DwpCDRnX.js");
1058
+ return new e(t, n, r, i);
1059
+ });
1060
+ if (e) return e;
1061
+ }
1062
+ if (e === "indexeddb") return r.report("storage.degraded", "IndexedDB was asked for by name and is unavailable, using memory"), new M(n, i);
1063
+ }
1064
+ return tn(r) ? new Zt(n, r, i) : (r.report("storage.degraded", "no persistent storage available, offline logs are memory only"), new M(n, i));
1065
+ }
1066
+ //#endregion
1067
+ //#region src/utils/sanitize.ts
1068
+ function N(e, t) {
1069
+ if (e.length <= t) return e;
1070
+ let n = rn(e.charCodeAt(t - 1)) ? t - 1 : t;
1071
+ return `${e.slice(0, n)}… [truncated ${String(e.length - n)} chars]`;
1072
+ }
1073
+ function rn(e) {
1074
+ return e >= 55296 && e <= 56319;
1075
+ }
1076
+ function an(e) {
1077
+ return `[Element ${(e.nodeName ?? "NODE").toLowerCase()}${e.id ? `#${e.id}` : ""}${typeof e.className == "string" && e.className ? `.${e.className.trim().split(/\s+/).slice(0, 3).join(".")}` : ""}]`;
1078
+ }
1079
+ function P(e, t) {
1080
+ let n = { bytes: 0 };
1081
+ return {
1082
+ value: I(e, t, /* @__PURE__ */ new WeakSet(), 0, n),
1083
+ bytes: n.bytes
1084
+ };
1085
+ }
1086
+ function F(e, t) {
1087
+ return t.bytes += L(e) + 2, e;
1088
+ }
1089
+ function I(e, t, n, r, i) {
1090
+ if (e == null) return i.bytes += 4, e;
1091
+ if (typeof e == "string") return F(N(e, t.maxAttributeChars), i);
1092
+ if (typeof e == "number") return i.bytes += 8, Number.isFinite(e) ? e : String(e);
1093
+ if (typeof e == "boolean") return i.bytes += 5, e;
1094
+ if (typeof e == "bigint") return F(`${e.toString()}n`, i);
1095
+ if (typeof e == "symbol") return F(e.toString(), i);
1096
+ if (typeof e == "function") return F(`[Function ${e.name === "" ? "anonymous" : e.name}]`, i);
1097
+ if (r >= t.maxDepth) return F("[MaxDepth]", i);
1098
+ if (n.has(e)) return F("[Circular]", i);
1099
+ n.add(e), i.bytes += 2;
1100
+ try {
1101
+ if (e instanceof Error) return {
1102
+ name: F(e.name, i),
1103
+ message: F(N(e.message, t.maxAttributeChars), i),
1104
+ stack: e.stack ? F(N(e.stack, t.maxStackChars), i) : void 0,
1105
+ cause: e.cause ? I(e.cause, t, n, r + 1, i) : void 0
1106
+ };
1107
+ if (e instanceof Date) return F(e.toISOString(), i);
1108
+ if (e instanceof RegExp) return F(e.toString(), i);
1109
+ if (e instanceof Map) {
1110
+ let a = e, o = {}, s = 0;
1111
+ for (let [e, c] of a) {
1112
+ if (s >= t.maxArrayLength) {
1113
+ o["…"] = F(`[${String(a.size - t.maxArrayLength)} more entries]`, i);
1114
+ break;
1115
+ }
1116
+ s++;
1117
+ let l = String(e);
1118
+ i.bytes += L(l) + 4, o[l] = I(c, t, n, r + 1, i);
1119
+ }
1120
+ return o;
1121
+ }
1122
+ if (e instanceof Set) return I([...e].slice(0, t.maxArrayLength), t, n, r, i);
1123
+ if (ArrayBuffer.isView(e)) {
1124
+ let t = e.length ?? 0;
1125
+ return F(`[${e.constructor.name}(${String(t)})]`, i);
1126
+ }
1127
+ if (e instanceof Promise) return F("[Promise]", i);
1128
+ if (typeof Node < "u" && e instanceof Node) return F(an(e), i);
1129
+ if (Array.isArray(e)) {
1130
+ let a = e, o = a.slice(0, t.maxArrayLength).map((e) => I(e, t, n, r + 1, i));
1131
+ return a.length > t.maxArrayLength && o.push(F(`[${String(a.length - t.maxArrayLength)} more items]`, i)), o;
1132
+ }
1133
+ let a = e.toJSON;
1134
+ if (typeof a == "function") return I(a.call(e), t, n, r + 1, i);
1135
+ let o = e, s = Object.keys(o), c = {}, l = 0;
1136
+ for (let e of s) {
1137
+ if (l >= t.maxAttributeCount) {
1138
+ c["…"] = F(`[${String(s.length - l)} more keys]`, i);
1139
+ break;
1140
+ }
1141
+ l++, i.bytes += L(e) + 4, c[e] = I(o[e], t, n, r + 1, i);
1142
+ }
1143
+ return c;
1144
+ } catch (e) {
1145
+ return F(`[Unserializable: ${e instanceof Error ? e.name : "error"}]`, i);
1146
+ } finally {
1147
+ n.delete(e);
1148
+ }
1149
+ }
1150
+ function L(e) {
1151
+ let t = 0;
1152
+ for (let n = 0; n < e.length; n++) {
1153
+ let r = e.charCodeAt(n);
1154
+ r < 128 ? t += 1 : r < 2048 ? t += 2 : r >= 55296 && r <= 56319 ? (t += 4, n++) : t += 3;
1155
+ }
1156
+ return t;
1157
+ }
1158
+ //#endregion
1159
+ //#region src/transport/exit-flush.ts
1160
+ var on = class {
1161
+ deps;
1162
+ installed = !1;
1163
+ onVisibility = () => {
1164
+ document.visibilityState === "hidden" && this.flush("hidden");
1165
+ };
1166
+ onPageHide = () => {
1167
+ this.flush("pagehide");
1168
+ };
1169
+ onFreeze = () => {
1170
+ this.flush("freeze");
1171
+ };
1172
+ onOpenFinClose = () => {
1173
+ this.flush("openfin-close");
1174
+ };
1175
+ constructor(e) {
1176
+ this.deps = e;
1177
+ }
1178
+ install() {
1179
+ if (this.installed || typeof addEventListener > "u") return;
1180
+ this.installed = !0, typeof document < "u" && (document.addEventListener("visibilitychange", this.onVisibility), document.addEventListener("freeze", this.onFreeze)), addEventListener("pagehide", this.onPageHide);
1181
+ let e = globalThis.fin?.me;
1182
+ this.deps.diagnostics.guard("openfin.unavailable", "subscribing to close-requested", () => {
1183
+ e?.on?.("close-requested", this.onOpenFinClose);
1184
+ });
1185
+ }
1186
+ uninstall() {
1187
+ if (!this.installed) return;
1188
+ this.installed = !1, typeof document < "u" && (document.removeEventListener("visibilitychange", this.onVisibility), document.removeEventListener("freeze", this.onFreeze)), removeEventListener("pagehide", this.onPageHide);
1189
+ let e = globalThis.fin?.me;
1190
+ this.deps.diagnostics.guard("openfin.unavailable", "releasing close-requested", () => {
1191
+ e?.removeListener?.("close-requested", this.onOpenFinClose);
1192
+ });
1193
+ }
1194
+ flush(e) {
1195
+ let { diagnostics: t } = this.deps, n = this.endpointUrl();
1196
+ if (n === null) return;
1197
+ let r = this.deps.drainPending();
1198
+ if (!r || r.records.length === 0) return;
1199
+ let i = t.guard("transport.serialize_failed", `the ${e} exit flush could not serialize its batch`, () => this.deps.config.serializer.serialize(r.records));
1200
+ if (!i) return;
1201
+ if (L(i.body) > 6e4) {
1202
+ Jt(r, t);
1203
+ return;
1204
+ }
1205
+ n.searchParams.set(Ge, r.id), n.searchParams.set(je, e);
1206
+ let a = n.toString();
1207
+ this.beacon(a, i.body) || this.keepaliveFetch(a, i.body, e);
1208
+ }
1209
+ endpointUrl() {
1210
+ let { endpoint: e } = this.deps.config;
1211
+ return e ? this.deps.diagnostics.guard("config.invalid", `the exit flush cannot use endpoint ${e}`, () => new URL(e)) ?? null : null;
1212
+ }
1213
+ beacon(e, t) {
1214
+ return this.deps.diagnostics.guard("transport.http_error", "sendBeacon", () => {
1215
+ let n = globalThis.navigator;
1216
+ return n?.sendBeacon ? n.sendBeacon(e, new Blob([t], { type: o })) : !1;
1217
+ }) === !0;
1218
+ }
1219
+ keepaliveFetch(e, t, n) {
1220
+ let { config: r, diagnostics: i } = this.deps;
1221
+ i.guard("transport.http_error", "the keepalive fetch fallback", () => {
1222
+ fetch(e, {
1223
+ method: "POST",
1224
+ body: t,
1225
+ headers: { [u]: o },
1226
+ credentials: r.credentials,
1227
+ keepalive: !0
1228
+ }).catch((e) => {
1229
+ i.report("transport.http_error", "the exit flush failed", { reason: n }, e);
1230
+ });
1231
+ });
1232
+ }
1233
+ };
1234
+ //#endregion
1235
+ //#region src/transport/compression.ts
1236
+ async function sn(e) {
1237
+ let t = globalThis.CompressionStream;
1238
+ if (t === void 0) return null;
1239
+ let n = new Blob([e]).stream().pipeThrough(new t(ae)), r = await new Response(n).arrayBuffer();
1240
+ return new Uint8Array(r);
1241
+ }
1242
+ //#endregion
1243
+ //#region src/transport/errors.ts
1244
+ var R = class extends Error {
1245
+ kind;
1246
+ status;
1247
+ retryAfterMs;
1248
+ maxBytes;
1249
+ constructor(e, t, n, r, i) {
1250
+ super(t), this.kind = e, this.status = n, this.retryAfterMs = r, this.maxBytes = i, this.name = "TransportError";
1251
+ }
1252
+ };
1253
+ function cn(e) {
1254
+ if (!e) return;
1255
+ let t = Number(e);
1256
+ if (Number.isFinite(t)) return Math.max(0, t * se);
1257
+ let n = Date.parse(e);
1258
+ return Number.isNaN(n) ? void 0 : Math.max(0, n - Date.now());
1259
+ }
1260
+ //#endregion
1261
+ //#region src/transport/http-transport.ts
1262
+ var ln = class {
1263
+ config;
1264
+ diagnostics;
1265
+ throttledUntil = 0;
1266
+ constructor(e, t) {
1267
+ this.config = e, this.diagnostics = t;
1268
+ }
1269
+ async send(e) {
1270
+ !this.config.endpoint || e.records.length === 0 || await this.post(e);
1271
+ }
1272
+ throttledForMs() {
1273
+ return Math.max(0, this.throttledUntil - Date.now());
1274
+ }
1275
+ async post(e) {
1276
+ let { config: t } = this, r;
1277
+ try {
1278
+ r = t.serializer.serialize(e.records);
1279
+ } catch (t) {
1280
+ this.diagnostics.report("transport.serialize_failed", "serializer threw, dropping the batch", { batchId: e.id }, t);
1281
+ return;
1282
+ }
1283
+ let i = new Headers(await this.resolveHeaders());
1284
+ i.set(u, r.contentType), i.set(n, e.id), i.set(it, String(e.attempts));
1285
+ let a = await this.encodeBody(r.body);
1286
+ typeof a != "string" && i.set(pe, ae);
1287
+ let o = await this.dispatch(i, a);
1288
+ if (o.ok) {
1289
+ this.throttledUntil = 0;
1290
+ return;
1291
+ }
1292
+ throw await this.classify(o, e.id);
1293
+ }
1294
+ async encodeBody(e) {
1295
+ let { config: t } = this;
1296
+ return t.compression !== "gzip" || L(e) < t.compressionThresholdBytes ? e : await this.diagnostics.guardAsync("transport.http_error", "gzipping the payload", () => sn(e)) ?? e;
1297
+ }
1298
+ async dispatch(e, t) {
1299
+ let { config: n } = this, r = new AbortController(), i = setTimeout(() => {
1300
+ r.abort();
1301
+ }, n.requestTimeoutMs);
1302
+ try {
1303
+ return await fetch(n.endpoint, {
1304
+ method: "POST",
1305
+ headers: e,
1306
+ body: t,
1307
+ credentials: n.credentials,
1308
+ signal: r.signal,
1309
+ cache: "no-store"
1310
+ });
1311
+ } catch {
1312
+ if (r.signal.aborted) throw new R("timeout", `request exceeded ${String(n.requestTimeoutMs)}ms`);
1313
+ let e = globalThis.navigator?.onLine;
1314
+ throw new R(e === !1 ? "offline" : "transient", "network error");
1315
+ } finally {
1316
+ clearTimeout(i);
1317
+ }
1318
+ }
1319
+ async classify(e, t) {
1320
+ let n = e.status, r = cn(e.headers.get(fe));
1321
+ if (n === 401 || n === 403) return this.diagnostics.report("transport.rejected_credentials", `server returned ${String(n)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`, {
1322
+ status: n,
1323
+ endpoint: this.config.endpoint
1324
+ }), new R("permanent", `rejected with ${String(n)}`, n);
1325
+ if (n === 413) return new R("too_large", "payload too large", n, void 0, await this.readMaxBytes(e));
1326
+ if (n === 429 || n === 503) {
1327
+ let e = n === 429;
1328
+ return this.throttledUntil = Date.now() + (r ?? this.config.retry.baseDelayMs), e && this.diagnostics.report("transport.throttled", "server throttled us", { retryAfterMs: r }), new R("throttled", e ? "throttled" : "service unavailable", n, r);
1329
+ }
1330
+ return n === 408 || n >= 500 ? new R("transient", `server error ${String(n)}`, n) : (this.diagnostics.report("transport.dropped_permanent", `server rejected the batch with ${String(n)}, dropping it`, {
1331
+ batchId: t,
1332
+ status: n
1333
+ }), new R("permanent", `rejected with ${String(n)}`, n));
1334
+ }
1335
+ async readMaxBytes(e) {
1336
+ return this.diagnostics.guardAsync("transport.http_error", "reading the 413 body", async () => {
1337
+ let t = JSON.parse(await e.text());
1338
+ return typeof t.maxBytes == "number" ? t.maxBytes : void 0;
1339
+ });
1340
+ }
1341
+ async resolveHeaders() {
1342
+ let { headers: e } = this.config;
1343
+ return e ? typeof e == "function" ? await this.diagnostics.guardAsync("transport.http_error", "headers() threw", () => Promise.resolve(e())) ?? {} : e : {};
1344
+ }
1345
+ };
1346
+ //#endregion
1347
+ //#region src/utils/identity.ts
1348
+ function z(e) {
1349
+ let t = new Uint8Array(e);
1350
+ if (typeof crypto < "u" && typeof crypto.getRandomValues == "function") crypto.getRandomValues(t);
1351
+ else for (let n = 0; n < e; n++) t[n] = Math.floor(Math.random() * 256);
1352
+ return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
1353
+ }
1354
+ function B() {
1355
+ try {
1356
+ if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
1357
+ } catch {}
1358
+ return z(16);
1359
+ }
1360
+ function un(e, t, n) {
1361
+ return n.guard("storage.unavailable", `reading ${e}Storage`, () => (e === "local" ? localStorage : sessionStorage).getItem(t)) ?? null;
1362
+ }
1363
+ function V(e, t, n, r) {
1364
+ r.guard("storage.unavailable", `writing ${e}Storage`, () => {
1365
+ (e === "local" ? localStorage : sessionStorage).setItem(t, n);
1366
+ });
1367
+ }
1368
+ function dn(e) {
1369
+ let t = B(), n = Date.now(), r = B(), a = un("local", i, e);
1370
+ if (a) try {
1371
+ let e = JSON.parse(a);
1372
+ e.id && n - (e.lastSeenAt ?? 0) < 18e5 && (r = e.id);
1373
+ } catch {
1374
+ e.report("storage.degraded", "session record was not JSON, starting a new session");
1375
+ }
1376
+ let o = JSON.stringify({
1377
+ id: r,
1378
+ lastSeenAt: n
1379
+ });
1380
+ V("local", i, o, e);
1381
+ let s = un("session", "ui-observability.tab", e) ?? "";
1382
+ return s || (s = B(), V("session", te, s, e)), {
1383
+ sessionId: r,
1384
+ tabId: s,
1385
+ contextId: t
1386
+ };
1387
+ }
1388
+ var fn = 0;
1389
+ function pn(e, t) {
1390
+ let n = Date.now();
1391
+ if (n - fn < 6e4) return;
1392
+ fn = n;
1393
+ let r = JSON.stringify({
1394
+ id: e,
1395
+ lastSeenAt: n
1396
+ });
1397
+ V("local", i, r, t);
1398
+ }
1399
+ //#endregion
1400
+ //#region src/models/batch.ts
1401
+ function mn(e) {
1402
+ if (e.records.length < 2) return null;
1403
+ let t = Math.floor(e.records.length / 2), n = (t) => ({
1404
+ id: B(),
1405
+ records: t,
1406
+ createdAt: e.createdAt,
1407
+ attempts: e.attempts
1408
+ });
1409
+ return [n(e.records.slice(0, t)), n(e.records.slice(t))];
1410
+ }
1411
+ //#endregion
1412
+ //#region src/transport/retry-engine.ts
1413
+ var hn = class {
1414
+ storage;
1415
+ transport;
1416
+ diagnostics;
1417
+ config;
1418
+ batchesPerDrain;
1419
+ timer = null;
1420
+ attempt = 0;
1421
+ draining = !1;
1422
+ stopped = !1;
1423
+ onOnline = () => {
1424
+ this.attempt = 0, this.schedule(0);
1425
+ };
1426
+ constructor(e, t, n, r, i = 20) {
1427
+ this.storage = e, this.transport = t, this.diagnostics = n, this.config = r, this.batchesPerDrain = i;
1428
+ }
1429
+ start() {
1430
+ this.stopped = !1, typeof addEventListener < "u" && addEventListener("online", this.onOnline), this.schedule(this.config.retry.idleDelayMs);
1431
+ }
1432
+ nudge() {
1433
+ this.draining || this.schedule(this.config.retry.baseDelayMs);
1434
+ }
1435
+ stop() {
1436
+ this.stopped = !0, typeof removeEventListener < "u" && removeEventListener("online", this.onOnline), this.clearTimer();
1437
+ }
1438
+ schedule(e) {
1439
+ if (this.stopped) return;
1440
+ this.clearTimer();
1441
+ let t = setTimeout(() => {
1442
+ this.drain();
1443
+ }, e);
1444
+ this.timer = t, C(t);
1445
+ }
1446
+ clearTimer() {
1447
+ this.timer !== null && (clearTimeout(this.timer), this.timer = null);
1448
+ }
1449
+ backoffMs() {
1450
+ let e = Math.min(this.config.retry.baseDelayMs * 2 ** this.attempt, this.config.retry.maxDelayMs);
1451
+ return Math.random() * e;
1452
+ }
1453
+ async drain() {
1454
+ if (!this.draining) {
1455
+ this.draining = !0;
1456
+ try {
1457
+ await A("ui-observability.drain", this.diagnostics, () => this.drainLocked()) !== !0 && this.schedule(this.config.retry.idleDelayMs);
1458
+ } finally {
1459
+ this.draining = !1;
1460
+ }
1461
+ }
1462
+ }
1463
+ async drainLocked() {
1464
+ try {
1465
+ if (globalThis.navigator?.onLine === !1) return this.schedule(this.config.retry.idleDelayMs), !0;
1466
+ let e = await this.storage.take(this.batchesPerDrain);
1467
+ if (e.length === 0) return this.schedule(this.config.retry.idleDelayMs), !0;
1468
+ for (let t of e) if (this.stopped || !await this.deliver(t)) return !0;
1469
+ return this.schedule(e.length === this.batchesPerDrain ? 0 : this.config.retry.idleDelayMs), !0;
1470
+ } catch (e) {
1471
+ return this.diagnostics.report("storage.degraded", "the drain loop threw", void 0, e), this.attempt++, this.schedule(this.backoffMs()), !0;
1472
+ }
1473
+ }
1474
+ async deliver(e) {
1475
+ if (e.attempts >= this.config.storage.maxAttempts) return this.diagnostics.report("storage.dead_lettered", `giving up on a batch after ${e.attempts.toString()} attempts`, {
1476
+ batchId: e.id,
1477
+ records: e.records.length
1478
+ }), await this.storage.remove(e.id), !0;
1479
+ try {
1480
+ return await this.transport.send(e), await this.storage.remove(e.id), this.attempt = 0, !0;
1481
+ } catch (t) {
1482
+ let n = t instanceof R ? t : void 0;
1483
+ return n?.kind === "permanent" ? (await this.storage.remove(e.id), !0) : n?.kind === "too_large" ? (await this.splitStored(e, n.maxBytes), !0) : n?.kind === "offline" ? (this.schedule(this.config.retry.idleDelayMs), !1) : (await this.storage.bumpAttempts(e.id, e.attempts + 1), this.attempt++, this.schedule(n?.retryAfterMs ?? this.backoffMs()), !1);
1484
+ }
1485
+ }
1486
+ async splitStored(e, t) {
1487
+ let n = mn(e);
1488
+ if (await this.storage.remove(e.id), !n) {
1489
+ this.diagnostics.report("transport.dropped_permanent", "a single record exceeds the server limit and was dropped", {
1490
+ batchId: e.id,
1491
+ bodies: e.records.map((e) => e.body)
1492
+ });
1493
+ return;
1494
+ }
1495
+ this.diagnostics.report("transport.batch_split", "the server refused the batch as too large", {
1496
+ from: e.records.length,
1497
+ to: n[0].records.length,
1498
+ serverMaxBytes: t
1499
+ });
1500
+ for (let e of n) await this.storage.save(e);
1501
+ }
1502
+ }, gn = {
1503
+ TRACE: "debug",
1504
+ DEBUG: "debug",
1505
+ INFO: "info",
1506
+ WARN: "warn",
1507
+ ERROR: "error",
1508
+ FATAL: "error"
1509
+ }, _n = class {
1510
+ enabled;
1511
+ minLevel;
1512
+ constructor(e, t) {
1513
+ this.enabled = e, this.minLevel = t;
1514
+ }
1515
+ update(e, t) {
1516
+ this.enabled = e, this.minLevel = t;
1517
+ }
1518
+ write(e, t, n) {
1519
+ if (!this.enabled || p[e] < p[this.minLevel] || typeof console > "u") return;
1520
+ let i = `%c${he}%c ${e}`;
1521
+ if (n === void 0) {
1522
+ console[gn[e]](i, r, "", t);
1523
+ return;
1524
+ }
1525
+ console[gn[e]](i, r, "", t, n);
1526
+ }
1527
+ }, H = null;
1528
+ function U(e, t) {
1529
+ let n = e[t];
1530
+ return n !== void 0 && e instanceof n;
1531
+ }
1532
+ function vn(e) {
1533
+ if (H) return H;
1534
+ let t = globalThis, n = t.navigator?.userAgent ?? "", r = "browser", i, a, o = !1, s = t.fin?.me;
1535
+ return U(t, "ServiceWorkerGlobalScope") ? (r = "service_worker", o = !0) : U(t, "SharedWorkerGlobalScope") ? (r = "shared_worker", o = !0) : U(t, "WorkerGlobalScope") ? (r = "web_worker", o = !0) : s === void 0 ? t.Capacitor !== void 0 || t.Ionic !== void 0 ? r = "ionic" : t.cordova !== void 0 || yn(n) ? r = "mobile_webview" : typeof document > "u" && typeof process < "u" && (r = "node") : (r = ze.test(n) ? "openfin" : "openfin_web", e.guard("openfin.unavailable", "reading fin.me.identity", () => {
1536
+ let e = s.identity;
1537
+ i = e?.uuid, a = e?.name;
1538
+ })), H = {
1539
+ platform: r,
1540
+ openfinUuid: i,
1541
+ openfinName: a,
1542
+ userAgent: n,
1543
+ isWorker: o,
1544
+ isTopLevelDocument: bn()
1545
+ }, H;
1546
+ }
1547
+ function yn(t) {
1548
+ return Je.test(t) ? !0 : (m.test(t) || ge.test(t) && e.test(t)) && t.includes("AppleWebKit") && !t.includes("Safari/");
1549
+ }
1550
+ function bn() {
1551
+ if (typeof window > "u") return !1;
1552
+ try {
1553
+ return window.self === window.top;
1554
+ } catch {
1555
+ return !1;
1556
+ }
1557
+ }
1558
+ function xn() {
1559
+ try {
1560
+ return typeof location < "u" ? location.href : "";
1561
+ } catch {
1562
+ return "";
1563
+ }
1564
+ }
1565
+ //#endregion
1566
+ //#region src/utils/sequence.ts
1567
+ var Sn = class {
1568
+ value = 0;
1569
+ next() {
1570
+ return ++this.value;
1571
+ }
1572
+ reset() {
1573
+ this.value = 0;
1574
+ }
1575
+ };
1576
+ //#endregion
1577
+ //#region src/utils/tracing.ts
1578
+ function Cn() {
1579
+ return z(16);
1580
+ }
1581
+ function wn() {
1582
+ return z(8);
1583
+ }
1584
+ function Tn() {
1585
+ return {
1586
+ traceId: Cn(),
1587
+ spanId: wn(),
1588
+ traceFlags: 1,
1589
+ startedAt: Date.now()
1590
+ };
1591
+ }
1592
+ function En(e) {
1593
+ return {
1594
+ traceId: e.traceId,
1595
+ spanId: e.spanId,
1596
+ traceFlags: e.traceFlags
1597
+ };
1598
+ }
1599
+ var Dn = class {
1600
+ diagnostics;
1601
+ maxAgeMs;
1602
+ ambient = Tn();
1603
+ constructor(e, t = f) {
1604
+ this.diagnostics = e, this.maxAgeMs = t;
1605
+ }
1606
+ resolve() {
1607
+ let e = this.diagnostics.guard("trace.otel_failed", "reading the active OpenTelemetry span", () => {
1608
+ let e = lt.getActiveSpan();
1609
+ if (e === void 0) return;
1610
+ let t = e.spanContext();
1611
+ if (st(t)) return {
1612
+ traceId: t.traceId,
1613
+ spanId: t.spanId,
1614
+ traceFlags: t.traceFlags
1615
+ };
1616
+ });
1617
+ return e === void 0 ? (Date.now() - this.ambient.startedAt > this.maxAgeMs && this.rotate("maxAge"), En(this.ambient)) : e;
1618
+ }
1619
+ rotate(e) {
1620
+ return this.ambient = Tn(), En(this.ambient);
1621
+ }
1622
+ headers() {
1623
+ let e = {};
1624
+ if (this.diagnostics.guard("trace.otel_failed", "injecting OpenTelemetry headers", () => {
1625
+ ct.inject(ot.active(), e);
1626
+ }), !e.traceparent) {
1627
+ let t = this.resolve(), n = (t.traceFlags & 255).toString(16).padStart(2, "0");
1628
+ e.traceparent = `00-${t.traceId}-${t.spanId}-${n}`;
1629
+ }
1630
+ return e;
1631
+ }
1632
+ }, On = class {
1633
+ buffer;
1634
+ pointer = 0;
1635
+ filled = !1;
1636
+ capacity;
1637
+ constructor(e) {
1638
+ this.capacity = Math.max(e, 1), this.buffer = Array(this.capacity);
1639
+ }
1640
+ resize(e) {
1641
+ let t = Math.max(e, 1);
1642
+ if (t === this.capacity) return;
1643
+ let n = this.snapshot().slice(-t);
1644
+ this.capacity = t, this.clear();
1645
+ for (let e of n) this.push(e);
1646
+ }
1647
+ push(e) {
1648
+ this.buffer[this.pointer] = e, this.pointer = (this.pointer + 1) % this.capacity, this.pointer === 0 && (this.filled = !0);
1649
+ }
1650
+ snapshot() {
1651
+ return (this.filled ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)] : this.buffer.slice(0, this.pointer)).filter((e) => e !== void 0);
1652
+ }
1653
+ clear() {
1654
+ this.buffer = Array(this.capacity), this.pointer = 0, this.filled = !1;
1655
+ }
1656
+ }, kn = {
1657
+ name: "ecs",
1658
+ serialize(e) {
1659
+ return {
1660
+ body: `${e.map((e) => {
1661
+ let t = Number(BigInt(e.timeUnixNano) / Te);
1662
+ return JSON.stringify({
1663
+ "@timestamp": new Date(t).toISOString(),
1664
+ message: e.body,
1665
+ log: { level: e.severityText.toLowerCase() },
1666
+ trace: { id: e.traceId },
1667
+ span: { id: e.spanId },
1668
+ service: {
1669
+ name: e.resource[_],
1670
+ version: e.resource[Ue],
1671
+ environment: e.resource[Se]
1672
+ },
1673
+ user_agent: { original: e.resource[Ve] },
1674
+ url: { full: e.attributes["url.full"] ?? e.attributes["page.url"] },
1675
+ labels: {
1676
+ ...e.resource,
1677
+ ...e.attributes
1678
+ }
1679
+ });
1680
+ }).join("\n")}\n`,
1681
+ contentType: ue
1682
+ };
1683
+ }
1684
+ };
1685
+ //#endregion
1686
+ //#region src/transport/serializers/otlp.ts
1687
+ function An(e) {
1688
+ return e == null ? null : typeof e == "string" ? { stringValue: e } : typeof e == "boolean" ? { boolValue: e } : typeof e == "number" ? Number.isInteger(e) ? { intValue: String(e) } : { doubleValue: e } : typeof e == "bigint" ? { intValue: e.toString() } : Array.isArray(e) ? { arrayValue: { values: e.map(An).filter((e) => e !== null) } } : typeof e == "object" ? { kvlistValue: { values: W(e) } } : null;
1689
+ }
1690
+ function W(e) {
1691
+ let t = [];
1692
+ for (let [n, r] of Object.entries(e)) {
1693
+ let e = An(r);
1694
+ e && t.push({
1695
+ key: n,
1696
+ value: e
1697
+ });
1698
+ }
1699
+ return t;
1700
+ }
1701
+ var jn = /* @__PURE__ */ new WeakMap();
1702
+ function Mn(e) {
1703
+ let t = jn.get(e);
1704
+ if (t !== void 0) return t;
1705
+ let n = JSON.stringify(e);
1706
+ return jn.set(e, n), n;
1707
+ }
1708
+ var G = {
1709
+ name: nt,
1710
+ serialize(e) {
1711
+ let t = /* @__PURE__ */ new Map();
1712
+ for (let n of e) {
1713
+ let e = Mn(n.resource), r = t.get(e);
1714
+ if (r) {
1715
+ r.records.push(n);
1716
+ continue;
1717
+ }
1718
+ t.set(e, {
1719
+ resource: n.resource,
1720
+ records: [n]
1721
+ });
1722
+ }
1723
+ let n = [...t.values()].map((e) => ({
1724
+ resource: { attributes: W(e.resource) },
1725
+ scopeLogs: [{
1726
+ scope: {
1727
+ name: oe,
1728
+ version: l
1729
+ },
1730
+ logRecords: e.records.map((e) => ({
1731
+ timeUnixNano: e.timeUnixNano,
1732
+ observedTimeUnixNano: e.observedTimeUnixNano ?? e.timeUnixNano,
1733
+ severityNumber: e.severityNumber,
1734
+ severityText: e.severityText,
1735
+ body: { stringValue: e.body },
1736
+ traceId: e.traceId,
1737
+ spanId: e.spanId,
1738
+ flags: e.traceFlags,
1739
+ attributes: W(e.attributes)
1740
+ }))
1741
+ }]
1742
+ }));
1743
+ return {
1744
+ body: JSON.stringify({ resourceLogs: n }),
1745
+ contentType: et
1746
+ };
1747
+ }
1748
+ };
1749
+ //#endregion
1750
+ //#region src/core/config.ts
1751
+ function Nn(e) {
1752
+ return typeof e != "object" || !e ? !1 : typeof Reflect.get(e, "serialize") == "function";
1753
+ }
1754
+ function Pn(e, t, n) {
1755
+ return e === void 0 ? t ?? G : e === "otlp" ? G : e === "ecs" ? kn : Nn(e) ? e : (n.report("config.invalid", `serializer must be "${nt}", "ecs" or an implementation`), G);
1756
+ }
1757
+ function Fn(e, t, n) {
1758
+ let r = n ?? a, i = {
1759
+ ...r,
1760
+ ...e,
1761
+ serializer: Pn(e.serializer, n?.serializer, t),
1762
+ streams: {
1763
+ logs: {
1764
+ ...r.streams.logs,
1765
+ ...e.streams?.logs
1766
+ },
1767
+ metrics: {
1768
+ ...r.streams.metrics,
1769
+ ...e.streams?.metrics
1770
+ }
1771
+ },
1772
+ storage: {
1773
+ ...r.storage,
1774
+ ...e.storage
1775
+ },
1776
+ retry: {
1777
+ ...r.retry,
1778
+ ...e.retry
1779
+ },
1780
+ sampling: {
1781
+ ...r.sampling,
1782
+ ...e.sampling,
1783
+ rates: {
1784
+ ...r.sampling.rates,
1785
+ ...e.sampling?.rates
1786
+ }
1787
+ },
1788
+ journey: {
1789
+ ...r.journey,
1790
+ ...e.journey
1791
+ },
1792
+ bus: {
1793
+ ...r.bus,
1794
+ ...e.bus
1795
+ },
1796
+ capture: {
1797
+ ...r.capture,
1798
+ ...e.capture
1799
+ },
1800
+ limits: {
1801
+ ...r.limits,
1802
+ ...e.limits
1803
+ },
1804
+ console: {
1805
+ ...r.console,
1806
+ ...e.console
1807
+ }
1808
+ };
1809
+ if (!i.endpoint) t.report("config.invalid", "endpoint is missing. Records will be built and dropped, never sent.");
1810
+ else try {
1811
+ new URL(i.endpoint);
1812
+ } catch (e) {
1813
+ t.report("config.invalid", `endpoint is not a valid absolute URL: ${i.endpoint}`, void 0, e);
1814
+ }
1815
+ i.serviceName ||= (t.report("config.invalid", `serviceName is missing. Every record will report service.name as '${at}'.`), at);
1816
+ let o = i.sampling.defaultRate;
1817
+ (typeof o != "number" || o < 0 || o > 1) && (t.report("config.invalid", `sampling.defaultRate must be 0..1, got ${String(o)}`), i.sampling.defaultRate = 1);
1818
+ let s = Object.entries(i.sampling.rates);
1819
+ for (let [e, n] of s) (typeof n != "number" || n < 0 || n > 1) && (t.report("config.invalid", `sampling.rates["${e}"] must be 0..1, got ${String(n)}`), i.sampling.rates[e] = 1);
1820
+ i.capture.ignoreUrls = i.capture.ignoreUrls.filter((e) => e !== n?.endpoint), i.endpoint && !i.capture.ignoreUrls.includes(i.endpoint) && (i.capture.ignoreUrls = [...i.capture.ignoreUrls, i.endpoint]);
1821
+ let c = /* @__PURE__ */ new Set([...Object.keys(a), ...ce]);
1822
+ for (let n of Object.keys(e)) c.has(n) || t.report("config.invalid", `unknown config key "${n}", ignored. Typo?`);
1823
+ return i;
1824
+ }
1825
+ function In(e, t) {
1826
+ for (let n of Object.keys(t)) le.includes(n) || Object.assign(e, { [n]: t[n] });
1827
+ for (let n of le) Object.assign(e[n], t[n]);
1828
+ }
1829
+ //#endregion
1830
+ //#region src/core/context.ts
1831
+ var Ln = class {
1832
+ map = /* @__PURE__ */ new Map();
1833
+ set(e, t) {
1834
+ this.map.set(e, t);
1835
+ }
1836
+ setMany(e) {
1837
+ for (let [t, n] of Object.entries(e)) this.map.set(t, n);
1838
+ }
1839
+ get(e) {
1840
+ return this.map.get(e);
1841
+ }
1842
+ remove(e) {
1843
+ this.map.delete(e);
1844
+ }
1845
+ clear() {
1846
+ this.map.clear();
1847
+ }
1848
+ getAll() {
1849
+ return Object.fromEntries(this.map);
1850
+ }
1851
+ }, Rn = class {
1852
+ handler;
1853
+ throttleMs;
1854
+ counters = /* @__PURE__ */ new Map();
1855
+ lastEmitted = /* @__PURE__ */ new Map();
1856
+ constructor(e, t = Pe) {
1857
+ this.handler = e, this.throttleMs = t;
1858
+ }
1859
+ setHandler(e) {
1860
+ this.handler = e;
1861
+ }
1862
+ count(e, t = 1) {
1863
+ let n = (this.counters.get(e) ?? 0) + t;
1864
+ return this.counters.set(e, n), n;
1865
+ }
1866
+ report(e, t, n, r) {
1867
+ let i = this.count(e), a = Date.now();
1868
+ if (a - (this.lastEmitted.get(e) ?? 0) < this.throttleMs) return;
1869
+ this.lastEmitted.set(e, a);
1870
+ let o = {
1871
+ code: e,
1872
+ message: t,
1873
+ detail: n,
1874
+ cause: r,
1875
+ at: a,
1876
+ count: i
1877
+ };
1878
+ if (this.handler) try {
1879
+ this.handler(o);
1880
+ } catch (e) {
1881
+ this.count("handler.threw"), typeof console < "u" && console.warn(`${he} onDiagnostic handler threw`, e);
1882
+ }
1883
+ }
1884
+ guard(e, t, n) {
1885
+ try {
1886
+ return n();
1887
+ } catch (n) {
1888
+ this.report(e, t, void 0, n);
1889
+ return;
1890
+ }
1891
+ }
1892
+ async guardAsync(e, t, n) {
1893
+ try {
1894
+ return await n();
1895
+ } catch (n) {
1896
+ this.report(e, t, void 0, n);
1897
+ return;
1898
+ }
1899
+ }
1900
+ snapshot() {
1901
+ return Object.fromEntries(this.counters);
1902
+ }
1903
+ reset() {
1904
+ this.counters.clear(), this.lastEmitted.clear();
1905
+ }
1906
+ };
1907
+ //#endregion
1908
+ //#region src/core/journey.ts
1909
+ function K(e, t) {
1910
+ let n = Reflect.get(e, t);
1911
+ return typeof n == "string" && n !== "" ? n : void 0;
1912
+ }
1913
+ function zn(e, t) {
1914
+ let n = Reflect.get(e, t);
1915
+ return typeof n == "number" && Number.isFinite(n) ? n : void 0;
1916
+ }
1917
+ function Bn(e) {
1918
+ if (typeof e != "object" || !e) return null;
1919
+ let t = K(e, "id"), n = K(e, "name"), r = zn(e, "startedAt");
1920
+ return t === void 0 || n === void 0 || r === void 0 ? null : {
1921
+ id: t,
1922
+ name: n,
1923
+ startedAt: r,
1924
+ parentId: K(e, "parentId"),
1925
+ ownerContextId: K(e, "ownerContextId") ?? ""
1926
+ };
1927
+ }
1928
+ function Vn(e) {
1929
+ if (typeof e != "object" || !e) return null;
1930
+ let t = K(e, "i"), n = K(e, "n");
1931
+ return t === void 0 || n === void 0 ? null : {
1932
+ id: t,
1933
+ name: n,
1934
+ startedAt: zn(e, "s") ?? Date.now(),
1935
+ parentId: void 0,
1936
+ ownerContextId: ""
1937
+ };
1938
+ }
1939
+ function Hn(e) {
1940
+ let t = JSON.stringify({
1941
+ i: e.id,
1942
+ n: e.name.slice(0, 64),
1943
+ s: e.startedAt
1944
+ }), n = new TextEncoder().encode(t), r = "";
1945
+ for (let e of n) r += String.fromCharCode(e);
1946
+ return btoa(r).replace(Ee, "-").replace(_e, "_").replace(Oe, "");
1947
+ }
1948
+ var Un = class {
1949
+ options;
1950
+ diagnostics;
1951
+ contextId;
1952
+ onLocalChange;
1953
+ journey = null;
1954
+ expiryTimer = null;
1955
+ constructor(e, t, n, r) {
1956
+ this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r;
1957
+ }
1958
+ current() {
1959
+ return this.journey;
1960
+ }
1961
+ async bootstrap() {
1962
+ let e = this.readUrlToken();
1963
+ if (e && this.adopt(e, "url")) return;
1964
+ let t = this.diagnostics.guard("storage.unavailable", "reading the persisted journey", () => sessionStorage.getItem(b));
1965
+ if (t && this.restore(t)) return;
1966
+ let n = await this.readOpenFinToken();
1967
+ n !== null && this.adopt(n, "openfin.customData");
1968
+ }
1969
+ start(e, t = {}) {
1970
+ let n = {
1971
+ id: t.id ?? B(),
1972
+ name: e,
1973
+ startedAt: Date.now(),
1974
+ parentId: t.parent ? this.journey?.id : void 0,
1975
+ ownerContextId: this.contextId
1976
+ };
1977
+ return this.setJourney(n), this.onLocalChange(n), n;
1978
+ }
1979
+ end() {
1980
+ this.journey !== null && (this.setJourney(null), this.onLocalChange(null));
1981
+ }
1982
+ applyRemote(e) {
1983
+ let t = this.journey;
1984
+ (e === null || t === null || e.id !== t.id) && this.setJourney(e);
1985
+ }
1986
+ getToken() {
1987
+ let e = this.journey;
1988
+ if (e === null) return;
1989
+ let t = Hn(e);
1990
+ if (t.length > 256) {
1991
+ this.diagnostics.report("journey.token_too_large", "journey token exceeded the size cap and was not issued", { length: t.length });
1992
+ return;
1993
+ }
1994
+ return t;
1995
+ }
1996
+ adopt(e, t, n = !1) {
1997
+ let r = this.decodeToken(e);
1998
+ return r === null ? !1 : Date.now() - r.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "discarded a seeded journey older than maxAgeMs", {
1999
+ source: t,
2000
+ name: r.name
2001
+ }), !1) : (this.setJourney(r), this.diagnostics.report("journey.adopted", `adopted journey "${r.name}"`, {
2002
+ source: t,
2003
+ journeyId: r.id
2004
+ }), n && this.onLocalChange(r), !0);
2005
+ }
2006
+ ownerClosed(e) {
2007
+ this.options.endOnOwnerClose && this.journey?.ownerContextId === e && this.end();
2008
+ }
2009
+ destroy() {
2010
+ this.clearTimer();
2011
+ }
2012
+ restore(e) {
2013
+ let t = Bn(this.diagnostics.guard("storage.degraded", "parsing the persisted journey", () => JSON.parse(e)));
2014
+ return t === null ? !1 : Date.now() - t.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "discarded a persisted journey older than maxAgeMs", { name: t.name }), this.clearStored(), !1) : (this.setJourney(t), this.diagnostics.report("journey.adopted", `resumed journey "${t.name}"`, {
2015
+ source: "sessionStorage",
2016
+ journeyId: t.id
2017
+ }), !0);
2018
+ }
2019
+ decodeToken(e) {
2020
+ return this.diagnostics.guard("config.invalid", "decoding a seeded journey token", () => {
2021
+ let t = e.replace(He, "+").replace(Le, "/"), n = (4 - t.length % 4) % 4, r = "=".repeat(n), i = Uint8Array.from(atob(t + r), (e) => e.charCodeAt(0));
2022
+ return Vn(JSON.parse(new TextDecoder().decode(i)));
2023
+ }) ?? null;
2024
+ }
2025
+ setJourney(e) {
2026
+ if (this.journey = e, this.clearTimer(), this.diagnostics.guard("storage.unavailable", "persisting the journey", () => {
2027
+ e === null ? sessionStorage.removeItem(b) : sessionStorage.setItem(b, JSON.stringify(e));
2028
+ }), e === null) return;
2029
+ let t = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), n = setTimeout(() => {
2030
+ this.diagnostics.report("journey.expired", `journey "${e.name}" hit maxAgeMs and was ended automatically`, { journeyId: e.id }), this.journey = null, this.expiryTimer = null, this.clearStored();
2031
+ }, t);
2032
+ this.expiryTimer = n, C(n);
2033
+ }
2034
+ clearStored() {
2035
+ this.diagnostics.guard("storage.unavailable", "clearing the persisted journey", () => {
2036
+ sessionStorage.removeItem(b);
2037
+ });
2038
+ }
2039
+ clearTimer() {
2040
+ this.expiryTimer !== null && (clearTimeout(this.expiryTimer), this.expiryTimer = null);
2041
+ }
2042
+ readUrlToken() {
2043
+ return this.diagnostics.guard("config.invalid", "reading the journey token from the URL", () => typeof location > "u" ? null : new URL(location.href).searchParams.get(this.options.urlParam)) ?? null;
2044
+ }
2045
+ async readOpenFinToken() {
2046
+ let e = globalThis.fin?.me, t = e?.getOptions;
2047
+ if (t === void 0) return null;
2048
+ let n = (await this.diagnostics.guardAsync("openfin.unavailable", "reading fin.me.getOptions()", () => t.call(e)))?.customData?.[Ye];
2049
+ return typeof n == "string" ? n : null;
2050
+ }
2051
+ };
2052
+ //#endregion
2053
+ //#region src/core/sampling.ts
2054
+ function Wn(e) {
2055
+ let t = d;
2056
+ for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, h);
2057
+ return t >>> 0;
2058
+ }
2059
+ function q(e, t) {
2060
+ let n = e.attributes[t];
2061
+ return typeof n == "string" ? n : "";
2062
+ }
2063
+ function Gn(e, t) {
2064
+ let { rates: n, defaultRate: r } = t.sampling, i, a = -1;
2065
+ for (let [t, r] of Object.entries(n)) (e === t || e.startsWith(`${t}.`)) && t.length > a && (i = r, a = t.length);
2066
+ return i ?? r;
2067
+ }
2068
+ function Kn(e, t) {
2069
+ if (e.severityText === "ERROR" || e.severityText === "FATAL" || t.sampling.alwaysSampleTypes.includes(q(e, "log.type"))) return !0;
2070
+ let n = Gn(q(e, y), t);
2071
+ return n >= 1 ? !0 : n <= 0 ? !1 : Wn(q(e, "journey.id") || e.traceId) / ee < n;
2072
+ }
2073
+ //#endregion
2074
+ //#region src/core/pipeline.ts
2075
+ function qn(e) {
2076
+ return e.attributes[v] === me;
2077
+ }
2078
+ var Jn = class {
2079
+ config;
2080
+ name;
2081
+ diagnostics;
2082
+ pending = [];
2083
+ constructor(e, t, n) {
2084
+ this.config = e, this.name = t, this.diagnostics = n;
2085
+ }
2086
+ get options() {
2087
+ return this.config.streams[this.name];
2088
+ }
2089
+ get capacity() {
2090
+ return Math.max(this.options.batchSize, 1) * 10;
2091
+ }
2092
+ add(e) {
2093
+ this.pending.length >= this.capacity && (this.pending.shift(), this.diagnostics.count("record.dropped_pending_full")), this.pending.push(e);
2094
+ }
2095
+ take() {
2096
+ let e = this.pending;
2097
+ return this.pending = [], e;
2098
+ }
2099
+ }, Yn = class {
2100
+ config;
2101
+ transport;
2102
+ storage;
2103
+ retry;
2104
+ diagnostics;
2105
+ records$ = new dt();
2106
+ streams;
2107
+ subscription = null;
2108
+ unconfirmed = /* @__PURE__ */ new Map();
2109
+ stopped = !1;
2110
+ constructor(e, t, n, r, i) {
2111
+ this.config = e, this.transport = t, this.storage = n, this.retry = r, this.diagnostics = i, this.streams = {
2112
+ logs: new Jn(e, "logs", i),
2113
+ metrics: new Jn(e, "metrics", i)
2114
+ }, this.subscribe();
2115
+ }
2116
+ push(e) {
2117
+ this.stopped || (e.observedTimeUnixNano = O(), this.records$.next(e));
2118
+ }
2119
+ drainPending() {
2120
+ let e = [
2121
+ ...[...this.unconfirmed.values()].flatMap((e) => e.records),
2122
+ ...this.streams.metrics.take(),
2123
+ ...this.streams.logs.take()
2124
+ ];
2125
+ return this.unconfirmed.clear(), e.length === 0 ? null : {
2126
+ id: B(),
2127
+ records: e,
2128
+ createdAt: Date.now(),
2129
+ attempts: 0
2130
+ };
2131
+ }
2132
+ refresh() {
2133
+ this.subscription?.unsubscribe(), this.subscribe();
2134
+ }
2135
+ destroy() {
2136
+ this.stopped = !0, this.subscription?.unsubscribe(), this.subscription = null, this.records$.complete();
2137
+ }
2138
+ subscribe() {
2139
+ if (this.stopped) return;
2140
+ let [e, t] = bt(this.records$, qn);
2141
+ this.subscription = _t(this.batches(e, this.streams.metrics), this.batches(t, this.streams.logs)).pipe(x((e) => (this.diagnostics.report("pipeline.crashed", "the pipeline errored and was restarted", void 0, e), this.subscribe(), ut)), yt(ft), vt((e) => ht(this.dispatch(e)).pipe(x((t) => (this.diagnostics.report("pipeline.crashed", "dispatch rejected, which it is written never to do", { batchId: e.id }, t), ut))), this.config.maxConcurrentRequests)).subscribe();
2142
+ }
2143
+ batches(e, t) {
2144
+ return e.pipe(mt((e) => Kn(e, this.config) ? !0 : (this.diagnostics.count("record.dropped_by_sampling"), !1)), xt((e) => {
2145
+ t.add(e);
2146
+ }), pt(t.options.flushIntervalMs, null, t.options.batchSize), gt(() => this.claim(t)), mt((e) => e !== null));
2147
+ }
2148
+ claim(e) {
2149
+ let t = e.take();
2150
+ if (t.length === 0) return null;
2151
+ let n = {
2152
+ id: B(),
2153
+ records: t,
2154
+ createdAt: Date.now(),
2155
+ attempts: 0
2156
+ };
2157
+ return this.unconfirmed.set(n.id, n), n;
2158
+ }
2159
+ async dispatch(e) {
2160
+ try {
2161
+ let t = this.transport.throttledForMs();
2162
+ if (t > 0) {
2163
+ await this.store(e), this.diagnostics.report("transport.throttled", "stored the batch rather than sending it", {
2164
+ batchId: e.id,
2165
+ records: e.records.length,
2166
+ throttledMs: t
2167
+ });
2168
+ return;
2169
+ }
2170
+ try {
2171
+ await this.transport.send(e);
2172
+ } catch (t) {
2173
+ await this.store({
2174
+ ...e,
2175
+ attempts: e.attempts + 1
2176
+ }), this.diagnostics.report("transport.http_error", "batch was stored for retry instead of being delivered", {
2177
+ batchId: e.id,
2178
+ records: e.records.length
2179
+ }, t);
2180
+ }
2181
+ } finally {
2182
+ this.unconfirmed.delete(e.id);
2183
+ }
2184
+ }
2185
+ async store(e) {
2186
+ await this.diagnostics.guardAsync("storage.degraded", "persisting an undelivered batch", async () => {
2187
+ await this.storage.save(e), this.retry.nudge();
2188
+ });
2189
+ }
2190
+ };
2191
+ //#endregion
2192
+ //#region src/core/record.ts
2193
+ function J(e) {
2194
+ return e;
2195
+ }
2196
+ var Xn = class {
2197
+ deps;
2198
+ resourceCache = null;
2199
+ constructor(e) {
2200
+ this.deps = e;
2201
+ }
2202
+ invalidateResource() {
2203
+ this.resourceCache = null;
2204
+ }
2205
+ isEnabled(e) {
2206
+ let { config: t } = this.deps;
2207
+ return t.enabled ? p[e] >= p[t.minLevel] : !1;
2208
+ }
2209
+ build(e) {
2210
+ let { config: t, diagnostics: n, tracing: r, journey: i, sequence: a } = this.deps;
2211
+ if (!this.isEnabled(e.level)) return n.count("record.dropped_by_level"), null;
2212
+ let o = t.limits, s = r.resolve(), c = i.current(), l = a.next(), u = xn(), d, f = 0;
2213
+ try {
2214
+ let t = P(this.deps.context.getAll(), o), n = P(e.scoped ?? {}, o), r = P(e.payload ?? {}, o);
2215
+ f = t.bytes + n.bytes + r.bytes, d = {
2216
+ ...J(t.value),
2217
+ ...J(n.value),
2218
+ ...J(r.value)
2219
+ };
2220
+ } catch (e) {
2221
+ n.report("record.sanitize_failed", "attributes could not be sanitized", void 0, e), d = { [Ce]: !0 };
2222
+ }
2223
+ d[v] = e.type, d[xe] = l, d[y] = e.namespace, d[Xe] = u, c && (d[ye] = c.id, d[Be] = c.name, c.parentId !== void 0 && (d[Ke] = c.parentId));
2224
+ let p = N(e.body, o.maxBodyChars);
2225
+ p !== e.body && n.count("record.truncated");
2226
+ let m = {
2227
+ timeUnixNano: O(),
2228
+ traceId: s.traceId,
2229
+ spanId: s.spanId,
2230
+ traceFlags: s.traceFlags,
2231
+ severityNumber: de[e.level],
2232
+ severityText: e.level,
2233
+ body: p,
2234
+ attributes: d,
2235
+ resource: this.resource()
2236
+ }, h = t.redact;
2237
+ if (h) {
2238
+ let e = n.guard("record.sanitize_failed", "redact hook threw", () => h(m));
2239
+ if (e === null) return n.count("record.dropped_by_redact"), null;
2240
+ if (e !== void 0 && e !== m) {
2241
+ if (k(e)) {
2242
+ let t = P(e.attributes, o);
2243
+ m = {
2244
+ ...e,
2245
+ attributes: J(t.value)
2246
+ }, f = t.bytes;
2247
+ } else n.report("record.sanitize_failed", "redact hook returned something that is not a record, keeping the original");
2248
+ }
2249
+ }
2250
+ if (f > o.maxRecordBytes) {
2251
+ n.report("record.truncated", "attributes exceeded the size budget and were dropped", {
2252
+ bytes: f,
2253
+ body: m.body
2254
+ });
2255
+ let t = {
2256
+ [v]: e.type,
2257
+ [xe]: l,
2258
+ [y]: e.namespace,
2259
+ [Xe]: u,
2260
+ [Ae]: !0,
2261
+ [We]: f
2262
+ };
2263
+ c && (t[ye] = c.id, t[Be] = c.name), m.attributes = t;
2264
+ }
2265
+ return m;
2266
+ }
2267
+ resource() {
2268
+ if (this.resourceCache) return this.resourceCache;
2269
+ let { config: e, identity: t, platform: n } = this.deps;
2270
+ return this.resourceCache = {
2271
+ [_]: e.serviceName,
2272
+ [Ue]: e.serviceVersion,
2273
+ [Se]: e.environment,
2274
+ [ve]: oe,
2275
+ [$e]: l,
2276
+ [De]: ne,
2277
+ [Ie]: n.platform,
2278
+ [Re]: t.sessionId,
2279
+ [ke]: t.tabId,
2280
+ [qe]: t.contextId,
2281
+ [Ve]: n.userAgent,
2282
+ ...n.openfinUuid === void 0 ? {} : { [we]: n.openfinUuid },
2283
+ ...n.openfinName === void 0 ? {} : { [Ze]: n.openfinName }
2284
+ }, this.resourceCache;
2285
+ }
2286
+ }, Y = Symbol.for(rt), X = class e {
2287
+ diagnostics;
2288
+ config;
2289
+ platform;
2290
+ identity;
2291
+ context = new Ln();
2292
+ breadcrumbs;
2293
+ tracing;
2294
+ sequence = new Sn();
2295
+ journey;
2296
+ builder;
2297
+ console;
2298
+ bus;
2299
+ storage;
2300
+ transport;
2301
+ retry;
2302
+ pipeline;
2303
+ exitFlush;
2304
+ captures = [];
2305
+ bootBuffer = [];
2306
+ forwardBuffer = [];
2307
+ forwardScheduled = !1;
2308
+ ready = !1;
2309
+ destroyed = !1;
2310
+ lastGapAt = 0;
2311
+ constructor(e) {
2312
+ this.diagnostics = new Rn(e.onDiagnostic), this.platform = vn(this.diagnostics), this.config = Fn(e, this.diagnostics), this.identity = dn(this.diagnostics), this.breadcrumbs = new On(this.config.capture.maxBreadcrumbs), this.tracing = new Dn(this.diagnostics), this.console = new _n(this.config.console.enabled, this.config.console.level), this.journey = new Un(this.config.journey, this.diagnostics, this.identity.contextId, (e) => {
2313
+ this.bus.broadcastJourney(e);
2314
+ }), this.builder = new Xn({
2315
+ config: this.config,
2316
+ diagnostics: this.diagnostics,
2317
+ context: this.context,
2318
+ journey: this.journey,
2319
+ tracing: this.tracing,
2320
+ sequence: this.sequence,
2321
+ identity: this.identity,
2322
+ platform: this.platform
2323
+ }), this.bus = new Lt(this.config, this.diagnostics, this.platform, this.identity.contextId, this.identity.tabId, {
2324
+ onRecords: (e) => {
2325
+ this.ingestForwarded(e);
2326
+ },
2327
+ onJourney: (e) => {
2328
+ this.journey.applyRemote(e);
2329
+ },
2330
+ onJourneyRequest: () => this.journey.current(),
2331
+ onTabConflict: () => {
2332
+ this.regenerateTabId();
2333
+ }
2334
+ });
2335
+ }
2336
+ busAccept = (e, t) => {
2337
+ this.destroyed || this.diagnostics.guard("bus.send_failed", "accepting a direct message from a child", () => {
2338
+ this.bus.acceptDirect(e, t);
2339
+ });
2340
+ };
2341
+ static current() {
2342
+ return globalThis[Y] ?? null;
2343
+ }
2344
+ static configure(t) {
2345
+ let n = e.current();
2346
+ if (n && !n.destroyed) return n.reconfigure(t), n;
2347
+ let r = new e(t);
2348
+ return globalThis[Y] = r, r.init(), r;
2349
+ }
2350
+ reconfigure(e) {
2351
+ In(this.config, Fn(e, this.diagnostics, this.config)), this.diagnostics.setHandler(this.config.onDiagnostic), this.builder.invalidateResource(), this.console.update(this.config.console.enabled, this.config.console.level), this.breadcrumbs.resize(this.config.capture.maxBreadcrumbs), this.pipeline?.refresh(), this.ready && this.reinstallCaptures(), this.diagnostics.report("config.reconfigured", "configure() was called again, the existing runtime was updated");
2352
+ }
2353
+ async init() {
2354
+ try {
2355
+ let e = this.journey.bootstrap();
2356
+ await this.bus.start() === "sender" && await this.becomeSender(), await e, this.installCaptures();
2357
+ } catch (e) {
2358
+ this.diagnostics.report("pipeline.crashed", "startup failed, continuing in a degraded state", void 0, e);
2359
+ } finally {
2360
+ this.ready = !0, this.releaseBootBuffer();
2361
+ }
2362
+ }
2363
+ async becomeSender() {
2364
+ this.storage = await nn(this.config.storage.strategy, this.config.storage.dbName, this.config.storage, this.diagnostics, this.reportGap), this.transport = new ln(this.config, this.diagnostics), this.retry = new hn(this.storage, this.transport, this.diagnostics, this.config), this.pipeline = new Yn(this.config, this.transport, this.storage, this.retry, this.diagnostics), this.exitFlush = new on({
2365
+ config: this.config,
2366
+ diagnostics: this.diagnostics,
2367
+ drainPending: () => this.pipeline?.drainPending() ?? null
2368
+ }), await Yt(this.storage, this.diagnostics), this.retry.start(), this.exitFlush.install();
2369
+ }
2370
+ installCaptures() {
2371
+ let e = {
2372
+ config: this.config,
2373
+ diagnostics: this.diagnostics,
2374
+ breadcrumbs: this.breadcrumbs,
2375
+ tracing: this.tracing,
2376
+ logger: new S(this, tt)
2377
+ }, t = this.config.capture;
2378
+ (t.errors || t.rejections || t.resourceErrors) && this.captures.push(new Rt(e)), (t.fetch || t.xhr) && this.captures.push(new Ht(e)), (t.interactions || t.navigation) && this.captures.push(new Bt(e)), t.webVitals && this.captures.push(new Wt(e));
2379
+ for (let e of this.captures) this.diagnostics.guard("capture.install_failed", `installing ${e.name}`, () => {
2380
+ e.install();
2381
+ });
2382
+ }
2383
+ reinstallCaptures() {
2384
+ for (let e of this.captures) this.diagnostics.guard("capture.install_failed", `uninstalling ${e.name}`, () => {
2385
+ e.uninstall();
2386
+ });
2387
+ this.captures.length = 0, this.installCaptures();
2388
+ }
2389
+ registerWorker(e) {
2390
+ this.destroyed || this.diagnostics.guard("bus.send_failed", "registering a worker", () => {
2391
+ this.bus.attachWorker(e);
2392
+ });
2393
+ }
2394
+ async destroy() {
2395
+ if (!this.destroyed) {
2396
+ this.destroyed = !0;
2397
+ for (let e of this.captures) e.uninstall();
2398
+ this.captures.length = 0, this.exitFlush?.flush("shutdown"), this.exitFlush?.uninstall(), this.retry?.stop(), this.pipeline?.destroy(), this.journey.destroy(), this.bus.destroy(), this.forwardBuffer = [], await this.storage?.close(), e.current() === this && Reflect.deleteProperty(globalThis, Y);
2399
+ }
2400
+ }
2401
+ emit(e) {
2402
+ if (!(!e || this.destroyed)) {
2403
+ if (pn(this.identity.sessionId, this.diagnostics), !this.ready) {
2404
+ this.bootBuffer.length >= this.config.bus.maxBootBufferRecords && (this.bootBuffer.shift(), this.diagnostics.count("record.dropped_boot_buffer_full")), this.bootBuffer.push(e);
2405
+ return;
2406
+ }
2407
+ this.route(e);
2408
+ }
2409
+ }
2410
+ route(e) {
2411
+ if (this.bus.getRole() === "forwarder") {
2412
+ this.forward(e);
2413
+ return;
2414
+ }
2415
+ this.pipeline?.push(e);
2416
+ }
2417
+ forward(e) {
2418
+ this.forwardBuffer.push(e), !this.forwardScheduled && (this.forwardScheduled = !0, queueMicrotask(() => {
2419
+ this.forwardScheduled = !1;
2420
+ let e = this.forwardBuffer;
2421
+ this.forwardBuffer = [], e.length > 0 && this.bus.sendRecords(e);
2422
+ }));
2423
+ }
2424
+ ingestForwarded(e) {
2425
+ if (!Array.isArray(e)) {
2426
+ this.diagnostics.count("record.dropped_malformed");
2427
+ return;
2428
+ }
2429
+ for (let t of e) {
2430
+ if (!k(t)) {
2431
+ this.diagnostics.count("record.dropped_malformed");
2432
+ continue;
2433
+ }
2434
+ this.pipeline?.push(t);
2435
+ }
2436
+ }
2437
+ releaseBootBuffer() {
2438
+ let e = this.bootBuffer;
2439
+ this.bootBuffer = [];
2440
+ let t = this.journey.current();
2441
+ for (let n of e) t && !n.attributes["journey.id"] && (n.attributes["journey.id"] = t.id, n.attributes["journey.name"] = t.name), this.route(n);
2442
+ }
2443
+ reportGap = (e) => {
2444
+ let t = Date.now();
2445
+ t - this.lastGapAt < 6e4 || (this.lastGapAt = t, new S(this, s).warn("stored records were dropped before delivery", {
2446
+ "gap.batches": e.batches,
2447
+ "gap.records": e.records,
2448
+ "gap.reason": e.reason
2449
+ }));
2450
+ };
2451
+ regenerateTabId() {
2452
+ let e = B();
2453
+ this.diagnostics.report("bus.role_resolved", "another context claimed this tab id, most likely a duplicated tab. Regenerating.", {
2454
+ was: this.identity.tabId,
2455
+ now: e
2456
+ }), this.identity.tabId = e, this.diagnostics.guard("storage.unavailable", "persisting the new tab id", () => {
2457
+ sessionStorage.setItem(te, e);
2458
+ }), this.builder.invalidateResource();
2459
+ }
2460
+ async queueDepth() {
2461
+ return await this.diagnostics.guardAsync("storage.degraded", "counting the batches waiting in storage", () => this.storage?.count() ?? Promise.resolve(0)) ?? 0;
2462
+ }
2463
+ async flush() {
2464
+ if (this.bus.getRole() === "forwarder") {
2465
+ let e = this.forwardBuffer;
2466
+ this.forwardBuffer = [], e.length > 0 && this.bus.sendRecords(e);
2467
+ return;
2468
+ }
2469
+ let e = this.pipeline?.drainPending();
2470
+ if (!(!e || !this.transport)) try {
2471
+ await this.transport.send(e);
2472
+ } catch (t) {
2473
+ await this.diagnostics.guardAsync("storage.degraded", "persisting the batch drained by flush()", async () => {
2474
+ await this.storage?.save({
2475
+ ...e,
2476
+ attempts: 1
2477
+ }), this.retry?.nudge();
2478
+ }), this.diagnostics.report("transport.http_error", "the batch drained by flush() was stored for retry instead of being delivered", {
2479
+ batchId: e.id,
2480
+ records: e.records.length
2481
+ }, t);
2482
+ }
2483
+ }
2484
+ }, Z = /* @__PURE__ */ new Map();
2485
+ function Q() {
2486
+ return X.current() || X.configure({});
2487
+ }
2488
+ function Zn(e) {
2489
+ X.configure(e), Z.clear();
2490
+ }
2491
+ function Qn(e, t) {
2492
+ let n = t ? `${e}::${JSON.stringify(t)}` : e, r = Z.get(n);
2493
+ return r || (r = new S(Q(), e, t), Z.set(n, r)), r;
2494
+ }
2495
+ function $() {
2496
+ return Qn("app");
2497
+ }
2498
+ function $n(e, t) {
2499
+ $().trace(e, t);
2500
+ }
2501
+ function er(e, t) {
2502
+ $().debug(e, t);
2503
+ }
2504
+ function tr(e, t) {
2505
+ $().info(e, t);
2506
+ }
2507
+ function nr(e, t) {
2508
+ $().warn(e, t);
2509
+ }
2510
+ function rr(e, t, n) {
2511
+ $().error(e, t, n);
2512
+ }
2513
+ function ir(e, t) {
2514
+ $().logAction(e, t);
2515
+ }
2516
+ function ar(e, t) {
2517
+ $().logEvent(e, t);
2518
+ }
2519
+ function or(e, t, n, r, i) {
2520
+ $().logMetric(e, t, n, r, i);
2521
+ }
2522
+ function sr(e, t, n) {
2523
+ return $().timeSync(e, t, n);
2524
+ }
2525
+ function cr(e, t, n) {
2526
+ return $().timeAsync(e, t, n);
2527
+ }
2528
+ function lr(e, t) {
2529
+ Q().context.set(e, t);
2530
+ }
2531
+ function ur(e) {
2532
+ Q().context.setMany(e);
2533
+ }
2534
+ function dr(e) {
2535
+ Q().context.remove(e);
2536
+ }
2537
+ function fr(e, t) {
2538
+ return Q().journey.start(e, t);
2539
+ }
2540
+ function pr() {
2541
+ Q().journey.end();
2542
+ }
2543
+ function mr() {
2544
+ return Q().journey.current();
2545
+ }
2546
+ function hr() {
2547
+ return Q().journey.getToken();
2548
+ }
2549
+ function gr(e) {
2550
+ return Q().journey.adopt(e, "manual", !0);
2551
+ }
2552
+ function _r(e) {
2553
+ Q().registerWorker(e);
2554
+ }
2555
+ function vr() {
2556
+ Q().tracing.rotate("explicit");
2557
+ }
2558
+ function yr() {
2559
+ return Q().tracing.headers();
2560
+ }
2561
+ function br() {
2562
+ return Q().flush();
2563
+ }
2564
+ function xr() {
2565
+ return Q().queueDepth();
2566
+ }
2567
+ function Sr() {
2568
+ return Q().diagnostics.snapshot();
2569
+ }
2570
+ async function Cr() {
2571
+ let e = X.current();
2572
+ Z.clear(), await e?.destroy();
2573
+ }
2574
+ //#endregion
2575
+ export { S as OneLogger, gr as adoptJourney, Zn as configure, mr as currentJourney, er as debug, pr as endJourney, rr as error, br as flush, Sr as getDiagnosticCounters, hr as getJourneyToken, Qn as getLogger, xr as getQueueDepth, yr as getTraceHeaders, tr as info, ir as logAction, ar as logEvent, or as logMetric, _r as registerWorker, dr as removeContext, lr as setContext, ur as setContextMap, Cr as shutdown, fr as startJourney, vr as startTrace, cr as timeAsync, sr as timeSync, $n as trace, nr as warn };
2576
+
2577
+ //# sourceMappingURL=index.js.map