@sourav732/error-tracker-js 0.0.0-stage → 0.2.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 (38) hide show
  1. package/README.md +228 -2
  2. package/dist/index.cjs +2 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.mjs +2 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/dist/types/collectors/breadcrumbCollector.d.ts +45 -0
  7. package/dist/types/collectors/collector.d.ts +22 -0
  8. package/dist/types/collectors/cspCollector.d.ts +63 -0
  9. package/dist/types/collectors/errorCollector.d.ts +26 -0
  10. package/dist/types/collectors/httpErrorCollector.d.ts +34 -0
  11. package/dist/types/collectors/jsonResponseCollector.d.ts +24 -0
  12. package/dist/types/collectors/memoryCollector.d.ts +38 -0
  13. package/dist/types/collectors/networkInterceptor.d.ts +54 -0
  14. package/dist/types/collectors/performanceCollector.d.ts +50 -0
  15. package/dist/types/collectors/resourceCollector.d.ts +45 -0
  16. package/dist/types/collectors/responsivenessCollector.d.ts +45 -0
  17. package/dist/types/collectors/screenshotCollector.d.ts +52 -0
  18. package/dist/types/collectors/workerCollector.d.ts +22 -0
  19. package/dist/types/constants.d.ts +108 -0
  20. package/dist/types/core/circularBuffer.d.ts +15 -0
  21. package/dist/types/core/client.d.ts +71 -0
  22. package/dist/types/core/config.d.ts +28 -0
  23. package/dist/types/core/device.d.ts +23 -0
  24. package/dist/types/core/env.d.ts +21 -0
  25. package/dist/types/core/eventFilters.d.ts +32 -0
  26. package/dist/types/core/eventQueue.d.ts +60 -0
  27. package/dist/types/core/logger.d.ts +19 -0
  28. package/dist/types/core/payloadBuilder.d.ts +32 -0
  29. package/dist/types/core/reportedErrors.d.ts +18 -0
  30. package/dist/types/core/retryManager.d.ts +18 -0
  31. package/dist/types/core/safe.d.ts +10 -0
  32. package/dist/types/core/serialize.d.ts +13 -0
  33. package/dist/types/core/stackParser.d.ts +5 -0
  34. package/dist/types/index.d.ts +55 -0
  35. package/dist/types/transport/httpTransport.d.ts +24 -0
  36. package/dist/types/transport/offlineStore.d.ts +33 -0
  37. package/dist/types/types.d.ts +161 -0
  38. package/package.json +62 -4
