@crashsense/types 1.0.7 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,194 +1,694 @@
1
+ /**
2
+ * Classification category for detected crash events.
3
+ *
4
+ * CrashSense classifies every crash into one of these categories based on
5
+ * system state, error characteristics, and contributing factors.
6
+ *
7
+ * - `runtime_error` -- Standard JavaScript errors (TypeError, ReferenceError, etc.)
8
+ * - `memory_issue` -- Memory leaks, heap pressure, or out-of-memory conditions
9
+ * - `event_loop_blocking` -- Long tasks, frozen UI, or infinite loops
10
+ * - `framework_react` -- React-specific issues (hydration mismatches, infinite re-renders, hook violations)
11
+ * - `framework_vue` -- Vue-specific issues (reactivity loops, lifecycle errors, watcher cascades)
12
+ * - `network_induced` -- Crashes caused by network failures, timeouts, or CORS blocks
13
+ * - `iframe_overload` -- Excessive iframes exhausting browser resources
14
+ * - `rendering` -- Rendering pipeline failures
15
+ * - `mobile_device` -- Mobile-specific resource constraints
16
+ * - `resource_exhaustion` -- General resource exhaustion (CPU, memory, file handles)
17
+ * - `browser_compatibility` -- Browser-specific incompatibilities or missing APIs
18
+ */
1
19
  type CrashCategory = 'runtime_error' | 'memory_issue' | 'event_loop_blocking' | 'framework_react' | 'framework_vue' | 'network_induced' | 'iframe_overload' | 'rendering' | 'mobile_device' | 'resource_exhaustion' | 'browser_compatibility';
20
+ /**
21
+ * Severity level of a crash event, from most to least severe.
22
+ *
23
+ * - `critical` -- Application is unusable or data loss is likely
24
+ * - `error` -- A significant failure that affects functionality
25
+ * - `warning` -- A potential issue that may degrade experience
26
+ * - `info` -- Informational event captured for diagnostic context
27
+ */
2
28
  type CrashSeverity = 'critical' | 'error' | 'warning' | 'info';
29
+ /**
30
+ * A single frame in a parsed stack trace.
31
+ *
32
+ * Stack frames are extracted from the raw error stack and normalized
33
+ * into a structured format for classification and display.
34
+ */
3
35
  interface StackFrame {
36
+ /** Absolute or relative path to the source file. */
4
37
  filename: string;
38
+ /** Name of the function where the error occurred. */
5
39
  function: string;
40
+ /** Line number in the source file. */
6
41
  lineno: number;
42
+ /** Column number in the source file. */
7
43
  colno: number;
44
+ /** Whether this frame belongs to application code (true) or a library/vendor (false). */
8
45
  inApp: boolean;
46
+ /** Surrounding source lines for context, if available. */
9
47
  context?: string[];
10
48
  }
49
+ /**
50
+ * Category of a breadcrumb event.
51
+ *
52
+ * - `click` -- User click interaction
53
+ * - `navigation` -- Page or route navigation
54
+ * - `network` -- HTTP request or response
55
+ * - `console` -- Console log, warn, or error output
56
+ * - `state` -- Application state change
57
+ * - `custom` -- Developer-defined breadcrumb
58
+ */
11
59
  type BreadcrumbType = 'click' | 'navigation' | 'network' | 'console' | 'state' | 'custom';
60
+ /**
61
+ * A timestamped event in the trail leading up to a crash.
62
+ *
63
+ * Breadcrumbs are automatically collected (clicks, navigation, network, console)
64
+ * and can also be added manually via `addBreadcrumb()`. They provide the
65
+ * sequential context needed to understand what the user did before a crash.
66
+ */
12
67
  interface Breadcrumb {
68
+ /** Category of this breadcrumb event. */
13
69
  type: BreadcrumbType;
70
+ /** Unix timestamp in milliseconds when this event occurred. */
14
71
  timestamp: number;
72
+ /** Human-readable description of the event. */
15
73
  message: string;
74
+ /** Optional structured data associated with this breadcrumb. */
16
75
  data?: Record<string, unknown>;
17
76
  }
77
+ /**
78
+ * Direction of memory usage over a recent time window.
79
+ *
80
+ * - `stable` -- Heap usage is relatively constant
81
+ * - `growing` -- Heap usage is increasing (potential leak)
82
+ * - `shrinking` -- Heap usage is decreasing (GC reclaiming)
83
+ * - `spike` -- Sudden sharp increase in heap usage
84
+ */
18
85
  type MemoryTrend = 'stable' | 'growing' | 'shrinking' | 'spike';
86
+ /**
87
+ * Current memory state of the JavaScript heap.
88
+ *
89
+ * Values are sourced from `performance.memory` (Chrome-only).
90
+ * In browsers that do not support this API, numeric fields will be null.
91
+ */
19
92
  interface MemoryState {
93
+ /** Bytes of heap currently in use. Null if unsupported. */
20
94
  usedJSHeapSize: number | null;
95
+ /** Total bytes allocated for the heap. Null if unsupported. */
21
96
  totalJSHeapSize: number | null;
97
+ /** Maximum heap size the browser will allocate. Null if unsupported. */
22
98
  heapSizeLimit: number | null;
99
+ /** Direction of memory usage over the recent sampling window. */
23
100
  trend: MemoryTrend;
101
+ /** Percentage of heap limit currently in use (0-100). Null if unsupported. */
24
102
  utilizationPercent: number | null;
25
103
  }
104
+ /**
105
+ * CPU and main-thread performance metrics.
106
+ *
107
+ * Derived from the Long Task API and PerformanceObserver.
108
+ */
26
109
  interface CpuState {
110
+ /** Number of long tasks (>50ms) detected in the last 30 seconds. */
27
111
  longTasksLast30s: number;
112
+ /** Average duration in milliseconds of long tasks in the last 30 seconds. */
28
113
  avgLongTaskDuration: number;
114
+ /** Maximum duration in milliseconds of a single long task in the last 30 seconds. */
29
115
  maxLongTaskDuration: number;
116
+ /** Total estimated blocking time in milliseconds from all long tasks. */
30
117
  estimatedBlockingTime: number;
31
118
  }
