@utk09/ui-observability 0.8.0 → 0.9.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 (177) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +52 -45
  3. package/dist/bus/bus.d.ts +46 -12
  4. package/dist/bus/links.d.ts +6 -3
  5. package/dist/bus-CtJWf9QN.cjs +2 -0
  6. package/dist/bus-CtJWf9QN.cjs.map +1 -0
  7. package/dist/{bus-DPDrlUBY.js → bus-D8kH58tb.js} +128 -71
  8. package/dist/bus-D8kH58tb.js.map +1 -0
  9. package/dist/capture/interactions.d.ts +7 -6
  10. package/dist/capture/network.d.ts +23 -9
  11. package/dist/capture/types.d.ts +3 -3
  12. package/dist/console-BpHfWstv.cjs +2 -0
  13. package/dist/console-BpHfWstv.cjs.map +1 -0
  14. package/dist/console-DjLbryED.js +82 -0
  15. package/dist/console-DjLbryED.js.map +1 -0
  16. package/dist/constants-Br3b89Wg.cjs +2 -0
  17. package/dist/constants-Br3b89Wg.cjs.map +1 -0
  18. package/dist/constants-DM94FjVX.js +96 -0
  19. package/dist/constants-DM94FjVX.js.map +1 -0
  20. package/dist/constants.d.ts +20 -9
  21. package/dist/core/diagnostics.d.ts +2 -2
  22. package/dist/core/journey.d.ts +16 -4
  23. package/dist/core/logger.d.ts +6 -2
  24. package/dist/core/pipeline.d.ts +18 -9
  25. package/dist/core/record.d.ts +11 -6
  26. package/dist/core/remote-sampling.d.ts +1 -1
  27. package/dist/core/runtime.d.ts +43 -15
  28. package/dist/core/sender.d.ts +15 -10
  29. package/dist/deadline-B5DINjD5.js +111 -0
  30. package/dist/deadline-B5DINjD5.js.map +1 -0
  31. package/dist/deadline-Cbg2cbUw.cjs +2 -0
  32. package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
  33. package/dist/error-like-Ywo5uRHo.js +19 -0
  34. package/dist/error-like-Ywo5uRHo.js.map +1 -0
  35. package/dist/error-like-gGRx2s36.cjs +2 -0
  36. package/dist/error-like-gGRx2s36.cjs.map +1 -0
  37. package/dist/errors-CpGRhhIf.cjs +3 -0
  38. package/dist/errors-CpGRhhIf.cjs.map +1 -0
  39. package/dist/{errors-Dnc-X4Ec.js → errors-DH4QJS0u.js} +39 -20
  40. package/dist/errors-DH4QJS0u.js.map +1 -0
  41. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  42. package/dist/global-scope-dp2jADRl.js.map +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +11 -4
  46. package/dist/index.js +561 -436
  47. package/dist/index.js.map +1 -1
  48. package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
  49. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
  50. package/dist/{indexeddb-storage-uD4oaRMc.js → indexeddb-storage-n1qkFBGA.js} +17 -17
  51. package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
  52. package/dist/interactions-31eHGwEQ.cjs +2 -0
  53. package/dist/interactions-31eHGwEQ.cjs.map +1 -0
  54. package/dist/{interactions-igKTAJvj.js → interactions-OU94MPXs.js} +22 -19
  55. package/dist/interactions-OU94MPXs.js.map +1 -0
  56. package/dist/journey-CE2EcwHW.cjs +2 -0
  57. package/dist/journey-CE2EcwHW.cjs.map +1 -0
  58. package/dist/journey-CeJ1QoT2.js +162 -0
  59. package/dist/journey-CeJ1QoT2.js.map +1 -0
  60. package/dist/{library-request-Br_T09Bn.cjs → library-request-C9uJFlbq.cjs} +2 -2
  61. package/dist/{library-request-Br_T09Bn.cjs.map → library-request-C9uJFlbq.cjs.map} +1 -1
  62. package/dist/{library-request-Dt0fXhcn.js → library-request-DvhuplAB.js} +2 -2
  63. package/dist/{library-request-Dt0fXhcn.js.map → library-request-DvhuplAB.js.map} +1 -1
  64. package/dist/{long-frames-DahhqM6u.cjs → long-frames-B8VdA_ny.cjs} +2 -2
  65. package/dist/{long-frames-DahhqM6u.cjs.map → long-frames-B8VdA_ny.cjs.map} +1 -1
  66. package/dist/{long-frames-6pnjWSSR.js → long-frames-C_7OutLs.js} +3 -3
  67. package/dist/{long-frames-6pnjWSSR.js.map → long-frames-C_7OutLs.js.map} +1 -1
  68. package/dist/models/batch.d.ts +1 -1
  69. package/dist/models/bus.d.ts +7 -4
  70. package/dist/models/config.d.ts +43 -12
  71. package/dist/models/log-record.d.ts +12 -6
  72. package/dist/network-BAV7ipyn.cjs +2 -0
  73. package/dist/network-BAV7ipyn.cjs.map +1 -0
  74. package/dist/network-D_lloS5t.js +174 -0
  75. package/dist/network-D_lloS5t.js.map +1 -0
  76. package/dist/patch-BX8KrPCT.cjs +2 -0
  77. package/dist/patch-BX8KrPCT.cjs.map +1 -0
  78. package/dist/patch-CCWfuEY7.js +9 -0
  79. package/dist/patch-CCWfuEY7.js.map +1 -0
  80. package/dist/{platform-D_XkVIF6.cjs → platform-D4wu1eIF.cjs} +2 -2
  81. package/dist/platform-D4wu1eIF.cjs.map +1 -0
  82. package/dist/platform-IHBZGqUe.js +48 -0
  83. package/dist/platform-IHBZGqUe.js.map +1 -0
  84. package/dist/{remote-rules-5UA23alm.js → remote-rules-Bt1XsdEQ.js} +14 -14
  85. package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
  86. package/dist/{remote-rules-rJJZKVG8.cjs → remote-rules-kuDf5gbe.cjs} +2 -2
  87. package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
  88. package/dist/sampling-BI15ds9D.cjs +2 -0
  89. package/dist/sampling-BI15ds9D.cjs.map +1 -0
  90. package/dist/sampling-o0VY1mqQ.js +63 -0
  91. package/dist/sampling-o0VY1mqQ.js.map +1 -0
  92. package/dist/sanitize-B9UheVKc.js +123 -0
  93. package/dist/sanitize-B9UheVKc.js.map +1 -0
  94. package/dist/sanitize-DSIP7amZ.cjs +2 -0
  95. package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
  96. package/dist/{sender-G6v4Uqi4.js → sender-BnNj9bOX.js} +234 -176
  97. package/dist/sender-BnNj9bOX.js.map +1 -0
  98. package/dist/sender-D0OsyB1c.cjs +3 -0
  99. package/dist/sender-D0OsyB1c.cjs.map +1 -0
  100. package/dist/storage/emergency-queue.d.ts +1 -1
  101. package/dist/storage/factory.d.ts +1 -1
  102. package/dist/storage/idb-driver.d.ts +1 -1
  103. package/dist/storage/local-storage.d.ts +3 -3
  104. package/dist/storage/memory-storage.d.ts +3 -3
  105. package/dist/{storm-DJkEZP_8.js → storm-BTw0J6eE.js} +2 -2
  106. package/dist/{storm-DJkEZP_8.js.map → storm-BTw0J6eE.js.map} +1 -1
  107. package/dist/{storm-BtzgLOCX.cjs → storm-Y-yuBhvv.cjs} +2 -2
  108. package/dist/{storm-BtzgLOCX.cjs.map → storm-Y-yuBhvv.cjs.map} +1 -1
  109. package/dist/transport/compression.d.ts +1 -1
  110. package/dist/transport/exit-flush.d.ts +21 -17
  111. package/dist/transport/http-transport.d.ts +61 -7
  112. package/dist/transport/retry-engine.d.ts +5 -5
  113. package/dist/transport/status-transport.d.ts +4 -2
  114. package/dist/utils/console.d.ts +1 -1
  115. package/dist/utils/error-like.d.ts +25 -0
  116. package/dist/utils/global-scope.d.ts +1 -1
  117. package/dist/utils/identity.d.ts +1 -1
  118. package/dist/utils/library-console.d.ts +1 -1
  119. package/dist/utils/library-request.d.ts +1 -1
  120. package/dist/utils/patch.d.ts +9 -0
  121. package/dist/utils/platform.d.ts +3 -3
  122. package/dist/utils/sequence.d.ts +0 -5
  123. package/dist/utils/timer.d.ts +1 -1
  124. package/dist/utils/tracing.d.ts +3 -3
  125. package/dist/utils/unref.d.ts +2 -2
  126. package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
  127. package/dist/web-vitals-Bflr5jSA.js.map +1 -0
  128. package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
  129. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
  130. package/package.json +2 -2
  131. package/dist/bus-CUXRY0JR.cjs +0 -2
  132. package/dist/bus-CUXRY0JR.cjs.map +0 -1
  133. package/dist/bus-DPDrlUBY.js.map +0 -1
  134. package/dist/console-CNljJict.js +0 -81
  135. package/dist/console-CNljJict.js.map +0 -1
  136. package/dist/console-PKzc-FmR.cjs +0 -2
  137. package/dist/console-PKzc-FmR.cjs.map +0 -1
  138. package/dist/constants-B28fDv2F.cjs +0 -2
  139. package/dist/constants-B28fDv2F.cjs.map +0 -1
  140. package/dist/constants-Bu49bm39.js +0 -93
  141. package/dist/constants-Bu49bm39.js.map +0 -1
  142. package/dist/errors-C78ZTjet.cjs +0 -3
  143. package/dist/errors-C78ZTjet.cjs.map +0 -1
  144. package/dist/errors-Dnc-X4Ec.js.map +0 -1
  145. package/dist/indexeddb-storage-D0p3iMD0.cjs +0 -2
  146. package/dist/indexeddb-storage-D0p3iMD0.cjs.map +0 -1
  147. package/dist/indexeddb-storage-uD4oaRMc.js.map +0 -1
  148. package/dist/interactions-CsE2y_fQ.cjs +0 -2
  149. package/dist/interactions-CsE2y_fQ.cjs.map +0 -1
  150. package/dist/interactions-igKTAJvj.js.map +0 -1
  151. package/dist/network-CZ0aFUsy.cjs +0 -2
  152. package/dist/network-CZ0aFUsy.cjs.map +0 -1
  153. package/dist/network-aSNbwpue.js +0 -112
  154. package/dist/network-aSNbwpue.js.map +0 -1
  155. package/dist/platform-BwbMRwHm.js +0 -48
  156. package/dist/platform-BwbMRwHm.js.map +0 -1
  157. package/dist/platform-D_XkVIF6.cjs.map +0 -1
  158. package/dist/remote-rules-5UA23alm.js.map +0 -1
  159. package/dist/remote-rules-rJJZKVG8.cjs.map +0 -1
  160. package/dist/sampling-E4x92Nn2.cjs +0 -2
  161. package/dist/sampling-E4x92Nn2.cjs.map +0 -1
  162. package/dist/sampling-J1eahbfT.js +0 -160
  163. package/dist/sampling-J1eahbfT.js.map +0 -1
  164. package/dist/sanitize-BMhh8ghJ.cjs +0 -2
  165. package/dist/sanitize-BMhh8ghJ.cjs.map +0 -1
  166. package/dist/sanitize-UJ-4Lb0n.js +0 -114
  167. package/dist/sanitize-UJ-4Lb0n.js.map +0 -1
  168. package/dist/sender-B6ufz26f.cjs +0 -3
  169. package/dist/sender-B6ufz26f.cjs.map +0 -1
  170. package/dist/sender-G6v4Uqi4.js.map +0 -1
  171. package/dist/unref-16maCyKA.js +0 -8
  172. package/dist/unref-16maCyKA.js.map +0 -1
  173. package/dist/unref-CU9Nyz_9.cjs +0 -2
  174. package/dist/unref-CU9Nyz_9.cjs.map +0 -1
  175. package/dist/web-vitals-B2FYsEAU.cjs +0 -2
  176. package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
  177. package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
