@utk09/ui-observability 0.9.0 → 0.9.1
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 +36 -0
- package/README.md +56 -36
- package/dist/batch-DEK4bv9N.js +31 -0
- package/dist/batch-DEK4bv9N.js.map +1 -0
- package/dist/batch-DEVFs28i.cjs +2 -0
- package/dist/batch-DEVFs28i.cjs.map +1 -0
- package/dist/{bus-CtJWf9QN.cjs → bus-DNFvTkif.cjs} +2 -2
- package/dist/{bus-CtJWf9QN.cjs.map → bus-DNFvTkif.cjs.map} +1 -1
- package/dist/{bus-D8kH58tb.js → bus-HVQ8E72V.js} +8 -8
- package/dist/{bus-D8kH58tb.js.map → bus-HVQ8E72V.js.map} +1 -1
- package/dist/{console-DjLbryED.js → console-C9Y639mn.js} +3 -3
- package/dist/{console-DjLbryED.js.map → console-C9Y639mn.js.map} +1 -1
- package/dist/{console-BpHfWstv.cjs → console-DssDxq1B.cjs} +2 -2
- package/dist/{console-BpHfWstv.cjs.map → console-DssDxq1B.cjs.map} +1 -1
- package/dist/constants-N99w84xy.js +117 -0
- package/dist/constants-N99w84xy.js.map +1 -0
- package/dist/constants-X86IDwkC.cjs +2 -0
- package/dist/constants-X86IDwkC.cjs.map +1 -0
- package/dist/constants.d.ts +18 -11
- package/dist/core/drops.d.ts +29 -0
- package/dist/core/hold-buffer.d.ts +27 -0
- package/dist/core/pipeline.d.ts +2 -7
- package/dist/core/runtime.d.ts +44 -8
- package/dist/core/sender.d.ts +4 -1
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/{errors-CpGRhhIf.cjs → errors-BTWuVnHZ.cjs} +2 -2
- package/dist/{errors-CpGRhhIf.cjs.map → errors-BTWuVnHZ.cjs.map} +1 -1
- package/dist/{errors-DH4QJS0u.js → errors-CQusIGWJ.js} +4 -4
- package/dist/{errors-DH4QJS0u.js.map → errors-CQusIGWJ.js.map} +1 -1
- package/dist/{deadline-Cbg2cbUw.cjs → identity-B1GDS1Tb.cjs} +2 -2
- package/dist/identity-B1GDS1Tb.cjs.map +1 -0
- package/dist/{deadline-B5DINjD5.js → identity-D4DPjTM9.js} +3 -26
- package/dist/identity-D4DPjTM9.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +467 -318
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-n1qkFBGA.js → indexeddb-storage-B8SGUzSV.js} +79 -50
- package/dist/indexeddb-storage-B8SGUzSV.js.map +1 -0
- package/dist/indexeddb-storage-ukzC82dm.cjs +2 -0
- package/dist/indexeddb-storage-ukzC82dm.cjs.map +1 -0
- package/dist/{interactions-31eHGwEQ.cjs → interactions-CcxrVzpg.cjs} +2 -2
- package/dist/{interactions-31eHGwEQ.cjs.map → interactions-CcxrVzpg.cjs.map} +1 -1
- package/dist/{interactions-OU94MPXs.js → interactions-CnjfQgw3.js} +2 -2
- package/dist/{interactions-OU94MPXs.js.map → interactions-CnjfQgw3.js.map} +1 -1
- package/dist/{journey-CeJ1QoT2.js → journey-DjvDzHyp.js} +17 -16
- package/dist/{journey-CeJ1QoT2.js.map → journey-DjvDzHyp.js.map} +1 -1
- package/dist/journey-DxlfdFJV.cjs +2 -0
- package/dist/journey-DxlfdFJV.cjs.map +1 -0
- package/dist/{library-request-C9uJFlbq.cjs → library-request-BZ1ekVtl.cjs} +2 -2
- package/dist/{library-request-C9uJFlbq.cjs.map → library-request-BZ1ekVtl.cjs.map} +1 -1
- package/dist/{library-request-DvhuplAB.js → library-request-C8kc5YWv.js} +2 -2
- package/dist/{library-request-DvhuplAB.js.map → library-request-C8kc5YWv.js.map} +1 -1
- package/dist/{long-frames-B8VdA_ny.cjs → long-frames-BGik_Yhy.cjs} +2 -2
- package/dist/{long-frames-B8VdA_ny.cjs.map → long-frames-BGik_Yhy.cjs.map} +1 -1
- package/dist/{long-frames-C_7OutLs.js → long-frames-CZk3XOkH.js} +3 -3
- package/dist/{long-frames-C_7OutLs.js.map → long-frames-CZk3XOkH.js.map} +1 -1
- package/dist/models/batch.d.ts +14 -0
- package/dist/models/config.d.ts +146 -0
- package/dist/models/drop.d.ts +39 -0
- package/dist/models/storage.d.ts +15 -3
- package/dist/{network-D_lloS5t.js → network-51iicpLl.js} +19 -19
- package/dist/{network-D_lloS5t.js.map → network-51iicpLl.js.map} +1 -1
- package/dist/{network-BAV7ipyn.cjs → network-jBbjyAJP.cjs} +2 -2
- package/dist/{network-BAV7ipyn.cjs.map → network-jBbjyAJP.cjs.map} +1 -1
- package/dist/{platform-IHBZGqUe.js → platform-Cjts-8k8.js} +2 -2
- package/dist/{platform-IHBZGqUe.js.map → platform-Cjts-8k8.js.map} +1 -1
- package/dist/{platform-D4wu1eIF.cjs → platform-DW3GFIUE.cjs} +2 -2
- package/dist/{platform-D4wu1eIF.cjs.map → platform-DW3GFIUE.cjs.map} +1 -1
- package/dist/{remote-rules-kuDf5gbe.cjs → remote-rules-ByS34k4e.cjs} +2 -2
- package/dist/{remote-rules-kuDf5gbe.cjs.map → remote-rules-ByS34k4e.cjs.map} +1 -1
- package/dist/{remote-rules-Bt1XsdEQ.js → remote-rules-M-XZ1xbe.js} +2 -2
- package/dist/{remote-rules-Bt1XsdEQ.js.map → remote-rules-M-XZ1xbe.js.map} +1 -1
- package/dist/{sampling-o0VY1mqQ.js → sampling-BN3Oi6SV.js} +9 -9
- package/dist/{sampling-o0VY1mqQ.js.map → sampling-BN3Oi6SV.js.map} +1 -1
- package/dist/{sampling-BI15ds9D.cjs → sampling-b2ck5X98.cjs} +2 -2
- package/dist/{sampling-BI15ds9D.cjs.map → sampling-b2ck5X98.cjs.map} +1 -1
- package/dist/{sanitize-DSIP7amZ.cjs → sanitize-DKp5MRsa.cjs} +2 -2
- package/dist/{sanitize-DSIP7amZ.cjs.map → sanitize-DKp5MRsa.cjs.map} +1 -1
- package/dist/{sanitize-B9UheVKc.js → sanitize-Dwj9JCkI.js} +2 -2
- package/dist/{sanitize-B9UheVKc.js.map → sanitize-Dwj9JCkI.js.map} +1 -1
- package/dist/{sender-BnNj9bOX.js → sender-BBY0IcUo.js} +328 -269
- package/dist/sender-BBY0IcUo.js.map +1 -0
- package/dist/sender-BXoAZKum.cjs +3 -0
- package/dist/sender-BXoAZKum.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +4 -1
- package/dist/storage/eviction.d.ts +40 -0
- package/dist/storage/idb-driver.d.ts +6 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -5
- package/dist/storage/local-storage.d.ts +24 -1
- package/dist/storage/memory-storage.d.ts +7 -0
- package/dist/{storm-Y-yuBhvv.cjs → storm-CKuaBp7i.cjs} +2 -2
- package/dist/{storm-Y-yuBhvv.cjs.map → storm-CKuaBp7i.cjs.map} +1 -1
- package/dist/{storm-BTw0J6eE.js → storm-DhtL2eVr.js} +2 -2
- package/dist/{storm-BTw0J6eE.js.map → storm-DhtL2eVr.js.map} +1 -1
- package/dist/transport/exit-flush.d.ts +6 -0
- package/dist/transport/retry-engine.d.ts +7 -3
- package/dist/transport/status-transport.d.ts +4 -1
- package/dist/utils/console.d.ts +4 -1
- package/package.json +1 -1
- package/dist/constants-Br3b89Wg.cjs +0 -2
- package/dist/constants-Br3b89Wg.cjs.map +0 -1
- package/dist/constants-DM94FjVX.js +0 -96
- package/dist/constants-DM94FjVX.js.map +0 -1
- package/dist/deadline-B5DINjD5.js.map +0 -1
- package/dist/deadline-Cbg2cbUw.cjs.map +0 -1
- package/dist/indexeddb-storage-DNdf1fmL.cjs +0 -2
- package/dist/indexeddb-storage-DNdf1fmL.cjs.map +0 -1
- package/dist/indexeddb-storage-n1qkFBGA.js.map +0 -1
- package/dist/journey-CE2EcwHW.cjs +0 -2
- package/dist/journey-CE2EcwHW.cjs.map +0 -1
- package/dist/sender-BnNj9bOX.js.map +0 -1
- package/dist/sender-D0OsyB1c.cjs +0 -3
- package/dist/sender-D0OsyB1c.cjs.map +0 -1
package/dist/models/storage.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { LogBatch } from "./batch";
|
|
2
|
+
import type { RetentionOptions } from "./config";
|
|
2
3
|
/** Persistent batch storage interface. All methods must resolve and never throw. */
|
|
3
4
|
export interface StorageAdapter {
|
|
4
5
|
/** Adapter identifier name. */
|
|
@@ -46,17 +47,28 @@ export interface StorageLimits {
|
|
|
46
47
|
/** Maximum delivery attempts before dead-letter drop. */
|
|
47
48
|
maxAttempts: number;
|
|
48
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Gives the storage limits of a retention setting. "until-delivered" has no age limit and no
|
|
52
|
+
* attempt limit. The batch cap still applies.
|
|
53
|
+
* @param retention Retention setting from the config.
|
|
54
|
+
* @returns The limits for the storage adapters and the retry engine.
|
|
55
|
+
*/
|
|
56
|
+
export declare function storageLimits(retention: RetentionOptions): StorageLimits;
|
|
49
57
|
/** Metrics for batches and records dropped during storage pruning. */
|
|
50
58
|
export interface PruneResult {
|
|
51
59
|
/** Total batches dropped. */
|
|
52
60
|
batches: number;
|
|
53
61
|
/** Total records dropped within evicted batches. */
|
|
54
62
|
records: number;
|
|
55
|
-
/**
|
|
56
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Cause of the drop. If more than one rule applies, this is the last rule. "not_stored" means
|
|
65
|
+
* that storage did not keep a batch after a failed send.
|
|
66
|
+
*/
|
|
67
|
+
reason: "expired" | "over_capacity" | "quota" | "not_stored";
|
|
57
68
|
}
|
|
58
69
|
/**
|
|
59
70
|
* Callback invoked when dropped records create a telemetry gap.
|
|
60
71
|
* @param result Summary of evicted data.
|
|
72
|
+
* @param dropped The dropped batches. A corrupt entry has no batch. The list then has none for it.
|
|
61
73
|
*/
|
|
62
|
-
export type GapReporter = (result: PruneResult) => void;
|
|
74
|
+
export type GapReporter = (result: PruneResult, dropped: readonly LogBatch[]) => void;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { r as e } from "./platform-
|
|
2
|
-
import { t } from "./
|
|
3
|
-
import { t as n } from "./
|
|
1
|
+
import { r as e } from "./platform-Cjts-8k8.js";
|
|
2
|
+
import { t } from "./library-request-C8kc5YWv.js";
|
|
3
|
+
import { t as n } from "./patch-CCWfuEY7.js";
|
|
4
4
|
//#region src/capture/types.ts
|
|
5
5
|
function r(e, t) {
|
|
6
6
|
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
@@ -47,7 +47,7 @@ var l = class {
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
ignored(e) {
|
|
50
|
-
return
|
|
50
|
+
return t() || r(e, this.ctx.config.capture.ignoreUrls);
|
|
51
51
|
}
|
|
52
52
|
propagates(e) {
|
|
53
53
|
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
@@ -57,13 +57,13 @@ var l = class {
|
|
|
57
57
|
}
|
|
58
58
|
installFetch() {
|
|
59
59
|
if (typeof globalThis.fetch != "function") return;
|
|
60
|
-
let e = !0,
|
|
60
|
+
let e = !0, t = (e, t) => this.prepareFetch(e, t), r = (e, t, n, r, i) => {
|
|
61
61
|
this.record(e, t, n, r, i);
|
|
62
|
-
}, i =
|
|
63
|
-
let i =
|
|
64
|
-
return async function(
|
|
65
|
-
let o = e ? n
|
|
66
|
-
if (!o) return i(
|
|
62
|
+
}, i = n(globalThis, "fetch", (n) => {
|
|
63
|
+
let i = n.bind(globalThis);
|
|
64
|
+
return async function(n, a) {
|
|
65
|
+
let o = e ? t(n, a) : void 0;
|
|
66
|
+
if (!o) return i(n, a);
|
|
67
67
|
let s = performance.now();
|
|
68
68
|
try {
|
|
69
69
|
let e = await i(o.input, o.init);
|
|
@@ -115,27 +115,27 @@ var l = class {
|
|
|
115
115
|
}
|
|
116
116
|
installXhr() {
|
|
117
117
|
if (typeof XMLHttpRequest > "u") return;
|
|
118
|
-
let e = !0,
|
|
118
|
+
let e = !0, t = this.ctx, r = (e) => this.ignored(e), o = (e) => this.propagates(e), s = (e, t, n, r) => {
|
|
119
119
|
this.record(e, t, n, r, void 0);
|
|
120
|
-
}, l = i(), d =
|
|
121
|
-
e &&
|
|
120
|
+
}, l = i(), d = n(l, "open", (n) => function(r, i, ...o) {
|
|
121
|
+
e && t.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
122
122
|
this.__uiobs = {
|
|
123
123
|
method: c(r),
|
|
124
124
|
url: a(i),
|
|
125
125
|
startedAt: 0
|
|
126
126
|
};
|
|
127
|
-
}),
|
|
127
|
+
}), n.apply(this, [
|
|
128
128
|
r,
|
|
129
129
|
i,
|
|
130
130
|
...o
|
|
131
131
|
]);
|
|
132
|
-
}), f =
|
|
132
|
+
}), f = n(l, "send", (n) => function(...i) {
|
|
133
133
|
let a = e ? this.__uiobs : void 0;
|
|
134
|
-
a &&
|
|
134
|
+
a && t.diagnostics.guard("capture.record_failed", `The library could not record ${a.method} ${a.url}.`, () => {
|
|
135
135
|
r(a.url) || (a.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
136
136
|
s(a.method, a.url, this.status, performance.now() - a.startedAt);
|
|
137
|
-
}), o(a.url) && u(this, a.url,
|
|
138
|
-
}),
|
|
137
|
+
}), o(a.url) && u(this, a.url, t));
|
|
138
|
+
}), n.apply(this, i);
|
|
139
139
|
});
|
|
140
140
|
this.restores.push(() => {
|
|
141
141
|
e = !1, d(), f();
|
|
@@ -171,4 +171,4 @@ function u(e, t, n) {
|
|
|
171
171
|
//#endregion
|
|
172
172
|
export { l as NetworkCapture };
|
|
173
173
|
|
|
174
|
-
//# sourceMappingURL=network-
|
|
174
|
+
//# sourceMappingURL=network-51iicpLl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-D_lloS5t.js","names":["stripUrlQuery","isLibraryRequest","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","patch","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;AAgHA,SAAgBE,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;ACvFA,SAASG,IAAyB;CAChC,OAAO,eAAe;AACxB;AAqBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAE,WAAQA;EAChB,IAAI,OAAOL,KAAQ,UACjB,OAAOA;CAEX;CAGA,OAAO,OAAOK,CAAK;AACrB;AAQA,SAASC,EAAgB,GAAgB,GAAuC;CAC9E,IAAIC,IAAqBC,GAAM;CAM/B,OAJID,MAAc,KAAA,KAAa,OAAOF,KAAU,YAAYA,MAC1D,IAAaA,EAA+B,SAGvCI,EAASF,KAAa,KAAK;AACpC;AAQA,SAASG,EAAe,GAAyB;CAC/C,OAAO,OAAOL,KAAU,YAAY,EAAEA,aAAiB,QAAQ,EAAEA,aAAiB;AACpF;AAOA,SAASI,EAAS,GAAyB;CACzC,OAAO,OAAOE,KAAW,WAAWA,EAAO,YAAY,IAAI,OAAOA,CAAM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A,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"network-51iicpLl.js","names":["stripUrlQuery","patch","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","isLibraryRequest","targets","origin","target","active","prepare","record","status","durationMs","error","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;AAgHA,SAAgBE,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;ACvFA,SAASG,IAAyB;CAChC,OAAO,eAAe;AACxB;AAqBA,SAASC,EAAQ,GAAwB;CACvC,IAAI,OAAOC,KAAU,UACnB,OAAOA;CAGT,IAAIA,aAAiB,KACnB,OAAOA,EAAM;CAGf,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAE,WAAQA;EAChB,IAAI,OAAOL,KAAQ,UACjB,OAAOA;CAEX;CAGA,OAAO,OAAOK,CAAK;AACrB;AAQA,SAASC,EAAgB,GAAgB,GAAuC;CAC9E,IAAIC,IAAqBC,GAAM;CAM/B,OAJID,MAAc,KAAA,KAAa,OAAOF,KAAU,YAAYA,MAC1D,IAAaA,EAA+B,SAGvCI,EAASF,KAAa,KAAK;AACpC;AAQA,SAASG,EAAe,GAAyB;CAC/C,OAAO,OAAOL,KAAU,YAAY,EA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CAACX,GAAKC,MAAU,OAAO,QAAQrB,EAAI,QAAQ,QAAQ,CAAC,GAC7D,EAAI,iBAAiBoB,GAAKC,CAAK;CAEnC,SAASV,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./platform-
|
|
2
|
-
//# sourceMappingURL=network-
|
|
1
|
+
const e=require("./platform-DW3GFIUE.cjs"),t=require("./library-request-BZ1ekVtl.cjs"),n=require("./patch-BX8KrPCT.cjs");function r(e,t){return typeof e==`string`&&t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function i(){return XMLHttpRequest.prototype}function a(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 o(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),c(n??`GET`)}function s(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function c(e){return typeof e==`string`?e.toUpperCase():String(e)}var l=class{ctx;name=`network`;installed=!1;restores=[];constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return t.t()||r(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),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)},i=n.t(globalThis,`fetch`,n=>{let i=n.bind(globalThis);return async function(n,a){let o=e?t(n,a):void 0;if(!o)return i(n,a);let s=performance.now();try{let e=await i(o.input,o.init);return r(o.method,o.url,e.status,performance.now()-s,void 0),e}catch(e){throw r(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=a(e);if(!this.ignored(n))return{method:o(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,c={method:r,url:i,input:e,init:t};if(!n.propagate||s(e))return c;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);c.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,r]of n)e.set(t,r);c.init={...t,headers:e}}}catch(n){c.input=e,c.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return c}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,r=e=>this.ignored(e),o=e=>this.propagates(e),s=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},l=i(),d=n.t(l,`open`,n=>function(r,i,...o){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:c(r),url:a(i),startedAt:0}}),n.apply(this,[r,i,...o])}),f=n.t(l,`send`,n=>function(...i){let a=e?this.__uiobs:void 0;a&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${a.method} ${a.url}.`,()=>{r(a.url)||(a.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{s(a.method,a.url,this.status,performance.now()-a.startedAt)}),o(a.url)&&u(this,a.url,t))}),n.apply(this,i)});this.restores.push(()=>{e=!1,d(),f()})}record(t,n,r,i,a){let o=this.ctx.config.capture.fullUrls?n:e.r(n);this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${t} ${o}.`,()=>{let e=Math.round(i);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${t} ${o} ${r===0?`failed`:String(r)}`,data:{durationMs:e}});let n={"http.request.method":t,"url.full":o,"http.response.status_code":r,"http.duration_ms":e};r===0?this.ctx.logger.error(`${t} ${o} failed`,a,n):r>=400?this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`,n):this.ctx.logger.debug(`${t} ${o}`,n)})}};function u(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=l;
|
|
2
|
+
//# sourceMappingURL=network-jBbjyAJP.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-BAV7ipyn.cjs","names":["isLibraryRequest","patch","stripUrlQuery","require_platform","require_patch","require_library_request","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes","xhr"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":"yHAgHA,SAAgBM,EAAW,EAAc,EAAwC,CAM/E,OAJI,OAAOC,GAAQ,UAIZC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWF,EAAI,SAASE,CAAO,EAAIA,EAAQ,KAAKF,CAAG,CACxE,CACF,CCvFA,SAASG,GAAyB,CAChC,OAAO,eAAe,SACxB,CAqBA,SAASC,EAAQ,E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MC,EAAa,CACjB,sBAAuBnC,EACvB,WAAYX,EACZ,4BAA6BqB,EAC7B,mBAAoBwB,CACtB,EAEIxB,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGV,EAAO,GAAGX,EAAI,SAAUuB,EAAOuB,CAAU,EAGhEzB,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGV,EAAO,GAAGX,EAAI,YAAY,OAAOqB,CAAM,IAAKyB,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGnC,EAAO,GAAGX,IAAO8C,CAAU,CACtD,CACF,CACF,CACF,EAQA,SAASH,EAAgB,EAAqB,EAAa,EAA2B,CACpF,GAAI,CACF,IAAK,GAAM,CAACX,EAAKC,KAAU,OAAO,QAAQpB,EAAI,QAAQ,QAAQ,CAAC,EAC7DkC,EAAI,iBAAiBf,EAAKC,CAAK,CAEnC,OAASV,EAAO,CACdV,EAAI,YAAY,OACd,wBACA,oFACA,CAAE,KAAI,EACNU,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"network-jBbjyAJP.cjs","names":["isLibraryRequest","patch","stripUrlQuery","require_platform","require_library_request","require_patch","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes","xhr"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":"yHAgHA,SAAgBM,EAAW,EAAc,EAAwC,CAM/E,OAJI,OAAOC,GAAQ,UAIZC,EAAS,KAAM,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AAI,EACZ,SAAU,OACV,QAAS,GAAGX,EAAO,GAAGX,EAAI,GAAGqB,IAAW,EAAI,SAAW,OAAOA,CAAM,IACpE,KAAM,CAAE,WAAYwB,CAAQ,CAC9B,CAAC,EAED,IAAMC,EAAa,CACjB,sBAAuBnC,EACvB,WAAYX,EACZ,4BAA6BqB,EAC7B,mBAAoBwB,CACtB,EAEIxB,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGV,EAAO,GAAGX,EAAI,SAAUuB,EAAOuB,CAAU,EAGhEzB,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGV,EAAO,GAAGX,EAAI,YAAY,OAAOqB,CAAM,IAAKyB,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGnC,EAAO,GAAGX,IAAO8C,CAAU,CACtD,CACF,CACF,CACF,EAQA,SAASH,EAAgB,EAAqB,EAAa,EAA2B,CACpF,GAAI,CACF,IAAK,GAAM,CAACX,EAAKC,KAAU,OAAO,QAAQpB,EAAI,QAAQ,QAAQ,CAAC,EAC7DkC,EAAI,iBAAiBf,EAAKC,CAAK,CAEnC,OAASV,EAAO,CACdV,EAAI,YAAY,OACd,wBACA,oFACA,CAAE,KAAI,EACNU,CACF,CACF,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { St as e, _t as t,
|
|
1
|
+
import { St as e, _t as t, ht as n, it as r, t as i } from "./constants-N99w84xy.js";
|
|
2
2
|
//#region src/utils/platform.ts
|
|
3
3
|
var a = null;
|
|
4
4
|
function o(e, t) {
|
|
@@ -45,4 +45,4 @@ function d(e) {
|
|
|
45
45
|
//#endregion
|
|
46
46
|
export { s as n, d as r, u as t };
|
|
47
47
|
|
|
48
|
-
//# sourceMappingURL=platform-
|
|
48
|
+
//# sourceMappingURL=platform-Cjts-8k8.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-
|
|
1
|
+
{"version":3,"file":"platform-Cjts-8k8.js","names":["OPENFIN_UA_PATTERN","MOBILE_UA_PATTERN","MACINTOSH_UA_PATTERN","IOS_DEVICE_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA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BAAsB,GACjC;CACT;AACF;AAQA,SAAgBI,EAAc,GAAqB;CACjD,IAAMC,IAAMC,EAAI,OAAO,MAAM;CAE7B,OAAOD,MAAQ,KAAKC,IAAMA,EAAI,MAAM,GAAGD,CAAG;AAC5C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=platform-
|
|
1
|
+
const e=require("./constants-X86IDwkC.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.St.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a(r)},t}function i(t){return e.t.test(t)?!0:(e.it.test(t)||e.ht.test(t)&&e._t.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function o(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=platform-DW3GFIUE.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-
|
|
1
|
+
{"version":3,"file":"platform-DW3GFIUE.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAM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M,sBAAsB,EACjC,EACT,CACF,CAOA,SAAgBG,EAAW,EAAkC,CAC3D,GAAI,CACF,OAAO,OAAO,SAAa,IAAc,SAAS,KAAO,EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=remote-rules-
|
|
1
|
+
const e=require("./constants-X86IDwkC.cjs");var t=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevel(){let{minLevel:t}=this.config,n=this.current()?.minLevel;return n!==void 0&&e.lt[n]<e.lt[t]?n:t}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},n=class extends Error{};function r(e){return typeof e==`number`&&e>=0&&e<=1}function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(t){if(t.length>4096)throw new n(`The header is longer than ${String(e.Dt)} characters.`);try{return JSON.parse(t)}catch{throw new n(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let t=`rates must be an object with at most 100 rates from 0 to 1.`;if(!i(e))throw new n(t);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>r(e)))throw new n(t);return Object.fromEntries(a)}function s(t){if(!i(t))throw new n(`The rules must be an object.`);if(t.v!==1)throw new n(`The version must be 1.`);let{ttlMs:a,defaultRate:s,minLevel:c}=t;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new n(`ttlMs must be a number more than 0 and at most ${String(e.Ot)}.`);if(s!==void 0&&!r(s))throw new n(`defaultRate must be a number from 0 to 1.`);if(c!==void 0&&!(typeof c==`string`&&Object.hasOwn(e.lt,c)))throw new n(`minLevel must be a level name, for example DEBUG.`);let l={rates:o(t.rates)};return s!==void 0&&(l.defaultRate=s),c!==void 0&&(l.minLevel=c),{rules:l,ttlMs:a}}function c(e,t){try{return s(typeof e==`string`?a(e):e)}catch(e){let r=e instanceof n?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${r}`,void 0,e),null}}function l(e,n,r){r&&(e.sampling??=new t(n)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
|
|
2
|
+
//# sourceMappingURL=remote-rules-ByS34k4e.cjs.map
|