119
+ /**
120
+ * Current state of the browser event loop.
121
+ */
32
122
  interface EventLoopState {
123
+ /** Whether the event loop is currently blocked by a long-running task. */
33
124
  isBlocked: boolean;
125
+ /** Duration in milliseconds of the current block, or null if not blocked. */
34
126
  blockDuration: number | null;
127
+ /** Estimated frames per second based on requestAnimationFrame timing. */
35
128
  fps: number;
36
129
  }
130
+ /**
131
+ * Network connectivity and request health metrics.
132
+ */
37
133
  interface NetworkState {
134
+ /** Number of in-flight HTTP requests. */
38
135
  pendingRequests: number;
136
+ /** Number of failed HTTP requests in the last 60 seconds. */
39
137
  failedRequestsLast60s: number;
138
+ /** Average response latency in milliseconds over the last 60 seconds. */
40
139
  avgLatencyLast60s: number;
140
+ /** Network connection type from the Network Information API, or null if unavailable. */
41
141
  connectionType: string | null;
142
+ /** Whether the browser reports an active network connection. */
42
143
  isOnline: boolean;
43
144
  }
145
+ /**
146
+ * State of iframe elements in the document.
147
+ *
148
+ * Tracked via MutationObserver when `enableIframeTracking` is enabled.
149
+ * Excessive iframes (ads, widgets, payment forms) can exhaust memory.
150
+ */
44
151
  interface IframeState {
152
+ /** Total number of iframe elements currently in the DOM. */
45
153
  totalCount: number;
154
+ /** Number of iframes added in the last 60 seconds. */
46
155
  addedLast60s: number;
156
+ /** Number of iframes removed in the last 60 seconds. */
47
157
  removedLast60s: number;
158
+ /** List of unique origin URLs from iframe src attributes. */
48
159
  origins: string[];
160
+ /** Number of iframes with a different origin than the host page. */
49
161
  crossOriginCount: number;
50
162
  }
163
+ /**
164
+ * Complete snapshot of system state at the time of a crash.
165
+ *
166
+ * Captured automatically by CrashSense monitors and included in every crash event.
167
+ */
51
168
  interface SystemState {
169
+ /** JavaScript heap memory metrics. */
52
170
  memory: MemoryState;
171
+ /** Main-thread CPU and long task metrics. */
53
172
  cpu: CpuState;
173
+ /** Event loop responsiveness metrics. */
54
174
  eventLoop: EventLoopState;
175
+ /** Network connectivity and request health. */
55
176
  network: NetworkState;
177
+ /** Iframe tracking state. Present only when `enableIframeTracking` is enabled. */
56
178
  iframe?: IframeState;
57
179
  }
180
+ /**
181
+ * Information about the user device and browser environment.
182
+ *
183
+ * Collected once at SDK initialization and included in every crash report.
184
+ * PII-sensitive fields (userAgent) are scrubbed when `piiScrubbing` is enabled.
185
+ */
58
186
  interface DeviceInfo {
187
+ /** Full user agent string from `navigator.userAgent`. */
59
188
  userAgent: string;
189
+ /** Operating system platform from `navigator.platform`. */
60
190
  platform: string;
191
+ /** Browser vendor from `navigator.vendor`. */
61
192
  vendor: string;
193
+ /** Device memory in gigabytes from `navigator.deviceMemory`, or null if unsupported. */
62
194
  deviceMemory: number | null;
195
+ /** Number of logical CPU cores from `navigator.hardwareConcurrency`, or null if unsupported. */
63
196
  hardwareConcurrency: number | null;
197
+ /** Current viewport dimensions in pixels. */
64
198
  viewport: {
65
199
  width: number;
66
200
  height: number;
67
201
  };
202
+ /** Device pixel ratio (e.g., 2 for Retina displays). */
68
203
  devicePixelRatio: number;
204
+ /** Whether the device supports touch input. */
69
205
  touchSupport: boolean;
206
+ /** User preferred color scheme. */
70
207
  colorScheme: 'light' | 'dark';
208
+ /** Whether the user prefers reduced motion. */
71
209
  reducedMotion: boolean;
210
+ /** Browser language from `navigator.language`. */
72
211
  language: string;
212
+ /** IANA timezone string from `Intl.DateTimeFormat`. */
73
213
  timezone: string;
74
214
  }
215
+ /**
216
+ * Framework-specific context attached to crash events.
217
+ *
218
+ * Populated automatically by framework adapters (@crashsense/react, @crashsense/vue)
219
+ * or set to default vanilla values when no adapter is active.
220
+ */
75
221
  interface FrameworkContext {
222
+ /** Framework identifier. Set by the active adapter or defaults to `'vanilla'`. */
76
223
  name: 'react' | 'vue' | 'vanilla' | string;
224
+ /** Framework version string (e.g., `'18.2.0'`). */
77
225
  version: string;
226
+ /** Name of the CrashSense adapter package (e.g., `'@crashsense/react'`). */
78
227
  adapter: string;
228
+ /** Component hierarchy from root to the component where the crash occurred. */
79
229
  componentTree?: string[];
230
+ /** Current route path at the time of the crash. */
80
231
  currentRoute?: string;
232
+ /** Snapshot of relevant application store state. */
81
233
  storeState?: Record<string, unknown>;
234
+ /** Framework lifecycle stage when the crash occurred (e.g., `'render'`, `'mounted'`). */
82
235
  lifecycleStage?: string;
236
+ /** Number of component renders since the last navigation. */
83
237
  renderCount?: number;
84
238
  }
