@utk09/ui-observability 0.9.2 → 0.9.4
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.
- package/CHANGELOG.md +51 -0
- package/README.md +108 -33
- package/dist/batch-C4oF6XZT.cjs +2 -0
- package/dist/batch-C4oF6XZT.cjs.map +1 -0
- package/dist/{batch-4xKzzSCj.js → batch-D-4xl7op.js} +8 -5
- package/dist/batch-D-4xl7op.js.map +1 -0
- package/dist/bus/bus.d.ts +0 -4
- package/dist/{bus-DrixwdiX.js → bus-Cyvq-Ngx.js} +59 -62
- package/dist/bus-Cyvq-Ngx.js.map +1 -0
- package/dist/bus-rOhVuRee.cjs +2 -0
- package/dist/bus-rOhVuRee.cjs.map +1 -0
- package/dist/capture/network.d.ts +1 -0
- package/dist/capture/storm.d.ts +2 -7
- package/dist/capture/types.d.ts +3 -0
- package/dist/capture/web-socket.d.ts +40 -0
- package/dist/{console-B3vGRW5p.js → console-BT7mcgU6.js} +3 -3
- package/dist/{console-B3vGRW5p.js.map → console-BT7mcgU6.js.map} +1 -1
- package/dist/{console-ChfuJlf9.cjs → console-Boqa7new.cjs} +2 -2
- package/dist/{console-ChfuJlf9.cjs.map → console-Boqa7new.cjs.map} +1 -1
- package/dist/constants-BgRS6MB0.cjs +2 -0
- package/dist/constants-BgRS6MB0.cjs.map +1 -0
- package/dist/constants-L_d5YvvQ.js +160 -0
- package/dist/constants-L_d5YvvQ.js.map +1 -0
- package/dist/constants.d.ts +36 -5
- package/dist/core/breadcrumbs.d.ts +4 -4
- package/dist/core/context.d.ts +0 -8
- package/dist/core/diagnostics.d.ts +1 -3
- package/dist/core/journey.d.ts +7 -0
- package/dist/core/meter.d.ts +19 -1
- package/dist/core/pipeline.d.ts +12 -4
- package/dist/core/record.d.ts +40 -8
- package/dist/core/remote-sampling.d.ts +7 -3
- package/dist/core/runtime.d.ts +62 -3
- package/dist/core/sampling.d.ts +33 -4
- package/dist/core/sender.d.ts +8 -0
- package/dist/core/spans.d.ts +34 -0
- package/dist/{errors-BGs5NOrw.js → errors-BDI96zKc.js} +6 -6
- package/dist/errors-BDI96zKc.js.map +1 -0
- package/dist/errors-_xEsCVXn.cjs +3 -0
- package/dist/errors-_xEsCVXn.cjs.map +1 -0
- package/dist/fixed-window-BR0bu32Y.cjs +2 -0
- package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
- package/dist/fixed-window-Re7jIRJH.js +9 -0
- package/dist/fixed-window-Re7jIRJH.js.map +1 -0
- package/dist/identity-Bwku7zzN.cjs +2 -0
- package/dist/identity-Bwku7zzN.cjs.map +1 -0
- package/dist/{identity-rpEyjvVg.js → identity-Dtv917nz.js} +33 -23
- package/dist/identity-Dtv917nz.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +23 -1
- package/dist/index.js +804 -537
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-Cvavrf-y.cjs +2 -0
- package/dist/indexeddb-storage-Cvavrf-y.cjs.map +1 -0
- package/dist/{indexeddb-storage-Q9fDYlyn.js → indexeddb-storage-HgkQUTyS.js} +57 -68
- package/dist/indexeddb-storage-HgkQUTyS.js.map +1 -0
- package/dist/{interactions-BAGRmtrv.cjs → interactions-Bhe1ft8P.cjs} +2 -2
- package/dist/interactions-Bhe1ft8P.cjs.map +1 -0
- package/dist/{interactions-B8zjCjga.js → interactions-Ck01cEij.js} +3 -3
- package/dist/interactions-Ck01cEij.js.map +1 -0
- package/dist/journey-Co9OlzrW.cjs +2 -0
- package/dist/journey-Co9OlzrW.cjs.map +1 -0
- package/dist/{journey-_dQQ1eMP.js → journey-DRK0A8u_.js} +37 -33
- package/dist/journey-DRK0A8u_.js.map +1 -0
- package/dist/{library-request-DX6ev9oG.js → library-request-ChCar5F8.js} +3 -3
- package/dist/{library-request-DX6ev9oG.js.map → library-request-ChCar5F8.js.map} +1 -1
- package/dist/{library-request-BIG3Xpx3.cjs → library-request-gMFOCNcn.cjs} +2 -2
- package/dist/{library-request-BIG3Xpx3.cjs.map → library-request-gMFOCNcn.cjs.map} +1 -1
- package/dist/log-record-cwFiLyPY.js +17 -0
- package/dist/log-record-cwFiLyPY.js.map +1 -0
- package/dist/log-record-jX9eWUP8.cjs +2 -0
- package/dist/log-record-jX9eWUP8.cjs.map +1 -0
- package/dist/{long-frames-Cq2LgNnp.cjs → long-frames-Bky6nZDF.cjs} +2 -2
- package/dist/long-frames-Bky6nZDF.cjs.map +1 -0
- package/dist/{long-frames-B0tKuChx.js → long-frames-DDumopji.js} +4 -4
- package/dist/long-frames-DDumopji.js.map +1 -0
- package/dist/models/batch.d.ts +6 -0
- package/dist/models/config.d.ts +56 -5
- package/dist/models/log-record.d.ts +1 -1
- package/dist/models/plugin.d.ts +47 -0
- package/dist/models/stats.d.ts +11 -0
- package/dist/{network-CMnEvGJB.js → network-BsBZ6_-Q.js} +43 -29
- package/dist/network-BsBZ6_-Q.js.map +1 -0
- package/dist/network-_4csBGBM.cjs +2 -0
- package/dist/network-_4csBGBM.cjs.map +1 -0
- package/dist/openfin-BwEN0uj4.js +8 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -0
- package/dist/openfin-DtH2f7zX.cjs +2 -0
- package/dist/openfin-DtH2f7zX.cjs.map +1 -0
- package/dist/platform-4yYjMD-B.js +57 -0
- package/dist/platform-4yYjMD-B.js.map +1 -0
- package/dist/platform-o7r1ocOu.cjs +2 -0
- package/dist/platform-o7r1ocOu.cjs.map +1 -0
- package/dist/remote-rules-1KqfVBIu.js +91 -0
- package/dist/remote-rules-1KqfVBIu.js.map +1 -0
- package/dist/remote-rules-BHgEGlYi.cjs +2 -0
- package/dist/remote-rules-BHgEGlYi.cjs.map +1 -0
- package/dist/sampling-C4my-ma0.cjs +2 -0
- package/dist/sampling-C4my-ma0.cjs.map +1 -0
- package/dist/sampling-nYIWP_vP.js +86 -0
- package/dist/sampling-nYIWP_vP.js.map +1 -0
- package/dist/{sanitize-BNwgPj_B.js → sanitize-BiUKCUG6.js} +2 -2
- package/dist/{sanitize-BNwgPj_B.js.map → sanitize-BiUKCUG6.js.map} +1 -1
- package/dist/{sanitize-BqzPc4Jg.cjs → sanitize-BxuPSXOk.cjs} +2 -2
- package/dist/{sanitize-BqzPc4Jg.cjs.map → sanitize-BxuPSXOk.cjs.map} +1 -1
- package/dist/sender-6vrT9fFL.cjs +3 -0
- package/dist/sender-6vrT9fFL.cjs.map +1 -0
- package/dist/{sender--0_VzPbN.js → sender-DFQMF39P.js} +380 -278
- package/dist/sender-DFQMF39P.js.map +1 -0
- package/dist/storage/gap.d.ts +20 -0
- package/dist/storage/indexeddb-storage.d.ts +1 -7
- package/dist/storage/keys.d.ts +9 -0
- package/dist/storage/local-storage.d.ts +0 -6
- package/dist/storage/memory-storage.d.ts +1 -1
- package/dist/storm-6YYbXzT_.cjs +2 -0
- package/dist/storm-6YYbXzT_.cjs.map +1 -0
- package/dist/storm-CfO0Sam2.js +10 -0
- package/dist/storm-CfO0Sam2.js.map +1 -0
- package/dist/transport/exit-flush.d.ts +6 -0
- package/dist/transport/http-transport.d.ts +2 -1
- package/dist/transport/serializers/otlp-traces.d.ts +3 -0
- package/dist/transport/serializers/select.d.ts +8 -5
- package/dist/transport/status-transport.d.ts +7 -0
- package/dist/types-BR9t_w28.js +8 -0
- package/dist/types-BR9t_w28.js.map +1 -0
- package/dist/types-C7WNpnG1.cjs +2 -0
- package/dist/types-C7WNpnG1.cjs.map +1 -0
- package/dist/utils/fixed-window.d.ts +15 -0
- package/dist/utils/guards.d.ts +6 -0
- package/dist/utils/identity.d.ts +11 -0
- package/dist/utils/openfin.d.ts +48 -0
- package/dist/utils/platform.d.ts +13 -0
- package/dist/utils/tracing.d.ts +82 -4
- package/dist/web-socket-Ar4cZxmd.js +102 -0
- package/dist/web-socket-Ar4cZxmd.js.map +1 -0
- package/dist/web-socket-BwJdwSHl.cjs +2 -0
- package/dist/web-socket-BwJdwSHl.cjs.map +1 -0
- package/package.json +2 -3
- package/dist/batch-4xKzzSCj.js.map +0 -1
- package/dist/batch-cys7e53Q.cjs +0 -2
- package/dist/batch-cys7e53Q.cjs.map +0 -1
- package/dist/bus-B6vzPmQM.cjs +0 -2
- package/dist/bus-B6vzPmQM.cjs.map +0 -1
- package/dist/bus-DrixwdiX.js.map +0 -1
- package/dist/constants-Be83LICb.cjs +0 -2
- package/dist/constants-Be83LICb.cjs.map +0 -1
- package/dist/constants-CQ_D7jIW.js +0 -144
- package/dist/constants-CQ_D7jIW.js.map +0 -1
- package/dist/deadline-5_PecIl5.js +0 -26
- package/dist/deadline-5_PecIl5.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/errors-BGs5NOrw.js.map +0 -1
- package/dist/errors-BMJm7KZZ.cjs +0 -3
- package/dist/errors-BMJm7KZZ.cjs.map +0 -1
- package/dist/identity-DXyV86o-.cjs +0 -2
- package/dist/identity-DXyV86o-.cjs.map +0 -1
- package/dist/identity-rpEyjvVg.js.map +0 -1
- package/dist/indexeddb-storage-BXaPVPyG.cjs +0 -2
- package/dist/indexeddb-storage-BXaPVPyG.cjs.map +0 -1
- package/dist/indexeddb-storage-Q9fDYlyn.js.map +0 -1
- package/dist/interactions-B8zjCjga.js.map +0 -1
- package/dist/interactions-BAGRmtrv.cjs.map +0 -1
- package/dist/journey-BGSyy8Es.cjs +0 -2
- package/dist/journey-BGSyy8Es.cjs.map +0 -1
- package/dist/journey-_dQQ1eMP.js.map +0 -1
- package/dist/long-frames-B0tKuChx.js.map +0 -1
- package/dist/long-frames-Cq2LgNnp.cjs.map +0 -1
- package/dist/network-C6kJbW6K.cjs +0 -2
- package/dist/network-C6kJbW6K.cjs.map +0 -1
- package/dist/network-CMnEvGJB.js.map +0 -1
- package/dist/platform-DNOJjpOm.cjs +0 -2
- package/dist/platform-DNOJjpOm.cjs.map +0 -1
- package/dist/platform-j0uMPwHi.js +0 -48
- package/dist/platform-j0uMPwHi.js.map +0 -1
- package/dist/remote-rules-DgoBJxZL.cjs +0 -2
- package/dist/remote-rules-DgoBJxZL.cjs.map +0 -1
- package/dist/remote-rules-UggoZqfP.js +0 -86
- package/dist/remote-rules-UggoZqfP.js.map +0 -1
- package/dist/sampling-BLMD8EGM.js +0 -64
- package/dist/sampling-BLMD8EGM.js.map +0 -1
- package/dist/sampling-MthcVXXU.cjs +0 -2
- package/dist/sampling-MthcVXXU.cjs.map +0 -1
- package/dist/sender--0_VzPbN.js.map +0 -1
- package/dist/sender-SPGMqZjD.cjs +0 -3
- package/dist/sender-SPGMqZjD.cjs.map +0 -1
- package/dist/storm-CTy1dfvs.cjs +0 -2
- package/dist/storm-CTy1dfvs.cjs.map +0 -1
- package/dist/storm-knaj4GUH.js +0 -10
- package/dist/storm-knaj4GUH.js.map +0 -1
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { OneLogger } from "../core/logger";
|
|
2
|
+
import type { Counter, Histogram, HistogramOptions, InstrumentOptions } from "./metric";
|
|
3
|
+
/** Tools that the library gives to a capture plugin. */
|
|
4
|
+
export interface PluginContext {
|
|
5
|
+
/** Logger for the namespace `uiobs.capture.<plugin name>`. */
|
|
6
|
+
logger: OneLogger;
|
|
7
|
+
/**
|
|
8
|
+
* Gives a counter. It is the same as `counter()`.
|
|
9
|
+
* @param name Metric name.
|
|
10
|
+
* @param options Unit of the values.
|
|
11
|
+
* @returns The counter.
|
|
12
|
+
*/
|
|
13
|
+
counter(name: string, options?: InstrumentOptions): Counter;
|
|
14
|
+
/**
|
|
15
|
+
* Gives a histogram. It is the same as `histogram()`.
|
|
16
|
+
* @param name Metric name.
|
|
17
|
+
* @param options Unit of the values and the bucket boundaries.
|
|
18
|
+
* @returns The histogram.
|
|
19
|
+
*/
|
|
20
|
+
histogram(name: string, options?: HistogramOptions): Histogram;
|
|
21
|
+
/**
|
|
22
|
+
* Adds a breadcrumb with the category `custom`. It is the same as `addBreadcrumb()`.
|
|
23
|
+
* @param message Description of the event.
|
|
24
|
+
* @param data Optional metadata.
|
|
25
|
+
*/
|
|
26
|
+
addBreadcrumb(message: string, data?: Record<string, unknown>): void;
|
|
27
|
+
/**
|
|
28
|
+
* Runs a function. The network capture does not record a request that the function starts
|
|
29
|
+
* synchronously, and does not add `traceparent` to it. Use it for the requests of the plugin.
|
|
30
|
+
* @param fn Function that starts the request.
|
|
31
|
+
* @returns The return value of the function.
|
|
32
|
+
*/
|
|
33
|
+
ownRequest<T>(fn: () => T): T;
|
|
34
|
+
}
|
|
35
|
+
/** Capture module from the app. The library installs it with the built-in capture modules. */
|
|
36
|
+
export interface CapturePlugin {
|
|
37
|
+
/** Name of the plugin. Its logger namespace and its diagnostic messages use it. */
|
|
38
|
+
readonly name: string;
|
|
39
|
+
/**
|
|
40
|
+
* Starts the capture. A later `configure()` that changes the capture section calls
|
|
41
|
+
* `uninstall()`, then calls `install()` again.
|
|
42
|
+
* @param ctx Tools of the plugin.
|
|
43
|
+
*/
|
|
44
|
+
install(ctx: PluginContext): void;
|
|
45
|
+
/** Stops the capture. Restore each function that the plugin replaced. */
|
|
46
|
+
uninstall(): void;
|
|
47
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Delivery state of this context. A forwarder reports only its own buffers. */
|
|
2
|
+
export interface DeliveryStats {
|
|
3
|
+
/** Records in a buffer of the library. No request carries them yet. */
|
|
4
|
+
pending: number;
|
|
5
|
+
/** Records in requests that have not completed. */
|
|
6
|
+
inFlight: number;
|
|
7
|
+
/** Batches in storage that wait for a retry. */
|
|
8
|
+
stored: number;
|
|
9
|
+
/** Epoch time in milliseconds when the server last accepted a batch, or null. */
|
|
10
|
+
lastSendAt: number | null;
|
|
11
|
+
}
|
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
import { r as e } from "./error-like-Ywo5uRHo.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { n as t, t as n } from "./library-request-ChCar5F8.js";
|
|
3
|
+
import { i as r } from "./platform-4yYjMD-B.js";
|
|
4
4
|
import { t as i } from "./patch-CCWfuEY7.js";
|
|
5
|
-
|
|
6
|
-
function a(e, t) {
|
|
7
|
-
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
8
|
-
}
|
|
9
|
-
//#endregion
|
|
5
|
+
import { t as a } from "./types-BR9t_w28.js";
|
|
10
6
|
//#region src/capture/network.ts
|
|
11
7
|
var o = 1e3, s = {
|
|
12
8
|
name: "http.client.request.duration",
|
|
@@ -81,7 +77,7 @@ var m = class {
|
|
|
81
77
|
}
|
|
82
78
|
}
|
|
83
79
|
ignored(e) {
|
|
84
|
-
return
|
|
80
|
+
return n() || a(e, this.ctx.config.capture.ignoreUrls);
|
|
85
81
|
}
|
|
86
82
|
propagates(e) {
|
|
87
83
|
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
@@ -91,8 +87,8 @@ var m = class {
|
|
|
91
87
|
}
|
|
92
88
|
installFetch() {
|
|
93
89
|
if (typeof globalThis.fetch != "function") return;
|
|
94
|
-
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r
|
|
95
|
-
this.record(e, t, n, r,
|
|
90
|
+
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r) => {
|
|
91
|
+
this.record(e.method, e.url, t, n, r, e.span);
|
|
96
92
|
}, r = i(globalThis, "fetch", (r) => {
|
|
97
93
|
let i = r.bind(globalThis);
|
|
98
94
|
return async function(r, a) {
|
|
@@ -101,9 +97,9 @@ var m = class {
|
|
|
101
97
|
let s = performance.now();
|
|
102
98
|
try {
|
|
103
99
|
let e = await i(o.input, o.init);
|
|
104
|
-
return n(o
|
|
100
|
+
return n(o, e.status, performance.now() - s, void 0), e;
|
|
105
101
|
} catch (e) {
|
|
106
|
-
throw n(o
|
|
102
|
+
throw n(o, 0, performance.now() - s, e), e;
|
|
107
103
|
}
|
|
108
104
|
};
|
|
109
105
|
});
|
|
@@ -129,19 +125,20 @@ var m = class {
|
|
|
129
125
|
};
|
|
130
126
|
if (!n.propagate || f(e)) return a;
|
|
131
127
|
try {
|
|
132
|
-
let n =
|
|
128
|
+
let n = this.ctx.tracing.request(), r = Object.entries(n.headers);
|
|
133
129
|
if (e instanceof Request) {
|
|
134
130
|
let t = new Headers(e.headers);
|
|
135
|
-
for (let [e,
|
|
131
|
+
for (let [e, n] of r) t.set(e, n);
|
|
136
132
|
a.input = new Request(e, { headers: t });
|
|
137
133
|
} else {
|
|
138
134
|
let e = new Headers(t?.headers);
|
|
139
|
-
for (let [t,
|
|
135
|
+
for (let [t, n] of r) e.set(t, n);
|
|
140
136
|
a.init = {
|
|
141
137
|
...t,
|
|
142
138
|
headers: e
|
|
143
139
|
};
|
|
144
140
|
}
|
|
141
|
+
a.span = n.span;
|
|
145
142
|
} catch (n) {
|
|
146
143
|
a.input = e, a.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);
|
|
147
144
|
}
|
|
@@ -149,8 +146,8 @@ var m = class {
|
|
|
149
146
|
}
|
|
150
147
|
installXhr() {
|
|
151
148
|
if (typeof XMLHttpRequest > "u") return;
|
|
152
|
-
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n
|
|
153
|
-
this.record(e, t, n,
|
|
149
|
+
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n) => {
|
|
150
|
+
this.record(e.method, e.url, t, n, void 0, e.span);
|
|
154
151
|
}, o = l(), s = i(o, "open", (n) => function(r, i, ...a) {
|
|
155
152
|
e && t.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
156
153
|
this.__uiobs = {
|
|
@@ -167,45 +164,62 @@ var m = class {
|
|
|
167
164
|
let s = e ? this.__uiobs : void 0;
|
|
168
165
|
s && t.diagnostics.guard("capture.record_failed", `The library could not record ${s.method} ${s.url}.`, () => {
|
|
169
166
|
n(s.url) || (s.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
170
|
-
a(s
|
|
171
|
-
}), r(s.url) && h(this, s.url, t));
|
|
167
|
+
a(s, this.status, performance.now() - s.startedAt);
|
|
168
|
+
}, { once: !0 }), r(s.url) && (s.span = h(this, s.url, t)));
|
|
172
169
|
}), i.apply(this, o);
|
|
173
170
|
});
|
|
174
171
|
this.restores.push(() => {
|
|
175
172
|
e = !1, s(), c();
|
|
176
173
|
});
|
|
177
174
|
}
|
|
178
|
-
record(e,
|
|
179
|
-
let
|
|
180
|
-
!this.warnedTransport &&
|
|
181
|
-
let t = c(e,
|
|
175
|
+
record(e, n, i, a, l, u) {
|
|
176
|
+
let d = r(n, this.ctx.config.capture.fullUrls);
|
|
177
|
+
!this.warnedTransport && t() && (this.warnedTransport = !0, this.ctx.diagnostics.report("capture.transport_request", `Network capture saw ${e} ${d} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)), this.ctx.config.capture.httpMetrics && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the duration of ${e} ${d}.`, () => {
|
|
178
|
+
let t = c(e, n, i, l);
|
|
182
179
|
this.ctx.recordMetric(s, a / o, t);
|
|
183
|
-
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${
|
|
180
|
+
}), u && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the span of ${e} ${d}.`, () => {
|
|
181
|
+
let t = Date.now();
|
|
182
|
+
this.ctx.recordSpan({
|
|
183
|
+
...u,
|
|
184
|
+
name: e,
|
|
185
|
+
kind: "client",
|
|
186
|
+
startMs: t - a,
|
|
187
|
+
endMs: t,
|
|
188
|
+
error: i === 0 || i >= 400,
|
|
189
|
+
attributes: {
|
|
190
|
+
...c(e, n, i, l),
|
|
191
|
+
"url.full": d
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${d}.`, () => {
|
|
184
195
|
let t = Math.round(a);
|
|
185
196
|
this.ctx.breadcrumbs.push({
|
|
186
197
|
t: Date.now(),
|
|
187
198
|
category: "http",
|
|
188
|
-
message: `${e} ${
|
|
199
|
+
message: `${e} ${d} ${i === 0 ? "failed" : String(i)}`,
|
|
189
200
|
data: { durationMs: t }
|
|
190
201
|
});
|
|
191
202
|
let n = {
|
|
192
203
|
"http.request.method": e,
|
|
193
|
-
"url.full":
|
|
204
|
+
"url.full": d,
|
|
194
205
|
"http.response.status_code": i,
|
|
195
206
|
"http.duration_ms": t
|
|
196
207
|
};
|
|
197
|
-
i === 0 ? this.ctx.logger.error(`${e} ${
|
|
208
|
+
i === 0 ? this.ctx.logger.error(`${e} ${d} failed`, l, n) : i >= 400 ? this.ctx.logger.warn(`${e} ${d} returned ${String(i)}`, n) : this.ctx.logger.debug(`${e} ${d}`, n);
|
|
198
209
|
});
|
|
199
210
|
}
|
|
200
211
|
};
|
|
201
212
|
function h(e, t, n) {
|
|
202
213
|
try {
|
|
203
|
-
|
|
214
|
+
let t = n.tracing.request();
|
|
215
|
+
for (let [n, r] of Object.entries(t.headers)) e.setRequestHeader(n, r);
|
|
216
|
+
return t.span;
|
|
204
217
|
} catch (e) {
|
|
205
218
|
n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
|
|
219
|
+
return;
|
|
206
220
|
}
|
|
207
221
|
}
|
|
208
222
|
//#endregion
|
|
209
223
|
export { m as NetworkCapture };
|
|
210
224
|
|
|
211
|
-
//# sourceMappingURL=network-
|
|
225
|
+
//# sourceMappingURL=network-BsBZ6_-Q.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-BsBZ6_-Q.js","names":["isErrorLike","isTransportPending","isLibraryRequest","recordedUrl","patch","matchesAny","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","span","endMs","rounded"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\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 /** Client span that the traceparent names. */\n span?: ClientSpan;\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 /** Client span that the traceparent names. */\n span?: ClientSpan;\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 /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\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 = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(plan.method, plan.url, status, durationMs, error, plan.span);\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, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 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 trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.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\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\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 = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(meta.method, meta.url, status, durationMs, undefined, meta.span);\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 // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = 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 * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\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 = recordedUrl(target, this.ctx.config.capture.fullUrls);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\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 * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\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 return undefined;\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAMM,IAAgB,KAMhBC,IAA+B;CACnC,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAO;EAAM;EAAO;EAAM;EAAO;EAAK;EAAM;EAAK;EAAM;EAAG;EAAK;EAAG;EAAK;CAAE;AACxF;AAWA,SAASC,EACP,GACA,GACA,GACA,GACkB;CAElB,IAAMC,IAAO,OAAO,WAAa,MAAc,SAAS,OAAO,KAAA,GACzDC,IAA+B;EACnC,uBAAuBC;EACvB,kBAAkB,IAAI,IAAIC,GAAKH,CAAI,CAAC,CAAC;CACvC;CAEA,IAAII,MAAW,GAAG;EAEhB,IAAMC,IAAOd,EAAYe,CAAK,IAAIA,EAAM,OAAO;EAE/C,OADA,EAAW,gBAAgBD,MAAS,KAAK,WAAWA,GAC7CJ;CACT;CAOA,OALA,EAAW,+BAA+BG,GACtCA,KAAU,QACZ,EAAW,gBAAgB,OAAOA,CAAM,IAGnCH;AACT;AA0BA,SAASM,IAAyB;CAChC,OAAO,eAAe;AACxB;AAuBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAE,WAAQA;EAChB,IAAI,OAAON,KAAQ,UACjB,OAAOA;CAEX;CAGA,OAAO,OAAOM,CAAK;AACrB;AAQA,SAASC,EAAgB,GAAgB,GAAuC;CAC9E,IA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=require("./error-like-gGRx2s36.cjs"),t=require("./library-request-gMFOCNcn.cjs"),n=require("./platform-o7r1ocOu.cjs"),r=require("./patch-BX8KrPCT.cjs"),i=require("./types-C7WNpnG1.cjs");var a=1e3,o={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function s(t,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":t,"server.address":new URL(n,a).hostname};if(r===0){let t=e.r(i)?i.name:``;return o[`error.type`]=t===``?`_OTHER`:t,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function c(){return XMLHttpRequest.prototype}function l(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function u(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),f(n??`GET`)}function d(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function f(e){return typeof e==`string`?e.toUpperCase():String(e)}var p=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return t.t()||i.t(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;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);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,t=(e,t)=>this.prepareFetch(e,t),n=(e,t,n,r)=>{this.record(e.method,e.url,t,n,r,e.span)},i=r.t(globalThis,`fetch`,r=>{let i=r.bind(globalThis);return async function(r,a){let o=e?t(r,a):void 0;if(!o)return i(r,a);let s=performance.now();try{let e=await i(o.input,o.init);return n(o,e.status,performance.now()-s,void 0),e}catch(e){throw n(o,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=l(e);if(!this.ignored(n))return{method:u(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t};if(!n.propagate||d(e))return a;try{let n=this.ctx.tracing.request(),r=Object.entries(n.headers);if(e instanceof Request){let t=new Headers(e.headers);for(let[e,n]of r)t.set(e,n);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,n]of r)e.set(t,n);a.init={...t,headers:e}}a.span=n.span}catch(n){a.input=e,a.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)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n)=>{this.record(e.method,e.url,t,n,void 0,e.span)},o=c(),s=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:f(r),url:l(i),startedAt:0}}),n.apply(this,[r,i,...a])}),u=r.t(o,`send`,r=>function(...o){let s=e?this.__uiobs:void 0;s&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${s.method} ${s.url}.`,()=>{n(s.url)||(s.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{a(s,this.status,performance.now()-s.startedAt)},{once:!0}),i(s.url)&&(s.span=m(this,s.url,t)))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l,u){let d=n.i(r,this.ctx.config.capture.fullUrls);!this.warnedTransport&&t.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${d} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${d}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),u&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the span of ${e} ${d}.`,()=>{let t=Date.now();this.ctx.recordSpan({...u,name:e,kind:`client`,startMs:t-c,endMs:t,error:i===0||i>=400,attributes:{...s(e,r,i,l),"url.full":d}})}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${d}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${d} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":d,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${d} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${d} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${d}`,n)})}};function m(e,t,n){try{let t=n.tracing.request();for(let[n,r]of Object.entries(t.headers))e.setRequestHeader(n,r);return t.span}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e);return}}exports.NetworkCapture=p;
|
|
2
|
+
//# sourceMappingURL=network-_4csBGBM.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-_4csBGBM.cjs","names":["isErrorLike","isLibraryRequest","matchesAny","patch","recordedUrl","isTransportPending","require_error_like","require_library_request","require_platform","require_patch","require_types","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","url","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","plan","durationMs","call","original","startedAt","response","read","trace","injected","headers","key","value","ignored","propagates","meta","proto","restoreOpen","rest","originalOpen","restoreSend","args","addTraceHeaders","originalSend","span","endMs","rounded","xhr"],"sources":["../src/capture/network.ts"],"sourcesContent":["// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { ClientSpan } from \"../utils/tracing\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\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 /** Client span that the traceparent names. */\n span?: ClientSpan;\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 /** Client span that the traceparent names. */\n span?: ClientSpan;\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 /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\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 = (plan: FetchPlan, status: number, durationMs: number, error: unknown): void => {\n this.record(plan.method, plan.url, status, durationMs, error, plan.span);\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, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan, 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 trace = this.ctx.tracing.request();\n const injected = Object.entries(trace.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\n // Record the client span only for a request that carries its traceparent.\n plan.span = trace.span;\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 = (meta: XhrMeta, status: number, durationMs: number): void => {\n this.record(meta.method, meta.url, status, durationMs, undefined, meta.span);\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 // A reused XHR gets a new listener at each send. The old one must not fire again.\n this.addEventListener(\n \"loadend\",\n () => {\n record(meta, this.status, performance.now() - meta.startedAt);\n },\n { once: true },\n );\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n meta.span = 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 * @param span Client span that the traceparent of the request names.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n span?: ClientSpan,\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 = recordedUrl(target, this.ctx.config.capture.fullUrls);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n if (span) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the span of ${method} ${url}.`,\n () => {\n const endMs = Date.now();\n this.ctx.recordSpan({\n ...span,\n name: method,\n kind: \"client\",\n startMs: endMs - durationMs,\n endMs,\n error: status === 0 || status >= 400,\n attributes: { ...durationAttributes(method, target, status, error), \"url.full\": url },\n });\n },\n );\n }\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 * @returns The client span that the traceparent names, or undefined.\n */\nfunction addTraceHeaders(\n xhr: XMLHttpRequest,\n url: string,\n ctx: CaptureContext,\n): ClientSpan | undefined {\n try {\n const trace = ctx.tracing.request();\n for (const [key, value] of Object.entries(trace.headers)) {\n xhr.setRequestHeader(key, value);\n }\n return trace.span;\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 return undefined;\n }\n}\n"],"mappings":"kMAgBA,IAAMW,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIC,EAAKH,CAAI,CAAC,CAAC,QACvC,EAEA,GAAII,IAAW,EAAG,CAEhB,IAAMC,EAAOnB,EAAAA,EAAYoB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS,GAAK,SAAWA,EAC7CJ,CACT,CAOA,MALA,GAAW,6BAA+BG,EACtCA,GAAU,MACZ,EAAW,cAAgB,OAAOA,CAAM,GAGnCH,CACT,CA0BA,SAASM,GAAyB,CAChC,OAAO,eAAe,SACxB,CAuBA,SAASC,EAAQ,EAAwB,CACvC,GAAI,OAAOC,GAAU,SACnB,OAAOA,EAGT,GAAIA,aAAiB,IACnB,OAAOA,EAAM,KAGf,GAAI,OAAOA,GAAU,UAAYA,EAAgB,CAC/C,GAAM,CAAE,OAAQA,EAChB,GAAI,OAAON,GAAQ,SACjB,OAAOA,CAEX,CAGA,OAAO,OAAOM,CAAK,CACrB,CAQA,SAASC,EAAgB,EAAgB,EAAuC,CAC9E,IAAIC,EAAqBC,GAAM,OAM/B,OA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sources":["../src/utils/openfin.ts"],"sourcesContent":["// src/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":";AAsDA,SAAgBA,IAA8B;CAC5C,OAAQ,WAAiC;AAC3C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openfin-DtH2f7zX.cjs","names":["getFin"],"sources":["../src/utils/openfin.ts"],"sourcesContent":["// src/utils/openfin.ts\n//\n// Reads the optional OpenFin runtime API. The library does not import an OpenFin package. The\n// types list only the members that the library reads. Each member is optional, because a test, an\n// older runtime or OpenFin web can leave it out.\n\n/** The InterApplicationBus operations that the bus link uses. */\nexport interface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/** The members of fin.me that the library reads. */\nexport interface FinMe {\n /** True in an OpenFin view. */\n isView?: boolean;\n /** Identity of the window or view. */\n identity?: { uuid?: string; name?: string };\n /** Resolves the creation options of the window, with customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n /** Adds a window event listener. */\n on?: (event: string, listener: () => void) => void;\n /** Removes a window event listener. */\n removeListener?: (event: string, listener: () => void) => void;\n}\n\n/** The members of the OpenFin global that the library reads. */\nexport interface FinLike {\n /** The window or view of this document. */\n me?: FinMe;\n /** The message bus of the OpenFin runtime. */\n InterApplicationBus?: FinIab;\n}\n\n/**\n * Gives the OpenFin global.\n * @returns The fin global, or undefined outside OpenFin.\n */\nexport function getFin(): FinLike | undefined {\n return (globalThis as { fin?: FinLike }).fin;\n}\n"],"mappings":"AAsDA,SAAgBA,GAA8B,CAC5C,OAAQ,WAAiC,GAC3C"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { At as e, Tt as t, bt as n, ot as r, t as i } from "./constants-L_d5YvvQ.js";
|
|
2
|
+
import { t as a } from "./openfin-BwEN0uj4.js";
|
|
3
|
+
//#region src/utils/platform.ts
|
|
4
|
+
var o = null;
|
|
5
|
+
function s(e, t) {
|
|
6
|
+
let n = e[t];
|
|
7
|
+
return n !== void 0 && e instanceof n;
|
|
8
|
+
}
|
|
9
|
+
function c(t) {
|
|
10
|
+
if (o) return o;
|
|
11
|
+
let n = globalThis, r = n.navigator?.userAgent ?? "", i = "browser", c, d, f = !1, p = a()?.me;
|
|
12
|
+
return s(n, "ServiceWorkerGlobalScope") ? (i = "service_worker", f = !0) : s(n, "SharedWorkerGlobalScope") ? (i = "shared_worker", f = !0) : s(n, "WorkerGlobalScope") ? (i = "web_worker", f = !0) : p === void 0 ? n.Capacitor !== void 0 || n.Ionic !== void 0 ? i = "ionic" : n.cordova !== void 0 || l(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.", () => {
|
|
13
|
+
let e = p.identity;
|
|
14
|
+
c = e?.uuid, d = e?.name;
|
|
15
|
+
})), o = {
|
|
16
|
+
platform: i,
|
|
17
|
+
openfinUuid: c,
|
|
18
|
+
openfinName: d,
|
|
19
|
+
userAgent: r,
|
|
20
|
+
isWorker: f,
|
|
21
|
+
isTopLevelDocument: u(t)
|
|
22
|
+
}, o;
|
|
23
|
+
}
|
|
24
|
+
function l(e) {
|
|
25
|
+
return i.test(e) ? !0 : (r.test(e) || n.test(e) && t.test(e)) && e.includes("AppleWebKit") && !e.includes("Safari/");
|
|
26
|
+
}
|
|
27
|
+
function u(e) {
|
|
28
|
+
if (typeof window > "u") return !1;
|
|
29
|
+
try {
|
|
30
|
+
return window.self === window.top;
|
|
31
|
+
} catch {
|
|
32
|
+
return e.count("platform.api_blocked"), !1;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function d(e) {
|
|
36
|
+
try {
|
|
37
|
+
return typeof location < "u" ? location.href : "";
|
|
38
|
+
} catch {
|
|
39
|
+
return e.count("platform.api_blocked"), "";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
var f = /^([a-z][a-z\d+.-]*:\/\/)[^/?#]*@/i;
|
|
43
|
+
function p(e, t) {
|
|
44
|
+
let n = e.replace(f, "$1");
|
|
45
|
+
return t ? n : m(n);
|
|
46
|
+
}
|
|
47
|
+
function m(e) {
|
|
48
|
+
let t = e.search(/[?#]/);
|
|
49
|
+
return t === -1 ? e : e.slice(0, t);
|
|
50
|
+
}
|
|
51
|
+
function h() {
|
|
52
|
+
return globalThis.navigator?.onLine !== !1;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { p as i, c as n, h as r, d as t };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=platform-4yYjMD-B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-4yYjMD-B.js","names":["OPENFIN_UA_PATTERN","MOBILE_UA_PATTERN","MACINTOSH_UA_PATTERN","IOS_DEVICE_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","getFin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","USER_INFO_PATTERN","recordedUrl","bare","url","fullUrls","stripUrlQuery","cut","isOnline"],"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\";\nimport { getFin } from \"./openfin\";\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/**\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 = getFin()?.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/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @returns The URL to record.\n */\nexport function recordedUrl(url: string, fullUrls: boolean): string {\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\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/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;;AAkDA,IAAIM,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAOA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAAQZ,EAAO,CAAC,EAAE;CAkCxB,OAhCIE,EAAcE,GAAG,0BAA0B,KAC7C,IAAW,kBACX,IAAW,MACFF,EAAcE,GAAG,yBAAyB,KACnD,IAAW,iBACX,IAAW,MACFF,EAAcE,GAAG,mBAAmB,KAC7C,IAAW,cACX,IAAW,MACFQ,MAAU,KAAA,IAOVR,EAAE,cAAc,KAAA,KAAaA,EAAE,UAAU,KAAA,IAClD,IAAW,UACFA,EAAE,YAAY,KAAA,KAAaS,EAAUN,CAAE,IAChD,IAAW,mBACF,OAAO,WAAa,OAAe,OAAO,UAAY,QAC/D,IAAW,WAXX,IAAWZ,EAAmB,KAAKY,CAAE,IAAI,YAAY,eACrDO,EAAY,MAAM,uBAAuB,qDAAqD;EAC5F,IAAMC,IAAWH,EAAM;EAEvB,AADA,IAAcG,GAAU,MACxB,IAAcA,GAAU;CAC1B,CAAC,IASH,IAAS;EACP;EACA;EACA;EACA,WAAWR;EACX;EACA,oBAAoBS,EAAWF,CAAW;CAC5C,GACOb;AACT;AAOA,SAASY,EAAU,GAAqB;CAMtC,OALId,EAA2B,KAAKQ,CAAE,IAC7B,MAGPT,EAAsB,KAAKS,CAAE,KAAMV,EAAqB,KAAKU,CAAE,KAAKX,EAAkB,KAAKW,CAAE,MACjFA,EAAG,SAAA,aAAwB,KAAK,CAACA,EAAG,SAAA,SAAwB;AAC5E;AAOA,SAAgBS,EAAW,GAAmC;CAC5D,IAAI,OAAO,SAAW,KACpB,OAAO;CAET,IAAI;EACF,OAAO,OAAO,SAAS,OAAO;CAChC,QAAQ;EAGN,OADAF,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAOA,SAAgBG,EAAW,GAAkC;CAC3D,IAAI;EACF,OAAO,OAAO,WAAa,MAAc,SAAS,OAAO;CAC3D,QAAQ;EAGN,OADAH,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAGA,IAAMI,IAAoB;AAS1B,SAAgBC,EAAY,GAAa,GAA2B;CAClE,IAAMC,IAAOC,EAAI,QAAQH,GAAmB,IAAI;CAChD,OAAOI,IAAWF,IAAOG,EAAcH,CAAI;AAC7C;AAQA,SAAgBG,EAAc,GAAqB;CACjD,IAAMC,IAAMH,EAAI,OAAO,MAAM;CAE7B,OAAOG,MAAQ,KAAKH,IAAMA,EAAI,MAAM,GAAGG,CAAG;AAC5C;AAMA,SAAgBC,IAAoB;CAClC,OAAQ,WAAoD,WAAW,WAAW;AACpF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-BgRS6MB0.cjs"),t=require("./openfin-DtH2f7zX.cjs");var n=null;function r(e,t){let n=e[t];return n!==void 0&&e instanceof n}function i(i){if(n)return n;let s=globalThis,c=s.navigator?.userAgent??``,l=`browser`,u,d,f=!1,p=t.t()?.me;return r(s,`ServiceWorkerGlobalScope`)?(l=`service_worker`,f=!0):r(s,`SharedWorkerGlobalScope`)?(l=`shared_worker`,f=!0):r(s,`WorkerGlobalScope`)?(l=`web_worker`,f=!0):p===void 0?s.Capacitor!==void 0||s.Ionic!==void 0?l=`ionic`:s.cordova!==void 0||a(c)?l=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(l=`node`):(l=e.At.test(c)?`openfin`:`openfin_web`,i.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=p.identity;u=e?.uuid,d=e?.name})),n={platform:l,openfinUuid:u,openfinName:d,userAgent:c,isWorker:f,isTopLevelDocument:o(i)},n}function a(t){return e.t.test(t)?!0:(e.ot.test(t)||e.bt.test(t)&&e.Tt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function o(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function s(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}var c=/^([a-z][a-z\d+.-]*:\/\/)[^/?#]*@/i;function l(e,t){let n=e.replace(c,`$1`);return t?n:u(n)}function u(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function d(){return globalThis.navigator?.onLine!==!1}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
+
//# sourceMappingURL=platform-o7r1ocOu.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-o7r1ocOu.cjs","names":["getFin","OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","require_openfin","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","USER_INFO_PATTERN","recordedUrl","bare","url","fullUrls","stripUrlQuery","cut","isOnline"],"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\";\nimport { getFin } from \"./openfin\";\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/**\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 = getFin()?.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/** Matches the user info of an absolute URL, for example \"user:pass@\". */\nconst USER_INFO_PATTERN = /^([a-z][a-z\\d+.-]*:\\/\\/)[^/?#]*@/i;\n\n/**\n * Gives the form of a URL that the library records. It always removes the user info, which is a\n * credential. Without fullUrls, it also removes the query and the fragment.\n * @param url Absolute or relative URL.\n * @param fullUrls Value of `capture.fullUrls`.\n * @returns The URL to record.\n */\nexport function recordedUrl(url: string, fullUrls: boolean): string {\n const bare = url.replace(USER_INFO_PATTERN, \"$1\");\n return fullUrls ? bare : stripUrlQuery(bare);\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/**\n * Tests if the browser can reach the network. A host without navigator.onLine counts as online.\n * @returns False only when navigator.onLine is false.\n */\nexport function isOnline(): boolean {\n return (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine !== false;\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"gFAkDA,IAAIQ,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAOA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAOA,EAET,IAAMG,EAAI,WAEJG,EAAMH,EAAE,WAAqC,WAAa,GAC5DI,EAAyB,UACzBC,EACAC,EACAC,EAAW,GAETC,EAAQnB,EAAAA,EAAO,CAAC,EAAE,GAkCxB,OAhCIS,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,EAAWb,EAAAA,GAAmB,KAAKa,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,OALIlB,EAAAA,EAA2B,KAAKY,CAAE,EAC7B,IAGPX,EAAAA,GAAsB,KAAKW,CAAE,GAAMV,EAAAA,GAAqB,KAAKU,CAAE,GAAKT,EAAAA,GAAkB,KAAKS,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,CAGA,IAAMI,EAAoB,oCAS1B,SAAgBC,EAAY,EAAa,EAA2B,CAClE,IAAMC,EAAOC,EAAI,QAAQH,EAAmB,IAAI,EAChD,OAAOI,EAAWF,EAAOG,EAAcH,CAAI,CAC7C,CAQA,SAAgBG,EAAc,EAAqB,CACjD,IAAMC,EAAMH,EAAI,OAAO,MAAM,EAE7B,OAAOG,IAAQ,GAAKH,EAAMA,EAAI,MAAM,EAAGG,CAAG,CAC5C,CAMA,SAAgBC,GAAoB,CAClC,OAAQ,WAAoD,WAAW,SAAW,EACpF"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { Ft as e, It as t, pt as n } from "./constants-L_d5YvvQ.js";
|
|
2
|
+
import { n as r, r as i, u as a } from "./sampling-nYIWP_vP.js";
|
|
3
|
+
//#region src/core/remote-sampling.ts
|
|
4
|
+
var o = class {
|
|
5
|
+
config;
|
|
6
|
+
rules = null;
|
|
7
|
+
receivedAt = 0;
|
|
8
|
+
until = 0;
|
|
9
|
+
constructor(e) {
|
|
10
|
+
this.config = e;
|
|
11
|
+
}
|
|
12
|
+
apply(e) {
|
|
13
|
+
if (!e) {
|
|
14
|
+
this.rules = null;
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
let t = Date.now();
|
|
18
|
+
this.rules = e.rules, this.receivedAt = t, this.until = t + e.ttlMs;
|
|
19
|
+
}
|
|
20
|
+
current() {
|
|
21
|
+
if (!this.rules) return null;
|
|
22
|
+
let e = Date.now();
|
|
23
|
+
return !this.config.sampling.remote || e < this.receivedAt || e >= this.until ? (this.rules = null, null) : this.rules;
|
|
24
|
+
}
|
|
25
|
+
minLevelFor(e) {
|
|
26
|
+
let t = r(e, this.config), a = this.current(), o = i(e, a?.minLevels ?? {})?.value ?? a?.minLevel;
|
|
27
|
+
return o !== void 0 && n[o] < n[t] ? o : t;
|
|
28
|
+
}
|
|
29
|
+
wire() {
|
|
30
|
+
let e = this.current();
|
|
31
|
+
return e ? {
|
|
32
|
+
...e,
|
|
33
|
+
v: 1,
|
|
34
|
+
ttlMs: this.until - Date.now()
|
|
35
|
+
} : null;
|
|
36
|
+
}
|
|
37
|
+
}, s = class extends Error {};
|
|
38
|
+
function c(e) {
|
|
39
|
+
return typeof e == "number" && e >= 0 && e <= 1;
|
|
40
|
+
}
|
|
41
|
+
function l(t) {
|
|
42
|
+
if (t.length > 4096) throw new s(`The header is longer than ${String(e)} characters.`);
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(t);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new s("The header is not valid JSON.");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function u(e) {
|
|
50
|
+
if (e === void 0) return {};
|
|
51
|
+
let t = "rates must be an object with at most 100 rates from 0 to 1.";
|
|
52
|
+
if (!a(e)) throw new s(t);
|
|
53
|
+
let n = Object.entries(e);
|
|
54
|
+
if (n.length > 100 || !n.every(([, e]) => c(e))) throw new s(t);
|
|
55
|
+
return Object.fromEntries(n);
|
|
56
|
+
}
|
|
57
|
+
function d(e) {
|
|
58
|
+
let t = "minLevels must be an object with at most 100 level names.";
|
|
59
|
+
if (!a(e)) throw new s(t);
|
|
60
|
+
let r = Object.entries(e), i = r.every(([, e]) => typeof e == "string" && Object.hasOwn(n, e));
|
|
61
|
+
if (r.length > 100 || !i) throw new s(t);
|
|
62
|
+
return Object.fromEntries(r);
|
|
63
|
+
}
|
|
64
|
+
function f(e) {
|
|
65
|
+
if (!a(e)) throw new s("The rules must be an object.");
|
|
66
|
+
if (e.v !== 1) throw new s("The version must be 1.");
|
|
67
|
+
let { ttlMs: r, defaultRate: i, minLevel: o } = e;
|
|
68
|
+
if (typeof r != "number" || !(r > 0 && r <= 36e5)) throw new s(`ttlMs must be a number more than 0 and at most ${String(t)}.`);
|
|
69
|
+
if (i !== void 0 && !c(i)) throw new s("defaultRate must be a number from 0 to 1.");
|
|
70
|
+
if (o !== void 0 && !(typeof o == "string" && Object.hasOwn(n, o))) throw new s("minLevel must be a level name, for example DEBUG.");
|
|
71
|
+
let l = { rates: u(e.rates) };
|
|
72
|
+
return i !== void 0 && (l.defaultRate = i), o !== void 0 && (l.minLevel = o), e.minLevels !== void 0 && (l.minLevels = d(e.minLevels)), {
|
|
73
|
+
rules: l,
|
|
74
|
+
ttlMs: r
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function p(e, t) {
|
|
78
|
+
try {
|
|
79
|
+
return f(typeof e == "string" ? l(e) : e);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
let n = e instanceof s ? ` ${e.message}` : "";
|
|
82
|
+
return t.report("config.invalid", `The library ignores the sampling rules from the server.${n}`, void 0, e), null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function m(e, t, n) {
|
|
86
|
+
n && (e.sampling ??= new o(t)), e.sampling?.apply(n);
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { p as n, m as t };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=remote-rules-1KqfVBIu.js.map
|