@utk09/ui-observability 0.4.1 → 0.5.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +69 -31
  3. package/dist/bus-D3OO0OcL.js +378 -0
  4. package/dist/bus-D3OO0OcL.js.map +1 -0
  5. package/dist/bus-OdRJVUzr.cjs +2 -0
  6. package/dist/bus-OdRJVUzr.cjs.map +1 -0
  7. package/dist/capture/web-vitals.d.ts +4 -1
  8. package/dist/{constants-DVbpJ1tv.js → constants-B6kdsCzF.js} +9 -8
  9. package/dist/constants-B6kdsCzF.js.map +1 -0
  10. package/dist/constants-DZH04585.cjs +2 -0
  11. package/dist/constants-DZH04585.cjs.map +1 -0
  12. package/dist/constants.d.ts +3 -1
  13. package/dist/core/journey.d.ts +5 -2
  14. package/dist/core/logger.d.ts +22 -3
  15. package/dist/core/runtime.d.ts +100 -18
  16. package/dist/core/sender.d.ts +58 -0
  17. package/dist/errors-DPju_xSI.cjs +3 -0
  18. package/dist/errors-DPju_xSI.cjs.map +1 -0
  19. package/dist/errors-Dme9tz-6.js +76 -0
  20. package/dist/errors-Dme9tz-6.js.map +1 -0
  21. package/dist/index.cjs +1 -3
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.js +452 -2223
  24. package/dist/index.js.map +1 -1
  25. package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
  26. package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
  27. package/dist/{indexeddb-storage-B6uqejZb.js → indexeddb-storage-nxs_rxGx.js} +4 -8
  28. package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
  29. package/dist/interactions-C1romMpE.js +67 -0
  30. package/dist/interactions-C1romMpE.js.map +1 -0
  31. package/dist/interactions-DP0-rIPJ.cjs +2 -0
  32. package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
  33. package/dist/models/config.d.ts +29 -11
  34. package/dist/network-DDVIJSHd.cjs +2 -0
  35. package/dist/network-DDVIJSHd.cjs.map +1 -0
  36. package/dist/network-au-Tqt1n.js +111 -0
  37. package/dist/network-au-Tqt1n.js.map +1 -0
  38. package/dist/platform-DMYo3AX3.js +48 -0
  39. package/dist/platform-DMYo3AX3.js.map +1 -0
  40. package/dist/platform-g99Kn755.cjs +2 -0
  41. package/dist/platform-g99Kn755.cjs.map +1 -0
  42. package/dist/sampling-ByI5H44E.js +248 -0
  43. package/dist/sampling-ByI5H44E.js.map +1 -0
  44. package/dist/sampling-Dui-Fp3u.cjs +2 -0
  45. package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
  46. package/dist/sender-R7lOpyNc.js +907 -0
  47. package/dist/sender-R7lOpyNc.js.map +1 -0
  48. package/dist/sender-vLcbQhiB.cjs +3 -0
  49. package/dist/sender-vLcbQhiB.cjs.map +1 -0
  50. package/dist/transport/http-transport.d.ts +2 -0
  51. package/dist/transport/serializers/select.d.ts +8 -0
  52. package/dist/unref-16maCyKA.js +8 -0
  53. package/dist/unref-16maCyKA.js.map +1 -0
  54. package/dist/unref-CU9Nyz_9.cjs +2 -0
  55. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  56. package/dist/utils/console.d.ts +11 -3
  57. package/dist/utils/identity.d.ts +47 -3
  58. package/dist/utils/tracing.d.ts +6 -5
  59. package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
  60. package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
  61. package/dist/web-vitals-DwWdLBq6.js +51 -0
  62. package/dist/web-vitals-DwWdLBq6.js.map +1 -0
  63. package/package.json +21 -11
  64. package/dist/constants-DVbpJ1tv.js.map +0 -1
  65. package/dist/constants-tQpoTzkY.cjs +0 -2
  66. package/dist/constants-tQpoTzkY.cjs.map +0 -1
  67. package/dist/indexeddb-storage-B6uqejZb.js.map +0 -1
  68. package/dist/indexeddb-storage-CgT1GLYj.cjs +0 -2
  69. package/dist/indexeddb-storage-CgT1GLYj.cjs.map +0 -1
@@ -7,15 +7,16 @@ export interface OneLoggerOptions {
7
7
  }
8
8
  /** Namespaced logger instance for recording structured events, metrics, and errors. */