239
+ /**
240
+ * A single factor that contributed to the crash classification decision.
241
+ *
242
+ * Each crash event includes an array of contributing factors with weights
243
+ * and evidence strings, so consumers can understand why the classifier
244
+ * chose a specific category and confidence score.
245
+ */
85
246
  interface ContributingFactor {
247
+ /** Machine-readable identifier for this factor (e.g., `'high_memory_utilization'`). */
86
248
  factor: string;
249
+ /** Relative weight of this factor in the classification (0.0 to 1.0). */
87
250
  weight: number;
251
+ /** Human-readable evidence string explaining the observation. */
88
252
  evidence: string;
89
253
  }
254
+ /**
255
+ * A fully classified crash event -- the primary output of the CrashSense SDK.
256
+ *
257
+ * Contains the error details, system state snapshot, device information,
258
+ * framework context, breadcrumb trail, classification result, and metadata.
259
+ * This is the object passed to plugins and included in CrashReport.
260
+ */
90
261
  interface CrashEvent {
262
+ /** Unique identifier for this crash event (UUID v4). */
91
263
  id: string;
264
+ /** Deterministic fingerprint for deduplication and grouping of similar crashes. */
92
265
  fingerprint: string;
266
+ /** Unix timestamp in milliseconds when the crash was detected. */
93
267
  timestamp: number;
268
+ /** Session identifier linking this crash to a user session. */
94
269
  sessionId: string;
270
+ /** Primary crash category determined by the classifier. */
95
271
  category: CrashCategory;
272
+ /** More specific sub-classification within the category (e.g., `'memory_leak'`, `'api_failure'`). */
96
273
  subcategory: string;
274
+ /** Severity level of this crash event. */
97
275
  severity: CrashSeverity;
276
+ /** Classifier confidence score for the assigned category (0.0 to 1.0). */
98
277
  confidence: number;
278
+ /** Structured error information extracted from the original exception. */
99
279
  error: {
280
+ /** Error constructor name (e.g., `'TypeError'`, `'RangeError'`). */
100
281
  type: string;
282
+ /** Error message string. */
101
283
  message: string;
284
+ /** Parsed and normalized stack trace frames. */
102
285
  stack: StackFrame[];
286
+ /** Original raw stack trace string. */
103
287
  raw: string;
104
288
  };
289
+ /** Complete system state snapshot captured at the moment of the crash. */
105
290
  system: SystemState;
291
+ /** Device and browser environment information. */
106
292
  device: DeviceInfo;
293
+ /** Framework-specific context from the active adapter. */
107
294
  framework: FrameworkContext;
295
+ /** Ordered trail of events leading up to the crash (most recent last). */
108
296
  breadcrumbs: Breadcrumb[];
297
+ /** Factors that contributed to the crash classification with weights and evidence. */
109
298
  contributingFactors: ContributingFactor[];
299
+ /** Application and SDK metadata for this crash event. */
110
300
  meta: CrashEventMeta;
111
301
  }
302
+ /**
303
+ * Metadata associated with a crash event.
304
+ *
305
+ * Contains application identifiers, environment info, user context,
306
+ * custom tags, and SDK version for filtering and grouping.
307
+ */
112
308
  interface CrashEventMeta {
309
+ /** Application identifier from CrashSense configuration. */
113
310
  appId: string;
311
+ /** Environment name (e.g., `'production'`, `'staging'`). */
114
312
  environment: string;
313
+ /** Application release or version tag, if configured. */
115
314
  release?: string;
315
+ /** User identifier set via `setUser()`, if available. */
116
316
  userId?: string;
317
+ /** Custom key-value tags for filtering and grouping crash events. */
117
318
  tags: Record<string, string>;
319
+ /** Version of the CrashSense SDK that generated this event. */
118
320
  sdkVersion: string;
119
321
  }
322
+ /**
323
+ * A raw crash event before classification.
324
+ *
325
+ * Built internally by CrashSense when an error is captured. Contains
326
+ * partial system state and framework context that will be completed
327
+ * during the classification pipeline before producing a full CrashEvent.
328
+ */
120
329
  interface RawCrashEvent {
330
+ /** Unique identifier for this event (UUID v4). */
121
331
  id: string;
332
+ /** Unix timestamp in milliseconds when the error was captured. */
122
333
  timestamp: number;
334
+ /** Session identifier for the current user session. */
123
335
  sessionId: string;
336
+ /** Error details extracted from the captured exception. */
124
337
  error: {
338
+ /** Error constructor name. */
125
339
  type: string;
340
+ /** Error message string. */
126
341
  message: string;
342
+ /** Parsed stack trace frames. */
127
343
  stack: StackFrame[];
344
+ /** Original raw stack trace string. */
128
345
  raw: string;
129
346
  };
347
+ /** Partial system state snapshot (may be incomplete before classification). */
130
348
  system: Partial<SystemState>;
349
+ /** Device information. */
131
350
  device: DeviceInfo;
351
+ /** Partial framework context (completed during classification). */
132
352
  framework: Partial<FrameworkContext>;
353
+ /** Breadcrumb trail collected up to the point of capture. */
133
354
  breadcrumbs: Breadcrumb[];
355
+ /** Event metadata including app ID, environment, and tags. */
134
356
  meta: CrashEventMeta;
135
357
  }