@@ -0,0 +1,174 @@
1
+ import { r as e } from "./platform-IHBZGqUe.js";
2
+ import { t } from "./patch-CCWfuEY7.js";
3
+ import { t as n } from "./library-request-DvhuplAB.js";
4
+ //#region src/capture/types.ts
5
+ function r(e, t) {
6
+ return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
7
+ }
8
+ //#endregion
9
+ //#region src/capture/network.ts
10
+ function i() {
11
+ return XMLHttpRequest.prototype;
12
+ }
13
+ function a(e) {
14
+ if (typeof e == "string") return e;
15
+ if (e instanceof URL) return e.href;
16
+ if (typeof e == "object" && e) {
17
+ let { url: t } = e;
18
+ if (typeof t == "string") return t;
19
+ }
20
+ return String(e);
21
+ }
22
+ function o(e, t) {
23
+ let n = t?.method;
24
+ return n === void 0 && typeof e == "object" && e && (n = e.method), c(n ?? "GET");
25
+ }
26
+ function s(e) {
27
+ return typeof e == "object" && !(e instanceof URL) && !(e instanceof Request);
28
+ }
29
+ function c(e) {
30
+ return typeof e == "string" ? e.toUpperCase() : String(e);
31
+ }
32
+ var l = class {
33
+ ctx;
34
+ name = "network";
35
+ installed = !1;
36
+ restores = [];
37
+ constructor(e) {
38
+ this.ctx = e;
39
+ }
40
+ install() {
41
+ this.installed || (this.installed = !0, this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr());
42
+ }
43
+ uninstall() {
44
+ if (this.installed) {
45
+ this.installed = !1;
46
+ for (let e of this.restores.splice(0)) e();
47
+ }
48
+ }
49
+ ignored(e) {
50
+ return n() || r(e, this.ctx.config.capture.ignoreUrls);
51
+ }
52
+ propagates(e) {
53
+ let t = this.ctx.config.capture.propagateTraceHeaderTo;
54
+ if (t.length === 0) return !1;
55
+ let n = this.ctx.diagnostics.guard("capture.header_failed", "The library could not read the origin of a request URL. Only a RegExp target can match it.", () => new URL(e, location.href).origin);
56
+ return t.some((t) => typeof t == "string" ? t === n : t.test(e));
57
+ }
58
+ installFetch() {
59
+ if (typeof globalThis.fetch != "function") return;
60
+ let e = !0, n = (e, t) => this.prepareFetch(e, t), r = (e, t, n, r, i) => {
61
+ this.record(e, t, n, r, i);
62
+ }, i = t(globalThis, "fetch", (t) => {
63
+ let i = t.bind(globalThis);
64
+ return async function(t, a) {
65
+ let o = e ? n(t, a) : void 0;
66
+ if (!o) return i(t, a);
67
+ let s = performance.now();
68
+ try {
69
+ let e = await i(o.input, o.init);
70
+ return r(o.method, o.url, e.status, performance.now() - s, void 0), e;
71
+ } catch (e) {
72
+ throw r(o.method, o.url, 0, performance.now() - s, e), e;
73
+ }
74
+ };
75
+ });
76
+ this.restores.push(() => {
77
+ e = !1, i();
78
+ });
79
+ }
80
+ prepareFetch(e, t) {
81
+ let n = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read a fetch request. It sends the request unchanged.", () => {
82
+ let n = a(e);
83
+ if (!this.ignored(n)) return {
84
+ method: o(e, t),
85
+ url: n,
86
+ propagate: this.propagates(n)
87
+ };
88
+ });
89
+ if (!n) return;
90
+ let { method: r, url: i } = n, c = {
91
+ method: r,
92
+ url: i,
93
+ input: e,
94
+ init: t
95
+ };
96
+ if (!n.propagate || s(e)) return c;
97
+ try {
98
+ let n = Object.entries(this.ctx.tracing.headers());
99
+ if (e instanceof Request) {
100
+ let t = new Headers(e.headers);
101
+ for (let [e, r] of n) t.set(e, r);
102
+ c.input = new Request(e, { headers: t });
103
+ } else {
104
+ let e = new Headers(t?.headers);
105
+ for (let [t, r] of n) e.set(t, r);
106
+ c.init = {
107
+ ...t,
108
+ headers: e
109
+ };
110
+ }
111
+ } catch (n) {
112
+ c.input = e, c.init = t, this.ctx.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: i }, n);
113
+ }
114
+ return c;
115
+ }
116
+ installXhr() {
117
+ if (typeof XMLHttpRequest > "u") return;
118
+ let e = !0, n = this.ctx, r = (e) => this.ignored(e), o = (e) => this.propagates(e), s = (e, t, n, r) => {
119
+ this.record(e, t, n, r, void 0);
120
+ }, l = i(), d = t(l, "open", (t) => function(r, i, ...o) {
121
+ e && n.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
122
+ this.__uiobs = {
123
+ method: c(r),
124
+ url: a(i),
125
+ startedAt: 0
126
+ };
127
+ }), t.apply(this, [
128
+ r,
129
+ i,
130
+ ...o
131
+ ]);
132
+ }), f = t(l, "send", (t) => function(...i) {
133
+ let a = e ? this.__uiobs : void 0;
134
+ a && n.diagnostics.guard("capture.record_failed", `The library could not record ${a.method} ${a.url}.`, () => {
135
+ r(a.url) || (a.startedAt = performance.now(), this.addEventListener("loadend", () => {
136
+ s(a.method, a.url, this.status, performance.now() - a.startedAt);
137
+ }), o(a.url) && u(this, a.url, n));
138
+ }), t.apply(this, i);
139
+ });
140
+ this.restores.push(() => {
141
+ e = !1, d(), f();
142
+ });
143
+ }
144
+ record(t, n, r, i, a) {
145
+ let o = this.ctx.config.capture.fullUrls ? n : e(n);
146
+ this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${t} ${o}.`, () => {
147
+ let e = Math.round(i);
148
+ this.ctx.breadcrumbs.push({
149
+ t: Date.now(),
150
+ category: "http",
151
+ message: `${t} ${o} ${r === 0 ? "failed" : String(r)}`,
152
+ data: { durationMs: e }
153
+ });
154
+ let n = {
155
+ "http.request.method": t,
156
+ "url.full": o,
157
+ "http.response.status_code": r,
158
+ "http.duration_ms": e
159
+ };
160
+ r === 0 ? this.ctx.logger.error(`${t} ${o} failed`, a, n) : r >= 400 ? this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`, n) : this.ctx.logger.debug(`${t} ${o}`, n);
161
+ });
162
+ }
163
+ };
164
+ function u(e, t, n) {
165
+ try {
166
+ for (let [t, r] of Object.entries(n.tracing.headers())) e.setRequestHeader(t, r);
167
+ } catch (e) {
168
+ n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
169
+ }
170
+ }
171
+ //#endregion
172
+ export { l as NetworkCapture };
173
+
174
+ //# sourceMappingURL=network-D_lloS5t.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-D_lloS5t.js","names":["stripUrlQuery","isLibraryRequest","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","patch","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;AAgHA,SAAgBE,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;ACvFA,SAASG,IAAyB;CAChC,OAAO,eAAe;AACxB;AAqBA,SAASC,EAAQ,GAAwB;CACvC,IAAI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BAAuBpC;IACvB,YAAYX;IACZ,6BAA6BqB;IAC7B,oBAAoByB;GACtB;GAEA,AAAIzB,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGV,EAAO,GAAGX,EAAI,UAAUuB,GAAOwB,CAAU,IAGhE1B,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGV,EAAO,GAAGX,EAAI,YAAY,OAAOqB,CAAM,KAAK0B,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGpC,EAAO,GAAGX,KAAO+C,CAAU;EACtD,CACF;CACF;AACF;AAQA,SAASH,EAAgB,GAAqB,GAAa,GAA2B;CACpF,IAAI;EACF,KAAK,IAAM,CAACX,GAAKC,MAAU,OAAO,QAAQrB,EAAI,QAAQ,QAAQ,CAAC,GAC7D,EAAI,iBAAiBoB,GAAKC,CAAK;CAEnC,SAASX,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ function e(e,t,n){let r=e[t],i=n(r);return e[t]=i,()=>e[t]===i&&(e[t]=r,!0)}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=patch-BX8KrPCT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch-BX8KrPCT.cjs","names":["patch","original","target","key","wrapper","wrap"],"sources":["../src/utils/patch.ts"],"sourcesContent":["// src/utils/patch.ts\n//\n// Replaces a host function with a wrapper and gives back a safe restore. A router or a\n// second SDK can wrap the same function after the library. A blind restore removes that\n// wrapper and breaks the host page.\n\n/**\n * Replaces `target[key]` with a wrapper of the current value.\n * @param target Object that holds the function, for example `console` or `globalThis`.\n * @param key Property to replace.\n * @param wrap Makes the wrapper from the original value.\n * @returns Restore function. It writes the original back only if the property still holds\n * the wrapper. It then returns true. If not, it changes nothing. It returns false.\n */\nexport function patch<T extends object, K extends keyof T>(\n target: T,\n key: K,\n wrap: (original: T[K]) => T[K],\n): () => boolean {\n const original = target[key];\n const wrapper = wrap(original);\n target[key] = wrapper;\n\n return () => {\n // Another script wrapped the property after the library. Keep its wrapper.\n if (target[key] !== wrapper) {\n return false;\n }\n\n target[key] = original;\n return true;\n };\n}\n"],"mappings":"AAcA,SAAgBA,EACd,EACA,EACA,EACe,CACf,IAAMC,EAAWC,EAAOC,GAClBC,EAAUC,EAAKJ,CAAQ,EAG7B,MAFA,GAAOE,GAAOC,MAIRF,EAAOC,KAASC,IAIpB,EAAOD,GAAOF,EACP,GAEX"}
@@ -0,0 +1,9 @@
1
+ //#region src/utils/patch.ts
2
+ function e(e, t, n) {
3
+ let r = e[t], i = n(r);
4
+ return e[t] = i, () => e[t] === i && (e[t] = r, !0);
5
+ }
6
+ //#endregion
7
+ export { e as t };
8
+
9
+ //# sourceMappingURL=patch-CCWfuEY7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch-CCWfuEY7.js","names":["patch","original","target","key","wrapper","wrap"],"sources":["../src/utils/patch.ts"],"sourcesContent":["// src/utils/patch.ts\n//\n// Replaces a host function with a wrapper and gives back a safe restore. A router or a\n// second SDK can wrap the same function after the library. A blind restore removes that\n// wrapper and breaks the host page.\n\n/**\n * Replaces `target[key]` with a wrapper of the current value.\n * @param target Object that holds the function, for example `console` or `globalThis`.\n * @param key Property to replace.\n * @param wrap Makes the wrapper from the original value.\n * @returns Restore function. It writes the original back only if the property still holds\n * the wrapper. It then returns true. If not, it changes nothing. It returns false.\n */\nexport function patch<T extends object, K extends keyof T>(\n target: T,\n key: K,\n wrap: (original: T[K]) => T[K],\n): () => boolean {\n const original = target[key];\n const wrapper = wrap(original);\n target[key] = wrapper;\n\n return () => {\n // Another script wrapped the property after the library. Keep its wrapper.\n if (target[key] !== wrapper) {\n return false;\n }\n\n target[key] = original;\n return true;\n };\n}\n"],"mappings":";AAcA,SAAgBA,EACd,GACA,GACA,GACe;CACf,IAAMC,IAAWC,EAAOC,IAClBC,IAAUC,EAAKJ,CAAQ;CAG7B,OAFA,EAAOE,KAAOC,SAIRF,EAAOC,OAASC,MAIpB,EAAOD,KAAOF,GACP;AAEX"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-B28fDv2F.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.yt.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a(r)},t}function i(t){return e.t.test(t)?!0:(e.tt.test(t)||e.dt.test(t)&&e.mt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function o(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
- //# sourceMappingURL=platform-D_XkVIF6.cjs.map
1
+ const e=require("./constants-Br3b89Wg.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.St.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a(r)},t}function i(t){return e.t.test(t)?!0:(e.rt.test(t)||e.mt.test(t)&&e._t.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function o(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
+ //# sourceMappingURL=platform-D4wu1eIF.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform-D4wu1eIF.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAYA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAOA,EAET,IAAMG,EAAI,WAEJG,EAAMH,EAAE,WAAqC,WAAa,GAC5DI,EAAyB,UACzBC,EACAC,EACAC,EAAW,GAETC,EAASR,EAAE,KAA6B,GAkC9C,OAhCIF,EAAcE,EAAG,0BAA0B,GAC7C,EAAW,iBACX,EAAW,IACFF,EAAcE,EAAG,yBAAyB,GACnD,EAAW,gBACX,EAAW,IACFF,EAAcE,EAAG,mBAAmB,GAC7C,EAAW,aACX,EAAW,IACFQ,IAAU,IAAA,GAOVR,EAAE,YAAc,IAAA,IAAaA,EAAE,QAAU,IAAA,GAClD,EAAW,QACFA,EAAE,UAAY,IAAA,IAAaS,EAAUN,CAAE,EAChD,EAAW,iBACF,OAAO,SAAa,KAAe,OAAO,QAAY,MAC/D,EAAW,SAXX,EAAWZ,EAAAA,GAAmB,KAAKY,CAAE,EAAI,UAAY,cACrDO,EAAY,MAAM,sBAAuB,kDAAqD,CAC5F,IAAMC,EAAWH,EAAM,SACvB,EAAcG,GAAU,KACxB,EAAcA,GAAU,IAC1B,CAAC,GASH,EAAS,CACP,WACA,cACA,cACA,UAAWR,EACX,WACA,mBAAoBS,EAAWF,CAAW,CAC5C,EACOb,CACT,CAOA,SAASY,EAAU,EAAqB,CAMtC,OALIjB,EAAAA,EAA2B,KAAKW,CAAE,EAC7B,IAGPV,EAAAA,GAAsB,KAAKU,CAAE,GAAMT,EAAAA,GAAqB,KAAKS,CAAE,GAAKR,EAAAA,GAAkB,KAAKQ,CAAE,IACjFA,EAAG,SAAA,aAAwB,GAAK,CAACA,EAAG,SAAA,SAAwB,CAC5E,CAOA,SAAgBS,EAAW,EAAmC,CAC5D,GAAI,OAAO,OAAW,IACpB,MAAO,GAET,GAAI,CACF,OAAO,OAAO,OAAS,OAAO,GAChC,MAAQ,CAGN,OADAF,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
@@ -0,0 +1,48 @@
1
+ import { St as e, _t as t, mt as n, rt as r, t as i } from "./constants-DM94FjVX.js";
2
+ //#region src/utils/platform.ts
3
+ var a = null;
4
+ function o(e, t) {
5
+ let n = e[t];
6
+ return n !== void 0 && e instanceof n;
7
+ }
8
+ function s(t) {
9
+ if (a) return a;
10
+ let n = globalThis, r = n.navigator?.userAgent ?? "", i = "browser", s, u, d = !1, f = n.fin?.me;
11
+ return o(n, "ServiceWorkerGlobalScope") ? (i = "service_worker", d = !0) : o(n, "SharedWorkerGlobalScope") ? (i = "shared_worker", d = !0) : o(n, "WorkerGlobalScope") ? (i = "web_worker", d = !0) : f === void 0 ? n.Capacitor !== void 0 || n.Ionic !== void 0 ? i = "ionic" : n.cordova !== void 0 || c(r) ? i = "mobile_webview" : typeof document > "u" && typeof process < "u" && (i = "node") : (i = e.test(r) ? "openfin" : "openfin_web", t.guard("openfin.unavailable", "The library could not read fin.me.identity.", () => {
12
+ let e = f.identity;
13
+ s = e?.uuid, u = e?.name;
14
+ })), a = {
15
+ platform: i,
16
+ openfinUuid: s,
17
+ openfinName: u,
18
+ userAgent: r,
19
+ isWorker: d,
20
+ isTopLevelDocument: l(t)
21
+ }, a;
22
+ }
23
+ function c(e) {
24
+ return i.test(e) ? !0 : (r.test(e) || n.test(e) && t.test(e)) && e.includes("AppleWebKit") && !e.includes("Safari/");
25
+ }
26
+ function l(e) {
27
+ if (typeof window > "u") return !1;
28
+ try {
29
+ return window.self === window.top;
30
+ } catch {
31
+ return e.count("platform.api_blocked"), !1;
32
+ }
33
+ }
34
+ function u(e) {
35
+ try {
36
+ return typeof location < "u" ? location.href : "";
37
+ } catch {
38
+ return e.count("platform.api_blocked"), "";
39
+ }
40
+ }
41
+ function d(e) {
42
+ let t = e.search(/[?#]/);
43
+ return t === -1 ? e : e.slice(0, t);
44
+ }
45
+ //#endregion
46
+ export { s as n, d as r, u as t };
47
+
48
+ //# sourceMappingURL=platform-IHBZGqUe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform-IHBZGqUe.js","names":["OPENFIN_UA_PATTERN","MOBILE_UA_PATTERN","MACINTOSH_UA_PATTERN","IOS_DEVICE_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC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M;CAE7B,OAAOD,MAAQ,KAAKC,IAAMA,EAAI,MAAM,GAAGD,CAAG;AAC5C"}
@@ -1,4 +1,4 @@
1
- import { Tt as e, at as t, wt as n } from "./constants-Bu49bm39.js";
1
+ import { Dt as e, Ot as t, ct as n } from "./constants-DM94FjVX.js";
2
2
  //#region src/core/remote-sampling.ts
3
3
  var r = class {
4
4
  config;
@@ -22,8 +22,8 @@ var r = class {
22
22
  return !this.config.sampling.remote || e < this.receivedAt || e >= this.until ? (this.rules = null, null) : this.rules;
23
23
  }
24
24
  minLevel() {
25
- let { minLevel: e } = this.config, n = this.current()?.minLevel;
26
- return n !== void 0 && t[n] < t[e] ? n : e;
25
+ let { minLevel: e } = this.config, t = this.current()?.minLevel;
26
+ return t !== void 0 && n[t] < n[e] ? t : e;
27
27
  }
28
28
  wire() {
29
29
  let e = this.current();
@@ -40,10 +40,10 @@ function a(e) {
40
40
  function o(e) {
41
41
  return typeof e == "object" && !!e && !Array.isArray(e);
42
42
  }
43
- function s(e) {
44
- if (e.length > 4096) throw new i(`The header is longer than ${String(n)} characters.`);
43
+ function s(t) {
44
+ if (t.length > 4096) throw new i(`The header is longer than ${String(e)} characters.`);
45
45
  try {
46
- return JSON.parse(e);
46
+ return JSON.parse(t);
47
47
  } catch {
48
48
  throw new i("The header is not valid JSON.");
49
49
  }
@@ -56,14 +56,14 @@ function c(e) {
56
56
  if (n.length > 100 || !n.every(([, e]) => a(e))) throw new i(t);
57
57
  return Object.fromEntries(n);
58
58
  }
59
- function l(n) {
60
- if (!o(n)) throw new i("The rules must be an object.");
61
- if (n.v !== 1) throw new i("The version must be 1.");
62
- let { ttlMs: r, defaultRate: s, minLevel: l } = n;
63
- if (typeof r != "number" || !(r > 0 && r <= 36e5)) throw new i(`ttlMs must be a number more than 0 and at most ${String(e)}.`);
59
+ function l(e) {
60
+ if (!o(e)) throw new i("The rules must be an object.");
61
+ if (e.v !== 1) throw new i("The version must be 1.");
62
+ let { ttlMs: r, defaultRate: s, minLevel: l } = e;
63
+ if (typeof r != "number" || !(r > 0 && r <= 36e5)) throw new i(`ttlMs must be a number more than 0 and at most ${String(t)}.`);
64
64
  if (s !== void 0 && !a(s)) throw new i("defaultRate must be a number from 0 to 1.");
65
- if (l !== void 0 && !(typeof l == "string" && Object.hasOwn(t, l))) throw new i("minLevel must be a level name, for example DEBUG.");
66
- let u = { rates: c(n.rates) };
65
+ if (l !== void 0 && !(typeof l == "string" && Object.hasOwn(n, l))) throw new i("minLevel must be a level name, for example DEBUG.");
66
+ let u = { rates: c(e.rates) };
67
67
  return s !== void 0 && (u.defaultRate = s), l !== void 0 && (u.minLevel = l), {
68
68
  rules: u,
69
69
  ttlMs: r
@@ -83,4 +83,4 @@ function d(e, t, n) {
83
83
  //#endregion
84
84
  export { u as n, d as t };
85
85
 
86
- //# sourceMappingURL=remote-rules-5UA23alm.js.map
86
+ //# sourceMappingURL=remote-rules-Bt1XsdEQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-rules-Bt1XsdEQ.js","names":["REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":";;AA2CA,IAAaG,IAAb,MAA4B;CAaG;CAX7B,QAAoC;CAGpC,aAAqB;CAGrB,QAAgB;CAKhB,YAAY,GAAyC;EAAxB,KAAA,SAAAC;CAAyB;CAMtD,MAAM,GAAmC;EACvC,IAAI,CAACC,GAAQ;GACX,KAAK,QAAQ;GACb;EACF;EAEA,IAAMC,IAAM,KAAK,IAAI;EAIrB,AAFA,KAAK,QAAQD,EAAO,OACpB,KAAK,aAAaC,GAClB,KAAK,QAAQA,IAAMD,EAAO;CAC5B;CAMA,UAA8B;EAC5B,IAAI,CAAC,KAAK,OACR,OAAO;EAGT,IAAMC,IAAM,KAAK,IAAI;EASrB,OALI,CAAC,KAAK,OAAO,SAAS,UAAUA,IAAM,KA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AU,8BAA8B;CAGpD,IAAIE,EAAM,MAAA,GACR,MAAM,IAAIF,EAAU,wBAAyD;CAG/E,IAAM,EAAE,UAAO,gBAAa,gBAAaE;CAEzC,IAAI,OAAOS,KAAU,YAAY,EAAEA,IAAQ,KAAKA,KAAA,OAC9C,MAAM,IAAIX,EACR,kDAAkD,OAAOT,CAA0B,EAAE,EACvF;CAGF,IAAIqB,MAAgB,KAAA,KAAa,CAACX,EAAOW,CAAW,GAClD,MAAM,IAAIZ,EAAU,2CAA2C;CAGjE,IACEF,MAAa,KAAA,KACb,EAAE,OAAOA,KAAa,YAAY,OAAO,OAAON,GAAaM,CAAQ,IAErE,MAAM,IAAIE,EAAU,mDAAmD;CAGzE,IAAMD,IAAqB,EAAE,OAAOO,EAAUJ,EAAM,KAAK,EAAE;CAU3D,OARIU,MAAgB,KAAA,MAClB,EAAM,cAAcA,IAGlBd,MAAa,KAAA,MACf,EAAM,WAAWA,IAGZ;EAAE;EAAO;CAAM;AACxB;AAQA,SAAgBe,EAAiB,GAAc,GAA+C;CAC5F,IAAI;EACF,OAAOH,EAAU,OAAOI,KAAQ,WAAWV,EAAUU,CAAG,IAAIA,CAAG;CACjE,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiBf,IAAY,IAAIe,EAAM,YAAY;EAQlE,OANAE,EAAY,OACV,kBACA,0DAA0DD,KAC1D,KAAA,GACAD,CACF,GACO;CACT;AACF;AAQA,SAAgBG,EACd,GACA,GACA,GACM;CAKN,AAJIvB,MACF,EAAK,aAAa,IAAIF,EAAeC,CAAM,IAG7CyB,EAAK,UAAU,MAAMxB,CAAM;AAC7B"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-B28fDv2F.cjs");var t=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevel(){let{minLevel:t}=this.config,n=this.current()?.minLevel;return n!==void 0&&e.at[n]<e.at[t]?n:t}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},n=class extends Error{};function r(e){return typeof e==`number`&&e>=0&&e<=1}function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(t){if(t.length>4096)throw new n(`The header is longer than ${String(e.wt)} characters.`);try{return JSON.parse(t)}catch{throw new n(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let t=`rates must be an object with at most 100 rates from 0 to 1.`;if(!i(e))throw new n(t);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>r(e)))throw new n(t);return Object.fromEntries(a)}function s(t){if(!i(t))throw new n(`The rules must be an object.`);if(t.v!==1)throw new n(`The version must be 1.`);let{ttlMs:a,defaultRate:s,minLevel:c}=t;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new n(`ttlMs must be a number more than 0 and at most ${String(e.Tt)}.`);if(s!==void 0&&!r(s))throw new n(`defaultRate must be a number from 0 to 1.`);if(c!==void 0&&!(typeof c==`string`&&Object.hasOwn(e.at,c)))throw new n(`minLevel must be a level name, for example DEBUG.`);let l={rates:o(t.rates)};return s!==void 0&&(l.defaultRate=s),c!==void 0&&(l.minLevel=c),{rules:l,ttlMs:a}}function c(e,t){try{return s(typeof e==`string`?a(e):e)}catch(e){let r=e instanceof n?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${r}`,void 0,e),null}}function l(e,n,r){r&&(e.sampling??=new t(n)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
2
- //# sourceMappingURL=remote-rules-rJJZKVG8.cjs.map
1
+ const e=require("./constants-Br3b89Wg.cjs");var t=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevel(){let{minLevel:t}=this.config,n=this.current()?.minLevel;return n!==void 0&&e.ct[n]<e.ct[t]?n:t}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},n=class extends Error{};function r(e){return typeof e==`number`&&e>=0&&e<=1}function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(t){if(t.length>4096)throw new n(`The header is longer than ${String(e.Dt)} characters.`);try{return JSON.parse(t)}catch{throw new n(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let t=`rates must be an object with at most 100 rates from 0 to 1.`;if(!i(e))throw new n(t);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>r(e)))throw new n(t);return Object.fromEntries(a)}function s(t){if(!i(t))throw new n(`The rules must be an object.`);if(t.v!==1)throw new n(`The version must be 1.`);let{ttlMs:a,defaultRate:s,minLevel:c}=t;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new n(`ttlMs must be a number more than 0 and at most ${String(e.Ot)}.`);if(s!==void 0&&!r(s))throw new n(`defaultRate must be a number from 0 to 1.`);if(c!==void 0&&!(typeof c==`string`&&Object.hasOwn(e.ct,c)))throw new n(`minLevel must be a level name, for example DEBUG.`);let l={rates:o(t.rates)};return s!==void 0&&(l.defaultRate=s),c!==void 0&&(l.minLevel=c),{rules:l,ttlMs:a}}function c(e,t){try{return s(typeof e==`string`?a(e):e)}catch(e){let r=e instanceof n?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${r}`,void 0,e),null}}function l(e,n,r){r&&(e.sampling??=new t(n)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
2
+ //# sourceMappingURL=remote-rules-kuDf5gbe.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-rules-kuDf5gbe.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF,CAEA,IAAMC,EAAM,KAAK,IAAI,EAErB,KAAK,MAAQD,EAAO,MACpB,KAAK,WAAaC,EAClB,KAAK,MAAQA,EAAMD,EAAO,KAC5B,CAMA,SAA8B,CAC5B,GAAI,CAAC,KAAK,MACR,OAAO,KAGT,IAAMC,EAAM,KAAK,IAAI,EASrB,MALI,CAAC,KAAK,OAAO,SAAS,QAAUA,EAAM,KAAK,YAAcA,GAAO,KAAK,OACvE,KAAK,MAAQ,KACN,MAGF,KAAK,KACd,CAMA,UAAqB,CACnB,GAAM,CAAE,YAAa,KAAK,OACpBC,EAAS,KAAK,QAAQ,CAAC,EAAE,SAE/B,OAAOA,IAAW,IAAA,IAAaT,EAAAA,GAAYS,GAAUT,EAAAA,GAAYU,GAAYD,EAASC,CACxF,CAMA,MAA0B,CACxB,IAAMC,EAAQ,KAAK,QAAQ,EAM3B,OAJKA,EAIE,CAAE,GAAGA,EAAO,EAAA,EAA4B,MAAO,KAAK,MAAQ,KAAK,IAAI,CAAE,EAHrE,IAIX,CACF,EC9FMC,EAAN,cAAwB,KAAM,CAAC,EAO/B,SAASC,EAAO,EAAiC,CAC/C,OAAO,OAAOC,GAAU,UAAYA,GAAA,GAA8BA,GAAA,CACpE,CAOA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOD,GAAU,YAAYA,GAAkB,CAA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GAGlBd,IAAa,IAAA,KACf,EAAM,SAAWA,GAGZ,CAAE,QAAO,OAAM,CACxB,CAQA,SAAgBe,EAAiB,EAAc,EAA+C,CAC5F,GAAI,CACF,OAAOH,EAAU,OAAOI,GAAQ,SAAWV,EAAUU,CAAG,EAAIA,CAAG,CACjE,OAASC,EAAO,CACd,IAAMC,EAASD,aAAiBf,EAAY,IAAIe,EAAM,UAAY,GAQlE,OANAE,EAAY,OACV,iBACA,0DAA0DD,IAC1D,IAAA,GACAD,CACF,EACO,IACT,CACF,CAQA,SAAgBG,EACd,EACA,EACA,EACM,CACFvB,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7CyB,EAAK,UAAU,MAAMxB,CAAM,CAC7B"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-Br3b89Wg.cjs");function t(){return`${String(Date.now())}000000`}function n(t){return typeof t==`string`&&Object.hasOwn(e.ct,t)}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;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}function i(t){let n=e.W;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.G);return n>>>0}function a(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function o(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={rate:i,length:r.length});return n}function s(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,s=o(e,r),c=n?o(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.rate,a):s?s.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function c(t,n,r){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let a=s(t.namespace,n,r),o=e.ct[t.level]<e.ct[n.minLevel];return r&&o&&!e.st.includes(t.type)&&(a=Math.min(a,n.sampling.remoteMaxRate)),a>=1?!0:a<=0?!1:i(t.journeyId||t.traceId)/e.gn<a}function l(t,n,r=null){return c({level:t.severityText,type:a(t,e.d),namespace:a(t,e.n),journeyId:a(t,e.s),traceId:t.traceId},n,r)}var u=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
2
+ //# sourceMappingURL=sampling-BI15ds9D.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampling-BI15ds9D.cjs","names":["LEVEL_ORDER","FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","LEVEL_BYPASS_TYPES","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","nowUnixNano","isLogLevel","value","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","belowMinLevel","shouldSample","ErrorCeiling","now"],"sources":["../src/models/log-record.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n // minLevel does not apply to an action or a metric. Do not cap them.\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"4CA0DA,SAAgBU,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOZ,EAAAA,GAAaY,CAAK,CACtE,CAUA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAME,EAASF,EACf,OACE,OAAOE,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA,EAAO,aAAe,MACtB,OAAOA,EAAO,UAAa,UAC3BA,EAAO,WAAa,IAExB,CClEA,SAASC,EAAK,EAAuB,CACnC,IAAIC,EAAIf,EAAAA,EAER,IAAK,IAAIgB,EAAI,EAAGA,EAAIL,EAAM,OAAQ,IAChC,GAAKA,EAAM,WAAWK,CAAC,EACvB,EAAI,KAAK,KAAKD,EAAGd,EAAAA,CAAS,EAG5B,OAAOc,IAAM,CACf,CASA,SAASE,EAAS,EAAmB,EAAqB,CACxD,IAAMN,EAAiBE,EAAO,WAAWK,GACzC,OAAO,OAAOP,GAAU,SAAWA,EAAQ,EAC7C,CAiBA,SAASQ,EAAc,EAAmB,EAAwD,CAChG,IAAIC,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EAC9C,UAAWW,EAASJ,EAAQN,EAAAA,CAAe,EAC3C,QAASM,EAAO,OAClB,EACAa,EACAG,CACF,CACF,CAQA,IAAaO,EAAb,KAA0B,CAExB,YAAsB,EAGtB,MAAgB,EAOhB,MAAM,EAA4B,CAChC,GAAIvB,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMwB,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
@@ -0,0 +1,63 @@
1
+ import { G as e, W as t, ct as n, d as r, gn as i, n as a, s as o, st as s } from "./constants-DM94FjVX.js";
2
+ //#region src/models/log-record.ts
3
+ function c() {
4
+ return `${String(Date.now())}000000`;
5
+ }
6
+ function l(e) {
7
+ return typeof e == "string" && Object.hasOwn(n, e);
8
+ }
9
+ function u(e) {
10
+ if (typeof e != "object" || !e) return !1;
11
+ let t = e;
12
+ 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;
13
+ }
14
+ //#endregion
15
+ //#region src/core/sampling.ts
16
+ function d(n) {
17
+ let r = t;
18
+ for (let t = 0; t < n.length; t++) r ^= n.charCodeAt(t), r = Math.imul(r, e);
19
+ return r >>> 0;
20
+ }
21
+ function f(e, t) {
22
+ let n = e.attributes[t];
23
+ return typeof n == "string" ? n : "";
24
+ }
25
+ function p(e, t) {
26
+ let n;
27
+ for (let [r, i] of Object.entries(t)) (e === r || e.startsWith(`${r}.`)) && r.length > (n?.length ?? -1) && (n = {
28
+ rate: i,
29
+ length: r.length
30
+ });
31
+ return n;
32
+ }
33
+ function m(e, t, n) {
34
+ let { rates: r, defaultRate: i, remoteMaxRate: a } = t.sampling, o = p(e, r), s = n ? p(e, n.rates) : void 0;
35
+ return s && s.length >= (o?.length ?? -1) ? Math.min(s.rate, a) : o ? o.rate : n?.defaultRate === void 0 ? i : Math.min(n.defaultRate, a);
36
+ }
37
+ function h(e, t, r) {
38
+ if (e.level === "ERROR" || e.level === "FATAL" || t.sampling.alwaysSampleTypes.includes(e.type)) return !0;
39
+ let a = m(e.namespace, t, r), o = n[e.level] < n[t.minLevel];
40
+ return r && o && !s.includes(e.type) && (a = Math.min(a, t.sampling.remoteMaxRate)), a >= 1 ? !0 : a <= 0 ? !1 : d(e.journeyId || e.traceId) / i < a;
41
+ }
42
+ function g(e, t, n = null) {
43
+ return h({
44
+ level: e.severityText,
45
+ type: f(e, r),
46
+ namespace: f(e, a),
47
+ journeyId: f(e, o),
48
+ traceId: e.traceId
49
+ }, t, n);
50
+ }
51
+ var _ = class {
52
+ windowStart = 0;
53
+ count = 0;
54
+ allow(e) {
55
+ if (e.severityText !== "ERROR" && e.severityText !== "FATAL") return !0;
56
+ let t = Date.now();
57
+ return t - this.windowStart > 1e4 && (this.windowStart = t, this.count = 0), this.count++, this.count <= 500;
58
+ }
59
+ };
60
+ //#endregion
61
+ export { u as a, l as i, g as n, c as o, h as r, _ as t };
62
+
63
+ //# sourceMappingURL=sampling-o0VY1mqQ.js.map