@utk09/ui-observability 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +77 -60
- package/dist/bus/bus.d.ts +10 -10
- package/dist/bus/links.d.ts +1 -1
- package/dist/{bus-D3OO0OcL.js → bus-BTMuVkDk.js} +19 -19
- package/dist/bus-BTMuVkDk.js.map +1 -0
- package/dist/bus-ChIXDAWD.cjs +2 -0
- package/dist/bus-ChIXDAWD.cjs.map +1 -0
- package/dist/capture/network.d.ts +2 -2
- package/dist/capture/types.d.ts +10 -10
- package/dist/capture/web-vitals.d.ts +3 -3
- package/dist/{constants-B6kdsCzF.js → constants-0-YchbAL.js} +2 -2
- package/dist/constants-0-YchbAL.js.map +1 -0
- package/dist/{constants-DZH04585.cjs → constants-TUFcy95w.cjs} +2 -2
- package/dist/constants-TUFcy95w.cjs.map +1 -0
- package/dist/constants.d.ts +53 -40
- package/dist/core/breadcrumbs.d.ts +14 -14
- package/dist/core/config.d.ts +5 -4
- package/dist/core/context.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +10 -9
- package/dist/core/journey.d.ts +23 -20
- package/dist/core/logger.d.ts +7 -7
- package/dist/core/pipeline.d.ts +34 -29
- package/dist/core/record.d.ts +6 -6
- package/dist/core/runtime.d.ts +20 -18
- package/dist/core/sampling.d.ts +15 -16
- package/dist/core/sender.d.ts +1 -1
- package/dist/{errors-DPju_xSI.cjs → errors-DRXBRqvm.cjs} +2 -2
- package/dist/errors-DRXBRqvm.cjs.map +1 -0
- package/dist/{errors-Dme9tz-6.js → errors-Dwm2SzBa.js} +4 -4
- package/dist/errors-Dwm2SzBa.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +61 -61
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-B5dwq4hW.cjs +2 -0
- package/dist/indexeddb-storage-B5dwq4hW.cjs.map +1 -0
- package/dist/{indexeddb-storage-nxs_rxGx.js → indexeddb-storage-DjY4Ml6t.js} +16 -16
- package/dist/indexeddb-storage-DjY4Ml6t.js.map +1 -0
- package/dist/{interactions-DP0-rIPJ.cjs → interactions-DVom6eYn.cjs} +2 -2
- package/dist/interactions-DVom6eYn.cjs.map +1 -0
- package/dist/{interactions-C1romMpE.js → interactions-DZmLu7l2.js} +2 -2
- package/dist/interactions-DZmLu7l2.js.map +1 -0
- package/dist/models/batch.d.ts +12 -9
- package/dist/models/bus.d.ts +12 -13
- package/dist/models/config.d.ts +58 -41
- package/dist/models/log-record.d.ts +12 -10
- package/dist/models/serializer.d.ts +3 -2
- package/dist/models/storage.d.ts +2 -2
- package/dist/{network-au-Tqt1n.js → network-C4d2uw2Z.js} +4 -4
- package/dist/network-C4d2uw2Z.js.map +1 -0
- package/dist/network-CuqWadNn.cjs +2 -0
- package/dist/network-CuqWadNn.cjs.map +1 -0
- package/dist/platform-CXio0W2n.cjs +2 -0
- package/dist/platform-CXio0W2n.cjs.map +1 -0
- package/dist/{platform-DMYo3AX3.js → platform-CY8S3hUs.js} +8 -8
- package/dist/platform-CY8S3hUs.js.map +1 -0
- package/dist/sampling-CEthcmEX.cjs +2 -0
- package/dist/sampling-CEthcmEX.cjs.map +1 -0
- package/dist/{sampling-ByI5H44E.js → sampling-CJsI_24L.js} +21 -18
- package/dist/sampling-CJsI_24L.js.map +1 -0
- package/dist/sender-ByFAkXVd.cjs +3 -0
- package/dist/sender-ByFAkXVd.cjs.map +1 -0
- package/dist/{sender-R7lOpyNc.js → sender-dpvR_bHM.js} +60 -60
- package/dist/sender-dpvR_bHM.js.map +1 -0
- package/dist/storage/emergency-queue.d.ts +2 -2
- package/dist/storage/factory.d.ts +2 -1
- package/dist/storage/idb-driver.d.ts +19 -19
- package/dist/storage/indexeddb-storage.d.ts +18 -17
- package/dist/storage/keys.d.ts +1 -1
- package/dist/storage/local-storage.d.ts +19 -18
- package/dist/storage/memory-storage.d.ts +12 -11
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +8 -7
- package/dist/transport/exit-flush.d.ts +27 -24
- package/dist/transport/http-transport.d.ts +18 -11
- package/dist/transport/retry-engine.d.ts +33 -28
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +1 -1
- package/dist/unref-16maCyKA.js.map +1 -1
- package/dist/unref-CU9Nyz_9.cjs.map +1 -1
- package/dist/utils/identity.d.ts +6 -5
- package/dist/utils/lock.d.ts +4 -4
- package/dist/utils/platform.d.ts +5 -3
- package/dist/utils/sanitize.d.ts +5 -2
- package/dist/utils/sequence.d.ts +2 -2
- package/dist/utils/tracing.d.ts +8 -7
- package/dist/web-vitals-B2FYsEAU.cjs +2 -0
- package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
- package/dist/{web-vitals-DwWdLBq6.js → web-vitals-DHZ0yA_H.js} +4 -4
- package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
- package/package.json +1 -1
- package/dist/bus-D3OO0OcL.js.map +0 -1
- package/dist/bus-OdRJVUzr.cjs +0 -2
- package/dist/bus-OdRJVUzr.cjs.map +0 -1
- package/dist/constants-B6kdsCzF.js.map +0 -1
- package/dist/constants-DZH04585.cjs.map +0 -1
- package/dist/errors-DPju_xSI.cjs.map +0 -1
- package/dist/errors-Dme9tz-6.js.map +0 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +0 -2
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +0 -1
- package/dist/indexeddb-storage-nxs_rxGx.js.map +0 -1
- package/dist/interactions-C1romMpE.js.map +0 -1
- package/dist/interactions-DP0-rIPJ.cjs.map +0 -1
- package/dist/network-DDVIJSHd.cjs +0 -2
- package/dist/network-DDVIJSHd.cjs.map +0 -1
- package/dist/network-au-Tqt1n.js.map +0 -1
- package/dist/platform-DMYo3AX3.js.map +0 -1
- package/dist/platform-g99Kn755.cjs +0 -2
- package/dist/platform-g99Kn755.cjs.map +0 -1
- package/dist/sampling-ByI5H44E.js.map +0 -1
- package/dist/sampling-Dui-Fp3u.cjs +0 -2
- package/dist/sampling-Dui-Fp3u.cjs.map +0 -1
- package/dist/sender-R7lOpyNc.js.map +0 -1
- package/dist/sender-vLcbQhiB.cjs +0 -3
- package/dist/sender-vLcbQhiB.cjs.map +0 -1
- package/dist/web-vitals-DM2nvcMJ.cjs +0 -2
- package/dist/web-vitals-DM2nvcMJ.cjs.map +0 -1
- package/dist/web-vitals-DwWdLBq6.js.map +0 -1
package/dist/core/pipeline.d.ts
CHANGED
|
@@ -4,18 +4,21 @@ import type { StorageAdapter } from "../models/storage";
|
|
|
4
4
|
import type { HttpTransport } from "../transport/http-transport";
|
|
5
5
|
import type { RetryEngine } from "../transport/retry-engine";
|
|
6
6
|
import type { Diagnostics } from "./diagnostics";
|
|
7
|
-
/**
|
|
7
|
+
/** Name of a pipeline stream. */
|
|
8
8
|
export type StreamName = "logs" | "metrics";
|
|
9
9
|
/** Batching policy for one record stream. */
|
|
10
10
|
export interface StreamOptions {
|
|
11
|
-
/**
|
|
11
|
+
/** Maximum time in milliseconds that a partial batch waits before the pipeline sends it. */
|
|
12
12
|
flushIntervalMs: number;
|
|
13
|
-
/**
|
|
13
|
+
/** Maximum records in a batch. At this count, the pipeline sends the batch early. */
|
|
14
14
|
batchSize: number;
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Batching policy per stream. Metrics use larger batches and a longer interval.
|
|
18
|
+
* Metrics have a higher volume, and no process waits for them.
|
|
19
|
+
*/
|
|
17
20
|
export declare const STREAM_OPTIONS: Record<StreamName, StreamOptions>;
|
|
18
|
-
/**
|
|
21
|
+
/** Buffers log and metric streams, makes batches and sends them over HTTP. */
|
|
19
22
|
export declare class LogPipeline {
|
|
20
23
|
private readonly transport;
|
|
21
24
|
private readonly storage;
|
|
@@ -23,7 +26,7 @@ export declare class LogPipeline {
|
|
|
23
26
|
private readonly diagnostics;
|
|
24
27
|
/** Buffer instances for logs and metrics streams. */
|
|
25
28
|
private readonly streams;
|
|
26
|
-
/**
|
|
29
|
+
/** In-flight batches without delivery confirmation. The exit flush sends them again. */
|
|
27
30
|
private readonly unconfirmed;
|
|
28
31
|
/** Closed batches waiting for a free dispatch slot. */
|
|
29
32
|
private readonly queue;
|
|
@@ -31,7 +34,7 @@ export declare class LogPipeline {
|
|
|
31
34
|
private readonly ceiling;
|
|
32
35
|
/** Dispatches currently in flight, capped at MAX_CONCURRENT_REQUESTS. */
|
|
33
36
|
private inFlight;
|
|
34
|
-
/**
|
|
37
|
+
/** It is true when a pump is in the queue. One microtask then drains a burst. */
|
|
35
38
|
private pumpScheduled;
|
|
36
39
|
/** Indicates whether the pipeline has been destroyed. */
|
|
37
40
|
private stopped;
|
|
@@ -44,22 +47,23 @@ export declare class LogPipeline {
|
|
|
44
47
|
*/
|
|
45
48
|
constructor(transport: HttpTransport, storage: StorageAdapter, retry: RetryEngine, diagnostics: Diagnostics, streamOptions?: Record<StreamName, StreamOptions>);
|
|
46
49
|
/**
|
|
47
|
-
*
|
|
50
|
+
* Sets the observed timestamp and adds a record to the pipeline.
|
|
48
51
|
* @param record Record to push.
|
|
49
52
|
*/
|
|
50
53
|
push(record: LogRecord): void;
|
|
51
54
|
/**
|
|
52
|
-
* Drains the stream buffers into one batch.
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
+
* Drains the stream buffers into one batch. It does not take in-flight batches.
|
|
56
|
+
* An in-flight batch has its own ID and its send is not complete. If this method
|
|
57
|
+
* takes it, the pipeline sends each record again under a new ID. The server cannot
|
|
58
|
+
* deduplicate that ID.
|
|
55
59
|
* @returns Combined LogBatch or null if no records are buffered.
|
|
56
60
|
*/
|
|
57
61
|
drainPending(): LogBatch | null;
|
|
58
62
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* A document
|
|
63
|
+
* Drains all buffered and unconfirmed in-flight records into one exit batch in one step.
|
|
64
|
+
* Records already given to fetch go again under a new batch ID. The server cannot
|
|
65
|
+
* deduplicate them. Thus the exit flush can deliver duplicates. This is intentional.
|
|
66
|
+
* A closing document cannot confirm delivery.
|
|
63
67
|
* @returns Combined LogBatch or null if no records are pending.
|
|
64
68
|
*/
|
|
65
69
|
drainForExit(): LogBatch | null;
|
|
@@ -72,23 +76,23 @@ export declare class LogPipeline {
|
|
|
72
76
|
*/
|
|
73
77
|
private toBatch;
|
|
74
78
|
/**
|
|
75
|
-
* Sorts a record into its stream. Sampling already ran
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
+
* Sorts a record into its stream. Sampling already ran. RecordBuilder samples a local
|
|
80
|
+
* record. The runtime samples a forwarded record. This method catches each fault.
|
|
81
|
+
* A record without `attributes` makes isMetric throw. An uncaught throw goes into the
|
|
82
|
+
* log call of the caller.
|
|
79
83
|
* @param record Record to sort.
|
|
80
84
|
*/
|
|
81
85
|
private route;
|
|
82
86
|
/**
|
|
83
|
-
* Drains a stream buffer into a new batch and queues
|
|
84
|
-
* buffer always
|
|
85
|
-
*
|
|
87
|
+
* Drains a stream buffer into a new batch and queues the batch for dispatch.
|
|
88
|
+
* The buffer always has one or more records here. Only a push starts a timer.
|
|
89
|
+
* Each `take` stops the timer that calls this method.
|
|
86
90
|
* @param stream Stream buffer to drain.
|
|
87
91
|
*/
|
|
88
92
|
private claim;
|
|
89
93
|
/**
|
|
90
|
-
* Queues a batch and schedules the pump on a microtask.
|
|
91
|
-
*
|
|
94
|
+
* Queues a batch and schedules the pump on a microtask. An inline dispatch starts
|
|
95
|
+
* a fetch inside the log call of the application.
|
|
92
96
|
* @param batch Batch ready for delivery.
|
|
93
97
|
*/
|
|
94
98
|
private enqueue;
|
|
@@ -100,20 +104,21 @@ export declare class LogPipeline {
|
|
|
100
104
|
*/
|
|
101
105
|
private run;
|
|
102
106
|
/**
|
|
103
|
-
* Sends a batch over HTTP transport
|
|
107
|
+
* Sends a batch over the HTTP transport. If the transport throttles or fails, it stores
|
|
108
|
+
* the batch.
|
|
104
109
|
* @param batch Batch to deliver.
|
|
105
110
|
*/
|
|
106
111
|
private dispatch;
|
|
107
112
|
/**
|
|
108
|
-
*
|
|
109
|
-
*
|
|
113
|
+
* Stores a batch that the transport refused. The retry engine splits a 413 and
|
|
114
|
+
* drops a batch that the server does not accept.
|
|
110
115
|
* @param batch Batch to persist, with its attempt already counted.
|
|
111
116
|
* @param error Failure thrown by the transport.
|
|
112
117
|
*/
|
|
113
118
|
private storeFailed;
|
|
114
119
|
/**
|
|
115
|
-
*
|
|
116
|
-
*
|
|
120
|
+
* Stores an undelivered batch and triggers the retry engine. A deadline limits the
|
|
121
|
+
* wait. A storage call that does not settle holds this dispatch slot. Two such calls
|
|
117
122
|
* stop the pipeline.
|
|
118
123
|
* @param batch Batch to persist.
|
|
119
124
|
*/
|
package/dist/core/record.d.ts
CHANGED
|
@@ -24,12 +24,12 @@ export interface RecordBuilderDeps {
|
|
|
24
24
|
tracing: TraceEngine;
|
|
25
25
|
/** Monotonic sequence counter. */
|
|
26
26
|
sequence: Sequence;
|
|
27
|
-
/** Context, session
|
|
27
|
+
/** Context, session and tab identity. */
|
|
28
28
|
identity: Identity;
|
|
29
29
|
/** Detected host platform metadata. */
|
|
30
30
|
platform: PlatformMetadata;
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
32
|
+
/** Size limits for each record. The builder applies them after sanitize and after redact. */
|
|
33
33
|
export interface RecordLimits extends SanitizeLimits {
|
|
34
34
|
/** Max record body length, in characters. */
|
|
35
35
|
maxBodyChars: number;
|
|
@@ -42,7 +42,7 @@ export type DropReason = "level" | "sampling" | "redact";
|
|
|
42
42
|
export interface BuildResult {
|
|
43
43
|
/** Completed record, or null when it was dropped. */
|
|
44
44
|
record: LogRecord | null;
|
|
45
|
-
/**
|
|
45
|
+
/** Reason for the drop. It is absent when the builder built a record. */
|
|
46
46
|
dropped?: DropReason;
|
|
47
47
|
}
|
|
48
48
|
/** Input parameters for constructing a single log record. */
|
|
@@ -69,16 +69,16 @@ export declare class RecordBuilder {
|
|
|
69
69
|
* @param deps Injected builder dependencies.
|
|
70
70
|
*/
|
|
71
71
|
constructor(deps: RecordBuilderDeps);
|
|
72
|
-
/**
|
|
72
|
+
/** Clears the cached resource attributes. The next build computes them again. */
|
|
73
73
|
invalidateResource(): void;
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
75
|
+
* Checks if logging is on and the level is at or above minLevel.
|
|
76
76
|
* @param level Target log severity level.
|
|
77
77
|
* @returns True if the level is enabled.
|
|
78
78
|
*/
|
|
79
79
|
isEnabled(level: LogLevel): boolean;
|
|
80
80
|
/**
|
|
81
|
-
* Builds a structured LogRecord from input
|
|
81
|
+
* Builds a structured LogRecord from the input. It sanitizes attributes and applies size limits.
|
|
82
82
|
* @param input Logger call input parameters.
|
|
83
83
|
* @returns The record, or null with the reason it was dropped.
|
|
84
84
|
*/
|
package/dist/core/runtime.d.ts
CHANGED
|
@@ -12,11 +12,11 @@ import { ContextStore } from "./context";
|
|
|
12
12
|
import { Diagnostics } from "./diagnostics";
|
|
13
13
|
import { JourneyEngine } from "./journey";
|
|
14
14
|
import { RecordBuilder } from "./record";
|
|
15
|
-
/**
|
|
15
|
+
/** Manages subsystem lifecycles, bus coordination and record delivery. */
|
|
16
16
|
export declare class ObservabilityRuntime {
|
|
17
17
|
/** Diagnostics reporter for internal faults. */
|
|
18
18
|
readonly diagnostics: Diagnostics;
|
|
19
|
-
/** Active configuration instance
|
|
19
|
+
/** Active configuration instance. A reconfigure changes it in place. */
|
|
20
20
|
readonly config: ResolvedConfig;
|
|
21
21
|
/** Detected host platform metadata. */
|
|
22
22
|
readonly platform: PlatformMetadata;
|
|
@@ -51,7 +51,7 @@ export declare class ObservabilityRuntime {
|
|
|
51
51
|
private busBuilt?;
|
|
52
52
|
/** Load and start of the bus. It is undefined until the first need. */
|
|
53
53
|
private busLoad?;
|
|
54
|
-
/** Storage strategy the adapter
|
|
54
|
+
/** Storage strategy of the adapter. The runtime sets it when the build starts. */
|
|
55
55
|
private storageBuiltAs?;
|
|
56
56
|
/** Delivery stack. The runtime sets it in the sender role with an endpoint, after the chunk loads. */
|
|
57
57
|
private sender?;
|
|
@@ -75,7 +75,7 @@ export declare class ObservabilityRuntime {
|
|
|
75
75
|
private roleResolved;
|
|
76
76
|
/** Indicates whether asynchronous initialization has completed. */
|
|
77
77
|
private ready;
|
|
78
|
-
/** Indicates whether the runtime
|
|
78
|
+
/** Indicates whether shutdown stopped the runtime. */
|
|
79
79
|
private destroyed;
|
|
80
80
|
/** Timestamp of the last reported storage gap warning in epoch milliseconds. */
|
|
81
81
|
private lastGapAt;
|
|
@@ -84,7 +84,7 @@ export declare class ObservabilityRuntime {
|
|
|
84
84
|
*/
|
|
85
85
|
private constructor();
|
|
86
86
|
/**
|
|
87
|
-
*
|
|
87
|
+
* Receives direct messages from same-origin child frames.
|
|
88
88
|
* @param message Inbound bus message.
|
|
89
89
|
* @param reply Direct response callback.
|
|
90
90
|
*/
|
|
@@ -116,9 +116,9 @@ export declare class ObservabilityRuntime {
|
|
|
116
116
|
*/
|
|
117
117
|
private reconfigure;
|
|
118
118
|
/**
|
|
119
|
-
* Restores the storage strategy the adapter
|
|
120
|
-
* live
|
|
121
|
-
*
|
|
119
|
+
* Restores the storage strategy of the built adapter. The runtime reads all other keys
|
|
120
|
+
* live. It builds the adapter only one time. A new adapter strands the batches in the
|
|
121
|
+
* old adapter. That loss is worse than a refused change.
|
|
122
122
|
*/
|
|
123
123
|
private keepBuiltStorage;
|
|
124
124
|
/**
|
|
@@ -159,7 +159,7 @@ export declare class ObservabilityRuntime {
|
|
|
159
159
|
private role;
|
|
160
160
|
/**
|
|
161
161
|
* Loads the delivery stack if this context is the sender and has an endpoint.
|
|
162
|
-
* @returns Promise resolving when the load completes, or
|
|
162
|
+
* @returns Promise resolving when the load completes, or immediately when nothing loads.
|
|
163
163
|
*/
|
|
164
164
|
private syncSender;
|
|
165
165
|
/**
|
|
@@ -188,11 +188,12 @@ export declare class ObservabilityRuntime {
|
|
|
188
188
|
destroy(): Promise<void>;
|
|
189
189
|
/**
|
|
190
190
|
* Routes a completed log record to the pipeline or forward buffer.
|
|
191
|
-
* @param record Log record to emit, or null
|
|
191
|
+
* @param record Log record to emit, or null when the build dropped it.
|
|
192
192
|
*/
|
|
193
193
|
emit(record: LogRecord | null): void;
|
|
194
194
|
/**
|
|
195
|
-
*
|
|
195
|
+
* Sends a record to the forward buffer or to the local pipeline. The bus role selects
|
|
196
|
+
* the path.
|
|
196
197
|
* @param record Log record to route.
|
|
197
198
|
*/
|
|
198
199
|
private route;
|
|
@@ -214,24 +215,25 @@ export declare class ObservabilityRuntime {
|
|
|
214
215
|
*/
|
|
215
216
|
private forward;
|
|
216
217
|
/**
|
|
217
|
-
* Validates, samples and
|
|
218
|
-
* A forwarded record arrives built
|
|
219
|
-
*
|
|
218
|
+
* Validates, samples and queues records from child frames or workers.
|
|
219
|
+
* A forwarded record arrives built. This is the first point in this context where
|
|
220
|
+
* sampling can run. RecordBuilder samples a local record.
|
|
220
221
|
* @param records Inbound payload from bus.
|
|
221
222
|
*/
|
|
222
223
|
private ingestForwarded;
|
|
223
|
-
/** Flushes
|
|
224
|
+
/** Flushes the startup records. It adds the active journey to records without a journey. */
|
|
224
225
|
private releaseBootBuffer;
|
|
225
226
|
/**
|
|
226
|
-
* Emits a warning
|
|
227
|
+
* Emits a warning record when storage evicts batches.
|
|
227
228
|
* @param result Storage prune summary metrics.
|
|
228
229
|
*/
|
|
229
230
|
private readonly reportGap;
|
|
230
|
-
/**
|
|
231
|
+
/** Makes and stores a new tab ID after a tab ID collision. */
|
|
231
232
|
private regenerateTabId;
|
|
232
233
|
/**
|
|
233
234
|
* Counts the batches held in storage after a failed or deferred delivery.
|
|
234
|
-
* @returns Promise resolving to the number of stored batches. A forwarder
|
|
235
|
+
* @returns Promise resolving to the number of stored batches. A forwarder stores
|
|
236
|
+
* nothing and reports 0.
|
|
235
237
|
*/
|
|
236
238
|
queueDepth(): Promise<number>;
|
|
237
239
|
/**
|
package/dist/core/sampling.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ResolvedConfig } from "../models/config";
|
|
2
2
|
import type { LogRecord } from "../models/log-record";
|
|
3
|
-
/**
|
|
3
|
+
/** Fields that sampling reads. The caller knows all of them before it builds a record. */
|
|
4
4
|
export interface SampleInput {
|
|
5
5
|
/** Severity level of the entry. */
|
|
6
6
|
level: string;
|
|
@@ -8,43 +8,42 @@ export interface SampleInput {
|
|
|
8
8
|
type: string;
|
|
9
9
|
/** Originating application namespace. */
|
|
10
10
|
namespace: string;
|
|
11
|
-
/** Active journey
|
|
11
|
+
/** Active journey ID. It is empty when no journey runs. */
|
|
12
12
|
journeyId: string;
|
|
13
|
-
/** Trace
|
|
13
|
+
/** Trace ID. It is the sampling key when no journey runs. */
|
|
14
14
|
traceId: string;
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* a dropped entry must not pay for.
|
|
17
|
+
* Decides if sampling keeps an entry. It reads fields, not a record.
|
|
18
|
+
* This lets the caller drop an entry before the attribute walk runs.
|
|
20
19
|
* @param input Fields the sampling decision reads.
|
|
21
20
|
* @param config Active configuration instance.
|
|
22
|
-
* @returns True if the
|
|
21
|
+
* @returns True if the runtime keeps and sends the entry.
|
|
23
22
|
*/
|
|
24
23
|
export declare function shouldSampleInput(input: SampleInput, config: ResolvedConfig): boolean;
|
|
25
24
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
25
|
+
* Decides if sampling keeps a built log record. The runtime uses it for records
|
|
26
|
+
* that a child context sends over the bus.
|
|
28
27
|
* @param record Record to evaluate.
|
|
29
28
|
* @param config Active configuration instance.
|
|
30
|
-
* @returns True if the
|
|
29
|
+
* @returns True if the runtime keeps and sends the record.
|
|
31
30
|
*/
|
|
32
31
|
export declare function shouldSample(record: LogRecord, config: ResolvedConfig): boolean;
|
|
33
32
|
/**
|
|
34
|
-
*
|
|
33
|
+
* Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.
|
|
35
34
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
* ErrorCapture already limits auto-captured errors. This class limits the remaining case.
|
|
36
|
+
* An example is application code that calls logger.error in a render loop.
|
|
38
37
|
*/
|
|
39
38
|
export declare class ErrorCeiling {
|
|
40
|
-
/** Start of the window
|
|
39
|
+
/** Start of the current window, in epoch milliseconds. */
|
|
41
40
|
private windowStart;
|
|
42
41
|
/** ERROR and FATAL records admitted in the current window. */
|
|
43
42
|
private count;
|
|
44
43
|
/**
|
|
45
|
-
*
|
|
44
|
+
* Checks a record against the limit. It counts only ERROR and FATAL records.
|
|
46
45
|
* @param record Record about to enter a stream.
|
|
47
|
-
* @returns False when the window
|
|
46
|
+
* @returns False when the window has no allowance left. The caller must drop the record.
|
|
48
47
|
*/
|
|
49
48
|
allow(record: LogRecord): boolean;
|
|
50
49
|
}
|
package/dist/core/sender.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ export declare class Sender {
|
|
|
50
50
|
*/
|
|
51
51
|
queueDepth(): Promise<number>;
|
|
52
52
|
/**
|
|
53
|
-
* Sends pending records
|
|
53
|
+
* Sends pending records and stops all timers and listeners. Then it closes storage.
|
|
54
54
|
* The synchronous steps run before the first await. The runtime relies on this order.
|
|
55
55
|
* @returns Promise resolving when storage is closed.
|
|
56
56
|
*/
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
1
|
+
const e=require("./constants-TUFcy95w.cjs"),t=require("./platform-CXio0W2n.cjs");var n=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let n=e.target,r=n?.src??n?.href??``;if(n!==null&&n!==globalThis&&r!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?r:t.r(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":n.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let i=e,a=i.message===``?`unknown error`:i.message,o=i.error??Error(a);this.report(`window.onerror`,o,{"error.source":i.filename,"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`More than 20 errors occurred in ${String(e.V)} ms. The library ignores the other errors in this window.`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
|
|
2
2
|
`)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};exports.ErrorCapture=n;
|
|
3
|
-
//# sourceMappingURL=errors-
|
|
3
|
+
//# sourceMappingURL=errors-DRXBRqvm.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-DRXBRqvm.cjs","names":["stripUrlQuery","ERROR_STORM_WINDOW_MS","require_constants","require_platform","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":"iFAsBA,IAAaI,EAAb,KAA6C,CAmBd,IAjB7B,KAAgB,SAGhB,UAAoB,GAGpB,KAAwB,IAAI,IAG5B,YAAsB,EAGtB,YAAsB,EAKtB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,iBAAqB,MAGlD,KAAK,UAAY,GAGjB,iBAAiB,QAAS,KAAK,QAAS,EAAI,EAC5C,iBAAiB,qBAAsB,KAAK,WAAW,EACzD,CAGA,WAAkB,CACX,KAAK,YAGV,KAAK,UAAY,GAEjB,oBAAoB,QAAS,KAAK,QAAS,EAAI,EAC/C,oBAAoB,qBAAsB,KAAK,WAAW,EAC1D,KAAK,KAAK,MAAM,EAClB,CAGA,QAA4B,GAAoC,CAC9D,IAAMC,EAASC,EAAM,OACfC,EAAcF,GAAQ,KAAOA,GAAQ,MAAQ,GAGnD,GACEA,IAAW,MACXA,IAAY,YACZE,IAAgB,GAChB,CACA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,eAC3B,OAKF,IAAMC,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAWD,EAAcR,EAAAA,EAAcQ,CAAW,EAEtF,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,oBAAoBC,GAC/B,CAAC,EACD,KAAK,IAAI,OAAO,KAAK,0BAA2B,CAC9C,aAAc,WACd,eAAgBA,EAChB,eAAgBH,EAAO,QAAQ,YAAY,CAC7C,CAAC,EACD,MACF,CAEA,GAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,OAC3B,OAGF,IAAMI,EAAaH,EACbI,EAAWD,EAAW,UAAY,GAAK,gBAAkBA,EAAW,QAEpEE,EADkBF,EAAW,OACP,MAAMC,CAAQ,EAE1C,KAAK,OAAO,iBAAkBC,EAAO,CACnC,eAAgBF,EAAW,SAC3B,aAAcA,EAAW,OACzB,eAAgBA,EAAW,KAC7B,CAAC,CACH,EAGA,YAAgC,GAAuC,CAChE,KAAK,IAAI,OAAO,QAAQ,YAI7B,KAAK,OAAO,qBAAsBH,EAAM,OAAQ,CAC9C,aAAc,oBAChB,CAAC,CACH,EAQA,OAAe,EAAgB,EAAgB,EAAsC,CACnF,IAAMM,EAAM,KAAK,IAAI,EAQrB,GANIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,YAAc,GAGrB,KAAK,cACD,KAAK,YAAA,GAA0C,CAGjD,KAAK,IAAI,YAAY,OACnB,uBACA,mCAAsE,OAAOZ,EAAAA,CAAqB,EAAE,0DACtG,EACA,MACF,CAEA,IAAMa,EAAUF,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,EAClEG,GAASD,EAAQ,OAAS,GAAA,CAAI,MAAM;CAAI,CAAC,CAAC,IAAM,GAChDE,EAAM,GAAGF,EAAQ,KAAK,GAAGA,EAAQ,QAAQ,GAAGC,IAC5CE,EAAW,KAAK,KAAK,IAAID,CAAG,EAElC,GAAIC,GAAYJ,EAAMI,EAAS,GAAA,IAAsB,CACnD,EAAS,QACT,EAAS,GAAKJ,EACd,MACF,CAIA,IAAMK,EAAaD,EAAWA,EAAS,MAAQ,EAAI,EASnD,GALA,KAAK,KAAK,OAAOD,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIH,EAAK,MAAO,CAAE,CAAC,EAIpC,KAAK,KAAK,KAAA,IAAqC,CACjD,GAAM,CAACM,GAAU,KAAK,KAAK,KAAK,EAChC,KAAK,KAAK,OAAOA,CAAM,CACzB,CAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,UAAY,GAAKM,EAASN,EAAQ,QAASA,EAAS,CAChF,GAAGO,EACH,oBAAqBD,EACrB,yBAA0BF,CAC5B,CAAC,CACH,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { V as e } from "./constants-
|
|
2
|
-
import { r as t } from "./platform-
|
|
1
|
+
import { V as e } from "./constants-0-YchbAL.js";
|
|
2
|
+
import { r as t } from "./platform-CY8S3hUs.js";
|
|
3
3
|
//#region src/capture/errors.ts
|
|
4
4
|
var n = class {
|
|
5
5
|
ctx;
|
|
@@ -47,7 +47,7 @@ var n = class {
|
|
|
47
47
|
report(t, n, r) {
|
|
48
48
|
let i = Date.now();
|
|
49
49
|
if (i - this.windowStart > 1e4 && (this.windowStart = i, this.windowCount = 0), this.windowCount++, this.windowCount > 20) {
|
|
50
|
-
this.ctx.diagnostics.report("capture.rate_limited", `
|
|
50
|
+
this.ctx.diagnostics.report("capture.rate_limited", `More than 20 errors occurred in ${String(e)} ms. The library ignores the other errors in this window.`);
|
|
51
51
|
return;
|
|
52
52
|
}
|
|
53
53
|
let a = n instanceof Error ? n : Error(String(n)), o = (a.stack ?? "").split("\n")[1] ?? "", s = `${a.name}|${a.message}|${o}`, c = this.seen.get(s);
|
|
@@ -73,4 +73,4 @@ var n = class {
|
|
|
73
73
|
//#endregion
|
|
74
74
|
export { n as ErrorCapture };
|
|
75
75
|
|
|
76
|
-
//# sourceMappingURL=errors-
|
|
76
|
+
//# sourceMappingURL=errors-Dwm2SzBa.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-Dwm2SzBa.js","names":["ERROR_STORM_WINDOW_MS","stripUrlQuery","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","asError","frame","key","previous","suppressed","oldest","source","extra"],"sources":["../src/capture/errors.ts"],"sourcesContent":["// src/capture/errors.ts\n//\n// Captures uncaught errors, unhandled rejections and failed resource loads.\n\nimport {\n ERROR_DEDUPE_MS,\n ERROR_STORM_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n MAX_TRACKED_ERROR_SIGNATURES,\n} from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Tracking metadata for a deduplicated error signature. */\ninterface SeenError {\n /** Time of the last report for the signature, in epoch milliseconds. */\n at: number;\n /** Occurrences recorded since the last report. */\n count: number;\n}\n\n/** Captures uncaught exceptions, unhandled promise rejections, and failed resource loads. */\nexport class ErrorCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"errors\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Recently reported error signatures in LRU order. */\n private readonly seen = new Map<string, SeenError>();\n\n /** Start timestamp of the active throttling window in epoch milliseconds. */\n private windowStart = 0;\n\n /** Errors reported during the active throttling window. */\n private windowCount = 0;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Subscribes to global error and unhandledrejection events. */\n install(): void {\n if (this.installed || typeof addEventListener === \"undefined\") {\n return;\n }\n this.installed = true;\n\n // Uses capture phase to observe non-bubbling resource load errors.\n addEventListener(\"error\", this.onError, true);\n addEventListener(\"unhandledrejection\", this.onRejection);\n }\n\n /** Removes event listeners and clears tracked error signatures. */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"error\", this.onError, true);\n removeEventListener(\"unhandledrejection\", this.onRejection);\n this.seen.clear();\n }\n\n /** Routes resource load failures and uncaught script errors. */\n private readonly onError = (event: ErrorEvent | Event): void => {\n const target = event.target as (HTMLElement & { src?: string; href?: string }) | null;\n const resourceUrl = target?.src ?? target?.href ?? \"\";\n\n // Filters element-level resource load failures from script errors.\n if (\n target !== null &&\n target !== (globalThis as unknown as EventTarget) &&\n resourceUrl !== \"\"\n ) {\n if (!this.ctx.config.capture.resourceErrors) {\n return;\n }\n\n // A cache buster is noise. A signed URL is a credential.\n // The record keeps neither unless fullUrls is set.\n const url = this.ctx.config.capture.fullUrls ? resourceUrl : stripUrlQuery(resourceUrl);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `resource failed: ${url}`,\n });\n this.ctx.logger.warn(\"resource failed to load\", {\n \"error.type\": \"resource\",\n \"resource.url\": url,\n \"resource.tag\": target.tagName.toLowerCase(),\n });\n return;\n }\n\n if (!this.ctx.config.capture.errors) {\n return;\n }\n\n const errorEvent = event as ErrorEvent;\n const fallback = errorEvent.message === \"\" ? \"unknown error\" : errorEvent.message;\n const thrown: unknown = errorEvent.error;\n const error = thrown ?? new Error(fallback);\n\n this.report(\"window.onerror\", error, {\n \"error.source\": errorEvent.filename,\n \"error.line\": errorEvent.lineno,\n \"error.column\": errorEvent.colno,\n });\n };\n\n /** Captures unhandled promise rejections. */\n private readonly onRejection = (event: PromiseRejectionEvent): void => {\n if (!this.ctx.config.capture.rejections) {\n return;\n }\n\n this.report(\"unhandledrejection\", event.reason, {\n \"error.type\": \"unhandledrejection\",\n });\n };\n\n /**\n * Rate limits, deduplicates, and logs captured errors.\n * @param source Originating capture event name.\n * @param error Caught error instance or thrown value.\n * @param extra Contextual error attributes.\n */\n private report(source: string, error: unknown, extra: Record<string, unknown>): void {\n const now = Date.now();\n\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n\n this.windowCount++;\n if (this.windowCount > ERROR_STORM_MAX_PER_WINDOW) {\n // A render loop that throws in requestAnimationFrame makes thousands of errors each second.\n // Sending all of them is a denial of service on the ingest endpoint.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `More than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors occurred in ${String(ERROR_STORM_WINDOW_MS)} ms. The library ignores the other errors in this window.`,\n );\n return;\n }\n\n const asError = error instanceof Error ? error : new Error(String(error));\n const frame = (asError.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n const key = `${asError.name}|${asError.message}|${frame}`;\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < ERROR_DEDUPE_MS) {\n previous.count++;\n previous.at = now;\n return;\n }\n\n // This is the number of occurrences that deduplication dropped since the last report.\n // Without this count, many errors look like few errors.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Delete, then set, to move the key to the end of the map. The map stays in\n // least-recently-reported order. The eviction below needs this order.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page can throw with a new message at each render, for example from a template literal\n // in a loop. Without this cap, the map grows until the document closes.\n if (this.seen.size > MAX_TRACKED_ERROR_SIGNATURES) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n this.ctx.logger.error(asError.message === \"\" ? source : asError.message, asError, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;AAsBA,IAAaE,IAAb,MAA6C;CAmBd;CAjB7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,cAAsB;CAGtB,cAAsB;CAKtB,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,mBAAqB,QAGlD,KAAK,YAAY,IAGjB,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAC5C,iBAAiB,sBAAsB,KAAK,WAAW;CACzD;CAGA,YAAkB;EAChB,AAAK,KAAK,cAGV,KAAK,YAAY,IAEjB,oBAAoB,SAAS,KAAK,SAAS,EAAI,GAC/C,oBAAoB,sBAAsB,KAAK,WAAW,GAC1D,KAAK,KAAK,MAAM;CAClB;CAGA,WAA4B,MAAoC;EAC9D,IAAMC,IAASC,EAAM,QACfC,IAAcF,GAAQ,OAAOA,GAAQ,QAAQ;EAGnD,IACEA,MAAW,QACXA,MAAY,cACZE,MAAgB,IAChB;GACA,IAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,gBAC3B;GAKF,IAAMC,IAAM,KAAK,IAAI,OAAO,QAAQ,WAAWD,IAAcL,EAAcK,CAAW;GAOtF,AALA,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,oBAAoBC;GAC/B,CAAC,GACD,KAAK,IAAI,OAAO,KAAK,2BAA2B;IAC9C,cAAc;IACd,gBAAgBA;IAChB,gBAAgBH,EAAO,QAAQ,YAAY;GAC7C,CAAC;GACD;EACF;EAEA,IAAI,CAAC,KAAK,IAAI,OAAO,QAAQ,QAC3B;EAGF,IAAMI,IAAaH,GACbI,IAAWD,EAAW,YAAY,KAAK,kBAAkBA,EAAW,SAEpEE,IADkBF,EAAW,SACP,MAAMC,CAAQ;EAE1C,KAAK,OAAO,kBAAkBC,GAAO;GACnC,gBAAgBF,EAAW;GAC3B,cAAcA,EAAW;GACzB,gBAAgBA,EAAW;EAC7B,CAAC;CACH;CAGA,eAAgC,MAAuC;EACrE,AAAK,KAAK,IAAI,OAAO,QAAQ,cAI7B,KAAK,OAAO,sBAAsBH,EAAM,QAAQ,EAC9C,cAAc,qBAChB,CAAC;CACH;CAQA,OAAe,GAAgB,GAAgB,GAAsC;EACnF,IAAMM,IAAM,KAAK,IAAI;EAQrB,IANIA,IAAM,KAAK,cAAA,QACb,KAAK,cAAcA,GACnB,KAAK,cAAc,IAGrB,KAAK,eACD,KAAK,cAAA,IAA0C;GAGjD,KAAK,IAAI,YAAY,OACnB,wBACA,mCAAsE,OAAOX,CAAqB,EAAE,0DACtG;GACA;EACF;EAEA,IAAMY,IAAUF,aAAiB,QAAQA,IAAY,MAAM,OAAOA,CAAK,CAAC,GAClEG,KAASD,EAAQ,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM,IAChDE,IAAM,GAAGF,EAAQ,KAAK,GAAGA,EAAQ,QAAQ,GAAGC,KAC5CE,IAAW,KAAK,KAAK,IAAID,CAAG;EAElC,IAAIC,KAAYJ,IAAMI,EAAS,KAAA,KAAsB;GAEnD,AADA,EAAS,SACT,EAAS,KAAKJ;GACd;EACF;EAIA,IAAMK,IAAaD,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOD,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIH;GAAK,OAAO;EAAE,CAAC,GAIpC,KAAK,KAAK,OAAA,KAAqC;GACjD,IAAM,CAACM,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAEA,KAAK,IAAI,OAAO,MAAML,EAAQ,YAAY,KAAKM,IAASN,EAAQ,SAASA,GAAS;GAChF,GAAGO;GACH,qBAAqBD;GACrB,0BAA0BF;EAC5B,CAAC;CACH;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-DZH04585.cjs"),t=require("./sampling-Dui-Fp3u.cjs"),n=require("./platform-g99Kn755.cjs"),r=require("./unref-CU9Nyz_9.cjs");function i(t){return Math.round((performance.now()-t)*e.F)/e.F}function a(e,t,n,r,a){e.logMetric(`${t}.duration`,i(n),`ms`,`histogram`,{status:r,...a})}function o(e,t,n,r,a){e.error(`${t} failed`,r,{"action.duration_ms":i(n),status:`FAILURE`,...a})}function s(e,t,n,r){let i=performance.now();try{let o=n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}async function c(e,t,n,r){let i=performance.now();try{let o=await n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}function l(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`describing an error reason`,()=>String(e));return Error(n??typeof e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var d=class t{bind;namespace;options;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>s(this,e,t,n);timeAsync=(e,t,n)=>c(this,e,t,n);write(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;if(!i.builder.isEnabled(e)){this.mirrors(i,e)&&this.print(i,e,n,r,void 0,null);return}let{record:a,dropped:o}=i.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&o!==`redact`&&i.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.print(i,e,n,r,void 0,a),i.emit(a)}writeError(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;let a=i.builder.isEnabled(e);if(!a&&!this.mirrors(i,e))return;let o=r===void 0&&u(n),s=o?n:r,c=o||n===void 0?void 0:l(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:d}=i.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...s,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:i.breadcrumbs.snapshot()}});this.print(i,e,t,s,c,d),i.emit(d)}print(e,t,n,r,i,a){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},f={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},p=class{minLevel;diagnostics;constructor(e,t){this.minLevel=e,this.diagnostics=t}update(e){this.minLevel=e}accepts(t){return this.minLevel!==null&&e.it[t]>=e.it[this.minLevel]}write(n,r,i,a,o){if(!this.accepts(r)||typeof console>`u`)return;let s=`%c[%s]%c ${r}`,c=f[r];this.diagnostics.guard(`handler.threw`,`mirroring to console.${c}`,()=>{let r=[];o!==void 0&&r.push(o),a!==void 0&&r.push(t.p(a,e.bt)),console[c](s,e.D,n,``,i,...r)})}},m=class{value=0;next(){return++this.value}reset(){this.value=0}},h=/^[0-9a-f]{32}$/,g=/^[0-9a-f]{16}$/,_=/[1-9a-f]/;function v(e){return h.test(e.traceId)&&_.test(e.traceId)&&g.test(e.spanId)&&_.test(e.spanId)}function y(){return t.u(16)}function b(){return t.u(8)}function x(){return{traceId:y(),spanId:b(),traceFlags:1,startedAt:Date.now()}}function S(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var C=class{diagnostics;maxAgeMs;load;ambient=x();otel;constructor(t,n=e.on,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`@opentelemetry/api is not available, so records carry this library's own trace ids`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),S(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`reading the active OpenTelemetry span`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(v(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=x(),S(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`injecting OpenTelemetry headers`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.an]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},w=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function T(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function E(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||T(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Vt}", "ecs" or an implementation`),e.Vt)}function D(t,n){return t===void 0?n:t===!1?null:t===!0?e.E:t}function O(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:E(t.serializer,r?.serializer,n),console:D(t.console,i.console),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(a.endpoint===``)n.report(`config.invalid`,`endpoint is missing. The library builds records and drops them. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record will report service.name as '${e.un}'.`),e.un);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1, got ${String(o)}`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1, got ${String(t)}`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),k(t,n),a}function k(t,n){let r=new Set([...Object.keys(e.j),...e.cn]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`unknown config key "${e}", ignored. Typo?`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.ln[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`unknown config key "${r}.${e}", ignored. Typo?`)}}function A(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var j=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},M=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.at} onDiagnostic handler threw`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},N={maxAgeMs:e.tt,endOnOwnerClose:!1,urlParam:e.rt};function P(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function F(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function I(e){if(typeof e!=`object`||!e)return null;let t=P(e,`id`),n=P(e,`name`),r=F(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:P(e,`parentId`),ownerContextId:P(e,`ownerContextId`)??``}}function L(e){if(typeof e!=`object`||!e)return null;let t=P(e,`i`),n=P(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:F(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function R(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}var z=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.a){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`reading the persisted journey`,()=>this.stores.session().getItem(e.nt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.c(),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=R(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`journey token exceeded the size cap and was not issued`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a seeded journey older than maxAgeMs`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`adopted journey "${r.name}"`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=I(this.diagnostics.guard(`storage.degraded`,`parsing the persisted journey`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a persisted journey older than maxAgeMs`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`resumed journey "${t.name}"`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`decoding a seeded journey token`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return L(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`persisting the journey`,()=>{t===null?this.stores.session().removeItem(e.nt):this.stores.session().setItem(e.nt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`journey "${t.name}" hit maxAgeMs and was ended automatically`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=i,r.t(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`clearing the persisted journey`,()=>{this.stores.session().removeItem(e.nt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`reading the journey token from the URL`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`reading fin.me.getOptions()`,()=>t.i(r.call(n),e.ht)))?.customData?.[e.mt];return typeof i==`string`?i:null}};function B(e){return e}var V=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.it[t]>=e.it[n.minLevel]:!1}build(r){let{config:i,diagnostics:a,tracing:o,journey:s,sequence:c,limits:l}=this.deps;if(!this.isEnabled(r.level))return a.count(`record.dropped_by_level`),{record:null,dropped:`level`};let u=o.resolve(),d=s.current();if(!t.r({level:r.level,type:r.type,namespace:r.namespace,journeyId:d?.id??``,traceId:u.traceId},i))return a.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let f=c.next(),p=n.t(),m=i.capture.fullUrls?p:n.r(p),h,g=0;try{let e=t.m(this.deps.context.getAll(),l),n=t.m(r.scoped??{},l),i=t.m(r.payload??{},l);g=e.bytes+n.bytes+i.bytes,h={...B(e.value),...B(n.value),...B(i.value)}}catch(t){a.report(`record.sanitize_failed`,`attributes could not be sanitized`,void 0,t),h={[e.d]:!0}}h[e.l]=r.type,h[e.c]=f,h[e.n]=r.namespace,h[e.u]=m,d&&(h[e.a]=d.id,h[e.o]=d.name,d.parentId!==void 0&&(h[e.s]=d.parentId));let _=t.h(r.body,l.maxBodyChars);_!==r.body&&a.count(`record.truncated`);let v={timeUnixNano:t._(),traceId:u.traceId,spanId:u.spanId,traceFlags:u.traceFlags,severityNumber:e.Gt[r.level],severityText:r.level,body:_,attributes:h,resource:this.resource()},y=i.redact;if(y){let e=a.guard(`record.sanitize_failed`,`redact hook threw`,()=>y(v));if(e===null)return a.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==v){if(t.g(e)){let n=t.m(e.attributes,l);v={...e,attributes:B(n.value)},g=n.bytes}else a.report(`record.sanitize_failed`,`redact hook returned something that is not a record, keeping the original`)}}if(g>l.maxRecordBytes){a.report(`record.truncated`,`attributes exceeded the size budget and were dropped`,{bytes:g,body:v.body});let t={[e.l]:r.type,[e.c]:f,[e.n]:r.namespace,[e.u]:m,[e.i]:!0,[e.r]:g};d&&(t[e.a]=d.id,t[e.o]=d.name),v.attributes=t}return{record:v}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Ot]:t.serviceName,[e.kt]:t.serviceVersion,[e.wt]:t.environment,[e.Nt]:e.rn,[e.Pt]:e.in,[e.Mt]:e.nn,[e.Tt]:r.platform,[e.At]:n.sessionId,[e.jt]:n.tabId,[e.Ct]:n.contextId,[e.St]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Dt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Et]:r.openfinName}},this.resourceCache}},H={errors:async()=>(await Promise.resolve().then(()=>require("./errors-DPju_xSI.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-DDVIJSHd.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-DP0-rIPJ.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-DM2nvcMJ.cjs"))).WebVitalsCapture},U=Symbol.for(e.Rt),W=Symbol.for(e.zt),G=class r{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new j;breadcrumbs;tracing;sequence=new m;journey;builder;console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(r){this.diagnostics=new M(r.onDiagnostic),this.platform=n.n(this.diagnostics),this.config=O(r,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.s():t.a,this.identity=t.d(this.diagnostics,this.stores),this.sessionTouch=new t.o(this.diagnostics,this.stores),this.breadcrumbs=new w(50),this.tracing=new C(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new p(this.config.console,this.diagnostics),this.journey=new z(N,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new V({config:this.config,limits:e.bt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`accepting a direct message from a child`,()=>{n.acceptDirect(e,t)})})};static current(){return globalThis[U]??null}static stopped(){return globalThis[W]??null}isDestroyed(){return this.destroyed}static configure(e){let t=r.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let n=new r(e);return globalThis[U]=n,Reflect.deleteProperty(globalThis,W),n.init(),n}reconfigure(e){let t=this.keepEndpoint(e);A(this.config,O(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`configure() was called again, the existing runtime was updated`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup, still ${e}`,{requested:this.config.storage}),this.config.storage=e)}keepEndpoint(e){return this.senderLoad===void 0||e.endpoint!==null&&e.endpoint!==``?e:(this.diagnostics.report(`config.invalid`,`endpoint cannot be removed after the delivery stack loads. The endpoint in force stays.`),{...e,endpoint:void 0})}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`startup failed, continuing in a degraded state`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}await e}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`the bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-OdRJVUzr.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`the bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.config.endpoint||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-vLcbQhiB.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`the delivery stack did not load. Records are not sent.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new d(()=>this,e.C),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`installing ${e.name}`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`uninstalling ${e.name}`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`loading the ${e} capture`,H[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`registering a worker`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,r.current()===this&&(Reflect.deleteProperty(globalThis,U),globalThis[W]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad&&this.pushCapped(this.pendingRecords,e)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let n of e)t.g(n)?t.n(n,this.config)?this.deliver(n):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new d(()=>this,e.Yt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.c();this.diagnostics.report(`bus.role_resolved`,`another context claimed this tab id, most likely a duplicated tab. Regenerating.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,t.l(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}},K=new Map;function q(){return(G.current()??G.stopped())||G.configure({})}function J(e){G.configure(e)}function Y(e,t){if(t)return new d(q,e,t);let n=K.get(e);return n||(n=new d(q,e),K.set(e,n)),n}function X(){return Y(`app`)}function Z(e,t){X().trace(e,t)}function Q(e,t){X().debug(e,t)}function $(e,t){X().info(e,t)}function ee(e,t){X().warn(e,t)}function te(e,t,n){X().error(e,t,n)}function ne(e,t){X().logAction(e,t)}function re(e,t){X().logEvent(e,t)}function ie(e,t,n,r,i){X().logMetric(e,t,n,r,i)}function ae(e,t,n){return X().timeSync(e,t,n)}function oe(e,t,n){return X().timeAsync(e,t,n)}function se(e,t){q().context.set(e,t)}function ce(e){q().context.setMany(e)}function le(e){q().context.remove(e)}function ue(e,t){return q().journey.start(e,t)}function de(){q().journey.end()}function fe(){return q().journey.current()}function pe(){return q().journey.getToken()}function me(e){return q().journey.adopt(e,`manual`,!0)}function he(e){q().registerWorker(e)}function ge(){q().tracing.rotate(`explicit`)}function _e(){return q().tracing.headers()}function ve(){return q().flush()}function ye(){return q().queueDepth()}function be(){return q().diagnostics.snapshot()}async function xe(){await G.current()?.destroy()}exports.OneLogger=d,exports.adoptJourney=me,exports.configure=J,exports.currentJourney=fe,exports.debug=Q,exports.endJourney=de,exports.error=te,exports.flush=ve,exports.getDiagnosticCounters=be,exports.getJourneyToken=pe,exports.getLogger=Y,exports.getQueueDepth=ye,exports.getTraceHeaders=_e,exports.info=$,exports.logAction=ne,exports.logEvent=re,exports.logMetric=ie,exports.registerWorker=he,exports.removeContext=le,exports.setContext=se,exports.setContextMap=ce,exports.shutdown=xe,exports.startJourney=ue,exports.startTrace=ge,exports.timeAsync=oe,exports.timeSync=ae,exports.trace=Z,exports.warn=ee;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-TUFcy95w.cjs"),t=require("./sampling-CEthcmEX.cjs"),n=require("./platform-CXio0W2n.cjs"),r=require("./unref-CU9Nyz_9.cjs");function i(t){return Math.round((performance.now()-t)*e.F)/e.F}function a(e,t,n,r,a){e.logMetric(`${t}.duration`,i(n),`ms`,`histogram`,{status:r,...a})}function o(e,t,n,r,a){e.error(`${t} failed`,r,{"action.duration_ms":i(n),status:`FAILURE`,...a})}function s(e,t,n,r){let i=performance.now();try{let o=n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}async function c(e,t,n,r){let i=performance.now();try{let o=await n();return a(e,t,i,`SUCCESS`,r),o}catch(n){throw o(e,t,i,n,r),n}}function l(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`The library could not convert the error reason to text.`,()=>String(e));return Error(n??typeof e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var d=class t{bind;namespace;options;constructor(e,t,n={}){this.bind=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.bind,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>s(this,e,t,n);timeAsync=(e,t,n)=>c(this,e,t,n);write(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;if(!i.builder.isEnabled(e)){this.mirrors(i,e)&&this.print(i,e,n,r,void 0,null);return}let{record:a,dropped:o}=i.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&o!==`redact`&&i.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.print(i,e,n,r,void 0,a),i.emit(a)}writeError(e,t,n,r){let i=this.bind();if(i.isDestroyed())return;let a=i.builder.isEnabled(e);if(!a&&!this.mirrors(i,e))return;let o=r===void 0&&u(n),s=o?n:r,c=o||n===void 0?void 0:l(n,i.diagnostics);if(!a){this.print(i,e,t,s,c,null);return}let{record:d}=i.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...s,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:i.breadcrumbs.snapshot()}});this.print(i,e,t,s,c,d),i.emit(d)}print(e,t,n,r,i,a){e.config.redact?a?e.console.write(this.namespace,t,a.body,a.attributes):e.console.write(this.namespace,t,n,void 0,i):e.console.write(this.namespace,t,n,r,i)}mirrors(e,t){return e.config.enabled&&e.console.accepts(t)}},f={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},p=class{minLevel;diagnostics;constructor(e,t){this.minLevel=e,this.diagnostics=t}update(e){this.minLevel=e}accepts(t){return this.minLevel!==null&&e.it[t]>=e.it[this.minLevel]}write(n,r,i,a,o){if(!this.accepts(r)||typeof console>`u`)return;let s=`%c[%s]%c ${r}`,c=f[r];this.diagnostics.guard(`handler.threw`,`The library could not print to console.${c}.`,()=>{let r=[];o!==void 0&&r.push(o),a!==void 0&&r.push(t.p(a,e.bt,this.diagnostics)),console[c](s,e.D,n,``,i,...r)})}},m=class{value=0;next(){return++this.value}reset(){this.value=0}},h=/^[0-9a-f]{32}$/,g=/^[0-9a-f]{16}$/,_=/[1-9a-f]/;function v(e){return h.test(e.traceId)&&_.test(e.traceId)&&g.test(e.spanId)&&_.test(e.spanId)}function y(){return t.u(16)}function b(){return t.u(8)}function x(){return{traceId:y(),spanId:b(),traceFlags:1,startedAt:Date.now()}}function S(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var C=class{diagnostics;maxAgeMs;load;ambient=x();otel;constructor(t,n=e.on,r){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){if(this.load)try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`The library could not load @opentelemetry/api. Records use the trace ids of the library.`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),S(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`The library could not read the active OpenTelemetry span.`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(v(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=x(),S(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`The library could not add the OpenTelemetry headers.`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.an]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},w=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function T(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function E(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||T(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Vt}", "ecs" or an implementation. The library uses "${e.Vt}".`),e.Vt)}function D(t,n){return t===void 0?n:t===!1?null:t===!0?e.E:t}function O(t,n,r){let i=r??e.j,a={...i,...t,endpoint:t.endpoint===void 0?i.endpoint:t.endpoint,serializer:E(t.serializer,r?.serializer,n),console:D(t.console,i.console),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(a.endpoint===``)n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);else if(a.endpoint!==null)try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}.`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.un}'.`),e.un);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1. The value is ${String(o)}. The library uses 1.`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1. The value is ${String(t)}. The library uses 1.`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),k(t,n),a}function k(t,n){let r=new Set([...Object.keys(e.j),...e.cn]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.ln[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function A(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var j=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},M=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.at} The onDiagnostic handler threw an error.`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},N={maxAgeMs:e.tt,endOnOwnerClose:!1,urlParam:e.rt};function P(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function F(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function I(e){if(typeof e!=`object`||!e)return null;let t=P(e,`id`),n=P(e,`name`),r=F(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:P(e,`parentId`),ownerContextId:P(e,`ownerContextId`)??``}}function L(e){if(typeof e!=`object`||!e)return null;let t=P(e,`i`),n=P(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:F(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function R(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.g,`-`).replace(e._,`_`).replace(e.h,``)}var z=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.a){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.nt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.c(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=R(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=I(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return L(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.nt):this.stores.session().setItem(e.nt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=i,r.t(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.nt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let n=globalThis.fin?.me,r=n?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>t.i(r.call(n),e.ht)))?.customData?.[e.mt];return typeof i==`string`?i:null}};function B(e){return e}var V=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.it[t]>=e.it[n.minLevel]:!1}build(r){let{config:i,diagnostics:a,tracing:o,journey:s,sequence:c,limits:l}=this.deps;if(!this.isEnabled(r.level))return a.count(`record.dropped_by_level`),{record:null,dropped:`level`};let u=o.resolve(),d=s.current();if(!t.r({level:r.level,type:r.type,namespace:r.namespace,journeyId:d?.id??``,traceId:u.traceId},i))return a.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let f=c.next(),p=n.t(a),m=i.capture.fullUrls?p:n.r(p),h,g=0;try{let e=t.m(this.deps.context.getAll(),l,a),n=t.m(r.scoped??{},l,a),i=t.m(r.payload??{},l,a);g=e.bytes+n.bytes+i.bytes,h={...B(e.value),...B(n.value),...B(i.value)}}catch(t){a.report(`record.sanitize_failed`,`The library could not sanitize the attributes.`,void 0,t),h={[e.d]:!0}}h[e.l]=r.type,h[e.c]=f,h[e.n]=r.namespace,h[e.u]=m,d&&(h[e.a]=d.id,h[e.o]=d.name,d.parentId!==void 0&&(h[e.s]=d.parentId));let _=t.h(r.body,l.maxBodyChars);_!==r.body&&a.count(`record.truncated`);let v={timeUnixNano:t._(),traceId:u.traceId,spanId:u.spanId,traceFlags:u.traceFlags,severityNumber:e.Gt[r.level],severityText:r.level,body:_,attributes:h,resource:this.resource()},y=i.redact;if(y){let e=a.guard(`record.sanitize_failed`,`The redact hook threw an error.`,()=>y(v));if(e===null)return a.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==v){if(t.g(e)){let n=t.m(e.attributes,l,a);v={...e,attributes:B(n.value)},g=n.bytes}else a.report(`record.sanitize_failed`,`The redact hook returned a value that is not a record. The library keeps the original record.`)}}if(g>l.maxRecordBytes){a.report(`record.truncated`,`The attributes are larger than the size limit. The library dropped them.`,{bytes:g,body:v.body});let t={[e.l]:r.type,[e.c]:f,[e.n]:r.namespace,[e.u]:m,[e.i]:!0,[e.r]:g};d&&(t[e.a]=d.id,t[e.o]=d.name),v.attributes=t}return{record:v}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Ot]:t.serviceName,[e.kt]:t.serviceVersion,[e.wt]:t.environment,[e.Nt]:e.rn,[e.Pt]:e.in,[e.Mt]:e.nn,[e.Tt]:r.platform,[e.At]:n.sessionId,[e.jt]:n.tabId,[e.Ct]:n.contextId,[e.St]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Dt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Et]:r.openfinName}},this.resourceCache}},H={errors:async()=>(await Promise.resolve().then(()=>require("./errors-DRXBRqvm.cjs"))).ErrorCapture,network:async()=>(await Promise.resolve().then(()=>require("./network-CuqWadNn.cjs"))).NetworkCapture,interactions:async()=>(await Promise.resolve().then(()=>require("./interactions-DVom6eYn.cjs"))).InteractionCapture,webVitals:async()=>(await Promise.resolve().then(()=>require("./web-vitals-B2FYsEAU.cjs"))).WebVitalsCapture},U=Symbol.for(e.Rt),W=Symbol.for(e.zt),G=class r{diagnostics;config;platform;identity;stores;identityBuiltAs;sessionTouch;context=new j;breadcrumbs;tracing;sequence=new m;journey;builder;console;bus=null;busBuilt;busLoad;storageBuiltAs;sender;senderLoad;pendingRecords=[];captures=[];captureGeneration=0;captureOnce={webVitals:!1,navigationTiming:!1};bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;roleResolved=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(r){this.diagnostics=new M(r.onDiagnostic),this.platform=n.n(this.diagnostics),this.config=O(r,this.diagnostics),this.identityBuiltAs=this.config.identity,this.stores=this.identityBuiltAs===`memory`?t.s():t.a,this.identity=t.d(this.diagnostics,this.stores),this.sessionTouch=new t.o(this.diagnostics,this.stores),this.breadcrumbs=new w(50),this.tracing=new C(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new p(this.config.console,this.diagnostics),this.journey=new z(N,this.diagnostics,this.identity.contextId,e=>{this.bus?.broadcastJourney(e)},this.stores),this.builder=new V({config:this.config,limits:e.bt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform})}busAccept=(e,t)=>{this.destroyed||this.ensureBus().then(n=>{n&&!this.destroyed&&this.diagnostics.guard(`bus.send_failed`,`The bus could not accept a direct message from a child frame.`,()=>{n.acceptDirect(e,t)})})};static current(){return globalThis[U]??null}static stopped(){return globalThis[W]??null}isDestroyed(){return this.destroyed}static configure(e){let t=r.current();if(t&&!t.destroyed)return t.reconfigure(e),t;let n=new r(e);return globalThis[U]=n,Reflect.deleteProperty(globalThis,W),n.init(),n}reconfigure(e){let t=this.keepEndpoint(e);A(this.config,O(t,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.keepBuiltIdentity(),this.installCaptures(),this.roleResolved&&this.syncSender(),this.diagnostics.report(`config.reconfigured`,`A later configure() call updated the runtime.`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup. It stays ${e}.`,{requested:this.config.storage}),this.config.storage=e)}keepEndpoint(e){return this.senderLoad===void 0||e.endpoint!==null&&e.endpoint!==``?e:(this.diagnostics.report(`config.invalid`,`You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.`),{...e,endpoint:void 0})}keepBuiltIdentity(){let e=this.identityBuiltAs;this.config.identity!==e&&(this.diagnostics.report(`config.invalid`,`identity cannot change after startup. It stays ${e}.`,{requested:this.config.identity}),this.config.identity=e)}async init(){let e=this.installCaptures();try{let e=this.journey.bootstrap();this.config.bus.mode!==`off`&&await this.ensureBus(),this.roleResolved=!0,await this.syncSender(),await e}catch(e){this.diagnostics.report(`pipeline.crashed`,`Startup failed. The runtime continues with reduced function.`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}await e}ensureBus(){return this.busLoad??=this.startBus(),this.busLoad}constructBus(){return this.busBuilt??=this.buildBus(),this.busBuilt}async startBus(){let e=await this.constructBus();if(!e)return null;try{return await e.start(),e}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not start. This context sends its own records.`,void 0,e),null}}async buildBus(){try{let{Bus:e}=await Promise.resolve().then(()=>require("./bus-ChIXDAWD.cjs"));if(this.destroyed)return null;let t=new e(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}});return this.bus=t,t}catch(e){return this.diagnostics.report(`pipeline.crashed`,`The bus did not load. This context sends its own records.`,void 0,e),null}}role(){return this.bus?.getRole()??`sender`}syncSender(){return!this.config.endpoint||this.role()!==`sender`?Promise.resolve():this.loadSender()}loadSender(){return this.senderLoad??=this.buildSender(),this.senderLoad}async buildSender(){this.storageBuiltAs=this.config.storage;try{let{Sender:e}=await Promise.resolve().then(()=>require("./sender-ByFAkXVd.cjs")),t=this.destroyed?null:await e.create({config:this.config,diagnostics:this.diagnostics,onGap:this.reportGap});if(!t||this.destroyed){await t?.destroy();return}this.sender=t}catch(e){this.senderLoad=void 0,this.diagnostics.report(`pipeline.crashed`,`The delivery stack did not load. The library does not send records.`,{held:this.pendingRecords.length},e)}let e=this.pendingRecords;this.pendingRecords=[];for(let t of e)this.sender?.push(t)}async installCaptures(){let t=++this.captureGeneration,n=this.config.capture,r=[];(n.errors||n.rejections||n.resourceErrors)&&r.push(`errors`),(n.fetch||n.xhr)&&r.push(`network`),(n.interactions||n.navigation)&&r.push(`interactions`),n.webVitals&&r.push(`webVitals`);let i=await Promise.all(r.map(e=>this.loadCapture(e)));if(t!==this.captureGeneration||this.destroyed)return;this.uninstallCaptures();let a={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new d(()=>this,e.C),once:this.captureOnce};for(let e of i)e&&this.captures.push(new e(a));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not install the ${e.name} capture.`,()=>{e.install()})}uninstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`The library could not uninstall the ${e.name} capture.`,()=>{e.uninstall()});this.captures.length=0}loadCapture(e){return this.diagnostics.guardAsync(`capture.install_failed`,`The library could not load the ${e} capture.`,H[e])}registerWorker(e){this.destroyed||this.constructBus().then(t=>{t&&!this.destroyed&&(this.diagnostics.guard(`bus.send_failed`,`The library could not register the worker.`,()=>{t.attachWorker(e)}),this.ensureBus())})}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.uninstallCaptures();let e=this.sender?.destroy();this.journey.destroy(),this.bus?.destroy(),this.forwardBuffer=[],this.pendingRecords=[],await e,await this.senderLoad,r.current()===this&&(Reflect.deleteProperty(globalThis,U),globalThis[W]=this)}emit(e){e&&!this.destroyed&&(this.sessionTouch.touch(this.identity.sessionId),this.ready?this.route(e):this.pushCapped(this.bootBuffer,e))}route(e){this.role()===`forwarder`?this.forward(e):this.deliver(e)}deliver(e){this.sender?this.sender.push(e):this.senderLoad&&this.pushCapped(this.pendingRecords,e)}pushCapped(e,t){e.length>=500&&(e.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),e.push(t)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e))this.diagnostics.count(`record.dropped_malformed`);else for(let n of e)t.g(n)?t.n(n,this.config)?this.deliver(n):this.diagnostics.count(`record.dropped_by_sampling`):this.diagnostics.count(`record.dropped_malformed`)}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new d(()=>this,e.Yt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let e=t.c(this.diagnostics);this.diagnostics.report(`bus.role_resolved`,`Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.`,{was:this.identity.tabId,now:e}),this.identity.tabId=e,t.l(e,this.diagnostics,this.stores),this.builder.invalidateResource()}async queueDepth(){return await this.senderLoad,await this.sender?.queueDepth()??0}async flush(){if(this.role()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus?.sendRecords(e)}else await this.senderLoad,await this.sender?.flush()}},K=new Map;function q(){return(G.current()??G.stopped())||G.configure({})}function J(e){G.configure(e)}function Y(e,t){if(t)return new d(q,e,t);let n=K.get(e);return n||(n=new d(q,e),K.set(e,n)),n}function X(){return Y(`app`)}function Z(e,t){X().trace(e,t)}function Q(e,t){X().debug(e,t)}function $(e,t){X().info(e,t)}function ee(e,t){X().warn(e,t)}function te(e,t,n){X().error(e,t,n)}function ne(e,t){X().logAction(e,t)}function re(e,t){X().logEvent(e,t)}function ie(e,t,n,r,i){X().logMetric(e,t,n,r,i)}function ae(e,t,n){return X().timeSync(e,t,n)}function oe(e,t,n){return X().timeAsync(e,t,n)}function se(e,t){q().context.set(e,t)}function ce(e){q().context.setMany(e)}function le(e){q().context.remove(e)}function ue(e,t){return q().journey.start(e,t)}function de(){q().journey.end()}function fe(){return q().journey.current()}function pe(){return q().journey.getToken()}function me(e){return q().journey.adopt(e,`manual`,!0)}function he(e){q().registerWorker(e)}function ge(){q().tracing.rotate(`explicit`)}function _e(){return q().tracing.headers()}function ve(){return q().flush()}function ye(){return q().queueDepth()}function be(){return q().diagnostics.snapshot()}async function xe(){await G.current()?.destroy()}exports.OneLogger=d,exports.adoptJourney=me,exports.configure=J,exports.currentJourney=fe,exports.debug=Q,exports.endJourney=de,exports.error=te,exports.flush=ve,exports.getDiagnosticCounters=be,exports.getJourneyToken=pe,exports.getLogger=Y,exports.getQueueDepth=ye,exports.getTraceHeaders=_e,exports.info=$,exports.logAction=ne,exports.logEvent=re,exports.logMetric=ie,exports.registerWorker=he,exports.removeContext=le,exports.setContext=se,exports.setContextMap=ce,exports.shutdown=xe,exports.startJourney=ue,exports.startTrace=ge,exports.timeAsync=oe,exports.timeSync=ae,exports.trace=Z,exports.warn=ee;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|