@utk09/ui-observability 0.9.2 → 0.9.3
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 +6 -0
- package/dist/batch-D5qvsMQ_.cjs +2 -0
- package/dist/batch-D5qvsMQ_.cjs.map +1 -0
- package/dist/{batch-4xKzzSCj.js → batch-DDgxg16_.js} +7 -4
- package/dist/batch-DDgxg16_.js.map +1 -0
- package/dist/bus/bus.d.ts +0 -4
- package/dist/{bus-DrixwdiX.js → bus-C6RwKzPW.js} +59 -62
- package/dist/bus-C6RwKzPW.js.map +1 -0
- package/dist/bus-WPVDFw2y.cjs +2 -0
- package/dist/bus-WPVDFw2y.cjs.map +1 -0
- package/dist/capture/storm.d.ts +2 -7
- package/dist/{console-ChfuJlf9.cjs → console-BSusX_M-.cjs} +2 -2
- package/dist/{console-ChfuJlf9.cjs.map → console-BSusX_M-.cjs.map} +1 -1
- package/dist/{console-B3vGRW5p.js → console-Dv5GfaNn.js} +3 -3
- package/dist/{console-B3vGRW5p.js.map → console-Dv5GfaNn.js.map} +1 -1
- package/dist/{constants-Be83LICb.cjs → constants-Cb92egPS.cjs} +2 -2
- package/dist/constants-Cb92egPS.cjs.map +1 -0
- package/dist/{constants-CQ_D7jIW.js → constants-DhH6VI5a.js} +2 -2
- package/dist/constants-DhH6VI5a.js.map +1 -0
- package/dist/constants.d.ts +2 -3
- package/dist/core/breadcrumbs.d.ts +1 -3
- package/dist/core/context.d.ts +0 -8
- package/dist/core/diagnostics.d.ts +0 -2
- package/dist/core/sampling.d.ts +1 -3
- package/dist/deadline-CUrH0Hd8.cjs +2 -0
- package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
- package/dist/deadline-DeqXEliN.js +31 -0
- package/dist/deadline-DeqXEliN.js.map +1 -0
- package/dist/{errors-BGs5NOrw.js → errors-DCZWcHkd.js} +4 -4
- package/dist/{errors-BGs5NOrw.js.map → errors-DCZWcHkd.js.map} +1 -1
- package/dist/{errors-BMJm7KZZ.cjs → errors-ERu-su8m.cjs} +3 -3
- package/dist/{errors-BMJm7KZZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
- 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-DXyV86o-.cjs → identity-C1WLItSl.cjs} +2 -2
- package/dist/{identity-DXyV86o-.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
- package/dist/{identity-rpEyjvVg.js → identity-Di-QXGCC.js} +2 -2
- package/dist/{identity-rpEyjvVg.js.map → identity-Di-QXGCC.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +224 -236
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
- package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
- package/dist/{indexeddb-storage-Q9fDYlyn.js → indexeddb-storage-T9YIYVYC.js} +39 -50
- package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
- package/dist/{interactions-B8zjCjga.js → interactions-BLH_tX87.js} +2 -2
- package/dist/{interactions-B8zjCjga.js.map → interactions-BLH_tX87.js.map} +1 -1
- package/dist/{interactions-BAGRmtrv.cjs → interactions-_hfOerfC.cjs} +2 -2
- package/dist/{interactions-BAGRmtrv.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
- package/dist/journey-BRUj0hqD.cjs +2 -0
- package/dist/journey-BRUj0hqD.cjs.map +1 -0
- package/dist/{journey-_dQQ1eMP.js → journey-yALMEWF7.js} +26 -25
- package/dist/journey-yALMEWF7.js.map +1 -0
- package/dist/{library-request-BIG3Xpx3.cjs → library-request-BcAxuwsf.cjs} +2 -2
- package/dist/{library-request-BIG3Xpx3.cjs.map → library-request-BcAxuwsf.cjs.map} +1 -1
- package/dist/{library-request-DX6ev9oG.js → library-request-CQD4HUiP.js} +2 -2
- package/dist/{library-request-DX6ev9oG.js.map → library-request-CQD4HUiP.js.map} +1 -1
- package/dist/{long-frames-Cq2LgNnp.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
- package/dist/{long-frames-Cq2LgNnp.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
- package/dist/{long-frames-B0tKuChx.js → long-frames-DD_Um9_4.js} +3 -3
- package/dist/{long-frames-B0tKuChx.js.map → long-frames-DD_Um9_4.js.map} +1 -1
- package/dist/models/batch.d.ts +6 -0
- package/dist/{network-CMnEvGJB.js → network--GoE7_Or.js} +3 -3
- package/dist/{network-CMnEvGJB.js.map → network--GoE7_Or.js.map} +1 -1
- package/dist/{network-C6kJbW6K.cjs → network-DcuS2H1P.cjs} +2 -2
- package/dist/{network-C6kJbW6K.cjs.map → network-DcuS2H1P.cjs.map} +1 -1
- 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-j0uMPwHi.js → platform-GaM6h7XM.js} +25 -21
- package/dist/platform-GaM6h7XM.js.map +1 -0
- package/dist/platform-kIL5AZB7.cjs +2 -0
- package/dist/platform-kIL5AZB7.cjs.map +1 -0
- package/dist/{remote-rules-UggoZqfP.js → remote-rules-6ePq8CrI.js} +19 -21
- package/dist/remote-rules-6ePq8CrI.js.map +1 -0
- package/dist/remote-rules-CI3gbRCL.cjs +2 -0
- package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
- package/dist/sampling-C-M8p3FK.cjs +2 -0
- package/dist/sampling-C-M8p3FK.cjs.map +1 -0
- package/dist/sampling-Ud_WiuU9.js +65 -0
- package/dist/sampling-Ud_WiuU9.js.map +1 -0
- package/dist/{sanitize-BqzPc4Jg.cjs → sanitize--_e4oOPX.cjs} +2 -2
- package/dist/{sanitize-BqzPc4Jg.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
- package/dist/{sanitize-BNwgPj_B.js → sanitize-DP0xDPrt.js} +2 -2
- package/dist/{sanitize-BNwgPj_B.js.map → sanitize-DP0xDPrt.js.map} +1 -1
- package/dist/sender-BESHz6my.cjs +3 -0
- package/dist/sender-BESHz6my.cjs.map +1 -0
- package/dist/{sender--0_VzPbN.js → sender-BUBWLn5i.js} +202 -207
- package/dist/sender-BUBWLn5i.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-DhHGHhOc.cjs +2 -0
- package/dist/storm-DhHGHhOc.cjs.map +1 -0
- package/dist/storm-OD5J6Ylm.js +10 -0
- package/dist/storm-OD5J6Ylm.js.map +1 -0
- package/dist/utils/fixed-window.d.ts +15 -0
- package/dist/utils/guards.d.ts +6 -0
- package/dist/utils/openfin.d.ts +48 -0
- package/dist/utils/platform.d.ts +5 -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.map +0 -1
- 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/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/journey-BGSyy8Es.cjs +0 -2
- package/dist/journey-BGSyy8Es.cjs.map +0 -1
- package/dist/journey-_dQQ1eMP.js.map +0 -1
- package/dist/platform-DNOJjpOm.cjs +0 -2
- package/dist/platform-DNOJjpOm.cjs.map +0 -1
- 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.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
|
@@ -1,43 +1,44 @@
|
|
|
1
|
-
import { Tt as e, _ as t, b as n, ct as r, g as i, ot as a, st as o, v as s, wt as c, y as l } from "./constants-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { Tt as e, _ as t, b as n, ct as r, g as i, ot as a, st as o, v as s, wt as c, y as l } from "./constants-DhH6VI5a.js";
|
|
2
|
+
import { n as u, r as d } from "./deadline-DeqXEliN.js";
|
|
3
|
+
import { i as f, t as p } from "./identity-Di-QXGCC.js";
|
|
4
|
+
import { t as m } from "./openfin-BwEN0uj4.js";
|
|
4
5
|
//#region src/core/journey.ts
|
|
5
|
-
var
|
|
6
|
+
var h = {
|
|
6
7
|
maxAgeMs: a,
|
|
7
8
|
endOnOwnerClose: !1,
|
|
8
9
|
urlParam: r
|
|
9
10
|
};
|
|
10
|
-
function
|
|
11
|
+
function g(e, t) {
|
|
11
12
|
let n = Reflect.get(e, t);
|
|
12
13
|
return typeof n == "string" && n !== "" ? n : void 0;
|
|
13
14
|
}
|
|
14
|
-
function
|
|
15
|
+
function _(e, t) {
|
|
15
16
|
let n = Reflect.get(e, t);
|
|
16
17
|
return typeof n == "number" && Number.isFinite(n) ? n : void 0;
|
|
17
18
|
}
|
|
18
|
-
function
|
|
19
|
+
function v(e) {
|
|
19
20
|
if (typeof e != "object" || !e) return null;
|
|
20
|
-
let t =
|
|
21
|
+
let t = g(e, "id"), n = g(e, "name"), r = _(e, "startedAt");
|
|
21
22
|
return t === void 0 || n === void 0 || r === void 0 ? null : {
|
|
22
23
|
id: t,
|
|
23
24
|
name: n,
|
|
24
25
|
startedAt: r,
|
|
25
|
-
parentId:
|
|
26
|
-
ownerContextId:
|
|
26
|
+
parentId: g(e, "parentId"),
|
|
27
|
+
ownerContextId: g(e, "ownerContextId") ?? ""
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
+
function y(e) {
|
|
30
31
|
if (typeof e != "object" || !e) return null;
|
|
31
|
-
let t =
|
|
32
|
+
let t = g(e, "i"), n = g(e, "n");
|
|
32
33
|
return t === void 0 || n === void 0 ? null : {
|
|
33
34
|
id: t,
|
|
34
35
|
name: n,
|
|
35
|
-
startedAt:
|
|
36
|
+
startedAt: _(e, "s") ?? Date.now(),
|
|
36
37
|
parentId: void 0,
|
|
37
38
|
ownerContextId: ""
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
|
-
function
|
|
41
|
+
function b(e) {
|
|
41
42
|
let t = JSON.stringify({
|
|
42
43
|
i: e.id,
|
|
43
44
|
n: e.name.slice(0, 64),
|
|
@@ -46,7 +47,7 @@ function y(e) {
|
|
|
46
47
|
for (let e of r) i += String.fromCharCode(e);
|
|
47
48
|
return btoa(i).replace(l, "-").replace(n, "_").replace(s, "");
|
|
48
49
|
}
|
|
49
|
-
var
|
|
50
|
+
var x = class {
|
|
50
51
|
options;
|
|
51
52
|
diagnostics;
|
|
52
53
|
contextId;
|
|
@@ -54,7 +55,7 @@ var b = class {
|
|
|
54
55
|
stores;
|
|
55
56
|
journey = null;
|
|
56
57
|
expiryTimer = null;
|
|
57
|
-
constructor(e, t, n, r, i =
|
|
58
|
+
constructor(e, t, n, r, i = p) {
|
|
58
59
|
this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r, this.stores = i;
|
|
59
60
|
}
|
|
60
61
|
current() {
|
|
@@ -73,7 +74,7 @@ var b = class {
|
|
|
73
74
|
}
|
|
74
75
|
start(e, t = {}) {
|
|
75
76
|
let n = {
|
|
76
|
-
id: t.id ??
|
|
77
|
+
id: t.id ?? f(this.diagnostics),
|
|
77
78
|
name: e,
|
|
78
79
|
startedAt: Date.now(),
|
|
79
80
|
parentId: t.parent ? this.journey?.id : void 0,
|
|
@@ -91,7 +92,7 @@ var b = class {
|
|
|
91
92
|
getToken() {
|
|
92
93
|
let e = this.journey;
|
|
93
94
|
if (e === null) return;
|
|
94
|
-
let t =
|
|
95
|
+
let t = b(e);
|
|
95
96
|
if (t.length > 256) this.diagnostics.report("journey.token_too_large", "The journey token is larger than the size limit. The library does not issue it.", { length: t.length });
|
|
96
97
|
else return t;
|
|
97
98
|
}
|
|
@@ -112,7 +113,7 @@ var b = class {
|
|
|
112
113
|
this.clearTimer();
|
|
113
114
|
}
|
|
114
115
|
restore(e) {
|
|
115
|
-
let t =
|
|
116
|
+
let t = v(this.diagnostics.guard("storage.degraded", "The library could not parse the persisted journey.", () => JSON.parse(e)));
|
|
116
117
|
return t === null ? !1 : Date.now() - t.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "The library discarded a persisted journey older than maxAgeMs.", { name: t.name }), this.clearStored(), !1) : (this.setJourney(t), this.diagnostics.report("journey.adopted", `The library resumed the journey "${t.name}".`, {
|
|
117
118
|
source: "sessionStorage",
|
|
118
119
|
journeyId: t.id
|
|
@@ -121,7 +122,7 @@ var b = class {
|
|
|
121
122
|
decodeToken(e) {
|
|
122
123
|
return this.diagnostics.guard("config.invalid", "The library could not decode a seeded journey token.", () => {
|
|
123
124
|
let n = e.replace(i, "+").replace(t, "/"), r = (4 - n.length % 4) % 4, a = "=".repeat(r), o = Uint8Array.from(atob(n + a), (e) => e.charCodeAt(0));
|
|
124
|
-
return
|
|
125
|
+
return y(JSON.parse(new TextDecoder().decode(o)));
|
|
125
126
|
}) ?? null;
|
|
126
127
|
}
|
|
127
128
|
setJourney(e) {
|
|
@@ -131,7 +132,7 @@ var b = class {
|
|
|
131
132
|
let t = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), n = setTimeout(() => {
|
|
132
133
|
this.diagnostics.report("journey.expired", `The journey "${e.name}" reached maxAgeMs. The library ended it.`, { journeyId: e.id }), this.journey = null, this.expiryTimer = null, this.clearStored();
|
|
133
134
|
}, t);
|
|
134
|
-
this.expiryTimer = n,
|
|
135
|
+
this.expiryTimer = n, d(n);
|
|
135
136
|
}
|
|
136
137
|
clearStored() {
|
|
137
138
|
this.diagnostics.guard("storage.unavailable", "The library could not clear the persisted journey.", () => {
|
|
@@ -151,13 +152,13 @@ var b = class {
|
|
|
151
152
|
});
|
|
152
153
|
}
|
|
153
154
|
async readOpenFinToken() {
|
|
154
|
-
let t =
|
|
155
|
+
let t = m()?.me, n = t?.getOptions;
|
|
155
156
|
if (n === void 0) return null;
|
|
156
|
-
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () =>
|
|
157
|
+
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => u(n.call(t), e)))?.customData?.[c];
|
|
157
158
|
return typeof r == "string" ? r : null;
|
|
158
159
|
}
|
|
159
160
|
};
|
|
160
161
|
//#endregion
|
|
161
|
-
export {
|
|
162
|
+
export { x as n, v as r, h as t };
|
|
162
163
|
|
|
163
|
-
//# sourceMappingURL=journey-
|
|
164
|
+
//# sourceMappingURL=journey-yALMEWF7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journey-yALMEWF7.js","names":["OPENFIN_OPTIONS_TIMEOUT_MS","BASE64URL_UNDERSCORE_PATTERN","BASE64_SLASH_PATTERN","JOURNEY_URL_PARAM","BASE64URL_DASH_PATTERN","JOURNEY_MAX_AGE_MS","JOURNEY_STORAGE_KEY","BASE64_PADDING_PATTERN","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PLUS_PATTERN","withDeadline","unrefTimer","newId","BROWSER_STORES","getFin","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { getFin } from \"../utils/openfin\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = getFin()?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;;;AAuCA,IAAae,IAAkC;CAC7C,UAAUV;CACV,iBAAA;CACA,UAAUF;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7B,KAAK,cAAc;CAEvB;CAMA,eAAsC;EAWpC,OAVc,KAAK,YAAY,MAC7B,kBACA,oEAEM,OAAO,WAAa,MACf,OAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,KAAS;CAClB;CAMA,iBAA+B;EAC7B,KAAK,YAAY,MACf,wBACA,sEACM;GACJ,IAAMgD,IAAM,IAAI,IAAI,SAAS,IAAI;GAGjC,AAFAA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,GAE7C,QAAQ,aAAa,QAAQ,OAAO,IAAIA,EAAI,IAAI;EAClD,CACF;CACF;CAQA,MAAc,mBAA2C;EACvD,IAAMC,IAAKzC,EAAO,CAAC,EAAE,IACf0C,IAAaD,GAAI;EACvB,IAAIC,MAAe,KAAA,GACjB,OAAO;EAUT,IAAMb,KAAQ,MALQ,KAAK,YAAY,WACrC,uBACA,yDACMjC,EAAa8C,EAAW,KAAKD,CAAE,GAAGvD,CAA0B,CACpE,EAAA,EACuB,aAAaQ;EACpC,OAAO,OAAOmC,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=library-request-
|
|
1
|
+
const e=require("./constants-Cb92egPS.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.pt),n=Symbol.for(e.yn),r=globalThis,i=()=>r[n]??0;function a(e){return t.run(e)}function o(){return t.open()}async function s(e){r[n]=i()+1;try{return await e()}finally{r[n]=i()-1}}function c(){return i()>0}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=library-request-BcAxuwsf.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"library-request-
|
|
1
|
+
{"version":3,"file":"library-request-BcAxuwsf.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","require_constants","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":"4CAUA,IAAMI,uCAAQJ,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAGvCI,EAAQ,OAAO,IAAIH,EAAAA,EAAkB,EACrCI,EAAQ,WACRC,MAAwBD,EAAMD,IAAU,EAQ9C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOJ,EAAM,IAAIK,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAON,EAAM,KAAK,CACpB,CAQA,eAAsBO,EAAsB,EAA0C,CACpF,EAAMN,GAASE,EAAQ,EAAI,EAE3B,GAAI,CACF,OAAO,MAAME,EAAG,CAClB,QAAU,CACR,EAAMJ,GAASE,EAAQ,EAAI,CAC7B,CACF,CAMA,SAAgBK,GAA8B,CAC5C,OAAOL,EAAQ,EAAI,CACrB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { pt as e, yn as t } from "./constants-
|
|
1
|
+
import { pt as e, yn as t } from "./constants-DhH6VI5a.js";
|
|
2
2
|
import { t as n } from "./global-scope-dp2jADRl.js";
|
|
3
3
|
//#region src/utils/library-request.ts
|
|
4
4
|
var r = n(e), i = Symbol.for(t), a = globalThis, o = () => a[i] ?? 0;
|
|
@@ -22,4 +22,4 @@ function u() {
|
|
|
22
22
|
//#endregion
|
|
23
23
|
export { l as i, u as n, s as r, c as t };
|
|
24
24
|
|
|
25
|
-
//# sourceMappingURL=library-request-
|
|
25
|
+
//# sourceMappingURL=library-request-CQD4HUiP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"library-request-
|
|
1
|
+
{"version":3,"file":"library-request-CQD4HUiP.js","names":["LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","globalScope","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":";;;AAUA,IAAMG,IAAQD,EAAYF,CAAmB,GAGvCI,IAAQ,OAAO,IAAIH,CAAkB,GACrCI,IAAQ,YACRC,UAAwBD,EAAMD,MAAU;AAQ9C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOJ,EAAM,IAAIK,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAON,EAAM,KAAK;AACpB;AAQA,eAAsBO,EAAsB,GAA0C;CACpF,EAAMN,KAASE,EAAQ,IAAI;CAE3B,IAAI;EACF,OAAO,MAAME,EAAG;CAClB,UAAU;EACR,EAAMJ,KAASE,EAAQ,IAAI;CAC7B;AACF;AAMA,SAAgBK,IAA8B;CAC5C,OAAOL,EAAQ,IAAI;AACrB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./platform-
|
|
2
|
-
//# sourceMappingURL=long-frames-
|
|
1
|
+
const e=require("./platform-kIL5AZB7.cjs"),t=require("./storm-DhHGHhOc.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.i(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
|
|
2
|
+
//# sourceMappingURL=long-frames-D4Bm3Zkz.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"long-frames-
|
|
1
|
+
{"version":3,"file":"long-frames-D4Bm3Zkz.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5D,UAAA,IAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,KAAK,SACP,OAKF,GAAM,CAAE,QAAS,KAAK,IAChBC,EAAQ,CAACC,EAAK,WACpB,EAAK,WAAa,GAGlB,IAAMC,EACJ,OAAO,oBAAwB,IAC3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,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t } from "./storm-
|
|
1
|
+
import { i as e } from "./platform-GaM6h7XM.js";
|
|
2
|
+
import { t } from "./storm-OD5J6Ylm.js";
|
|
3
3
|
//#region src/capture/long-frames.ts
|
|
4
4
|
var n = ["long-animation-frame", "longtask"];
|
|
5
5
|
function r(e) {
|
|
@@ -62,4 +62,4 @@ var i = class {
|
|
|
62
62
|
//#endregion
|
|
63
63
|
export { i as LongFrameCapture };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=long-frames-
|
|
65
|
+
//# sourceMappingURL=long-frames-DD_Um9_4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"long-frames-
|
|
1
|
+
{"version":3,"file":"long-frames-DD_Um9_4.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY,KAAK,cAAc,GACpC,KAAK,WAAW,IAAI,qBAAqB,MAAS;GAChD,KAAK,IAAMK,KAASC,EAAK,WAAW,GAClC,KAAK,OAAOD,CAAK;EAErB,CAAC,GAGD,KAAK,SAAS,QAAQ;GAAE;GAAM,UAAUL;EAAM,CAAC;CACjD;CAGA,YAAkB;EAEhB,AADA,KAAK,UAAU,WAAW,GAC1B,KAAK,WAAW,KAAA;CAClB;CAMA,gBAAgC;EAC9B,IAAMO,IAAiB,KAAK,IAAI,OAAO,QAAQ;EAU/C,OARI,OAAOA,KAAU,YAAY,OAAO,SAASA,CAAK,KAAKA,KAAS,IAC3DA,KAGT,KAAK,IAAI,YAAY,OACnB,kBACA,mFACF,GACA;CACF;CAMA,OAAe,GAAyB;EACtC,IAAIF,EAAM,WAAW,KAAK,WACxB;EAGF,IAAM,EAAE,mBAAgB,KAAK;EAE7B,IAAI,CAACG,EAAc,KAAK,QAAA,IAAmCC,GAAa,aAAa,GACnF;EAGF,IAAMC,IAAW,KAAK,MAAML,EAAM,QAAQ,GACpCM,IAAiC,EAAE,cAAcN,EAAM,UAAU;EAEvE,AAAIA,EAAM,qBAAqB,KAAA,MAC7B,EAAM,uBAAuB,KAAK,MAAMA,EAAM,gBAAgB;EAGhE,IAAMT,IAASF,EAAcW,EAAM,OAAO,GAGpCO,KAAO,MACX,KAAK,IAAI,OAAO,QAAQ,WAAWL,IAAQf,EAAce,CAAK;EAEhE,IAAIX,GAAQ,SAAS;GAGnB,IAAM,EAAE,eAAYA;GACpB,EAAM,0BAA0BiB,EAAQ,SAAS,KAAK,IAAID,EAAIC,CAAO,IAAIA;EAC3E;EAWA,AATIjB,GAAQ,cACV,EAAM,yBAAyBgB,EAAIhB,EAAO,SAAS,IAGrD,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,cAAc,OAAOc,CAAQ,EAAE;EAC1C,CAAC,GACD,KAAK,IAAI,OAAO,UAAU,0BAA0BA,GAAU,MAAM,aAAaC,CAAK;CACxF;AACF"}
|
package/dist/models/batch.d.ts
CHANGED
|
@@ -46,3 +46,9 @@ export declare function attributeOf(record: LogRecord, key: string): unknown;
|
|
|
46
46
|
* @returns True for an action record.
|
|
47
47
|
*/
|
|
48
48
|
export declare function isActionRecord(record: LogRecord): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Returns the total record count of the batches.
|
|
51
|
+
* @param batches Batches to measure.
|
|
52
|
+
* @returns Total record count.
|
|
53
|
+
*/
|
|
54
|
+
export declare function countRecords(batches: readonly LogBatch[]): number;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as e } from "./error-like-Ywo5uRHo.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n, t as r } from "./library-request-
|
|
2
|
+
import { i as t } from "./platform-GaM6h7XM.js";
|
|
3
|
+
import { n, t as r } from "./library-request-CQD4HUiP.js";
|
|
4
4
|
import { t as i } from "./patch-CCWfuEY7.js";
|
|
5
5
|
//#region src/capture/types.ts
|
|
6
6
|
function a(e, t) {
|
|
@@ -208,4 +208,4 @@ function h(e, t, n) {
|
|
|
208
208
|
//#endregion
|
|
209
209
|
export { m as NetworkCapture };
|
|
210
210
|
|
|
211
|
-
//# sourceMappingURL=network
|
|
211
|
+
//# sourceMappingURL=network--GoE7_Or.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-CMnEvGJB.js","names":["isErrorLike","stripUrlQuery","isLibraryRequest","patch","matchesAny","url","patterns","pattern","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","durationMs","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","isTransportPending","rounded"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n /** Adds a value to a counter or a histogram of the runtime. */\n recordMetric: (def: InstrumentDef, value: number, attributes?: MetricAttributes) => void;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport 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 { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** 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}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** 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 = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // 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 // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;;AAmHA,SAAgBI,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;AC7GA,IAAMG,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,IAAIR,GAAKM,CAAI,CAAC,CAAC;CACvC;CAEA,IAAIG,MAAW,GAAG;EAEhB,IAAMC,IAAOf,EAAYgB,CAAK,IAAIA,EAAM,OAAO;EAE/C,OADA,EAAW,gBAAgBD,MAAS,KAAK,WAAWA,GAC7CH;CACT;CAOA,OALA,EAAW,+BAA+BE,GACtCA,KAAU,QACZ,EAAW,gBAAgB,OAAOA,CAAM,IAGnCF;AACT;AAwBA,SAASK,IAAyB;CAChC,OAAO,eAAe;AACxB;AAqBA,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,OAAOd,KAAQ,UACjB,OAAOA;CAEX;CAGA,OAAO,OAAOc,CAAK;AACrB;AAQA,SAASC,EAAgB,GAAgB,GAAuC;CAC9E,IAAIC,IAAqBC,GAAM;CAM/B,OAJID,MAAc,KAAA,KAAa,OAAOF,KAAU,YAA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;IACpE,MAAM,EAAE,YAAY2C,EAAQ;GAC9B,CAAC;GAED,IAAM7C,IAAa;IACjB,uBAAuBC;IACvB,YAAYR;IACZ,6BAA6BS;IAC7B,oBAAoB2C;GACtB;GAEA,AAAI3C,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGR,EAAI,UAAUW,GAAOJ,CAAU,IAGhEE,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGR,EAAI,YAAY,OAAOS,CAAM,KAAKF,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGC,EAAO,GAAGR,KAAOO,CAAU;EACtD,CACF;CACF;AACF;AAQA,SAAS0C,EAAgB,GAAqB,GAAa,GAA2B;CACpF,IAAI;EACF,KAAK,IAAM,CAACX,GAAKC,MAAU,OAAO,QAAQlB,EAAI,QAAQ,QAAQ,CAAC,GAC7D,EAAI,iBAAiBiB,GAAKC,CAAK;CAEnC,SAAS5B,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"network--GoE7_Or.js","names":["isErrorLike","stripUrlQuery","isLibraryRequest","patch","matchesAny","url","patterns","pattern","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","durationMs","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","isTransportPending","rounded"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n /** Adds a value to a counter or a histogram of the runtime. */\n recordMetric: (def: InstrumentDef, value: number, attributes?: MetricAttributes) => void;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport 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 { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** 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}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** 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 = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // 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 // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;;AAmHA,SAAgBI,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;AC7GA,IAAMG,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,IAAIR,GAAKM,CAAI,CAAC,CAAC;CACvC;CAEA,IAAIG,MAAW,GAAG;EAEhB,IAAMC,IAAOf,EAAYgB,CAAK,IAAIA,EAAM,OAAO;EAE/C,OADA,EAAW,gBAAgBD,MAAS,KAAK,WAAWA,GAC7CH;CACT;CAOA,OALA,EAAW,+BAA+BE,GACtCA,KAAU,QACZ,EAAW,gBAAgB,OAAOA,CAAM,IAGnCF;AACT;AAwBA,SAASK,IAAyB;CAChC,OAAO,eAAe;AACxB;AAqBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/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,EAAO,GAAGR,EAAI,UACxC;GACJ,IAAMoD,IAAU,KAAK,MAAMvB,CAAU;GAErC,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,GAAGrB,EAAO,GAAGR,EAAI,GAAGS,MAAW,IAAI,WAAW,OAAOA,CAAM;IACpE,MAAM,EAAE,YAAY2C,EAAQ;GAC9B,CAAC;GAED,IAAM7C,IAAa;IACjB,uBAAuBC;IACvB,YAAYR;IACZ,6BAA6BS;IAC7B,oBAAoB2C;GACtB;GAEA,AAAI3C,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGR,EAAI,UAAUW,GAAOJ,CAAU,IAGhEE,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGR,EAAI,YAAY,OAAOS,CAAM,KAAKF,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGC,EAAO,GAAGR,KAAOO,CAAU;EACtD,CACF;CACF;AACF;AAQA,SAAS0C,EAAgB,GAAqB,GAAa,GAA2B;CACpF,IAAI;EACF,KAAK,IAAM,CAACX,GAAKC,MAAU,OAAO,QAAQlB,EAAI,QAAQ,QAAQ,CAAC,GAC7D,EAAI,iBAAiBiB,GAAKC,CAAK;CAEnC,SAAS5B,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-
|
|
2
|
-
//# sourceMappingURL=network-
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-kIL5AZB7.cjs"),n=require("./library-request-BcAxuwsf.cjs"),r=require("./patch-BX8KrPCT.cjs");function i(e,t){return typeof e==`string`&&t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}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 n.t()||i(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,i)=>{this.record(e,t,n,r,i)},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.method,o.url,e.status,performance.now()-s,void 0),e}catch(e){throw n(o.method,o.url,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=Object.entries(this.ctx.tracing.headers());if(e instanceof Request){let t=new Headers(e.headers);for(let[e,r]of n)t.set(e,r);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,r]of n)e.set(t,r);a.init={...t,headers:e}}}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,r)=>{this.record(e,t,n,r,void 0)},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.method,s.url,this.status,performance.now()-s.startedAt)}),i(s.url)&&m(this,s.url,t))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l){let u=this.ctx.config.capture.fullUrls?r:t.i(r);!this.warnedTransport&&n.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${u} 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} ${u}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${u}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${u} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":u,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${u} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${u} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${u}`,n)})}};function m(e,t,n){try{for(let[t,r]of Object.entries(n.tracing.headers()))e.setRequestHeader(t,r)}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e)}}exports.NetworkCapture=p;
|
|
2
|
+
//# sourceMappingURL=network-DcuS2H1P.cjs.map
|