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