@utk09/ui-observability 0.9.4 → 0.9.5
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 +45 -0
- package/README.md +122 -94
- package/dist/batch-BQFtb3i5.cjs +2 -0
- package/dist/batch-BQFtb3i5.cjs.map +1 -0
- package/dist/{batch-D-4xl7op.js → batch-BUJh-1jZ.js} +7 -5
- package/dist/batch-BUJh-1jZ.js.map +1 -0
- package/dist/bus/bus.d.ts +76 -2
- package/dist/bus/links.d.ts +9 -2
- package/dist/bus/validation.d.ts +7 -0
- package/dist/bus-BW6N-pY8.cjs +2 -0
- package/dist/bus-BW6N-pY8.cjs.map +1 -0
- package/dist/bus-DeOPHWaD.js +647 -0
- package/dist/bus-DeOPHWaD.js.map +1 -0
- package/dist/capture/storm.d.ts +2 -1
- package/dist/capture/types.d.ts +2 -0
- package/dist/{console-Boqa7new.cjs → console-Ce6heqZZ.cjs} +2 -2
- package/dist/console-Ce6heqZZ.cjs.map +1 -0
- package/dist/{console-BT7mcgU6.js → console-DbAZYJuy.js} +4 -4
- package/dist/console-DbAZYJuy.js.map +1 -0
- package/dist/constants-CN7GE1Lt.js +246 -0
- package/dist/constants-CN7GE1Lt.js.map +1 -0
- package/dist/constants-CW-MlHdY.cjs +2 -0
- package/dist/constants-CW-MlHdY.cjs.map +1 -0
- package/dist/constants.d.ts +29 -9
- package/dist/context-storage-BjzeBSxH.cjs +2 -0
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
- package/dist/context-storage-DxZf4Gfh.js +52 -0
- package/dist/context-storage-DxZf4Gfh.js.map +1 -0
- package/dist/core/breadcrumbs.d.ts +7 -2
- package/dist/core/context.d.ts +2 -0
- package/dist/core/diagnostics.d.ts +11 -3
- package/dist/core/meter.d.ts +6 -1
- package/dist/core/pipeline.d.ts +29 -2
- package/dist/core/record.d.ts +2 -1
- package/dist/core/runtime.d.ts +91 -3
- package/dist/core/sampling.d.ts +3 -1
- package/dist/core/sender.d.ts +35 -1
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/emergency-queue-BYUyDHGD.js +69 -0
- package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
- package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
- package/dist/{errors-BDI96zKc.js → errors-BhC7HTSt.js} +8 -9
- package/dist/errors-BhC7HTSt.js.map +1 -0
- package/dist/errors-CgY633cG.cjs +3 -0
- package/dist/errors-CgY633cG.cjs.map +1 -0
- package/dist/factory-C5TujXlU.js +280 -0
- package/dist/factory-C5TujXlU.js.map +1 -0
- package/dist/factory-CNj4DH3n.cjs +2 -0
- package/dist/factory-CNj4DH3n.cjs.map +1 -0
- package/dist/fixed-window-CtaFHanJ.js +12 -0
- package/dist/fixed-window-CtaFHanJ.js.map +1 -0
- package/dist/fixed-window-CvESpFYV.cjs +2 -0
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
- package/dist/identity-8vKkyAWm.js +103 -0
- package/dist/identity-8vKkyAWm.js.map +1 -0
- package/dist/identity-Da9TkuKd.cjs +2 -0
- package/dist/identity-Da9TkuKd.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +45 -7
- package/dist/index.js +908 -529
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
- package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
- package/dist/{indexeddb-storage-HgkQUTyS.js → indexeddb-storage-CCA1LvtO.js} +33 -18
- package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
- package/dist/{interactions-Ck01cEij.js → interactions-BUDLxbv1.js} +16 -12
- package/dist/interactions-BUDLxbv1.js.map +1 -0
- package/dist/interactions-NHbLKrqe.cjs +2 -0
- package/dist/interactions-NHbLKrqe.cjs.map +1 -0
- package/dist/{journey-DRK0A8u_.js → journey-BUJ4WJxP.js} +12 -12
- package/dist/{journey-DRK0A8u_.js.map → journey-BUJ4WJxP.js.map} +1 -1
- package/dist/{journey-Co9OlzrW.cjs → journey-B_tTnvac.cjs} +2 -2
- package/dist/{journey-Co9OlzrW.cjs.map → journey-B_tTnvac.cjs.map} +1 -1
- package/dist/keys-BHhw_0Wh.cjs +2 -0
- package/dist/keys-BHhw_0Wh.cjs.map +1 -0
- package/dist/keys-D5r_GH9q.js +17 -0
- package/dist/keys-D5r_GH9q.js.map +1 -0
- package/dist/{library-request-ChCar5F8.js → library-request-BKOcaKtQ.js} +2 -2
- package/dist/{library-request-ChCar5F8.js.map → library-request-BKOcaKtQ.js.map} +1 -1
- package/dist/{library-request-gMFOCNcn.cjs → library-request-BaZOi4eg.cjs} +2 -2
- package/dist/{library-request-gMFOCNcn.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
- package/dist/{long-frames-Bky6nZDF.cjs → long-frames-CF3qiSAX.cjs} +2 -2
- package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
- package/dist/{long-frames-DDumopji.js → long-frames-DI5ypfAF.js} +5 -5
- package/dist/long-frames-DI5ypfAF.js.map +1 -0
- package/dist/models/batch.d.ts +4 -0
- package/dist/models/bus.d.ts +32 -9
- package/dist/models/config.d.ts +347 -9
- package/dist/models/drop.d.ts +1 -1
- package/dist/models/health.d.ts +27 -0
- package/dist/models/storage.d.ts +13 -0
- package/dist/network-CF8UO5PK.cjs +2 -0
- package/dist/network-CF8UO5PK.cjs.map +1 -0
- package/dist/{network-BsBZ6_-Q.js → network-DdzXDI3J.js} +18 -16
- package/dist/network-DdzXDI3J.js.map +1 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{platform-4yYjMD-B.js → platform-Bw1btWCT.js} +16 -10
- package/dist/platform-Bw1btWCT.js.map +1 -0
- package/dist/platform-DBSKTvFn.cjs +2 -0
- package/dist/platform-DBSKTvFn.cjs.map +1 -0
- package/dist/{remote-rules-1KqfVBIu.js → remote-rules-DIcC5vVC.js} +3 -3
- package/dist/{remote-rules-1KqfVBIu.js.map → remote-rules-DIcC5vVC.js.map} +1 -1
- package/dist/{remote-rules-BHgEGlYi.cjs → remote-rules-DpFmOef2.cjs} +2 -2
- package/dist/{remote-rules-BHgEGlYi.cjs.map → remote-rules-DpFmOef2.cjs.map} +1 -1
- package/dist/sampling-BVjspJWu.cjs +2 -0
- package/dist/sampling-BVjspJWu.cjs.map +1 -0
- package/dist/{sampling-nYIWP_vP.js → sampling-Cm3WhI0a.js} +26 -36
- package/dist/sampling-Cm3WhI0a.js.map +1 -0
- package/dist/{sanitize-BiUKCUG6.js → sanitize-C-ahCFsG.js} +2 -2
- package/dist/{sanitize-BiUKCUG6.js.map → sanitize-C-ahCFsG.js.map} +1 -1
- package/dist/{sanitize-BxuPSXOk.cjs → sanitize-DHucKGdi.cjs} +2 -2
- package/dist/{sanitize-BxuPSXOk.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
- package/dist/sender-D3fRCR8d.cjs +3 -0
- package/dist/sender-D3fRCR8d.cjs.map +1 -0
- package/dist/sender-DUUmSglb.js +1163 -0
- package/dist/sender-DUUmSglb.js.map +1 -0
- package/dist/storage/context-storage.d.ts +89 -0
- package/dist/storage/emergency-queue.d.ts +9 -1
- package/dist/storage/factory.d.ts +7 -1
- package/dist/storage/idb-driver.d.ts +13 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -0
- package/dist/storage/local-storage.d.ts +21 -1
- package/dist/storage/memory-storage.d.ts +13 -0
- package/dist/storage-BA9RqRO-.cjs +2 -0
- package/dist/storage-BA9RqRO-.cjs.map +1 -0
- package/dist/storage-w7Tslvlq.js +17 -0
- package/dist/storage-w7Tslvlq.js.map +1 -0
- package/dist/storm-CNZjsw4T.cjs +2 -0
- package/dist/storm-CNZjsw4T.cjs.map +1 -0
- package/dist/storm-Daq2jGHU.js +10 -0
- package/dist/storm-Daq2jGHU.js.map +1 -0
- package/dist/transport/retry-engine.d.ts +7 -2
- package/dist/transport/status-transport.d.ts +17 -0
- package/dist/types-BR9t_w28.js.map +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/utils/fixed-window.d.ts +9 -0
- package/dist/utils/identity.d.ts +9 -2
- package/dist/utils/lock.d.ts +8 -0
- package/dist/utils/openfin.d.ts +1 -1
- package/dist/utils/platform.d.ts +3 -1
- package/dist/web-socket-BacvKOvD.cjs +2 -0
- package/dist/web-socket-BacvKOvD.cjs.map +1 -0
- package/dist/web-socket-CpsD8WAa.js +105 -0
- package/dist/web-socket-CpsD8WAa.js.map +1 -0
- package/package.json +1 -1
- package/dist/batch-C4oF6XZT.cjs +0 -2
- package/dist/batch-C4oF6XZT.cjs.map +0 -1
- package/dist/batch-D-4xl7op.js.map +0 -1
- package/dist/bus-Cyvq-Ngx.js +0 -478
- package/dist/bus-Cyvq-Ngx.js.map +0 -1
- package/dist/bus-rOhVuRee.cjs +0 -2
- package/dist/bus-rOhVuRee.cjs.map +0 -1
- package/dist/console-BT7mcgU6.js.map +0 -1
- package/dist/console-Boqa7new.cjs.map +0 -1
- package/dist/constants-BgRS6MB0.cjs +0 -2
- package/dist/constants-BgRS6MB0.cjs.map +0 -1
- package/dist/constants-L_d5YvvQ.js +0 -160
- package/dist/constants-L_d5YvvQ.js.map +0 -1
- package/dist/errors-BDI96zKc.js.map +0 -1
- package/dist/errors-_xEsCVXn.cjs +0 -3
- package/dist/errors-_xEsCVXn.cjs.map +0 -1
- package/dist/fixed-window-BR0bu32Y.cjs +0 -2
- package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
- package/dist/fixed-window-Re7jIRJH.js +0 -9
- package/dist/fixed-window-Re7jIRJH.js.map +0 -1
- package/dist/identity-Bwku7zzN.cjs +0 -2
- package/dist/identity-Bwku7zzN.cjs.map +0 -1
- package/dist/identity-Dtv917nz.js +0 -98
- package/dist/identity-Dtv917nz.js.map +0 -1
- package/dist/indexeddb-storage-Cvavrf-y.cjs +0 -2
- package/dist/indexeddb-storage-Cvavrf-y.cjs.map +0 -1
- package/dist/indexeddb-storage-HgkQUTyS.js.map +0 -1
- package/dist/interactions-Bhe1ft8P.cjs +0 -2
- package/dist/interactions-Bhe1ft8P.cjs.map +0 -1
- package/dist/interactions-Ck01cEij.js.map +0 -1
- package/dist/log-record-cwFiLyPY.js +0 -17
- package/dist/log-record-cwFiLyPY.js.map +0 -1
- package/dist/log-record-jX9eWUP8.cjs +0 -2
- package/dist/log-record-jX9eWUP8.cjs.map +0 -1
- package/dist/long-frames-Bky6nZDF.cjs.map +0 -1
- package/dist/long-frames-DDumopji.js.map +0 -1
- package/dist/network-BsBZ6_-Q.js.map +0 -1
- package/dist/network-_4csBGBM.cjs +0 -2
- package/dist/network-_4csBGBM.cjs.map +0 -1
- package/dist/platform-4yYjMD-B.js.map +0 -1
- package/dist/platform-o7r1ocOu.cjs +0 -2
- package/dist/platform-o7r1ocOu.cjs.map +0 -1
- package/dist/sampling-C4my-ma0.cjs +0 -2
- package/dist/sampling-C4my-ma0.cjs.map +0 -1
- package/dist/sampling-nYIWP_vP.js.map +0 -1
- package/dist/sender-6vrT9fFL.cjs +0 -3
- package/dist/sender-6vrT9fFL.cjs.map +0 -1
- package/dist/sender-DFQMF39P.js +0 -1351
- package/dist/sender-DFQMF39P.js.map +0 -1
- package/dist/storm-6YYbXzT_.cjs +0 -2
- package/dist/storm-6YYbXzT_.cjs.map +0 -1
- package/dist/storm-CfO0Sam2.js +0 -10
- package/dist/storm-CfO0Sam2.js.map +0 -1
- package/dist/web-socket-Ar4cZxmd.js +0 -102
- package/dist/web-socket-Ar4cZxmd.js.map +0 -1
- package/dist/web-socket-BwJdwSHl.cjs +0 -2
- package/dist/web-socket-BwJdwSHl.cjs.map +0 -1
package/dist/core/record.d.ts
CHANGED
|
@@ -98,9 +98,10 @@ export declare class RecordBuilder {
|
|
|
98
98
|
/**
|
|
99
99
|
* Builds a structured LogRecord from the input. It sanitizes attributes and applies size limits.
|
|
100
100
|
* @param input Logger call input parameters.
|
|
101
|
+
* @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.
|
|
101
102
|
* @returns The record, or null with the reason of the drop.
|
|
102
103
|
*/
|
|
103
|
-
build(input: BuildInput): BuildResult;
|
|
104
|
+
build(input: BuildInput, forConsole?: boolean): BuildResult;
|
|
104
105
|
/**
|
|
105
106
|
* Runs the redact hook on a record from another context. A child context without redact
|
|
106
107
|
* forwards raw records. The sender is the last privacy gate.
|
package/dist/core/runtime.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Receive, WorkerLike } from "../bus/links";
|
|
2
2
|
import type { BusMessage } from "../models/bus";
|
|
3
|
-
import type {
|
|
3
|
+
import type { FrameOptions, SourceOptions } from "../models/bus";
|
|
4
|
+
import type { ObservabilityConfig, ResolvedConfig, SecurityContextUpdate, SecurityContextRotationOptions } from "../models/config";
|
|
4
5
|
import type { InstrumentDef, MetricAttributes } from "../models/metric";
|
|
5
6
|
import { type LogRecord } from "../models/log-record";
|
|
6
7
|
import type { DeliveryStats } from "../models/stats";
|
|
8
|
+
import type { ObservabilityHealth } from "../models/health";
|
|
7
9
|
import { ConsoleSink } from "../utils/console";
|
|
8
10
|
import { type Identity } from "../utils/identity";
|
|
9
11
|
import { type PlatformMetadata } from "../utils/platform";
|
|
@@ -16,6 +18,33 @@ import { JourneyEngine } from "./journey";
|
|
|
16
18
|
import { RecordBuilder } from "./record";
|
|
17
19
|
/** Manages subsystem lifecycles, bus coordination and record delivery. */
|
|
18
20
|
export declare class ObservabilityRuntime {
|
|
21
|
+
/** True while the runtime changes the security context. */
|
|
22
|
+
private rotating;
|
|
23
|
+
/** True while the runtime collects the last records of the old context. */
|
|
24
|
+
private closingContext;
|
|
25
|
+
/** Version of another SDK copy that owns the page runtime, or null. */
|
|
26
|
+
private mismatchVersion;
|
|
27
|
+
/** True if the configured context id differs from the owner context id. */
|
|
28
|
+
private contextMismatch;
|
|
29
|
+
/** Current context change. Shutdown waits for this promise. */
|
|
30
|
+
private rotation?;
|
|
31
|
+
/** Memory store kept for later context changes. */
|
|
32
|
+
private memoryStorage?;
|
|
33
|
+
/** True if the app supplied a context id at startup. */
|
|
34
|
+
private explicitSecurityContext;
|
|
35
|
+
/** True after this forwarder takes a context id from its owner. */
|
|
36
|
+
private ownerAdopted;
|
|
37
|
+
/**
|
|
38
|
+
* Checks if a security context change is in progress.
|
|
39
|
+
* @returns True until the current change completes.
|
|
40
|
+
*/
|
|
41
|
+
isRotating(): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Locks or unlocks configuration at the request of the app. Other code of this origin can
|
|
44
|
+
* call this method. The lock does not control access.
|
|
45
|
+
* @param locked True to refuse changes through configure().
|
|
46
|
+
*/
|
|
47
|
+
setConfigurationLocked(locked: boolean): void;
|
|
19
48
|
/**
|
|
20
49
|
* Runtime of this copy of the library when another version owns the page runtime.
|
|
21
50
|
* It stays off the global key.
|
|
@@ -150,12 +179,20 @@ export declare class ObservabilityRuntime {
|
|
|
150
179
|
* @param fields Metric fields of the point. The record limits do not cut them.
|
|
151
180
|
*/
|
|
152
181
|
private emitPoint;
|
|
182
|
+
/**
|
|
183
|
+
* Checks the source policy before a direct child link opens.
|
|
184
|
+
* @param source Child window.
|
|
185
|
+
* @param origin Origin of the child window.
|
|
186
|
+
* @returns True if the bus permits this source.
|
|
187
|
+
*/
|
|
188
|
+
readonly busCanAccept: (source: Window, origin: string) => boolean;
|
|
153
189
|
/**
|
|
154
190
|
* Receives direct messages from same-origin child frames.
|
|
155
191
|
* @param message Inbound bus message.
|
|
156
192
|
* @param reply Direct response callback.
|
|
193
|
+
* @param source Window of the child frame.
|
|
157
194
|
*/
|
|
158
|
-
readonly busAccept: (message: BusMessage, reply: Receive) => void;
|
|
195
|
+
readonly busAccept: (message: BusMessage, reply: Receive, source?: Window) => void;
|
|
159
196
|
/**
|
|
160
197
|
* Returns the runtime on the global key of this realm. Another copy of the library can own it.
|
|
161
198
|
* @returns Pinned runtime instance or null.
|
|
@@ -210,6 +247,12 @@ export declare class ObservabilityRuntime {
|
|
|
210
247
|
* @returns The options that the runtime accepts.
|
|
211
248
|
*/
|
|
212
249
|
private allowed;
|
|
250
|
+
/**
|
|
251
|
+
* Removes delivery and identity changes while isolation is on. The other settings still apply.
|
|
252
|
+
* @param input Consumer configuration options.
|
|
253
|
+
* @returns The options without the refused delivery or identity changes.
|
|
254
|
+
*/
|
|
255
|
+
private keepRouting;
|
|
213
256
|
/**
|
|
214
257
|
* Restores the startup tunables in the next config. A part of the runtime reads each tunable
|
|
215
258
|
* one time. A later change has no effect. The runtime then refuses it.
|
|
@@ -308,7 +351,14 @@ export declare class ObservabilityRuntime {
|
|
|
308
351
|
* Attaches a Web Worker or MessagePort to the bus for record forwarding.
|
|
309
352
|
* @param worker Target Worker or MessagePort instance.
|
|
310
353
|
*/
|
|
311
|
-
registerWorker(worker: WorkerLike): void;
|
|
354
|
+
registerWorker(worker: WorkerLike, options?: SourceOptions): () => void;
|
|
355
|
+
/**
|
|
356
|
+
* Registers a frame after the bus loads. Early removal cancels the registration.
|
|
357
|
+
* @param frame Child frame or window.
|
|
358
|
+
* @param options Expected origin and source permissions.
|
|
359
|
+
* @returns Function that removes this registration.
|
|
360
|
+
*/
|
|
361
|
+
registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void;
|
|
312
362
|
/** Flushes pending telemetry, unregisters listeners, and unpins the runtime instance. */
|
|
313
363
|
destroy(): Promise<void>;
|
|
314
364
|
/**
|
|
@@ -371,11 +421,49 @@ export declare class ObservabilityRuntime {
|
|
|
371
421
|
* startup.
|
|
372
422
|
*/
|
|
373
423
|
newSession(): void;
|
|
424
|
+
/**
|
|
425
|
+
* Closes the work of the old session and starts the given session.
|
|
426
|
+
* @param sessionId Id of the session to start.
|
|
427
|
+
*/
|
|
428
|
+
private resetSession;
|
|
429
|
+
/**
|
|
430
|
+
* Changes the delivery context in one operation. A second change must wait for this change.
|
|
431
|
+
* @param update New identity, delivery settings and context attributes.
|
|
432
|
+
* @param options Rule for records of the old context and the flush deadline.
|
|
433
|
+
* @returns Promise that resolves when the change completes. Invalid settings reject it.
|
|
434
|
+
*/
|
|
435
|
+
rotateSecurityContext(update: SecurityContextUpdate, options?: SecurityContextRotationOptions): Promise<void>;
|
|
436
|
+
/**
|
|
437
|
+
* Checks new settings, stops old delivery and starts the new context.
|
|
438
|
+
* @param update New identity, delivery settings and attributes.
|
|
439
|
+
* @param pending Rule for the old records.
|
|
440
|
+
* @param timeoutMs Maximum wait for an old-context flush, in milliseconds.
|
|
441
|
+
* @returns Promise that resolves when the context change completes.
|
|
442
|
+
*/
|
|
443
|
+
private rotateContext;
|
|
444
|
+
/**
|
|
445
|
+
* Moves the records of the old context into the new context.
|
|
446
|
+
* @param live Records that were in memory. They go through the live buffer.
|
|
447
|
+
* @param stored Batches that were stored. The new sender stores them again.
|
|
448
|
+
* @returns Promise that resolves when the stored batches are stored again.
|
|
449
|
+
*/
|
|
450
|
+
private carry;
|
|
451
|
+
/**
|
|
452
|
+
* Reads the state of this runtime. It does not wait for startup or the sender to load.
|
|
453
|
+
* @returns State, delivery counts and policies. The facade adds the logger cache counts.
|
|
454
|
+
*/
|
|
455
|
+
health(): Promise<Omit<ObservabilityHealth, "loggerCache">>;
|
|
374
456
|
/**
|
|
375
457
|
* Reads the delivery state of this context.
|
|
376
458
|
* @returns Promise that resolves to the counts and the time of the last accepted send.
|
|
377
459
|
*/
|
|
378
460
|
stats(): Promise<DeliveryStats>;
|
|
461
|
+
/**
|
|
462
|
+
* Removes stored records of one context or all contexts in the application namespace.
|
|
463
|
+
* @param scope Part of storage to clear.
|
|
464
|
+
* @returns Promise that resolves when removal completes.
|
|
465
|
+
*/
|
|
466
|
+
clearPersisted(scope: "context" | "namespace"): Promise<void>;
|
|
379
467
|
/**
|
|
380
468
|
* Counts the batches held in storage after a failed or deferred delivery.
|
|
381
469
|
* @returns Promise that resolves to the number of stored batches. A forwarder stores
|
package/dist/core/sampling.d.ts
CHANGED
|
@@ -76,8 +76,10 @@ export declare class ErrorCeiling {
|
|
|
76
76
|
/**
|
|
77
77
|
* Checks a record against the limit. It counts only ERROR and FATAL records.
|
|
78
78
|
* @param record Record about to enter a stream.
|
|
79
|
+
* @param limit Maximum records in one window. Set 0 for no limit.
|
|
80
|
+
* @param windowMs Rate limit window, in milliseconds.
|
|
79
81
|
* @returns False when the window has no allowance left. The caller must drop the record.
|
|
80
82
|
*/
|
|
81
|
-
allow(record: LogRecord): boolean;
|
|
83
|
+
allow(record: LogRecord, limit?: number, windowMs?: number): boolean;
|
|
82
84
|
}
|
|
83
85
|
export {};
|
package/dist/core/sender.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import type { LogBatch } from "../models/batch";
|
|
1
2
|
import type { ResolvedConfig } from "../models/config";
|
|
2
3
|
import type { LossReporter } from "../models/drop";
|
|
3
4
|
import type { LogRecord } from "../models/log-record";
|
|
4
5
|
import type { DeliveryStats } from "../models/stats";
|
|
5
|
-
import { type GapReporter } from "../models/storage";
|
|
6
|
+
import { type GapReporter, type StorageAdapter } from "../models/storage";
|
|
6
7
|
import type { Diagnostics } from "./diagnostics";
|
|
7
8
|
import type { RemoteSlot } from "./remote-sampling";
|
|
8
9
|
/** Inputs to build the delivery stack. */
|
|
9
10
|
export interface SenderDeps {
|
|
11
|
+
/** Memory store that this runtime keeps when the security context changes. */
|
|
12
|
+
storage?: StorageAdapter;
|
|
13
|
+
onStorage?: (storage: StorageAdapter) => void;
|
|
10
14
|
/** Active configuration instance. */
|
|
11
15
|
config: ResolvedConfig;
|
|
12
16
|
/** Diagnostics reporter. */
|
|
@@ -28,6 +32,10 @@ export declare class Sender {
|
|
|
28
32
|
private readonly exitFlush;
|
|
29
33
|
private readonly diagnostics;
|
|
30
34
|
private readonly transport;
|
|
35
|
+
/** True after retire(). A late emergency import then does not wake the retry engine. */
|
|
36
|
+
private retired;
|
|
37
|
+
/** Emergency queue import. retire() waits for it before it reads storage. */
|
|
38
|
+
private emergencyImport;
|
|
31
39
|
/**
|
|
32
40
|
* @param storage Storage adapter for undelivered batches.
|
|
33
41
|
* @param retry Retry engine for stored batches.
|
|
@@ -54,6 +62,13 @@ export declare class Sender {
|
|
|
54
62
|
* @returns Promise that resolves when the pipeline sends or stores each batch.
|
|
55
63
|
*/
|
|
56
64
|
flush(): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Removes stored normal and emergency batches without sending them.
|
|
67
|
+
* @param scope Part of storage to clear.
|
|
68
|
+
* @param contextId Active delivery context id.
|
|
69
|
+
* @returns Promise that resolves when removal completes.
|
|
70
|
+
*/
|
|
71
|
+
clearPersisted(scope: "context" | "namespace", contextId: string): Promise<void>;
|
|
57
72
|
/**
|
|
58
73
|
* Counts the batches held in storage.
|
|
59
74
|
* @returns Promise that resolves to the batch count, or 0 if storage fails.
|
|
@@ -71,6 +86,25 @@ export declare class Sender {
|
|
|
71
86
|
* @returns Promise that resolves when storage closes.
|
|
72
87
|
*/
|
|
73
88
|
destroy(): Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* Stops this sender before a new delivery identity takes effect. It does not run exit delivery.
|
|
91
|
+
* @param policy Rule for the old records.
|
|
92
|
+
* @param timeoutMs Maximum wait for a flush, in milliseconds.
|
|
93
|
+
* @param contextId Identity of the old delivery context.
|
|
94
|
+
* @returns Records that were in memory, and the batches that were stored, after the delivery attempt.
|
|
95
|
+
*/
|
|
96
|
+
retire(policy: "discard" | "flush" | "retain" | "carry", timeoutMs: number, contextId: string): Promise<{
|
|
97
|
+
buffered: LogRecord[];
|
|
98
|
+
stored: LogBatch[];
|
|
99
|
+
}>;
|
|
100
|
+
/**
|
|
101
|
+
* Stores batches of an earlier context under this context. Then the retry engine sends them.
|
|
102
|
+
* The live buffer does not take them. A large backlog would exceed its budget.
|
|
103
|
+
* @param batches Stored batches of the earlier context.
|
|
104
|
+
* @param contextId Identity of this delivery context.
|
|
105
|
+
* @returns Promise that resolves when the batches are stored.
|
|
106
|
+
*/
|
|
107
|
+
adopt(batches: readonly LogBatch[], contextId: string): Promise<void>;
|
|
74
108
|
/**
|
|
75
109
|
* Moves the batches of the emergency queue into storage, then wakes the retry engine.
|
|
76
110
|
* The previous page load parked them during its unload.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/utils/unref.ts
|
|
2
|
+
function e(e) {
|
|
3
|
+
typeof e != "number" && e.unref?.();
|
|
4
|
+
}
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/utils/deadline.ts
|
|
7
|
+
var t = class extends Error {
|
|
8
|
+
constructor(e) {
|
|
9
|
+
super(`The operation took longer than ${String(e)} ms.`), this.name = "DeadlineError";
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
function n(n, r) {
|
|
13
|
+
let i, a = new Promise((n, a) => {
|
|
14
|
+
let o = setTimeout(() => {
|
|
15
|
+
a(new t(r));
|
|
16
|
+
}, r);
|
|
17
|
+
i = o, e(o);
|
|
18
|
+
});
|
|
19
|
+
return Promise.race([n, a]).finally(() => {
|
|
20
|
+
clearTimeout(i);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { n, e as r, t };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=deadline-5_PecIl5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deadline-5_PecIl5.js","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":";AAYA,SAAgBA,EAAW,GAA0B;CACnD,AAAI,OAAOC,KAAU,YACnBA,EAAM,QAAQ;AAElB;;;ACRA,IAAaC,IAAb,cAAmC,MAAM;CAIvC,YAAY,GAAY;EAEtB,AADA,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,GACxD,KAAK,OAAO;CACd;AACF;AAQA,SAAgBC,EAAgB,GAAkB,GAAwB;CACxE,IAAIC,GAEEC,IAAW,IAAI,SAAgB,GAAU,MAAW;EACxD,IAAML,IAAQ,iBAAiB;GAC7B,EAAO,IAAIC,EAAcC,CAAE,CAAC;EAC9B,GAAGA,CAAE;EAGL,AADA,IAASF,GACTD,EAAWC,CAAK;CAClB,CAAC;CAGD,OAAO,QAAQ,KAAK,CAACM,GAAMD,CAAQ,CAAC,CAAC,CAAC,cAAc;EAClD,aAAaD,CAAM;CACrB,CAAC;AACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){typeof e!=`number`&&e.unref?.()}var t=class extends Error{constructor(e){super(`The operation took longer than ${String(e)} ms.`),this.name=`DeadlineError`}};function n(n,r){let i,a=new Promise((n,a)=>{let o=setTimeout(()=>{a(new t(r))},r);i=o,e(o)});return Promise.race([n,a]).finally(()=>{clearTimeout(i)})}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
|
|
2
|
+
//# sourceMappingURL=deadline-XSnm95pg.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deadline-XSnm95pg.cjs","names":["unrefTimer","timer","DeadlineError","ms","withDeadline","expire","deadline","reject","work"],"sources":["../src/utils/unref.ts","../src/utils/deadline.ts"],"sourcesContent":["// src/utils/unref.ts\n//\n// Unreferences timer handles in Node and browser environments. A pending timer\n// keeps a Node process alive under SSR and in tests.\n\n/** Timer handle. It is a number in a browser and a Timeout object in Node. */\nexport type TimerHandle = number | { unref?: () => void };\n\n/**\n * Unreferences a timer handle. A pending timer then does not keep a Node.js process alive.\n * @param timer Timer handle returned by setTimeout.\n */\nexport function unrefTimer(timer: TimerHandle): void {\n if (typeof timer !== \"number\") {\n timer.unref?.();\n }\n}\n","// src/utils/deadline.ts\n//\n// Sets a deadline for a promise that can stay pending. A pending promise raises no\n// diagnostics event. Without a deadline, its caller waits forever and keeps its slot.\n\nimport { unrefTimer } from \"./unref\";\n\n/** Error of a promise that did not settle before its deadline. */\nexport class DeadlineError extends Error {\n /**\n * @param ms Deadline in milliseconds.\n */\n constructor(ms: number) {\n super(`The operation took longer than ${String(ms)} ms.`);\n this.name = \"DeadlineError\";\n }\n}\n\n/**\n * Rejects when a promise does not settle within a deadline.\n * @param work Promise to bound.\n * @param ms Deadline in milliseconds.\n * @returns The value of the promise, or a rejection after the deadline.\n */\nexport function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {\n let expire: ReturnType<typeof setTimeout> | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new DeadlineError(ms));\n }, ms);\n\n expire = timer;\n unrefTimer(timer);\n });\n\n // Clear the timer on success and on failure. If not, each storage call leaves an armed timer.\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(expire);\n });\n}\n"],"mappings":"AAYA,SAAgBA,EAAW,EAA0B,CAC/C,OAAOC,GAAU,UACnBA,EAAM,QAAQ,CAElB,CCRA,IAAaC,EAAb,cAAmC,KAAM,CAIvC,YAAY,EAAY,CACtB,MAAM,kCAAkC,OAAOC,CAAE,EAAE,KAAK,EACxD,KAAK,KAAO,eACd,CACF,EAQA,SAAgBC,EAAgB,EAAkB,EAAwB,CACxE,IAAIC,EAEEC,EAAW,IAAI,SAAgB,EAAU,IAAW,CACxD,IAAML,EAAQ,eAAiB,CAC7BM,EAAO,IAAIL,EAAcC,CAAE,CAAC,CAC9B,EAAGA,CAAE,EAEL,EAASF,EACTD,EAAWC,CAAK,CAClB,CAAC,EAGD,OAAO,QAAQ,KAAK,CAACO,EAAMF,CAAQ,CAAC,CAAC,CAAC,YAAc,CAClD,aAAaD,CAAM,CACrB,CAAC,CACH"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { G as e, cn as t } from "./constants-CN7GE1Lt.js";
|
|
2
|
+
import { n } from "./deadline-5_PecIl5.js";
|
|
3
|
+
import { i as r } from "./batch-BUJh-1jZ.js";
|
|
4
|
+
import { n as i, t as a } from "./keys-D5r_GH9q.js";
|
|
5
|
+
//#region src/utils/lock.ts
|
|
6
|
+
function o(e, t, n, { skipIfBusy: r = !0 } = {}) {
|
|
7
|
+
let i = globalThis.navigator?.locks;
|
|
8
|
+
return i?.request ? t.guardAsync("storage.degraded", `The library could not get the lock ${e}.`, () => i.request(e, { ifAvailable: r }, (e) => e ? n() : Promise.resolve(void 0))) : n();
|
|
9
|
+
}
|
|
10
|
+
function s(e, t) {
|
|
11
|
+
return t ? `${e}:${encodeURIComponent(t)}` : e;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/storage/emergency-queue.ts
|
|
15
|
+
function c(e, t) {
|
|
16
|
+
let n = t.guard("storage.degraded", "An emergency entry is not valid JSON. The library dropped it.", () => JSON.parse(e));
|
|
17
|
+
return n === void 0 ? null : r(n) ? n : (t.report("storage.degraded", "An emergency entry is not a batch. The library dropped it."), null);
|
|
18
|
+
}
|
|
19
|
+
async function l(e, r, a, o) {
|
|
20
|
+
let s = 0;
|
|
21
|
+
for (let l of i(o, r)) {
|
|
22
|
+
let i = r.guard("storage.unavailable", "The library could not read the emergency queue.", () => {
|
|
23
|
+
let e = localStorage.getItem(l), t = e ? c(e, r) : null;
|
|
24
|
+
return t && !a(t) ? null : (localStorage.removeItem(l), t);
|
|
25
|
+
});
|
|
26
|
+
if (i) try {
|
|
27
|
+
await n(e.save(i), t), s++;
|
|
28
|
+
} catch (e) {
|
|
29
|
+
r.report("storage.degraded", "The library could not recover an emergency batch.", { key: l }, e);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return s;
|
|
33
|
+
}
|
|
34
|
+
function u(e, t, n) {
|
|
35
|
+
let r = p(e.persistenceNamespace), o = `writing the emergency queue, ${String(e.records.length)} records`, s = [], l = t.guard("storage.quota_exceeded", o, () => {
|
|
36
|
+
let n = i(r, t);
|
|
37
|
+
for (let e of n.slice(0, Math.max(0, n.length - 20 + 1))) {
|
|
38
|
+
let n = c(String(localStorage.getItem(e)), t);
|
|
39
|
+
n !== null && s.push(n), localStorage.removeItem(e);
|
|
40
|
+
}
|
|
41
|
+
return localStorage.setItem(a(r, e), JSON.stringify(e)), !0;
|
|
42
|
+
});
|
|
43
|
+
t.guard("pipeline.crashed", "The loss report of the emergency queue failed.", () => {
|
|
44
|
+
if (s.length > 0) {
|
|
45
|
+
let e = s.flatMap((e) => e.records);
|
|
46
|
+
n?.("exit_queue_full", e, s.map((e) => e.id));
|
|
47
|
+
}
|
|
48
|
+
l !== !0 && n?.("quota", e.records, [e.id]);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function d(e, t, n = () => !0, r = "") {
|
|
52
|
+
return await o(s("ui-observability.emergency", r), t, () => l(e, t, n, p(r)), { skipIfBusy: !1 }) ?? 0;
|
|
53
|
+
}
|
|
54
|
+
function f(e, t, n = "", r = !1) {
|
|
55
|
+
let a = p(n);
|
|
56
|
+
t.guard("storage.unavailable", "The library could not clear the retired emergency queue.", () => {
|
|
57
|
+
for (let n of i(a, t)) {
|
|
58
|
+
let i = localStorage.getItem(n);
|
|
59
|
+
i && (r || c(i, t)?.routingContextId === e) && localStorage.removeItem(n);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function p(t = "") {
|
|
64
|
+
return t ? `ui-observability:namespaced:${encodeURIComponent(t)}:emergency:` : e;
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { f as clearEmergencyContext, d as drainEmergencyQueue, o as n, u as saveToEmergencyQueue, s as t };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=emergency-queue-BYUyDHGD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emergency-queue-BYUyDHGD.js","names":["EMERGENCY_STORAGE_KEY_PREFIX","STORAGE_DEADLINE_MS","isLogBatch","keysWithPrefix","batchKey","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","withDeadline","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, every window on the origin drains and sends the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock is not available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * It runs the task directly when the Web Locks API is not available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Gives the lock name of one application namespace. Two namespaces on one origin then do not wait for each other.\n * Without it, the retry pass of one application skips while the other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns Lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch. Parse each entry one time.\n // A batch of another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. Each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of the old entries that the queue drops, and of a\n * batch that the store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window removed gives null. readBatch then rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this function. A throw here skips the shutdown of the sender.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes emergency entries of one context, or all entries in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace Application storage namespace.\n * @param all True to remove entries of all contexts in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Gives the emergency storage prefix of one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns Prefix for this application emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":";;;;;AAoCA,SAAgBK,EACd,GACA,GACA,GACA,EAAE,gBAAa,OAAmC,CAAC,GAC3B;CACxB,IAAMC,IAAS,WAA2D,WAAW;CAOrF,OAJKA,GAAO,UAILC,EAAY,WACjB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+BAA+B,mBAAmBA,CAAS,EAAE,eAC7Db;AACN"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-CW-MlHdY.cjs"),t=require("./deadline-XSnm95pg.cjs"),n=require("./batch-BQFtb3i5.cjs"),r=require("./keys-BHhw_0Wh.cjs");function i(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`The library could not get the lock ${e}.`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function a(e,t){return t?`${e}:${encodeURIComponent(t)}`:e}function o(e,t){let r=t.guard(`storage.degraded`,`An emergency entry is not valid JSON. The library dropped it.`,()=>JSON.parse(e));return r===void 0?null:n.i(r)?r:(t.report(`storage.degraded`,`An emergency entry is not a batch. The library dropped it.`),null)}async function s(n,i,a,s){let c=0;for(let l of r.n(s,i)){let r=i.guard(`storage.unavailable`,`The library could not read the emergency queue.`,()=>{let e=localStorage.getItem(l),t=e?o(e,i):null;return t&&!a(t)?null:(localStorage.removeItem(l),t)});if(r)try{await t.n(n.save(r),e.cn),c++}catch(e){i.report(`storage.degraded`,`The library could not recover an emergency batch.`,{key:l},e)}}return c}function c(e,t,n){let i=d(e.persistenceNamespace),a=`writing the emergency queue, ${String(e.records.length)} records`,s=[],c=t.guard(`storage.quota_exceeded`,a,()=>{let n=r.n(i,t);for(let e of n.slice(0,Math.max(0,n.length-20+1))){let n=o(String(localStorage.getItem(e)),t);n!==null&&s.push(n),localStorage.removeItem(e)}return localStorage.setItem(r.t(i,e),JSON.stringify(e)),!0});t.guard(`pipeline.crashed`,`The loss report of the emergency queue failed.`,()=>{if(s.length>0){let e=s.flatMap(e=>e.records);n?.(`exit_queue_full`,e,s.map(e=>e.id))}c!==!0&&n?.(`quota`,e.records,[e.id])})}async function l(e,t,n=()=>!0,r=``){return await i(a(`ui-observability.emergency`,r),t,()=>s(e,t,n,d(r)),{skipIfBusy:!1})??0}function u(e,t,n=``,i=!1){let a=d(n);t.guard(`storage.unavailable`,`The library could not clear the retired emergency queue.`,()=>{for(let n of r.n(a,t)){let r=localStorage.getItem(n);r&&(i||o(r,t)?.routingContextId===e)&&localStorage.removeItem(n)}})}function d(t=``){return t?`ui-observability:namespaced:${encodeURIComponent(t)}:emergency:`:e.G}exports.clearEmergencyContext=u,exports.drainEmergencyQueue=l,exports.n=i,exports.saveToEmergencyQueue=c,exports.t=a;
|
|
2
|
+
//# sourceMappingURL=emergency-queue-Cs1hrjsC.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emergency-queue-Cs1hrjsC.cjs","names":["isLogBatch","keysWithPrefix","withDeadline","STORAGE_DEADLINE_MS","batchKey","EMERGENCY_STORAGE_KEY_PREFIX","require_constants","require_deadline","require_batch","require_keys","withDrainLock","locks","diagnostics","name","skipIfBusy","lock","fn","lockName","namespace","readBatch","parsed","raw","importAll","moved","key","prefix","batch","value","accepts","storage","error","saveToEmergencyQueue","emergencyPrefix","context","evicted","saved","keys","old","dropped","records","one","onLoss","drainEmergencyQueue","clearEmergencyContext","all","id"],"sources":["../src/utils/lock.ts","../src/storage/emergency-queue.ts"],"sourcesContent":["// src/utils/lock.ts\n//\n// Coordinates origin-wide batch draining operations using the Web Locks API.\n// Without the lock, every window on the origin drains and sends the same batches.\n\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Lock grant object, or null when the lock is not available. */\ntype LockGrant = { name: string } | null;\n\n/** Structural interface for navigator.locks operations. */\ninterface LockManagerLike {\n /**\n * Requests a lock and executes a callback under the acquired lock grant.\n * @param name Lock name.\n * @param options Lock request options.\n * @param callback Callback that runs with the lock grant.\n */\n request<T>(\n name: string,\n options: { ifAvailable?: boolean },\n callback: (lock: LockGrant) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Executes an asynchronous function under a Web Locks API origin-wide lock.\n * It runs the task directly when the Web Locks API is not available.\n * @param name Origin-scoped lock identifier.\n * @param diagnostics Diagnostics reporter.\n * @param fn Asynchronous task to execute while holding the lock.\n * @param options Lock acquisition options.\n * @param options.skipIfBusy When true, the task does not run if another context holds the lock.\n * @returns Promise of the task result. It resolves to undefined when another context holds the\n * lock. A caller that reads undefined as a task result stops rescheduling.\n */\nexport function withDrainLock<T>(\n name: string,\n diagnostics: Diagnostics,\n fn: () => Promise<T>,\n { skipIfBusy = true }: { skipIfBusy?: boolean } = {},\n): Promise<T | undefined> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n\n // Run the task without a lock when the Web Locks API is not available.\n if (!locks?.request) {\n return fn();\n }\n\n return diagnostics.guardAsync(\n \"storage.degraded\",\n `The library could not get the lock ${name}.`,\n () =>\n locks.request(name, { ifAvailable: skipIfBusy }, (lock) =>\n lock ? fn() : Promise.resolve(undefined),\n ),\n );\n}\n\n/**\n * Gives the lock name of one application namespace. Two namespaces on one origin then do not wait for each other.\n * Without it, the retry pass of one application skips while the other holds the lock.\n * @param name Base lock name.\n * @param namespace Application storage namespace. An empty value keeps the base name.\n * @returns Lock name for this namespace.\n */\nexport function lockName(name: string, namespace: string): string {\n return namespace ? `${name}:${encodeURIComponent(namespace)}` : name;\n}\n","// src/storage/emergency-queue.ts\n//\n// This module keeps a synchronous localStorage queue. It holds oversized batches during unload.\n// Startup recovers them. The code is synchronous and never throws. It runs while the browser\n// destroys the document. No promise settles at that time.\n\nimport {\n EMERGENCY_LOCK_NAME,\n EMERGENCY_MAX_ENTRIES,\n EMERGENCY_STORAGE_KEY_PREFIX,\n STORAGE_DEADLINE_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { isLogBatch, type LogBatch } from \"../models/batch\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { StorageAdapter } from \"../models/storage\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { lockName, withDrainLock } from \"../utils/lock\";\nimport { batchKey, keysWithPrefix } from \"./keys\";\n\n/**\n * Parses a raw storage string and validates it as a LogBatch.\n * @param raw Raw serialized storage string.\n * @param diagnostics Diagnostics reporter.\n * @returns Validated LogBatch or null if unparseable or malformed.\n */\nfunction readBatch(raw: string, diagnostics: Diagnostics): LogBatch | null {\n const parsed = diagnostics.guard(\n \"storage.degraded\",\n \"An emergency entry is not valid JSON. The library dropped it.\",\n () => JSON.parse(raw) as unknown,\n );\n\n // The guard above already reported a parse failure.\n if (parsed === undefined) {\n return null;\n }\n\n if (!isLogBatch(parsed)) {\n diagnostics.report(\n \"storage.degraded\",\n \"An emergency entry is not a batch. The library dropped it.\",\n );\n return null;\n }\n\n return parsed;\n}\n\n/**\n * Imports all emergency queue entries into the target adapter in FIFO order.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Total number of recovered batches.\n */\nasync function importAll(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean,\n prefix: string,\n): Promise<number> {\n let moved = 0;\n\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n // Read and remove the key in one synchronous step, before the async save. A second window\n // that imports at the same time cannot take the same batch. Parse each entry one time.\n // A batch of another context stays in the queue.\n const batch = diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the emergency queue.\",\n (): LogBatch | null => {\n const value = localStorage.getItem(key);\n const parsed = value ? readBatch(value, diagnostics) : null;\n if (parsed && !accepts(parsed)) {\n return null;\n }\n localStorage.removeItem(key);\n return parsed;\n },\n );\n\n if (!batch) {\n continue;\n }\n\n try {\n // Set a deadline. This code runs during startup. A save that does not settle keeps the\n // runtime not ready. Each record then goes to the boot buffer.\n await withDeadline(storage.save(batch), STORAGE_DEADLINE_MS);\n moved++;\n } catch (error) {\n diagnostics.report(\n \"storage.degraded\",\n \"The library could not recover an emergency batch.\",\n { key },\n error,\n );\n }\n }\n\n return moved;\n}\n\n/**\n * Writes an unsent batch to the emergency queue synchronously during unload.\n * @param batch Oversized log batch.\n * @param diagnostics Diagnostics reporter.\n * @param onLoss Receives the records of the old entries that the queue drops, and of a\n * batch that the store refuses.\n */\nexport function saveToEmergencyQueue(\n batch: LogBatch,\n diagnostics: Diagnostics,\n onLoss?: LossReporter,\n): void {\n // Name the record count. A full localStorage drops this batch permanently. Removal of\n // emergency keys cannot free quota that the keys of other applications use.\n const prefix = emergencyPrefix(batch.persistenceNamespace);\n const context = `writing the emergency queue, ${String(batch.records.length)} records`;\n const evicted: LogBatch[] = [];\n\n const saved = diagnostics.guard(\"storage.quota_exceeded\", context, () => {\n const keys = keysWithPrefix(prefix, diagnostics);\n\n // Remove the oldest entries to keep the queue within its capacity.\n for (const old of keys.slice(0, Math.max(0, keys.length - EMERGENCY_MAX_ENTRIES + 1))) {\n // A key that another window removed gives null. readBatch then rejects it.\n const dropped = readBatch(String(localStorage.getItem(old)), diagnostics);\n if (dropped !== null) {\n evicted.push(dropped);\n }\n localStorage.removeItem(old);\n }\n\n localStorage.setItem(batchKey(prefix, batch), JSON.stringify(batch));\n return true;\n });\n\n // The exit flush calls this function. A throw here skips the shutdown of the sender.\n diagnostics.guard(\"pipeline.crashed\", \"The loss report of the emergency queue failed.\", () => {\n if (evicted.length > 0) {\n const records = evicted.flatMap((one) => one.records);\n onLoss?.(\n \"exit_queue_full\",\n records,\n evicted.map((one) => one.id),\n );\n }\n\n if (saved !== true) {\n onLoss?.(\"quota\", batch.records, [batch.id]);\n }\n });\n}\n\n/**\n * Recovers the batches that earlier shutdowns saved to emergency storage.\n * @param storage Destination storage adapter.\n * @param diagnostics Diagnostics reporter.\n * @returns Promise that resolves to the number of recovered batches.\n */\nexport async function drainEmergencyQueue(\n storage: StorageAdapter,\n diagnostics: Diagnostics,\n accepts: (batch: LogBatch) => boolean = () => true,\n namespace = \"\",\n): Promise<number> {\n const moved = await withDrainLock(\n lockName(EMERGENCY_LOCK_NAME, namespace),\n diagnostics,\n () => importAll(storage, diagnostics, accepts, emergencyPrefix(namespace)),\n { skipIfBusy: false },\n );\n\n return moved ?? 0;\n}\n\n/**\n * Removes emergency entries of one context, or all entries in its namespace.\n * @param id Delivery context id.\n * @param diagnostics Diagnostics reporter.\n * @param namespace Application storage namespace.\n * @param all True to remove entries of all contexts in this namespace.\n */\nexport function clearEmergencyContext(\n id: string,\n diagnostics: Diagnostics,\n namespace = \"\",\n all = false,\n): void {\n const prefix = emergencyPrefix(namespace);\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the retired emergency queue.\",\n () => {\n for (const key of keysWithPrefix(prefix, diagnostics)) {\n const raw = localStorage.getItem(key);\n if (raw && (all || readBatch(raw, diagnostics)?.routingContextId === id))\n localStorage.removeItem(key);\n }\n },\n );\n}\n\n/**\n * Gives the emergency storage prefix of one application namespace.\n * @param namespace Application namespace. An empty value uses the previous prefix.\n * @returns Prefix for this application emergency queue.\n */\nfunction emergencyPrefix(namespace = \"\"): string {\n return namespace\n ? `ui-observability:namespaced:${encodeURIComponent(namespace)}:emergency:`\n : EMERGENCY_STORAGE_KEY_PREFIX;\n}\n"],"mappings":"oJAoCA,SAAgBU,EACd,EACA,EACA,EACA,CAAE,aAAa,IAAmC,CAAC,EAC3B,CACxB,IAAMC,EAAS,WAA2D,WAAW,MAOrF,OAJKA,GAAO,QAILC,EAAY,WACjB,mBACA,sCAAsCC,EAAK,OAEzCF,EAAM,QAAQE,EAAM,CAAE,YAAaC,CAAW,EAAI,GAChDC,EAAOC,EAAG,EAAI,QAAQ,QAAQ,IAAA,EAAS,CACzC,CACJ,EAVSA,EAAG,CAWd,CASA,SAAgBC,EAAS,EAAc,EAA2B,CAChE,OAAOC,EAAY,GAAGL,EAAK,GAAG,mBAAmBK,CAAS,IAAML,CAClE,CC1CA,SAASM,EAAU,EAAa,EAA2C,CACzE,IAAMC,EAASR,EAAY,MACzB,mBACA,oEACM,KAAK,MAAMS,CAAG,CACtB,EAeA,OAZID,IAAW,IAAA,GACN,KAGJpB,EAAAA,EAAWoB,CAAM,EAQfA,GAPLR,EAAY,OACV,mBACA,4DACF,EACO,KAIX,CAQA,eAAeU,EACb,EACA,EACA,EACA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AQM,EAAI,OAAO,EACpDC,IACE,kBACAF,EACAL,EAAQ,IAAK,GAAQM,EAAI,EAAE,CAC7B,CACF,CAEIL,IAAU,IACZM,IAAS,QAASf,EAAM,QAAS,CAACA,EAAM,EAAE,CAAC,CAE/C,CAAC,CACH,CAQA,eAAsBgB,EACpB,EACA,EACA,MAA8C,GAC9C,EAAY,GACK,CAQjB,OAAO,MAPahC,EAClBO,EAAA,6BAA8BC,CAAS,EACvCN,MACMU,EAAUO,EAASjB,EAAagB,EAASI,EAAgBd,CAAS,CAAC,EACzE,CAAE,WAAY,EAAM,CACtB,GAEgB,CAClB,CASA,SAAgByB,EACd,EACA,EACA,EAAY,GACZ,EAAM,GACA,CACN,IAAMlB,EAASO,EAAgBd,CAAS,EACxCN,EAAY,MACV,sBACA,+DACM,CACJ,IAAK,IAAMY,KAAOvB,EAAAA,EAAewB,EAAQb,CAAW,EAAG,CACrD,IAAMS,EAAM,aAAa,QAAQG,CAAG,EAChCH,IAAQuB,GAAOzB,EAAUE,EAAKT,CAAW,CAAC,EAAE,mBAAqBiC,IACnE,aAAa,WAAWrB,CAAG,CAC/B,CACF,CACF,CACF,CAOA,SAASQ,EAAgB,EAAY,GAAY,CAC/C,OAAOd,EACH,+BAA+B,mBAAmBA,CAAS,EAAE,aAC7Db,EAAAA,CACN"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import "./constants-L_d5YvvQ.js";
|
|
2
1
|
import { r as e } from "./error-like-Ywo5uRHo.js";
|
|
3
|
-
import { i as t } from "./platform-
|
|
4
|
-
import { t as n } from "./storm-
|
|
2
|
+
import { i as t } from "./platform-Bw1btWCT.js";
|
|
3
|
+
import { t as n } from "./storm-Daq2jGHU.js";
|
|
5
4
|
//#region src/capture/errors.ts
|
|
6
5
|
function r(t) {
|
|
7
6
|
if (e(t)) {
|
|
@@ -39,7 +38,7 @@ var i = class {
|
|
|
39
38
|
let n = e.target, r = n?.src ?? n?.href ?? "";
|
|
40
39
|
if (n !== null && n !== globalThis && r !== "") {
|
|
41
40
|
if (!this.ctx.config.capture.resourceErrors) return;
|
|
42
|
-
let e = t(r, this.ctx.config.capture.fullUrls);
|
|
41
|
+
let e = t(r, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics);
|
|
43
42
|
this.ctx.breadcrumbs.push({
|
|
44
43
|
t: Date.now(),
|
|
45
44
|
category: "http",
|
|
@@ -54,7 +53,7 @@ var i = class {
|
|
|
54
53
|
if (!this.ctx.config.capture.errors) return;
|
|
55
54
|
let i = e, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
|
|
56
55
|
this.report("window.onerror", o, {
|
|
57
|
-
"error.source": t(i.filename, this.ctx.config.capture.fullUrls),
|
|
56
|
+
"error.source": t(i.filename, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, this.ctx.diagnostics),
|
|
58
57
|
"error.line": i.lineno,
|
|
59
58
|
"error.column": i.colno
|
|
60
59
|
});
|
|
@@ -63,12 +62,12 @@ var i = class {
|
|
|
63
62
|
this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
|
|
64
63
|
};
|
|
65
64
|
report(e, t, i) {
|
|
66
|
-
if (!n(this.window,
|
|
65
|
+
if (!n(this.window, this.ctx.config.capturePolicy.errorsPerWindow, this.ctx.diagnostics, "errors", this.ctx.config.capturePolicy.windowMs)) return;
|
|
67
66
|
let a = Date.now(), { message: o, key: s } = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read the error reason. It records the error without its message.", () => r(t)) ?? {
|
|
68
67
|
message: "",
|
|
69
68
|
key: `${typeof t}||`
|
|
70
69
|
}, c = this.seen.get(s);
|
|
71
|
-
if (c && a - c.at <
|
|
70
|
+
if (c && a - c.at < this.ctx.config.capturePolicy.errorDedupeMs) {
|
|
72
71
|
c.count++, c.at = a;
|
|
73
72
|
return;
|
|
74
73
|
}
|
|
@@ -76,7 +75,7 @@ var i = class {
|
|
|
76
75
|
if (this.seen.delete(s), this.seen.set(s, {
|
|
77
76
|
at: a,
|
|
78
77
|
count: 1
|
|
79
|
-
}), this.seen.size >
|
|
78
|
+
}), this.ctx.config.capturePolicy.maxErrorSignatures > 0 && this.seen.size > this.ctx.config.capturePolicy.maxErrorSignatures) {
|
|
80
79
|
let [e] = this.seen.keys();
|
|
81
80
|
this.seen.delete(e);
|
|
82
81
|
}
|
|
@@ -91,4 +90,4 @@ var i = class {
|
|
|
91
90
|
//#endregion
|
|
92
91
|
export { i as ErrorCapture };
|
|
93
92
|
|
|
94
|
-
//# sourceMappingURL=errors-
|
|
93
|
+
//# sourceMappingURL=errors-BhC7HTSt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-BhC7HTSt.js","names":["isErrorLike","recordedUrl","allowInWindow","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\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 // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\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 if (\n !allowInWindow(\n this.window,\n this.ctx.config.capturePolicy.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.capturePolicy.errorDedupeMs) {\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 (\n this.ctx.config.capturePolicy.maxErrorSignatures > 0 &&\n this.seen.size > this.ctx.config.capturePolicy.maxErrorSignatures\n ) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...extra,\n \"error.captured_by\": source,\n \"error.suppressed_count\": suppressed,\n });\n }\n}\n"],"mappings":";;;;AAgCA,SAASG,EAAY,GAA2B;CAC9C,IAAIH,EAAYI,CAAK,GAAG;EACtB,IAAMC,KAASD,EAAM,SAAS,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,MAAM;EACpD,OAAO;GAAE,SAASA,EAAM;GAAS,KAAK,GAAGA,EAAM,KAAK,GAAGA,EAAM,QAAQ,GAAGC;EAAQ;CAClF;CAEA,IAAMC,IAAU,OAAOF,CAAK;CAC5B,OAAO;EAAE;EAAS,KAAK,GAAG,OAAOA,EAAM,GAAGE,EAAQ;CAAG;AACvD;AAGA,IAAaC,IAAb,MAA6C;CAgBd;CAd7B,OAAgB;CAGhB,YAAoB;CAGpB,uBAAwB,IAAI,IAAuB;CAGnD,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAK5D,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,EA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,cAAc,QAChC,GAEA;EAGF,IAAMc,IAAM,KAAK,IAAI,GAGf,EAAE,YAAS,WAAQ,KAAK,IAAI,YAAY,MAC5C,yBACA,gGACMb,EAAYY,CAAK,CACzB,KAAK;GAAE,SAAS;GAAI,KAAK,GAAG,OAAOA,EAAM;EAAI,GACvCE,IAAW,KAAK,KAAK,IAAIC,CAAG;EAElC,IAAID,KAAYD,IAAMC,EAAS,KAAK,KAAK,IAAI,OAAO,cAAc,eAAe;GAE/E,AADA,EAAS,SACT,EAAS,KAAKD;GACd;EACF;EAIA,IAAMG,IAAaF,IAAWA,EAAS,QAAQ,IAAI;EASnD,IALA,KAAK,KAAK,OAAOC,CAAG,GACpB,KAAK,KAAK,IAAIA,GAAK;GAAE,IAAIF;GAAK,OAAO;EAAE,CAAC,GAKtC,KAAK,IAAI,OAAO,cAAc,qBAAqB,KACnD,KAAK,KAAK,OAAO,KAAK,IAAI,OAAO,cAAc,oBAC/C;GACA,IAAM,CAACI,KAAU,KAAK,KAAK,KAAK;GAChC,KAAK,KAAK,OAAOA,CAAM;EACzB;EAIA,IAAMC,IAASN,MAAU,KAAA,IAAgB,MAAMT,CAAO,IAAIS;EAC1D,KAAK,IAAI,OAAO,MAAMT,MAAY,KAAKgB,IAAShB,GAASe,GAAQ;GAC/D,GAAGE;GACH,qBAAqBD;GACrB,0BAA0BH;EAC5B,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-DBSKTvFn.cjs"),n=require("./storm-CNZjsw4T.cjs");function r(t){if(e.r(t)){let e=(t.stack??``).split(`
|
|
2
|
+
`)[1]??``;return{message:t.message,key:`${t.name}|${t.message}|${e}`}}let n=String(t);return{message:n,key:`${typeof t}|${n}|`}}var i=class{ctx;name=`errors`;installed=!1;seen=new Map;window={start:0,count: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=t.i(r,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics);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":t.i(i.filename,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,this.ctx.diagnostics),"error.line":i.lineno,"error.column":i.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(e,t,i){if(!n.t(this.window,this.ctx.config.capturePolicy.errorsPerWindow,this.ctx.diagnostics,`errors`,this.ctx.config.capturePolicy.windowMs))return;let a=Date.now(),{message:o,key:s}=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read the error reason. It records the error without its message.`,()=>r(t))??{message:``,key:`${typeof t}||`},c=this.seen.get(s);if(c&&a-c.at<this.ctx.config.capturePolicy.errorDedupeMs){c.count++,c.at=a;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:a,count:1}),this.ctx.config.capturePolicy.maxErrorSignatures>0&&this.seen.size>this.ctx.config.capturePolicy.maxErrorSignatures){let[e]=this.seen.keys();this.seen.delete(e)}let u=t===void 0?Error(o):t;this.ctx.logger.error(o===``?e:o,u,{...i,"error.captured_by":e,"error.suppressed_count":l})}};exports.ErrorCapture=i;
|
|
3
|
+
//# sourceMappingURL=errors-CgY633cG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-CgY633cG.cjs","names":["isErrorLike","recordedUrl","allowInWindow","require_error_like","require_platform","require_storm","signatureOf","value","frame","message","ErrorCapture","ctx","target","event","resourceUrl","url","errorEvent","fallback","error","now","previous","key","suppressed","oldest","reason","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 { isErrorLike } from \"../utils/error-like\";\nimport { recordedUrl } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\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/** Message and deduplication key of a thrown value. */\ninterface Signature {\n /** Message of the record. */\n message: string;\n /** Deduplication key. */\n key: string;\n}\n\n/**\n * Reads the message and the deduplication key of a thrown value.\n * Duck typing reads an error from another realm. That error fails `instanceof Error`.\n * @param value Thrown value or rejection reason.\n * @returns The signature.\n * @throws When a getter or the text form of the value throws. Call it inside a guard.\n */\nfunction signatureOf(value: unknown): Signature {\n if (isErrorLike(value)) {\n const frame = (value.stack ?? \"\").split(\"\\n\")[1] ?? \"\";\n return { message: value.message, key: `${value.name}|${value.message}|${frame}` };\n }\n\n const message = String(value);\n return { message, key: `${typeof value}|${message}|` };\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 /** Rate limit of this capture. Console noise has its own window and cannot use it. */\n private readonly window: StormWindow = { start: 0, count: 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 you set fullUrls.\n const url = recordedUrl(\n resourceUrl,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n );\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 // A signed script URL is a credential.\n \"error.source\": recordedUrl(\n errorEvent.filename,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n this.ctx.diagnostics,\n ),\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 if (\n !allowInWindow(\n this.window,\n this.ctx.config.capturePolicy.errorsPerWindow,\n this.ctx.diagnostics,\n \"errors\",\n this.ctx.config.capturePolicy.windowMs,\n )\n ) {\n return;\n }\n\n const now = Date.now();\n // A reason with no text form, for example a null-prototype object, gets an empty message.\n // The record then uses the source as its message.\n const { message, key } = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read the error reason. It records the error without its message.\",\n () => signatureOf(error),\n ) ?? { message: \"\", key: `${typeof error}||` };\n const previous = this.seen.get(key);\n\n if (previous && now - previous.at < this.ctx.config.capturePolicy.errorDedupeMs) {\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 (\n this.ctx.config.capturePolicy.maxErrorSignatures > 0 &&\n this.seen.size > this.ctx.config.capturePolicy.maxErrorSignatures\n ) {\n const [oldest] = this.seen.keys();\n this.seen.delete(oldest);\n }\n\n // Give the original value to the logger. It converts the reason and keeps its data.\n // Without a reason, the record still needs error.message and error.stack_trace.\n const reason = error === undefined ? new Error(message) : error;\n this.ctx.logger.error(message === \"\" ? source : message, reason, {\n ...ext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