358
+ /**
359
+ * User-facing configuration options for initializing CrashSense.
360
+ *
361
+ * Only `appId` is required. All other fields have sensible defaults
362
+ * and are resolved into a complete ResolvedConfig internally.
363
+ */
136
364
  interface CrashSenseConfig {
365
+ /** Unique identifier for your application. Used in crash event metadata. */
137
366
  appId: string;
367
+ /**
368
+ * Environment name for filtering crash events.
369
+ * @default 'production'
370
+ */
138
371
  environment?: string;
372
+ /**
373
+ * Application release or version tag included in crash metadata.
374
+ * @default ''
375
+ */
139
376
  release?: string;
377
+ /**
378
+ * Event sampling rate. Set to 0.5 to capture ~50% of events, 1.0 for all.
379
+ * @default 1.0
380
+ */
140
381
  sampleRate?: number;
382
+ /**
383
+ * Maximum number of crash events processed per minute. Prevents event storms.
384
+ * @default 30
385
+ */
141
386
  maxEventsPerMinute?: number;
387
+ /**
388
+ * Enable monitoring of JavaScript heap memory usage and trends.
389
+ * Requires `performance.memory` (Chrome-only; gracefully degrades elsewhere).
390
+ * @default true
391
+ */
142
392
  enableMemoryMonitoring?: boolean;
393
+ /**
394
+ * Enable monitoring of long tasks (>50ms) on the main thread via the Long Task API.
395
+ * @default true
396
+ */
143
397
  enableLongTaskMonitoring?: boolean;
398
+ /**
399
+ * Enable monitoring of network request failures and latency.
400
+ * @default true
401
+ */
144
402
  enableNetworkMonitoring?: boolean;
403
+ /**
404
+ * Enable tracking of iframe additions and removals via MutationObserver.
405
+ * Useful for detecting iframe-induced resource exhaustion from ads or widgets.
406
+ * @default false
407
+ */
145
408
  enableIframeTracking?: boolean;
409
+ /**
410
+ * Enable the 3-tier pre-crash warning system that detects dangerous
411
+ * memory or iframe conditions before the browser tab crashes.
412
+ * @default false
413
+ */
146
414
  enablePreCrashWarning?: boolean;
415
+ /**
416
+ * Memory utilization threshold (0.0 to 1.0) for triggering critical pre-crash warnings.
417
+ * Only used when `enablePreCrashWarning` is true.
418
+ * @default 0.85
419
+ */
147
420
  preCrashMemoryThreshold?: number;
421
+ /**
422
+ * Enable automatic scrubbing of PII (emails, IPs, tokens, credit card numbers)
423
+ * from error messages and breadcrumbs before events leave the SDK.
424
+ * @default true
425
+ */
148
426
  piiScrubbing?: boolean;
427
+ /**
428
+ * Enable debug mode. When true, crash reports are logged to the console.
429
+ * @default false
430
+ */
149
431
  debug?: boolean;
432
+ /**
433
+ * Callback invoked when a crash is detected and fully classified.
434
+ * Receives the complete CrashReport including the event and optional AI analysis.
435
+ * @default null
436
+ */
150
437
  onCrash?: (report: CrashReport) => void;
438
+ /**
439
+ * Callback invoked when a potential OOM recovery is detected on page reload.
440
+ * Only called when `enableOOMRecovery` is true and OOM signals are found.
441
+ * @default null
442
+ */
443
+ onOOMRecovery?: (report: OOMRecoveryReport) => void;
444
+ /**
445
+ * Enable OOM (Out-of-Memory) crash recovery detection.
446
+ * When enabled, CrashSense periodically checkpoints system state to sessionStorage
447
+ * and analyzes signals on page reload to determine if the previous session was OOM-killed.
448
+ * @default false
449
+ */
450
+ enableOOMRecovery?: boolean;
451
+ /**
452
+ * Interval in milliseconds between checkpoint writes to sessionStorage.
453
+ * Only used when `enableOOMRecovery` is true.
454
+ * @default 10000
455
+ */
456
+ checkpointInterval?: number;
457
+ /**
458
+ * Minimum OOM probability threshold (0.0 to 1.0) required to trigger
459
+ * the `onOOMRecovery` callback. Lower values increase sensitivity.
460
+ * @default 0.3
461
+ */
462
+ oomRecoveryThreshold?: number;
463
+ /**
464
+ * URL endpoint for emergency data flushing via `navigator.sendBeacon()`
465
+ * during page lifecycle events (visibilitychange, pagehide, freeze).
466
+ * When null, lifecycle flush is disabled.
467
+ * @default null
468
+ */
469
+ flushEndpoint?: string;
151
470
  }
471
+ /**
472
+ * Fully resolved configuration with all defaults applied.
473
+ *
474
+ * This is the internal configuration object used throughout the SDK.
475
+ * All optional fields from CrashSenseConfig are resolved to concrete values.
476
+ */
152
477
  interface ResolvedConfig {
478
+ /** Application identifier. */
153
479
  appId: string;
480
+ /**
481
+ * Resolved environment name.
482
+ * @default 'production'
483
+ */
154
484
  environment: string;
485
+ /**
486
+ * Resolved release tag.
487
+ * @default ''
488
+ */
155
489
  release: string;
490
+ /**
491
+ * Resolved sampling rate.
492
+ * @default 1.0
493
+ */
156
494
  sampleRate: number;
495
+ /**
496
+ * Resolved max events per minute.
497
+ * @default 30
498
+ */
157
499
  maxEventsPerMinute: number;
500
+ /**
501
+ * Whether memory monitoring is enabled.
502
+ * @default true
503
+ */
158
504
  enableMemoryMonitoring: boolean;
505
+ /**
506
+ * Whether long task monitoring is enabled.
507
+ * @default true
508
+ */
159
509
  enableLongTaskMonitoring: boolean;
510
+ /**
511
+ * Whether network monitoring is enabled.
512
+ * @default true
513
+ */
160
514
  enableNetworkMonitoring: boolean;
515
+ /**
516
+ * Whether iframe tracking is enabled.
517
+ * @default false
518
+ */
161
519
  enableIframeTracking: boolean;
520
+ /**
521
+ * Whether the pre-crash warning system is enabled.
522
+ * @default false
523
+ */
162
524
  enablePreCrashWarning: boolean;
525
+ /**
526
+ * Memory utilization threshold for critical pre-crash warnings.
527
+ * @default 0.85
528
+ */
163
529
  preCrashMemoryThreshold: number;
530
+ /**
531
+ * Whether PII scrubbing is enabled.
532
+ * @default true
533
+ */
164
534
  piiScrubbing: boolean;
535
+ /**
536
+ * Whether debug logging is enabled.
537
+ * @default false
538
+ */
165
539
  debug: boolean;
540
+ /**
541
+ * Crash callback, or null if not configured.
542
+ * @default null
543
+ */
166
544
  onCrash: ((report: CrashReport) => void) | null;
545
+ /**
546
+ * Whether OOM recovery detection is enabled.
547
+ * @default false
548
+ */
549
+ enableOOMRecovery: boolean;
550
+ /**
551
+ * Checkpoint write interval in milliseconds.
552
+ * @default 10000
553
+ */
554
+ checkpointInterval: number;
555
+ /**
556
+ * Minimum OOM probability threshold.
557
+ * @default 0.3
558
+ */
559
+ oomRecoveryThreshold: number;
560
+ /**
561
+ * Lifecycle flush endpoint URL, or null if disabled.
562
+ * @default null
563
+ */
564
+ flushEndpoint: string | null;
565
+ /**
566
+ * OOM recovery callback, or null if not configured.
567
+ * @default null
568
+ */
569
+ onOOMRecovery: ((report: OOMRecoveryReport) => void) | null;
167
570
  }