@@ -0,0 +1,71 @@
1
+ import { CapturedError, CollectorSink, PerformanceIssueKind } from '../collectors/collector';
2
+ import { MemoryReading } from '../collectors/memoryCollector';
3
+ import { ScreenshotCollector } from '../collectors/screenshotCollector';
4
+ import { Transport } from '../transport/httpTransport';
5
+ import { OfflineStore } from '../transport/offlineStore';
6
+ import { BreadcrumbInput, EventLevel, TrackedUser } from '../types';
7
+ import { ResolvedConfig } from './config';
8
+ import { Deduplicator, RateLimiter } from './eventFilters';
9
+ import { Logger } from './logger';
10
+ /** Dependency overrides, used by tests. */
11
+ export interface ClientDependencies {
12
+ transport?: Transport;
13
+ store?: OfflineStore;
14
+ random?: () => number;
15
+ rateLimiter?: RateLimiter;
16
+ deduplicator?: Deduplicator;
17
+ readMemory?: () => MemoryReading | null;
18
+ screenshot?: ScreenshotCollector;
19
+ queueRetryDelaysMs?: readonly number[];
20
+ queueFlushDelayMs?: number;
21
+ }
22
+ /**
23
+ * Owns all SDK state for one `init()` call: configuration, collectors,
24
+ * scope (user, breadcrumbs) and the delivery queue.
25
+ */
26
+ export declare class Client implements CollectorSink {
27
+ readonly logger: Logger;
28
+ private readonly config;
29
+ private readonly breadcrumbs;
30
+ private readonly device;
31
+ private readonly queue;
32
+ private readonly random;
33
+ private readonly rateLimiter;
34
+ private readonly deduplicator;
35
+ private readonly network;
36
+ private readonly performance;
37
+ private readonly memory;
38
+ private readonly responsiveness;
39
+ private readonly screenshot;
40
+ private readonly collectors;
41
+ private user;
42
+ private rateLimitWarned;
43
+ /** Events dropped by the rate limiter since the last summary event. */
44
+ private droppedCount;
45
+ private droppedTimer;
46
+ private started;
47
+ /** Events waiting on a screenshot before they can be queued. */
48
+ private pendingCaptures;
49
+ private readonly handleOnline;
50
+ private readonly handleVisibility;
51
+ private readonly handlePageHide;
52
+ constructor(config: ResolvedConfig, deps?: ClientDependencies);
53
+ /** Installs collectors and lifecycle listeners, then sends events left over from earlier sessions. */
54
+ start(): void;
55
+ /** Removes every hook from the page. Unsent events are persisted. */
56
+ close(): Promise<void>;
57
+ /** Waits for events still awaiting a screenshot, then sends everything queued. */
58
+ flush(): Promise<void>;
59
+ captureError(thrown: unknown, context?: object): void;
60
+ captureMessage(message: string, level: EventLevel): void;
61
+ setUser(user: TrackedUser | null): void;
62
+ onError(captured: CapturedError): void;
63
+ onBreadcrumb(input: BreadcrumbInput): void;
64
+ onPerformanceIssue(kind: PerformanceIssueKind, message: string): void;
65
+ onNavigation(): void;
66
+ private capture;
67
+ /** Counts a rate-limited event and schedules one summary event, so storms stay visible. */
68
+ private recordDropped;
69
+ private finish;
70
+ private scope;
71
+ }
@@ -0,0 +1,28 @@
1
+ import { ErrorTrackerConfig, TrackerEvent } from '../types';
2
+ /** Config with defaults applied and values validated. */
3
+ export interface ResolvedConfig {
4
+ apiKey: string;
5
+ endpoint: string;
6
+ environment: string;
7
+ appVersion: string | null;
8
+ sampleRate: number;
9
+ maxBreadcrumbs: number;
10
+ maskSelectors: string[];
11
+ debug: boolean;
12
+ captureHttpErrors: boolean;
13
+ captureNetworkErrors: boolean;
14
+ captureConsoleErrors: boolean;
15
+ captureScreenshots: boolean;
16
+ html2canvasUrl: string;
17
+ html2canvasIntegrity: string;
18
+ beforeSend: ((event: TrackerEvent) => TrackerEvent | null) | null;
19
+ }
20
+ export type ConfigResult = {
21
+ ok: true;
22
+ config: ResolvedConfig;
23
+ } | {
24
+ ok: false;
25
+ reason: string;
26
+ };
27
+ /** Validates user config and fills in defaults. Never throws. */
28
+ export declare function resolveConfig(input: ErrorTrackerConfig | null | undefined): ConfigResult;
@@ -0,0 +1,23 @@
1
+ import { DevicePayload } from '../types';
2
+ /** Browser/OS identity parsed from a user-agent string. */
3
+ export interface ParsedUserAgent {
4
+ browser: string | null;
5
+ browserVersion: string | null;
6
+ os: string | null;
7
+ osVersion: string | null;
8
+ model: string | null;
9
+ }
10
+ /** Pure user-agent parser; exported for testing. */
11
+ export declare function parseUserAgent(ua: string): ParsedUserAgent;
12
+ /**
13
+ * Collects static device information once, then refines the OS name
14
+ * asynchronously using UA Client Hints where the browser supports them.
15
+ */
16
+ export declare class DeviceInfo {
17
+ private parsed;
18
+ constructor();
19
+ /** Best-effort async refinement (distinguishes Windows 11 from 10, adds Android model). */
20
+ refine(): Promise<void>;
21
+ /** Snapshot for a payload; URL and screen size are read fresh each time. */
22
+ snapshot(): DevicePayload;
23
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Guarded access to browser globals so the SDK can be imported in Node.js,
3
+ * SSR and web workers without throwing.
4
+ */
5
+ export declare function getWindow(): Window | null;
6
+ export declare function getDocument(): Document | null;
7
+ export declare function getNavigator(): Navigator | null;
8
+ export declare function getPerformance(): Performance | null;
9
+ /** localStorage throws on access in some privacy modes, so even reading the property is guarded. */
10
+ export declare function getLocalStorage(): Storage | null;
11
+ export declare function isOnline(): boolean;
12
+ export declare function isPageVisible(): boolean;
13
+ export declare function nowIso(): string;
14
+ /** High-resolution monotonic time where available. */
15
+ export declare function nowMs(): number;
16
+ /** Removes the query string and fragment, which commonly carry tokens or PII. */
17
+ export declare function stripQuery(url: string): string;
18
+ /** Resolves relative URLs against the page so comparisons are reliable. */
19
+ export declare function absoluteUrl(url: string): string;
20
+ /** Rounds to whole milliseconds; negative or non-finite values become null. */
21
+ export declare function toMs(value: number | null | undefined): number | null;
@@ -0,0 +1,32 @@
1
+ import { ErrorPayload, StackFrame } from '../types';
2
+ type Clock = () => number;
3
+ /**
4
+ * Sliding-window rate limiter that protects the host app and the backend
5
+ * from error storms (e.g. an exception thrown inside an animation frame).
6
+ */
7
+ export declare class RateLimiter {
8
+ private readonly maxEvents;
9
+ private readonly windowMs;
10
+ private readonly clock;
11
+ private timestamps;
12
+ constructor(maxEvents?: number, windowMs?: number, clock?: Clock);
13
+ /** Returns true and records the event if it fits within the limit. */
14
+ tryAcquire(): boolean;
15
+ }
16
+ /**
17
+ * Drops events whose fingerprint was already seen within the dedup window,
18
+ * so a loop throwing the same error does not send hundreds of copies.
19
+ */
20
+ export declare class Deduplicator {
21
+ private readonly windowMs;
22
+ private readonly maxEntries;
23
+ private readonly clock;
24
+ private seen;
25
+ private order;
26
+ constructor(windowMs?: number, maxEntries?: number, clock?: Clock);
27
+ /** Returns true if this fingerprint is new (or its previous sighting has expired). */
28
+ isNew(fingerprint: string): boolean;
29
+ }
30
+ /** Fingerprint used for dedup: event type + error identity + top stack frame. */
31
+ export declare function fingerprint(eventType: string, error: ErrorPayload | null, stacktrace: StackFrame[]): string;
32
+ export {};
@@ -0,0 +1,60 @@
1
+ import { TrackerEvent } from '../types';
2
+ import { OfflineStore } from '../transport/offlineStore';
3
+ import { Transport } from '../transport/httpTransport';
4
+ import { Logger } from './logger';
5
+ import { Scheduler } from './retryManager';
6
+ export interface EventQueueOptions {
7
+ transport: Transport;
8
+ store: OfflineStore;
9
+ logger: Logger;
10
+ batchSize?: number;
11
+ /** Max serialized bytes per request; defaults to MAX_BATCH_BYTES. */
12
+ maxBatchBytes?: number;
13
+ flushDelayMs?: number;
14
+ retryDelaysMs?: readonly number[];
15
+ /** Injectable for tests; defaults to setTimeout. */
16
+ schedule?: Scheduler;
17
+ /** Injectable for tests; defaults to navigator.onLine. */
18
+ isOnline?: () => boolean;
19
+ }
20
+ /**
21
+ * In-memory event queue. Sends batches with retry, and falls back to the
22
+ * offline store when the device is offline or delivery keeps failing.
23
+ */
24
+ export declare class EventQueue {
25
+ private queue;
26
+ private flushTimer;
27
+ private inFlight;
28
+ private closed;
29
+ private readonly transport;
30
+ private readonly store;
31
+ private readonly logger;
32
+ private readonly batchSize;
33
+ private readonly maxBatchBytes;
34
+ private readonly flushDelayMs;
35
+ private readonly retryDelaysMs;
36
+ private readonly schedule;
37
+ private readonly online;
38
+ constructor(options: EventQueueOptions);
39
+ /** Number of events waiting in memory (not counting the batch in flight). */
40
+ get size(): number;
41
+ /** Adds an event and schedules delivery. */
42
+ enqueue(event: TrackerEvent): void;
43
+ /** Sends everything currently queued. Resolves when the queue is drained or parked offline. */
44
+ flush(): Promise<void>;
45
+ /** Moves events from the offline store back into the queue and sends them. */
46
+ restoreFromStore(): Promise<void>;
47
+ /** Writes queued (not in-flight) events to the offline store, e.g. when the page is hidden. */
48
+ persistPending(): void;
49
+ /** Stops accepting events. Pending events are persisted for the next session. */
50
+ close(): void;
51
+ private scheduleFlush;
52
+ private cancelTimer;
53
+ /**
54
+ * How many queued events fit in the next request: at most batchSize events
55
+ * and at most maxBatchBytes serialized (always at least one event).
56
+ */
57
+ private nextBatchLength;
58
+ /** Sends batch after batch until the queue is empty or delivery has to stop. */
59
+ private drain;
60
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Debug-only logger. Produces no output unless `debug: true` was configured.
3
+ *
4
+ * Every line starts with LOG_PREFIX; the breadcrumb collector's console hook
5
+ * uses it to keep SDK diagnostics out of the breadcrumb trail.
6
+ */
7
+ export declare const LOG_PREFIX = "[ErrorTracker]";
8
+ export declare class Logger {
9
+ private enabled;
10
+ constructor(enabled: boolean);
11
+ setEnabled(enabled: boolean): void;
12
+ isEnabled(): boolean;
13
+ info(message: string, ...details: unknown[]): void;
14
+ warn(message: string, ...details: unknown[]): void;
15
+ error(message: string, ...details: unknown[]): void;
16
+ private write;
17
+ }
18
+ /** Shared logger used before init() and by modules without a client reference. */
19
+ export declare const sharedLogger: Logger;
@@ -0,0 +1,32 @@
1
+ import { Breadcrumb, DevicePayload, ErrorPayload, EventLevel, EventType, JsonObject, MemoryPayload, PerformancePayload, StackFrame, TrackedUser, TrackerEvent } from '../types';
2
+ /** What happened: the event-specific part of a payload. */
3
+ export interface EventInput {
4
+ eventType: EventType;
5
+ level: EventLevel;
6
+ error: ErrorPayload | null;
7
+ stacktrace: StackFrame[];
8
+ context: JsonObject | null;
9
+ }
10
+ /** Ambient state captured at the moment of the event. */
11
+ export interface EventScope {
12
+ apiKey: string;
13
+ environment: string;
14
+ appVersion: string | null;
15
+ user: TrackedUser | null;
16
+ breadcrumbs: Breadcrumb[];
17
+ performance: PerformancePayload;
18
+ memory: MemoryPayload;
19
+ device: DevicePayload;
20
+ screenshot: string | null;
21
+ }
22
+ /** Performance block with every field present and nothing measured. */
23
+ export declare function emptyPerformance(): PerformancePayload;
24
+ /** Memory block with every field present and nothing measured. */
25
+ export declare function emptyMemory(): MemoryPayload;
26
+ /**
27
+ * Assembles a schema-complete event. All arrays and nested objects are copied
28
+ * so later mutation of SDK state cannot alter an event already in the queue.
29
+ */
30
+ export declare function buildEvent(input: EventInput, scope: EventScope, timestamp: string): TrackerEvent;
31
+ /** Returns a shallow copy of `event` with one top-level field replaced. */
32
+ export declare function withField<K extends keyof TrackerEvent>(event: TrackerEvent, key: K, value: TrackerEvent[K]): TrackerEvent;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Remembers error objects the SDK has already turned into events, so a single
3
+ * failure is never reported twice. Example: a failed `fetch` is reported as a
4
+ * NetworkError, and the same TypeError may later reach `unhandledrejection`
5
+ * or `console.error`; those later sightings are skipped.
6
+ *
7
+ * Uses a WeakSet, so remembered errors are still garbage-collected normally.
8
+ */
9
+ /** Marks `value` as reported. Primitives cannot be tracked and are ignored. */
10
+ export declare function markReported(value: unknown): void;
11
+ /** True if `value` was already turned into an event. */
12
+ export declare function wasReported(value: unknown): boolean;
13
+ /** Remembers a signature (e.g. message + file + line) as reported, for a short time. */
14
+ export declare function markSignatureReported(signature: string, now?: number): void;
15
+ /** True if the signature was reported within the last few seconds. */
16
+ export declare function wasSignatureReported(signature: string, now?: number): boolean;
17
+ /** Signature for an error that has only text and a location (no error object). */
18
+ export declare function locationSignature(message: string, filename: string | null, lineno: number | null): string;
@@ -0,0 +1,18 @@
1
+ /** Outcome of a single delivery attempt. */
2
+ export interface AttemptResult {
3
+ ok: boolean;
4
+ /** Whether trying again could succeed (network error, 5xx, 408, 429). */
5
+ retryable: boolean;
6
+ status: number | null;
7
+ }
8
+ /** Final outcome after all attempts. */
9
+ export interface RetryOutcome extends AttemptResult {
10
+ attempts: number;
11
+ }
12
+ export type Scheduler = (fn: () => void, delayMs: number) => void;
13
+ /**
14
+ * Runs `attempt` until it succeeds, fails non-retryably, or the backoff
15
+ * schedule (1s, 2s, 4s by default) is exhausted. Never rejects: a rejected
16
+ * attempt is treated as a retryable network failure.
17
+ */
18
+ export declare function retryWithBackoff(attempt: () => Promise<AttemptResult>, delaysMs?: readonly number[], schedule?: Scheduler): Promise<RetryOutcome>;
@@ -0,0 +1,10 @@
1
+ import { Logger } from './logger';
2
+ /**
3
+ * Runs `fn` and converts any exception into a debug warning plus `fallback`.
4
+ * This is the SDK's main guarantee that it never throws into the host app.
5
+ */
6
+ export declare function safely<T>(logger: Logger, label: string, fn: () => T, fallback: T): T;
7
+ /** `safely` for functions with no meaningful return value. */
8
+ export declare function safelyRun(logger: Logger, label: string, fn: () => void): void;
9
+ /** Wraps a callback so exceptions inside it are swallowed (with a debug log). */
10
+ export declare function guard<A extends unknown[]>(logger: Logger, label: string, fn: (...args: A) => void): (...args: A) => void;
@@ -0,0 +1,13 @@
1
+ import { JsonObject, JsonValue } from '../types';
2
+ /** Shortens a string to `max` characters, marking that it was cut. */
3
+ export declare function truncate(value: string, max: number): string;
4
+ /**
5
+ * Converts an arbitrary value into JSON-safe data: circular references,
6
+ * functions, DOM nodes, errors and deep/wide structures are all handled so
7
+ * `JSON.stringify` on the result can never throw.
8
+ */
9
+ export declare function normalize(value: unknown, depth?: number): JsonValue;
10
+ /** `normalize` for values that must end up as a JSON object. */
11
+ export declare function normalizeObject(value: unknown): JsonObject;
12
+ /** Converts any thrown value into a readable message string. */
13
+ export declare function describeValue(value: unknown): string;
@@ -0,0 +1,5 @@
1
+ import { StackFrame } from '../types';
2
+ /** Parses a raw stack string. Unrecognised lines are skipped. */
3
+ export declare function parseStack(stack: string | undefined | null): StackFrame[];
4
+ /** Extracts frames from any thrown value that carries a `stack` string. */
5
+ export declare function parseStackFromError(error: unknown): StackFrame[];
@@ -0,0 +1,55 @@
1
+ import { BreadcrumbInput, ErrorTrackerConfig, EventLevel, TrackedUser } from './types';
2
+ /**
3
+ * Starts the SDK: validates config, installs collectors and begins delivering
4
+ * events. Calling it again while running is ignored; call `close()` first to
5
+ * re-initialize. An invalid config leaves the SDK disabled (and logs a warning
6
+ * when `debug` is true) rather than throwing.
7
+ */
8
+ declare function init(config: ErrorTrackerConfig): void;
9
+ /**
10
+ * Reports a caught error. `handled` is `true` on the resulting event.
11
+ * @param error The thrown value; non-Error values are converted to a message.
12
+ * @param context Extra JSON-serializable data attached as `context`.
13
+ */
14
+ declare function captureError(error: unknown, context?: Record<string, unknown>): void;
15
+ /**
16
+ * Reports a free-form message.
17
+ * @param message Text of the message.
18
+ * @param level Severity; defaults to `'info'`.
19
+ */
20
+ declare function captureMessage(message: string, level?: EventLevel): void;
21
+ /**
22
+ * Attaches a user to all subsequent events. Pass `null` to clear it (e.g. on logout).
23
+ */
24
+ declare function setUser(user: TrackedUser | null): void;
25
+ /**
26
+ * Records a custom breadcrumb in the trail attached to future events.
27
+ */
28
+ declare function addBreadcrumb(breadcrumb: BreadcrumbInput): void;
29
+ /**
30
+ * Sends queued events immediately. Resolves when the queue is drained or
31
+ * parked offline; never rejects. Resolves immediately before `init()`.
32
+ */
33
+ declare function flush(): Promise<void>;
34
+ /**
35
+ * Flushes, then removes every hook the SDK installed (global handlers, fetch/XHR,
36
+ * history, console). Unsent events are persisted for the next session.
37
+ */
38
+ declare function close(): Promise<void>;
39
+ /** Whether `init()` has completed successfully. */
40
+ declare function isInitialized(): boolean;
41
+ /** The SDK's public surface. */
42
+ export declare const ErrorTracker: {
43
+ init: typeof init;
44
+ captureError: typeof captureError;
45
+ captureMessage: typeof captureMessage;
46
+ setUser: typeof setUser;
47
+ addBreadcrumb: typeof addBreadcrumb;
48
+ flush: typeof flush;
49
+ close: typeof close;
50
+ isInitialized: typeof isInitialized;
51
+ version: string;
52
+ };
53
+ export { init, captureError, captureMessage, setUser, addBreadcrumb, flush, close, isInitialized };
54
+ export default ErrorTracker;
55
+ export type { ApiCall, Breadcrumb, BreadcrumbInput, BreadcrumbType, DevicePayload, ErrorPayload, ErrorTrackerConfig, EventBatch, EventLevel, EventType, JsonObject, JsonValue, MemoryPayload, PerformancePayload, StackFrame, TrackedUser, TrackerEvent, UserPayload, } from './types';
@@ -0,0 +1,24 @@
1
+ import { Logger } from '../core/logger';
2
+ import { AttemptResult } from '../core/retryManager';
3
+ import { TrackerEvent } from '../types';
4
+ /** Anything that can deliver a batch of events. */
5
+ export interface Transport {
6
+ send(events: TrackerEvent[]): Promise<AttemptResult>;
7
+ }
8
+ type FetchFn = typeof fetch;
9
+ /** Classifies an HTTP status into the retry decision used by the queue. */
10
+ export declare function classifyStatus(status: number): AttemptResult;
11
+ /**
12
+ * POSTs batches as JSON using `fetch`. The API key is applied here, at send
13
+ * time, so it never needs to be written to persistent storage.
14
+ */
15
+ export declare class HttpTransport implements Transport {
16
+ private readonly endpoint;
17
+ private readonly apiKey;
18
+ private readonly logger;
19
+ private readonly fetchFn;
20
+ constructor(endpoint: string, apiKey: string, logger: Logger, fetchFn?: FetchFn);
21
+ send(events: TrackerEvent[]): Promise<AttemptResult>;
22
+ private serialize;
23
+ }
24
+ export {};
@@ -0,0 +1,33 @@
1
+ import { Logger } from '../core/logger';
2
+ import { TrackerEvent } from '../types';
3
+ /** Persistence for events that could not be delivered. */
4
+ export interface OfflineStore {
5
+ append(events: TrackerEvent[]): void;
6
+ /** Returns every stored event and clears storage. */
7
+ takeAll(): TrackerEvent[];
8
+ }
9
+ /**
10
+ * Stores undelivered events in localStorage under `_et_queue`.
11
+ *
12
+ * The API key is blanked before writing (it is re-applied by the transport
13
+ * at send time), and storage failures — quota exceeded, disabled storage,
14
+ * corrupt data — are handled without ever throwing.
15
+ */
16
+ export declare class LocalStorageStore implements OfflineStore {
17
+ private readonly logger;
18
+ private readonly maxEvents;
19
+ private readonly key;
20
+ constructor(logger: Logger, maxEvents?: number, key?: string);
21
+ append(events: TrackerEvent[]): void;
22
+ takeAll(): TrackerEvent[];
23
+ private read;
24
+ private write;
25
+ }
26
+ /** In-memory store for environments without localStorage, and for tests. */
27
+ export declare class MemoryStore implements OfflineStore {
28
+ private readonly maxEvents;
29
+ private events;
30
+ constructor(maxEvents?: number);
31
+ append(events: TrackerEvent[]): void;
32
+ takeAll(): TrackerEvent[];
33
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Public and wire-format types.
3
+ *
4
+ * The `TrackerEvent` interface mirrors the shared payload schema used by the
5
+ * JS, iOS and Android SDKs. Every field is always present on the wire; values
6
+ * that are unavailable on the web platform are `null`, never omitted.
7
+ */
8
+ /** JSON-safe value produced by the SDK's serializer. */
9
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
10
+ [key: string]: JsonValue;
11
+ };
12
+ export type JsonObject = {
13
+ [key: string]: JsonValue;
14
+ };
15
+ export type EventType = 'error' | 'message' | 'performance' | 'crash';
16
+ export type EventLevel = 'info' | 'warning' | 'error';
17
+ export type BreadcrumbType = 'navigation' | 'click' | 'api' | 'log' | 'lifecycle' | (string & {});
18
+ /** Options accepted by `ErrorTracker.init()`. */
19
+ export interface ErrorTrackerConfig {
20
+ /** Project API key. Kept in memory only and sent in the `X-API-Key` header. */
21
+ apiKey: string;
22
+ /** Ingestion URL, e.g. `https://api.yourcompany.com/v1/events`. */
23
+ endpoint: string;
24
+ /** Deployment environment such as `production`, `staging` or `development`. */
25
+ environment?: string;
26
+ /** Version of the host application. */
27
+ appVersion?: string;
28
+ /** Fraction of events to keep, 0.0–1.0. Defaults to 1.0. */
29
+ sampleRate?: number;
30
+ /** Size of the breadcrumb ring buffer. Defaults to 30. */
31
+ maxBreadcrumbs?: number;
32
+ /** CSS selectors whose elements are blacked out in screenshots and click breadcrumbs. */
33
+ maskSelectors?: string[];
34
+ /** Log SDK diagnostics to the console. Defaults to false. */
35
+ debug?: boolean;
36
+ /** Report fetch/XHR responses with a 4xx/5xx status as error events. Defaults to true. */
37
+ captureHttpErrors?: boolean;
38
+ /**
39
+ * Report fetch/XHR requests that got no response (offline, timeout, CORS,
40
+ * DNS/SSL failure) as NetworkError events. User-cancelled requests are
41
+ * never reported. Defaults to true.
42
+ */
43
+ captureNetworkErrors?: boolean;
44
+ /** Report every `console.error(...)` call as an error event. Defaults to false (libraries log a lot of noise). */
45
+ captureConsoleErrors?: boolean;
46
+ /** Attach a screenshot to error events. Defaults to true. */
47
+ captureScreenshots?: boolean;
48
+ /** Override where html2canvas is loaded from (self-hosting is recommended). */
49
+ html2canvasUrl?: string;
50
+ /** SRI hash for `html2canvasUrl`. Set to an empty string to disable the integrity check. */
51
+ html2canvasIntegrity?: string;
52
+ /**
53
+ * Last chance to scrub or drop an event before it is queued.
54
+ * Return the (optionally modified) event, or `null` to drop it.
55
+ */
56
+ beforeSend?: (event: TrackerEvent) => TrackerEvent | null;
57
+ }
58
+ /** User attached to every subsequent event. */
59
+ export interface TrackedUser {
60
+ id: string;
61
+ email?: string;
62
+ name?: string;
63
+ }
64
+ /** Breadcrumb supplied through `ErrorTracker.addBreadcrumb()`. */
65
+ export interface BreadcrumbInput {
66
+ type: BreadcrumbType;
67
+ message: string;
68
+ data?: object;
69
+ }
70
+ export interface SdkInfo {
71
+ name: string;
72
+ version: string;
73
+ }
74
+ export interface UserPayload {
75
+ id: string | null;
76
+ email: string | null;
77
+ name: string | null;
78
+ }
79
+ export interface ErrorPayload {
80
+ message: string;
81
+ type: string;
82
+ handled: boolean;
83
+ }
84
+ export interface StackFrame {
85
+ filename: string | null;
86
+ lineno: number | null;
87
+ colno: number | null;
88
+ function: string;
89
+ }
90
+ export interface Breadcrumb {
91
+ timestamp: string;
92
+ type: BreadcrumbType;
93
+ message: string;
94
+ data: JsonObject;
95
+ }
96
+ export interface ApiCall {
97
+ url: string;
98
+ method: string;
99
+ /** HTTP status; 0 when the request failed before a response arrived. */
100
+ status: number;
101
+ duration_ms: number;
102
+ }
103
+ export interface PerformancePayload {
104
+ page_load_ms: number | null;
105
+ ttfb_ms: number | null;
106
+ fcp_ms: number | null;
107
+ lcp_ms: number | null;
108
+ /** Cumulative Layout Shift score (unitless). JS-only extension of the shared schema. */
109
+ cls: number | null;
110
+ startup_ms: number | null;
111
+ frame_rate_fps: number | null;
112
+ slow_screen: boolean;
113
+ api_calls: ApiCall[];
114
+ slow_api_calls: ApiCall[];
115
+ }
116
+ export interface MemoryPayload {
117
+ used_mb: number | null;
118
+ total_mb: number | null;
119
+ leak_suspected: boolean | null;
120
+ oom_kill: boolean | null;
121
+ }
122
+ export interface DevicePayload {
123
+ platform: string;
124
+ os: string | null;
125
+ os_version: string | null;
126
+ manufacturer: string | null;
127
+ model: string | null;
128
+ browser: string | null;
129
+ browser_version: string | null;
130
+ screen_width: number | null;
131
+ screen_height: number | null;
132
+ url: string | null;
133
+ /** JS-only extension of the shared schema. */
134
+ referrer: string | null;
135
+ locale: string | null;
136
+ }
137
+ /** A single event as sent to the ingestion endpoint. */
138
+ export interface TrackerEvent {
139
+ sdk: SdkInfo;
140
+ api_key: string;
141
+ event_type: EventType;
142
+ /** Severity. JS-only extension of the shared schema. */
143
+ level: EventLevel;
144
+ timestamp: string;
145
+ environment: string;
146
+ app_version: string | null;
147
+ user: UserPayload;
148
+ error: ErrorPayload | null;
149
+ stacktrace: StackFrame[];
150
+ breadcrumbs: Breadcrumb[];
151
+ screenshot: string | null;
152
+ performance: PerformancePayload;
153
+ memory: MemoryPayload;
154
+ device: DevicePayload;
155
+ /** Extra data passed to `captureError(error, context)`. JS-only extension. */
156
+ context: JsonObject | null;
157
+ }
158
+ /** Body of a batched POST to the endpoint. */
159
+ export interface EventBatch {
160
+ events: TrackerEvent[];
161
+ }