9
9
  export declare class OneLogger {
10
- private readonly runtime;
10
+ private readonly bind;
11
11
  readonly namespace: string;
12
12
  private readonly options;
13
13
  /**
14
- * @param runtime Underlying observability runtime instance.
14
+ * @param bind Returns the runtime for each write.
15
+ * A logger that exists before configure() writes to the configured runtime.
15
16
  * @param namespace Application subsystem or module namespace.
16
17
  * @param options Scoped context options.
17
18
  */
18
- constructor(runtime: ObservabilityRuntime, namespace: string, options?: OneLoggerOptions);
19
+ constructor(bind: () => ObservabilityRuntime, namespace: string, options?: OneLoggerOptions);
19
20
  /**
20
21
  * Creates a child logger with a nested namespace and merged scoped context.
21
22
  * @param namespace Sub-namespace appended with dot notation.
@@ -116,4 +117,22 @@ export declare class OneLogger {
116
117
  * @param payload Optional contextual attributes.
117
118
  */
118
119
  private writeError;
120
+ /**
121
+ * Prints one log line. With a redact hook, the line shows only what redact returned.
122
+ * A host can record console arguments. The console must not show what redact removes.
123
+ * @param runtime Runtime of this write.
124
+ * @param level Severity level.
125
+ * @param message Primary message.
126
+ * @param payload Caller payload.
127
+ * @param error Error of an error call.
128
+ * @param record Built record, or null if the library did not build it or redact dropped it.
129
+ */
130
+ private print;
131
+ /**
132
+ * Tests whether the console prints a level that the library does not send.
133
+ * @param runtime Runtime of this write.
134
+ * @param level Severity level.
135
+ * @returns True if logging is on and the console accepts the level.
136
+ */
137
+ private mirrors;
119
138
  }
@@ -1,4 +1,3 @@
1
- import { Bus } from "../bus/bus";
2
1
  import type { Receive, WorkerLike } from "../bus/links";
3
2
  import type { BusMessage } from "../models/bus";
4
3
  import type { ObservabilityConfig, ResolvedConfig } from "../models/config";