571
+ /**
572
+ * Interface for CrashSense plugins.
573
+ *
574
+ * Plugins intercept, enrich, or drop crash events before they reach
575
+ * the `onCrash` callback. They receive the core instance during setup
576
+ * for access to configuration and SDK methods.
577
+ */
168
578
  interface CrashSensePlugin {
579
+ /** Unique name identifying this plugin. */
169
580
  name: string;
581
+ /**
582
+ * Called when the plugin is registered via `core.use()`.
583
+ * @param core - The CrashSense core instance.
584
+ */
170
585
  setup(core: CrashSenseCore): void;
586
+ /** Called when the CrashSense instance is destroyed. Clean up resources here. */
171
587
  teardown(): void;
588
+ /**
589
+ * Called for each crash event before it reaches the `onCrash` callback.
590
+ * Return the event (optionally modified) to pass it through, or null to drop it.
591
+ * @param event - The classified crash event.
592
+ * @returns The event to pass through, or null to suppress it.
593
+ */
172
594
  onCrashEvent?(event: CrashEvent): CrashEvent | null;
173
595
  }
596
+ /**
597
+ * Public interface of the CrashSense core instance.
598
+ *
599
+ * This is the main object returned by `createCrashSense()` and provided
600
+ * to plugins and framework adapters. It exposes methods for error capture,
601
+ * breadcrumb management, user context, and system state access.
602
+ */
174
603
  interface CrashSenseCore {
604
+ /** The fully resolved SDK configuration. */
175
605
  readonly config: ResolvedConfig;
606
+ /** Unique session identifier for the current CrashSense instance. */
176
607
  readonly sessionId: string;
608
+ /**
609
+ * Register a plugin to intercept crash events.
610
+ * @param plugin - The plugin to register.
611
+ */
177
612
  use(plugin: CrashSensePlugin): void;
613
+ /**
614
+ * Manually capture an exception with optional context.
615
+ * The error is classified and processed through the full crash pipeline.
616
+ * @param error - The error to capture. Can be an Error instance, string, or any value.
617
+ * @param context - Optional key-value context merged into event metadata.
618
+ */
178
619
  captureException(error: unknown, context?: Record<string, unknown>): void;
620
+ /**
621
+ * Capture a message as a crash event with the specified severity.
622
+ * @param message - The message to capture.
623
+ * @param severity - Severity level. Defaults to `'info'`.
624
+ */
179
625
  captureMessage(message: string, severity?: CrashSeverity): void;
626
+ /**
627
+ * Add a breadcrumb to the trail. Timestamp is set automatically.
628
+ * @param breadcrumb - The breadcrumb data (type and message required).
629
+ */
180
630
  addBreadcrumb(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void;
631
+ /**
632
+ * Set user context for crash reports. The `id` field is required;
633
+ * additional fields are included as user metadata.
634
+ * @param user - User object with at minimum an `id` field.
635
+ */
181
636
  setUser(user: {
182
637
  id: string;
183
638
  [key: string]: unknown;
184
639
  }): void;
640
+ /**
641
+ * Set a named context object. Context values are included in crash event tags.
642
+ * @param key - Context name.
643
+ * @param value - Context data as key-value pairs.
644
+ */
185
645
  setContext(key: string, value: Record<string, unknown>): void;
646
+ /**
647
+ * Get a snapshot of the current system state (memory, CPU, event loop, network, iframes).
648
+ * @returns Current system state.
649
+ */
186
650
  getSystemState(): SystemState;
651
+ /**
652
+ * Get device and browser environment information.
653
+ * @returns Device information collected at initialization.
654
+ */
187
655
  getDeviceInfo(): DeviceInfo;
656
+ /**
657
+ * Destroy the CrashSense instance. Stops all monitors, removes event listeners,
658
+ * tears down plugins, and releases resources.
659
+ */
188
660
  destroy(): void;
661
+ /**
662
+ * Internal: Used by monitors to report raw crash events into the classification pipeline.
663
+ * @internal
664
+ */
189
665
  _reportRawEvent(event: RawCrashEvent): void;
666
+ /**
667
+ * Internal: Access the event bus for subscribing to SDK events.
668
+ * @internal
669
+ */
190
670
  _getEventBus(): EventBus;
191
671
  }
672
+ /**
673
+ * Map of all event types emitted by the CrashSense internal event bus.
674
+ *
675
+ * Monitors emit events when they detect notable conditions. Plugins and
676
+ * internal components subscribe to these events for coordination.
677
+ *
678
+ * - `error` -- A caught JavaScript error
679
+ * - `unhandled_rejection` -- An unhandled Promise rejection
680
+ * - `memory_warning` -- Memory utilization crossed a warning threshold
681
+ * - `long_task` -- A long task (>50ms) was detected on the main thread
682
+ * - `network_failure` -- An HTTP request failed
683
+ * - `crash_detected` -- A crash event was fully classified
684
+ * - `iframe_added` -- An iframe was added to the DOM
685
+ * - `iframe_removed` -- An iframe was removed from the DOM
686
+ * - `pre_crash_warning` -- A pre-crash warning was escalated
687
+ * - `breadcrumb` -- A new breadcrumb was recorded
688
+ * - `oom_recovery` -- An OOM recovery was detected on page reload
689
+ * - `checkpoint_written` -- A checkpoint was persisted to sessionStorage
690
+ * - `lifecycle_flush` -- Data was flushed during a page lifecycle event
691
+ */
192
692
  type EventBusEventMap = {
193
693
  'error': {
194
694
  error: Error;
@@ -237,118 +737,359 @@ type EventBusEventMap = {
237
737
  timestamp: number;
238
738
  };
239
739
  'breadcrumb': Breadcrumb;
740
+ 'oom_recovery': {
741
+ report: OOMRecoveryReport;
742
+ };
743
+ 'checkpoint_written': {
744
+ timestamp: number;
745
+ sessionId: string;
746
+ };
747
+ 'lifecycle_flush': {
748
+ reason: string;
749
+ timestamp: number;
750
+ };
240
751
  };
752
+ /**
753
+ * Severity level of a pre-crash warning.
754
+ *
755
+ * Warnings escalate through three tiers as system conditions deteriorate:
756
+ * - `elevated` -- System under pressure (>70% memory or >5 iframes)
757
+ * - `critical` -- High risk of crash (>85% memory or >10 iframes)
758
+ * - `imminent` -- Crash likely within seconds (>95% memory or >15 iframes)
759
+ */
241
760
  type PreCrashLevel = 'elevated' | 'critical' | 'imminent';
761
+ /**
762
+ * Typed event bus for internal CrashSense event communication.
763
+ *
764
+ * Used by monitors, classifiers, and plugins to subscribe to and emit
765
+ * SDK events in a type-safe manner.
766
+ */
242
767
  interface EventBus {
768
+ /**
769
+ * Subscribe to an event.
770
+ * @param event - Event name to listen for.
771
+ * @param handler - Callback invoked when the event is emitted.
772
+ */
243
773
  on<K extends keyof EventBusEventMap>(event: K, handler: (data: EventBusEventMap[K]) => void): void;
774
+ /**
775
+ * Unsubscribe from an event.
776
+ * @param event - Event name to stop listening for.
777
+ * @param handler - The same handler function that was passed to `on()`.
778
+ */
244
779
  off<K extends keyof EventBusEventMap>(event: K, handler: (data: EventBusEventMap[K]) => void): void;
780
+ /**
781
+ * Emit an event to all registered handlers.
782
+ * @param event - Event name to emit.
783
+ * @param data - Event payload matching the EventBusEventMap type.
784
+ */
245
785
  emit<K extends keyof EventBusEventMap>(event: K, data: EventBusEventMap[K]): void;
246
786
  }
787
+ /**
788
+ * The final output delivered to the `onCrash` callback.
789
+ *
790
+ * Contains the fully classified crash event and an optional AI analysis
791
+ * (null unless an AI client is configured and analysis succeeds).
792
+ */
247
793
  interface CrashReport {
794
+ /** The fully classified crash event. */
248
795
  event: CrashEvent;
796
+ /** AI-generated crash analysis, or null if AI is not configured or analysis failed. */
249
797
  analysis: CrashAnalysis | null;
798
+ /** Unix timestamp in milliseconds when this report was generated. */
250
799
  timestamp: number;
251
800
  }
801
+ /**
802
+ * AI-generated analysis of a crash event.
803
+ *
804
+ * Produced by the @crashsense/ai package when configured with an LLM endpoint.
805
+ * Contains the root cause assessment, suggested fix, prevention advice,
806
+ * and alternative causes ranked by likelihood.
807
+ */
252
808
  interface CrashAnalysis {
809
+ /** Primary root cause of the crash as determined by the AI. */
253
810
  rootCause: string;
811
+ /** Detailed explanation of why the crash occurred. */
254
812
  explanation: string;
813
+ /** Suggested code fix, or null if no specific fix can be recommended. */
255
814
  fix: {
815
+ /** Human-readable description of what the fix does. */
256
816
  description: string;
817
+ /** Suggested code snippet to resolve the issue. */
257
818
  code: string;
819
+ /** File path where the fix should be applied. */
258
820
  filename: string;
259
821
  } | null;
822
+ /** List of preventive measures to avoid similar crashes. */
260
823
  prevention: string[];
824
+ /** AI confidence score for this analysis (0.0 to 1.0). */
261
825
  confidence: number;
826
+ /** Alternative possible causes ranked by likelihood. */
262
827
  alternativeCauses: Array<{
263
828
  cause: string;
264
829
  likelihood: number;
265
830
  }>;
831
+ /** Source of the analysis: heuristic (rules only), ai (LLM only), or hybrid (both). */
266
832
  source: 'heuristic' | 'ai' | 'hybrid';
267
833
  }
834
+ /**
835
+ * Configuration for the AI analysis client (@crashsense/ai).
836
+ *
837
+ * Supports OpenAI, Anthropic, Google, or any OpenAI-compatible endpoint.
838
+ */
268
839
  interface AIConfig {
840
+ /** URL of the LLM API endpoint (e.g., `'https://api.openai.com/v1/chat/completions'`). */
269
841
  endpoint: string;
842
+ /** API key for authenticating with the LLM provider. */
270
843
  apiKey: string;
844
+ /** Model identifier (e.g., `'gpt-4'`, `'claude-3-opus'`). Provider-specific. */
271
845
  model?: string;
846
+ /** Maximum tokens for the AI response. */
272
847
  maxTokens?: number;
848
+ /** Sampling temperature (0.0 to 2.0). Lower values produce more deterministic output. */
273
849
  temperature?: number;
850
+ /** Request timeout in milliseconds. */
274
851
  timeout?: number;
852
+ /** Number of retry attempts on transient failures. */
275
853
  retries?: number;
854
+ /** LLM provider hint for request formatting. Defaults to auto-detection from endpoint URL. */
276
855
  provider?: 'openai' | 'anthropic' | 'google' | 'custom';
277
856
  }
857
+ /**
858
+ * Token-optimized payload sent to the LLM endpoint for crash analysis.
859
+ *
860
+ * Built internally by the AI client from a CrashEvent. Contains only the
861
+ * fields most relevant for root cause analysis, compressed for token efficiency.
862
+ */
278
863
  interface AIPayload {
864
+ /** Summary of the crash classification. */
279
865
  crash_summary: {
866
+ /** Crash category. */
280
867
  category: CrashCategory;
868
+ /** Crash subcategory. */
281
869
  subcategory: string;
870
+ /** Heuristic classifier confidence score. */
282
871
  heuristic_confidence: number;
872
+ /** Crash severity level. */
283
873
  severity: CrashSeverity;
284
874
  };
875
+ /** Compressed error information. */
285
876
  error: {
877
+ /** Error constructor name. */
286
878
  type: string;
879
+ /** Error message. */
287
880
  message: string;
881
+ /** Top 5 stack frames as formatted strings. */
288
882
  stack_top_5: string[];
883
+ /** Stack frames identified as user application code. */
289
884
  user_code_frames: string[];
290
885
  };
886
+ /** System state metrics at crash time. */
291
887
  system_state: {
888
+ /** Memory utilization as a formatted string. */
292
889
  memory_utilization: string;
890
+ /** Memory usage trend direction. */
293
891
  memory_trend: MemoryTrend;
892
+ /** Number of long tasks in the last 30 seconds. */
294
893
  long_tasks_last_30s: number;
894
+ /** Estimated FPS at the time of crash. */
295
895
  fps_at_crash: number;
896
+ /** Number of pending HTTP requests. */
296
897
  pending_network_requests: number;
898
+ /** Number of failed HTTP requests in the last 60 seconds. */
297
899
  failed_requests_last_60s: number;
298
900
  };
901
+ /** Compressed device information. */
299
902
  device: {
903
+ /** OS platform. */
300
904
  platform: string;
905
+ /** Device memory as a formatted string. */
301
906
  memory: string;
907
+ /** Viewport dimensions as a formatted string. */
302
908
  viewport: string;
909
+ /** Network connection type. */
303
910
  connection: string;
304
911
  };
912
+ /** Framework context summary. */
305
913
  framework: {
914
+ /** Framework name. */
306
915
  name: string;
916
+ /** Framework version. */
307
917
  version: string;
918
+ /** Lifecycle stage at crash time. */
308
919
  lifecycle_stage: string;
920
+ /** Component tree path from root to crash site. */
309
921
  component_path: string[];
922
+ /** Number of renders since the last navigation. */
310
923
  render_count_since_nav: number;
311
924
  };
925
+ /** Last 5 breadcrumbs before the crash. */
312
926
  breadcrumbs_last_5: Array<{
927
+ /** Breadcrumb type. */
313
928
  type: BreadcrumbType;
929
+ /** Breadcrumb message. */
314
930
  message: string;
931
+ /** Relative time before crash as a formatted string. */
315
932
  time: string;
316
933
  }>;
934
+ /** Contributing factors from the heuristic classifier. */
317
935
  contributing_factors: Array<{
936
+ /** Factor identifier. */
318
937
  factor: string;
938
+ /** Factor weight. */
319
939
  weight: number;
940
+ /** Evidence string. */
320
941
  evidence: string;
321
942
  }>;
322
943
  }
944
+ /**
945
+ * Structured response from the LLM after analyzing a crash.
946
+ *
947
+ * Parsed and validated by the AI client before being wrapped
948
+ * into a CrashAnalysis object.
949
+ */
323
950
  interface AIResponse {
951
+ /** Primary root cause of the crash. */
324
952
  rootCause: string;
953
+ /** Detailed explanation of why the crash occurred. */
325
954
  explanation: string;
955
+ /** Suggested code fix. */
326
956
  fix: {
957
+ /** Description of what the fix does. */
327
958
  description: string;
959
+ /** Code snippet to resolve the issue. */
328
960
  code: string;
961
+ /** Target file path for the fix. */
329
962
  filename: string;
330
963
  };
964
+ /** Preventive measures to avoid recurrence. */
331
965
  prevention: string[];
966
+ /** AI confidence in this analysis (0.0 to 1.0). */
332
967
  confidence: number;
968
+ /** Alternative possible causes ranked by likelihood. */
333
969
  alternativeCauses: Array<{
334
970
  cause: string;
335
971
  likelihood: number;
336
972
  }>;
337
973
  }
974
+ /**
975
+ * Record of a single HTTP request captured by the network monitor.
976
+ */
338
977
  interface NetworkRequest {
978
+ /** Request URL. */
339
979
  url: string;
980
+ /** HTTP method (GET, POST, etc.). */
340
981
  method: string;
982
+ /** HTTP response status code (0 if the request failed before receiving a response). */
341
983
  status: number;
984
+ /** Total request duration in milliseconds. */
342
985
  duration: number;
986
+ /** Unix timestamp in milliseconds when the request started. */
343
987
  startTime: number;
988
+ /** Error message if the request failed, or null on success. */
344
989
  error: string | null;
990
+ /** Response body size in bytes, or null if unavailable. */
345
991
  responseSize: number | null;
346
992
  }
993
+ /**
994
+ * Output of the crash classifier.
995
+ *
996
+ * Contains the assigned category, subcategory, confidence score,
997
+ * and the contributing factors that led to the classification.
998
+ */
347
999
  interface ClassificationResult {
1000
+ /** Assigned crash category. */
348
1001
  category: CrashCategory;
1002
+ /** Specific subcategory within the category. */
349
1003
  subcategory: string;
1004
+ /** Classifier confidence score (0.0 to 1.0). */
350
1005
  confidence: number;
1006
+ /** Factors that contributed to this classification. */
351
1007
  contributingFactors: ContributingFactor[];
352
1008
  }
1009
+ /**
1010
+ * Snapshot of SDK state periodically written to sessionStorage.
1011
+ *
1012
+ * Used by the OOM recovery system to preserve context across
1013
+ * browser tab crashes. When the page reloads, the last checkpoint
1014
+ * is analyzed alongside OOM signals to determine if an OOM kill occurred.
1015
+ */
1016
+ interface CheckpointData {
1017
+ /** Schema version for forward compatibility. */
1018
+ version: number;
1019
+ /** Unix timestamp in milliseconds when this checkpoint was written. */
1020
+ timestamp: number;
1021
+ /** Session identifier at the time of the checkpoint. */
1022
+ sessionId: string;
1023
+ /** Application identifier from configuration. */
1024
+ appId: string;
1025
+ /** Page URL at the time of the checkpoint. */
1026
+ url: string;
1027
+ /** Breadcrumb trail at the time of the checkpoint. */
1028
+ breadcrumbs: Breadcrumb[];
1029
+ /** Partial system state snapshot. */
1030
+ systemState: Partial<SystemState>;
1031
+ /** Device information. */
1032
+ device: DeviceInfo;
1033
+ /** Pre-crash warnings that were active before the checkpoint. */
1034
+ preCrashWarnings: Array<{
1035
+ /** Warning severity level. */
1036
+ level: PreCrashLevel;
1037
+ /** Reason for the warning. */
1038
+ reason: string;
1039
+ /** When the warning was issued. */
1040
+ timestamp: number;
1041
+ }>;
1042
+ /** Memory trend direction at checkpoint time, or null if memory monitoring is disabled. */
1043
+ memoryTrend: MemoryTrend | null;
1044
+ /** Number of checkpoints written in this session. */
1045
+ checkpointCount: number;
1046
+ }
1047
+ /**
1048
+ * Report generated when CrashSense detects a likely OOM kill from a previous session.
1049
+ *
1050
+ * Delivered to the `onOOMRecovery` callback with full context from the last
1051
+ * checkpoint and the OOM signals that triggered the detection.
1052
+ */
1053
+ interface OOMRecoveryReport {
1054
+ /** Unique identifier for this recovery report (UUID v4). */
1055
+ id: string;
1056
+ /** Report type discriminator. Always `'oom_recovery'`. */
1057
+ type: 'oom_recovery';
1058
+ /** Unix timestamp in milliseconds when the recovery was detected. */
1059
+ timestamp: number;
1060
+ /** Estimated probability (0.0 to 1.0) that the previous session ended due to OOM. */
1061
+ probability: number;
1062
+ /** Session identifier for the current (recovered) session. */
1063
+ sessionId: string;
1064
+ /** Session identifier from the crashed session. */
1065
+ previousSessionId: string;
1066
+ /** Milliseconds between the last checkpoint and the current page load. */
1067
+ timeSinceLastCheckpoint: number;
1068
+ /** Whether `document.wasDiscarded` was true, indicating browser-initiated discard. Undefined if API unavailable. */
1069
+ wasDiscarded: boolean | undefined;
1070
+ /** Navigation type from `performance.getEntriesByType('navigation')`. */
1071
+ navigationType: string;
1072
+ /** Last checkpoint data from the previous session. */
1073
+ lastCheckpoint: CheckpointData;
1074
+ /** Device information from the current session. */
1075
+ device: DeviceInfo;
1076
+ /** Individual OOM signals that contributed to the probability score. */
1077
+ signals: OOMSignal[];
1078
+ }
1079
+ /**
1080
+ * A single signal used in OOM probability calculation.
1081
+ *
1082
+ * The OOM recovery system evaluates multiple signals (document.wasDiscarded,
1083
+ * navigation type, memory trends, etc.) and combines their weighted scores
1084
+ * to produce the overall OOM probability.
1085
+ */
1086
+ interface OOMSignal {
1087
+ /** Machine-readable signal identifier (e.g., `'was_discarded'`, `'memory_trend'`). */
1088
+ signal: string;
1089
+ /** Weight of this signal in the probability calculation (0.0 to 1.0). */
1090
+ weight: number;
1091
+ /** Human-readable evidence explaining what was observed. */
1092
+ evidence: string;
1093
+ }
353
1094
 
354
- export type { AIConfig, AIPayload, AIResponse, Breadcrumb, BreadcrumbType, ClassificationResult, ContributingFactor, CpuState, CrashAnalysis, CrashCategory, CrashEvent, CrashEventMeta, CrashReport, CrashSenseConfig, CrashSenseCore, CrashSensePlugin, CrashSeverity, DeviceInfo, EventBus, EventBusEventMap, EventLoopState, FrameworkContext, IframeState, MemoryState, MemoryTrend, NetworkRequest, NetworkState, PreCrashLevel, RawCrashEvent, ResolvedConfig, StackFrame, SystemState };
1095
+ export type { AIConfig, AIPayload, AIResponse, Breadcrumb, BreadcrumbType, CheckpointData, ClassificationResult, ContributingFactor, CpuState, CrashAnalysis, CrashCategory, CrashEvent, CrashEventMeta, CrashReport, CrashSenseConfig, CrashSenseCore, CrashSensePlugin, CrashSeverity, DeviceInfo, EventBus, EventBusEventMap, EventLoopState, FrameworkContext, IframeState, MemoryState, MemoryTrend, NetworkRequest, NetworkState, OOMRecoveryReport, OOMSignal, PreCrashLevel, RawCrashEvent, ResolvedConfig, StackFrame, SystemState };