@@ -23,6 +22,10 @@ export declare class ObservabilityRuntime {
23
22
  readonly platform: PlatformMetadata;
24
23
  /** Identity context containing session, tab, and context identifiers. */
25
24
  readonly identity: Identity;
25
+ /** Stores for identity and journey keys. The runtime sets them at startup. */
26
+ private readonly stores;
27
+ /** Identity strategy that the runtime used to make the stores. */
28
+ private readonly identityBuiltAs;
26
29
  /** Throttled writer of the session's last-seen timestamp. */
27
30
  private readonly sessionTouch;
28
31
  /** Store for ambient application context attributes. */
@@ -39,22 +42,27 @@ export declare class ObservabilityRuntime {
39
42
  readonly builder: RecordBuilder;
40
43
  /** Console sink for local developer output. */
41
44
  readonly console: ConsoleSink;
42
- /** Cross-realm communication bus. */
43
- readonly bus: Bus;
44
- /** Persistent storage adapter for offline batches (sender role only). */
45
- private storage?;
45
+ /**
46
+ * Cross-realm communication bus. It is null until its chunk loads.
47
+ * In bus.mode "off", it loads only when a child frame or a worker needs it.
48
+ */
49
+ private bus;
50
+ /** Load and construction of the bus. It is undefined until the first need. */
51
+ private busBuilt?;
52
+ /** Load and start of the bus. It is undefined until the first need. */
53
+ private busLoad?;
46
54
  /** Storage strategy the adapter was built from, set once the build starts. */
47
55
  private storageBuiltAs?;
48
- /** HTTP transport instance for live log delivery (sender role only). */
49
- private transport?;
50
- /** Background retry engine for redelivering failed batches (sender role only). */
51
- private retry?;
52
- /** Primary log pipeline managing stream buffering and delivery (sender role only). */
53
- private pipeline?;
54
- /** Exit flush handler executing atomic batch delivery on unload (sender role only). */
55
- private exitFlush?;
56
+ /** Delivery stack. The runtime sets it in the sender role with an endpoint, after the chunk loads. */
57
+ private sender?;
58
+ /** Load of the delivery stack. It is undefined when nothing loads. A record then has no destination. */
59
+ private senderLoad?;
60
+ /** Records that arrive while the delivery stack loads. */
61
+ private pendingRecords;
56
62
  /** Active auto-capture instrumentation modules. */
57
63
  private readonly captures;
64
+ /** Count of capture installs. An install that a later install replaced stops after its load. */
65
+ private captureGeneration;
58
66
  /** Capture work that a rebuild of the capture modules must not repeat. */
59
67
  private readonly captureOnce;
60
68
  /** Queue buffering records created before bus role resolution. */
@@ -63,6 +71,8 @@ export declare class ObservabilityRuntime {
63
71
  private forwardBuffer;
64
72
  /** Indicates whether a microtask drain is scheduled for the forward buffer. */
65
73
  private forwardScheduled;
74
+ /** Indicates whether startup has decided the bus role. A sender load waits for it. */
75
+ private roleResolved;
66
76
  /** Indicates whether asynchronous initialization has completed. */
67
77
  private ready;
68
78
  /** Indicates whether the runtime has been permanently shut down. */
@@ -84,6 +94,16 @@ export declare class ObservabilityRuntime {
84
94
  * @returns Active runtime instance or null.
85
95
  */
86
96
  static current(): ObservabilityRuntime | null;
97
+ /**
98
+ * Returns the runtime that shutdown() stopped, until the next configure().
99
+ * @returns Stopped runtime instance or null.
100
+ */
101
+ static stopped(): ObservabilityRuntime | null;
102
+ /**
103
+ * Tests whether shutdown() stopped this runtime.
104
+ * @returns True after destroy() starts.
105
+ */
106
+ isDestroyed(): boolean;
87
107
  /**
88
108
  * Initializes a new runtime instance or updates the existing singleton.
89
109
  * @param input Consumer configuration options.
@@ -101,14 +121,64 @@ export declare class ObservabilityRuntime {
101
121
  * persisted under the old one, which is worse than refusing the change.
102
122
  */
103
123
  private keepBuiltStorage;
124
+ /**
125
+ * Refuses to remove the endpoint once the delivery stack exists. Without an endpoint,
126
+ * the retry engine removes each stored batch as delivered.
127
+ * @param input Partial configuration to merge.
128
+ * @returns Input with the endpoint removal taken out.
129
+ */
130
+ private keepEndpoint;
131
+ /**
132
+ * Restores the identity strategy from startup. The ids exist from startup.
133
+ * A later change cannot move them to another store.
134
+ */
135
+ private keepBuiltIdentity;
104
136
  /** Initializes asynchronous subsystems and flushes the boot buffer. */
105
137
  private init;
106
- /** Initializes storage, transport, pipeline, and unload listeners for sender role. */
107
- private becomeSender;
108
- /** Instantiates and registers enabled auto-capture modules. */
138
+ /**
139
+ * Starts the load of the bus one time.
140
+ * @returns Promise resolving to the started bus, or null if it did not load.
141
+ */
142
+ private ensureBus;
143
+ /**
144
+ * Loads and constructs the bus one time. It does not call start().
145
+ * @returns Promise resolving to the constructed bus, or null if it did not load.
146
+ */
147
+ private constructBus;
148
+ /**
149
+ * Starts the constructed bus. It never rejects.
150
+ * @returns Promise resolving to the started bus, or null if it did not load or start.
151
+ */
152
+ private startBus;
153
+ /** Imports and constructs the bus. It never rejects. */
154
+ private buildBus;
155
+ /**
156
+ * Reads the bus role. Without a bus, this context is the sender.
157
+ * @returns Active bus role.
158
+ */
159
+ private role;
160
+ /**
161
+ * Loads the delivery stack if this context is the sender and has an endpoint.
162
+ * @returns Promise resolving when the load completes, or at once if nothing loads.
163
+ */
164
+ private syncSender;
165
+ /**
166
+ * Starts the load of the delivery stack one time.
167
+ * @returns Promise resolving when the load completes or fails.
168
+ */
169
+ private loadSender;
170
+ /** Imports and builds the delivery stack. It then moves the held records into it. It never rejects. */
171
+ private buildSender;
172
+ /** Loads, builds and installs the enabled capture modules. It never rejects. */
109
173
  private installCaptures;
110
- /** Uninstalls active capture modules and re-creates them from updated configuration. */
111
- private reinstallCaptures;
174
+ /** Uninstalls the active capture modules. */
175
+ private uninstallCaptures;
176
+ /**
177
+ * Imports one capture module. A failed import reports and skips that module only.
178
+ * @param name Capture module name.
179
+ * @returns Promise resolving to the class, or undefined if the import failed.
180
+ */
181
+ private loadCapture;
112
182
  /**
113
183
  * Attaches a Web Worker or MessagePort to the bus for record forwarding.
114
184
  * @param worker Target Worker or MessagePort instance.
@@ -126,6 +196,18 @@ export declare class ObservabilityRuntime {
126
196
  * @param record Log record to route.
127
197
  */
128
198
  private route;
199
+ /**
200
+ * Hands a record to the delivery stack. Holds the record while the stack loads.
201
+ * Drops the record when nothing loads, for example in console-only mode.
202
+ * @param record Log record to deliver.
203
+ */
204
+ private deliver;
205
+ /**
206
+ * Adds a record to a hold buffer. It drops the oldest record when the buffer is full.
207
+ * @param buffer Hold buffer.
208
+ * @param record Record to hold.
209
+ */
210
+ private pushCapped;
129
211
  /**
130
212
  * Batches records for asynchronous transmission to the upstream sender.
131
213
  * @param record Log record to forward.
@@ -0,0 +1,58 @@
1
+ import type { ResolvedConfig } from "../models/config";
2
+ import type { LogRecord } from "../models/log-record";
3
+ import type { GapReporter } from "../models/storage";
4
+ import type { Diagnostics } from "./diagnostics";
5
+ /** Inputs to build the delivery stack. */
6
+ export interface SenderDeps {
7
+ /** Active configuration instance. */
8
+ config: ResolvedConfig;
9
+ /** Diagnostics reporter. */
10
+ diagnostics: Diagnostics;
11
+ /** Receives a report when storage drops batches before delivery. */
12
+ onGap: GapReporter;
13
+ }
14
+ /** Delivery stack for one sender runtime. */
15
+ export declare class Sender {
16
+ private readonly storage;
17
+ private readonly transport;
18
+ private readonly retry;
19
+ private readonly pipeline;
20
+ private readonly exitFlush;
21
+ private readonly diagnostics;
22
+ /**
23
+ * @param storage Storage adapter for undelivered batches.
24
+ * @param transport HTTP transport for live delivery.
25
+ * @param retry Retry engine for stored batches.
26
+ * @param pipeline Pipeline that batches records.
27
+ * @param exitFlush Handler that sends pending records on unload.
28
+ * @param diagnostics Diagnostics reporter.
29
+ */
30
+ private constructor();
31
+ /**
32
+ * Builds the delivery stack, drains the emergency queue and starts the retry loop.
33
+ * @param deps Configuration, diagnostics and gap reporter.
34
+ * @returns Promise resolving to the started sender.
35
+ */
36
+ static create(deps: SenderDeps): Promise<Sender>;
37
+ /**
38
+ * Adds a record to the pipeline.
39
+ * @param record Record to deliver.
40
+ */
41
+ push(record: LogRecord): void;
42
+ /**
43
+ * Sends the records held in the stream buffers.
44
+ * @returns Promise resolving when the batch is sent or stored for retry.
45
+ */
46
+ flush(): Promise<void>;
47
+ /**
48
+ * Counts the batches held in storage.
49
+ * @returns Promise resolving to the batch count, or 0 if storage fails.
50
+ */
51
+ queueDepth(): Promise<number>;
52
+ /**
53
+ * Sends pending records, stops every timer and listener, then closes storage.
54
+ * The synchronous steps run before the first await. The runtime relies on this order.
55
+ * @returns Promise resolving when storage is closed.
56
+ */
57
+ destroy(): Promise<void>;
58
+ }
@@ -0,0 +1,3 @@
1
+ const e=require("./constants-DZH04585.cjs"),t=require("./platform-g99Kn755.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 in ${String(e.V)}ms, suppressing the rest of this window`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
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-DPju_xSI.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DPju_xSI.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 /** Timestamp when the signature was last reported 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. Neither is recorded.\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 throwing inside requestAnimationFrame produces thousands\n // per second. Shipping all of them is a denial of service on our ingest.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `more than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors in ${String(ERROR_STORM_WINDOW_MS)}ms, suppressing the rest of 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 // Occurrences swallowed since this signature was last reported. Counting\n // them and never emitting the number makes a storm look like a trickle.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Deleted before it is re-set so the map stays in least-recently-reported\n // order, which is what makes the eviction below evict the right entry.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page throwing with a fresh message every render, which is what a bad\n // template literal inside a loop looks like, would grow this map for as\n // long as the document stays open.\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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,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,EAUnD,GANA,KAAK,KAAK,OAAOD,CAAG,EACpB,KAAK,KAAK,IAAIA,EAAK,CAAE,GAAIH,EAAK,MAAO,CAAE,CAAC,EAKpC,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"}
@@ -0,0 +1,76 @@
1
+ import { V as e } from "./constants-B6kdsCzF.js";
2
+ import { r as t } from "./platform-DMYo3AX3.js";
3
+ //#region src/capture/errors.ts
4
+ var n = class {
5
+ ctx;
6
+ name = "errors";
7
+ installed = !1;
8
+ seen = /* @__PURE__ */ new Map();
9
+ windowStart = 0;
10
+ windowCount = 0;
11
+ constructor(e) {
12
+ this.ctx = e;
13
+ }
14
+ install() {
15
+ this.installed || typeof addEventListener > "u" || (this.installed = !0, addEventListener("error", this.onError, !0), addEventListener("unhandledrejection", this.onRejection));
16
+ }
17
+ uninstall() {
18
+ this.installed && (this.installed = !1, removeEventListener("error", this.onError, !0), removeEventListener("unhandledrejection", this.onRejection), this.seen.clear());
19
+ }
20
+ onError = (e) => {
21
+ let n = e.target, r = n?.src ?? n?.href ?? "";
22
+ if (n !== null && n !== globalThis && r !== "") {
23
+ if (!this.ctx.config.capture.resourceErrors) return;
24
+ let e = this.ctx.config.capture.fullUrls ? r : t(r);
25
+ this.ctx.breadcrumbs.push({
26
+ t: Date.now(),
27
+ category: "http",
28
+ message: `resource failed: ${e}`
29
+ }), this.ctx.logger.warn("resource failed to load", {
30
+ "error.type": "resource",
31
+ "resource.url": e,
32
+ "resource.tag": n.tagName.toLowerCase()
33
+ });
34
+ return;
35
+ }
36
+ if (!this.ctx.config.capture.errors) return;
37
+ let i = e, a = i.message === "" ? "unknown error" : i.message, o = i.error ?? Error(a);
38
+ this.report("window.onerror", o, {
39
+ "error.source": i.filename,
40
+ "error.line": i.lineno,
41
+ "error.column": i.colno
42
+ });
43
+ };
44
+ onRejection = (e) => {
45
+ this.ctx.config.capture.rejections && this.report("unhandledrejection", e.reason, { "error.type": "unhandledrejection" });
46
+ };
47
+ report(t, n, r) {
48
+ let i = Date.now();
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", `more than 20 errors in ${String(e)}ms, suppressing the rest of this window`);
51
+ return;
52
+ }
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);
54
+ if (c && i - c.at < 5e3) {
55
+ c.count++, c.at = i;
56
+ return;
57
+ }
58
+ let l = c ? c.count - 1 : 0;
59
+ if (this.seen.delete(s), this.seen.set(s, {
60
+ at: i,
61
+ count: 1
62
+ }), this.seen.size > 200) {
63
+ let [e] = this.seen.keys();
64
+ this.seen.delete(e);
65
+ }
66
+ this.ctx.logger.error(a.message === "" ? t : a.message, a, {
67
+ ...r,
68
+ "error.captured_by": t,
69
+ "error.suppressed_count": l
70
+ });
71
+ }
72
+ };
73
+ //#endregion
74
+ export { n as ErrorCapture };
75
+
76
+ //# sourceMappingURL=errors-Dme9tz-6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-Dme9tz-6.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 /** Timestamp when the signature was last reported 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. Neither is recorded.\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 throwing inside requestAnimationFrame produces thousands\n // per second. Shipping all of them is a denial of service on our ingest.\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n `more than ${String(ERROR_STORM_MAX_PER_WINDOW)} errors in ${String(ERROR_STORM_WINDOW_MS)}ms, suppressing the rest of 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 // Occurrences swallowed since this signature was last reported. Counting\n // them and never emitting the number makes a storm look like a trickle.\n const suppressed = previous ? previous.count - 1 : 0;\n\n // Deleted before it is re-set so the map stays in least-recently-reported\n // order, which is what makes the eviction below evict the right entry.\n this.seen.delete(key);\n this.seen.set(key, { at: now, count: 1 });\n\n // A page throwing with a fresh message every render, which is what a bad\n // template literal inside a loop looks like, would grow this map for as\n // long as the document stays open.\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,O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