UNPKG

@coralogix/browser

Version:

Official Coralogix SDK for browsers

465 lines (464 loc) 16.9 kB
import { Attributes } from '@opentelemetry/api'; import { CoralogixDomainsApiUrlMap } from './constants'; import { CoralogixLogSeverity } from './types-external'; import { ErrorSource } from './instrumentations/CoralogixErrorInstrumentation'; import { FetchSource } from './instrumentations/network/CoralogixFetchInstrumentation'; import { XHRSource } from './instrumentations/network/CoralogixXhrInstrumentation'; import { LogSource } from './instrumentations/CoralogixCustomLogInstrumentation'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; import { CoralogixUserInteractionInstrumentationConfig } from './instrumentations/user-interaction/CoralogixUserInteractionInstrumentation'; import { Metric } from 'web-vitals/attribution'; import { CoralogixWebVitalsInstrumentationConfig } from './instrumentations/instrumentation.model'; import { SessionConfig, SessionRecordingConfig } from './session/session.model'; import { CoralogixInternalEvent } from './instrumentations/CoralogixInternalInstrumentation'; import { SnapshotContext } from './snapshot/snapshot.model'; import { MetricWithAttribution } from 'web-vitals'; import { MemoryUsageContext } from './instrumentations/memory-usage'; import { MFEMetadata } from './mfe/mfe.types'; import { UrlBasedLabelProvider } from './label-providers/url-based-label-provider'; import { CustomTracer, CustomTracerIgnoredInstruments } from './custom-spans'; export interface CxStackFrame extends Partial<MFEMetadata> { fileName?: string; columnNumber?: number; lineNumber?: number; functionName?: string; isShell?: boolean; } export interface GlobalTTIHandler { e: PerformanceEntryList; o?: PerformanceObserver; } export interface CoralogixWindow { __tti: GlobalTTIHandler; CoralogixRum: CoralogixOtelWebType; } export declare enum CoralogixEventType { ERROR = "error", NETWORK_REQUEST = "network-request", LOG = "log", USER_INTERACTION = "user-interaction", WEB_VITALS = "web-vitals", LONG_TASK = "longtask", RESOURCES = "resources", INTERNAL = "internal", DOM = "dom", CUSTOM_MEASUREMENT = "custom-measurement", MEMORY_USAGE = "memory-usage", SCREENSHOT = "screenshot", CUSTOM_SPAN = "custom-span" } export declare enum PerformanceTypes { Resource = "resource", LongTask = "longtask", Navigation = "navigation", SoftNavigation = "soft-navigation" } export type CustomMeasurementData = number; export type WebVitalsRating = 'good' | 'needs-improvement' | 'poor'; export type CoralogixDomain = keyof typeof CoralogixDomainsApiUrlMap; export type CoralogixRumLabels = Record<string, any>; export interface UserContextConfig { user_id: string; user_name: string; user_email?: string; user_metadata?: { [key: string]: any; }; } export interface CustomTargetElement extends HTMLElement { type: string; value: string; } export interface ScreenshotContext { id: string; description?: string; } export interface ApplicationContextConfig { application: string; version: string; } export interface TraceHeaderConfiguration { enabled: boolean; options?: { /** urls outside of origin that should also add Traceparent to header */ propagateTraceHeaderCorsUrls?: Array<string | RegExp>; /** first-party origins urls called by your browser application. * If array is passed, only urls that match the array will add Traceparent to header. * */ allowedTracingUrls?: Array<string | RegExp>; /** provides HTTP header propagation for systems that are using AWS X-Amzn-Trace-Id format. */ propagateAwsXrayTraceHeader?: boolean; /** provides HTTP header propagation for systems that are using B3 format. */ propagateB3TraceHeader?: { singleHeader?: boolean; multiHeader?: boolean; }; }; } export interface CoralogixOtelWebOptionsInstrumentations { errors?: boolean; fetch?: boolean; xhr?: boolean; custom?: boolean; long_tasks?: boolean; resources?: boolean; interactions?: boolean | CoralogixUserInteractionInstrumentationConfig; web_vitals?: boolean | CoralogixWebVitalsInstrumentationConfig; } interface SendLog { log: (severity: CoralogixLogSeverity, message: string, data?: any) => void; debug: (message: string, data?: any) => void; verbose: (message: string, data?: any) => void; info: (message: string, data?: any) => void; warn: (message: string, data?: any) => void; error: (message: string, data?: any) => void; critical: (message: string, data?: any) => void; } export type UrlBlueprinter = (url: string) => string; export interface UrlBlueprinters { pageUrlBlueprinters?: UrlBlueprinter[]; networkUrlBlueprinters?: UrlBlueprinter[]; } export interface MemoryUsageConfig { enabled: boolean; interval?: number; } export type BeforeSendResult = EditableCxRumEvent | null | undefined; export interface NetworkExtraConfig { url: string | RegExp; reqHeaders?: string[]; resHeaders?: string[]; collectReqPayload?: boolean; collectResPayload?: boolean; } export interface CoralogixBrowserSdkConfig { /** Publicly-visible `public_key` value */ public_key?: string; /** Sets a value for the `application` attribute */ application: string; /** Coralogix account domain */ coralogixDomain: CoralogixDomain; /** Sets a value for the 'app.version' attribute */ version: string; /** Configuration for user context. */ user_context?: UserContextConfig; /** Turns on/off internal debug logging */ debug?: boolean; /** Sets labels added to every Span. */ labels?: CoralogixRumLabels; /** * Applies for XHR and Fetch URLs. URLs that partially match any regex in ignoreUrls will not be traced. * In addition, URLs that are _exact matches_ of strings in ignoreUrls will also not be traced. * */ ignoreUrls?: Array<string | RegExp>; /** A pattern for error messages which should not be sent to Coralogix. By default, all errors will be sent. * */ ignoreErrors?: Array<string | RegExp>; /** Configuration for instrumentation modules. */ instrumentations?: CoralogixOtelWebOptionsInstrumentations; /** Add trace context propagation in headers across service boundaries */ traceParentInHeader?: TraceHeaderConfiguration; /** Sets a value for the `environment` attribute */ environment?: string; /** Stringify custom log data property */ stringifyCustomLogData?: boolean; /** Modify the event's page or network url based on custom-defined functions */ urlBlueprinters?: UrlBlueprinters; /** Sets recording config for session replay */ sessionRecordingConfig?: SessionRecordingConfig; /** Sets session config */ sessionConfig?: SessionConfig; /** Provide labels based on url or event */ labelProviders?: Array<LabelProvider>; /** * @deprecated Use `sessionConfig` instead. * Percentage of overall sessions being tracked, defaults to 100% * */ sessionSampleRate?: number; /** Mask input types, defaults to ['password', 'email', 'tel'] */ maskInputTypes?: InputType[]; /** Class name that will mask elements, string or RegExp. defaults to 'cx-mask' */ maskClass?: string | RegExp; /** Enable event access and modification before sending to Coralogix, supporting content modification, and event discarding. */ beforeSend?: (event: EditableCxRumEvent) => BeforeSendResult; /** Send requests through a proxy */ proxyUrl?: string; /** Collect IP address and geolocation data. Defaults to true. */ collectIPData?: boolean; /** Track soft navigations such as SPA navigations. Defaults to false */ trackSoftNavigations?: boolean; /** Measure memory usage * @prop enabled Enable memory usage measurement. Defaults to false * @prop interval usage will be measured every `interval` millisecond. Default to 5 minutes. * */ memoryUsageConfig?: MemoryUsageConfig; /** networkExtraConfig is an array of rules for capturing and enhancing network request and response data, * including headers and payloads, from Fetch and XMLHttpRequest. */ networkExtraConfig?: NetworkExtraConfig[]; /** Enable MFE support. Defaults to false */ supportMfe?: boolean; } export interface CoralogixOtelWebType extends SendLog { /** * Init CoralogixRum. */ init: (options: CoralogixBrowserSdkConfig) => void; /** * Turn CoralogixRum off. */ shutdown: () => void; /** Sets labels to be added to every log after CoralogixRum initialization. */ setLabels: (labels: CoralogixRumLabels) => void; /** * Provides access to computed, final value of global attributes, which are applied to all created logs. */ getLabels: () => CoralogixRumLabels; /** Sets user context to be added to every log after CoralogixRum initialization. */ setUserContext: (userContext: UserContextConfig) => void; /** Sets application context to be added to every log after CoralogixRum initialization. */ setApplicationContext: (applicationContext: ApplicationContextConfig) => void; /** Manually capture error. */ captureError: (error: Error, customData?: unknown, labels?: CoralogixRumLabels) => void; /** Manually send custom measurement. */ sendCustomMeasurement: (name: string, value: CustomMeasurementData) => void; /** Add extra performance timing. */ addTiming: (name: string, duration?: number) => void; /** Manually measure user-agent-specific memory. */ measureUserAgentSpecificMemory: () => void; /** * Provides access to computed, final value of user context, which applied to all created logs. */ getUserContext: () => UserContextConfig | undefined; /** * Provides the session id. */ getSessionId: () => string | undefined; /** * Stop session recording */ stopSessionRecording: () => void; /** * Start session recording */ startSessionRecording: () => void; /** * Take screenshot */ screenshot: (description?: string) => string | undefined; /** * Starts measuring time for a given key. Key should be a unique identifier for the measurement. */ startTimeMeasure: (name: string, labels?: CoralogixRumLabels) => void; /** * Ends the measurement for a given key. */ endTimeMeasure: (name: string) => void; /** * Starts a new custom trace. @param ignoredInstruments - list of instruments to ignore in the trace */ getCustomTracer: (ignoredList?: { ignoredInstruments: CustomTracerIgnoredInstruments[]; }) => CustomTracer | undefined; readonly isInited: boolean; } export interface ErrorContext { error_type?: string; error_message?: string; error_custom_data?: unknown; original_stacktrace?: CxStackFrame[]; } export interface LogContext { message: string; data?: any; } export interface InternalContext { event: CoralogixInternalEvent; data?: any; } export interface NetworkRequestContext { method: string; status_code: number; url: string; url_blueprint: string; fragments: string; host: string; schema: string; status_text: string; response_content_length: string; duration: number; source: EventSource; request_headers?: Map<string, string>; response_headers?: Map<string, string>; response_payload?: string; request_payload?: string; } export interface InteractionContext { target_element: string; target_element_inner_text: string; target_element_type: string; event_name: string; element_id: string; element_classes: string; } export interface LongTaskContext extends Omit<PerformanceEntry, 'toJSON'> { id: string; } export interface WebVitalsContext extends Metric { attribution?: MetricWithAttribution; } export interface ResourceContext extends Omit<PerformanceResourceTiming, 'toJSON'> { responseStatus?: number; deliveryType?: string; firstInterimResponseStart?: number; renderBlockingStatus?: string; fragments: string; } export interface CustomMeasurementContext { name: string; value: CustomMeasurementData; } export interface EventTypeContext { error_context?: ErrorContext; log_context?: LogContext; internal_context?: InternalContext; network_request_context?: NetworkRequestContext; interaction_context?: InteractionContext; web_vitals_context?: WebVitalsContext; longtask_context?: LongTaskContext; resource_context?: ResourceContext; snapshot_context?: SnapshotContext; custom_measurement_context?: CustomMeasurementContext; screenshot_context?: ScreenshotContext; memory_usage_context?: MemoryUsageContext; } export interface UserMetadata { user_id: string; user_name?: string; user_email?: string; user_metadata?: { [key: string]: any; }; } export interface SessionContext extends UserMetadata { session_id: string; session_creation_date: number; prev_session?: { session_id: string; session_creation_date: number; hasRecording: boolean; hasScreenshot: boolean; }; user_agent: string; browser?: Browser; browserVersion: string; os: OS; osVersion: string; device: Device; hasRecording: boolean; hasScreenshot: boolean; hasError?: boolean; onlyWithErrorMode: boolean; } export type EventSource = ErrorSource | FetchSource | XHRSource | LogSource; export interface EventContext { type: CoralogixEventType; source: EventSource; severity: CoralogixLogSeverity; } interface SpanContext { readonly spanId: string; readonly traceId: string; sessionId: string; } interface OtelResource { attributes: Attributes; } interface InstrumentationData { otelSpan: Partial<ReadableSpan> & SpanContext; otelResource: OtelResource; } interface VersionMetaData { app_name: string; app_version: string; } export interface PageContext { page_url: string; page_url_blueprint: string; page_fragments: string; referrer: string; } export interface CxRumEvent extends EventTypeContext { browser_sdk: { version: string; }; platform: 'browser'; version_metadata: VersionMetaData; session_context: SessionContext; page_context: PageContext; event_context: EventContext; isNavigationEvent: boolean; labels: CoralogixRumLabels; spanId?: string; traceId?: string; parentSpanId?: string; environment: string; timestamp: number; isSnapshotEvent?: boolean; screenshot_context?: ScreenshotContext; screenshotId?: string; } export interface CxSpan { version_metadata: VersionMetaData; applicationName: string; subsystemName: string; timestamp: number; severity: CoralogixLogSeverity; isErrorWithStacktrace: boolean; instrumentation_data?: InstrumentationData; text: { cx_rum: CxRumEvent; }; } export interface Session { sessionId: string; sessionCreationDate: number; sessionExpirationDate: number; } export interface PrevSession extends Session { hasRecording: boolean; hasScreenshot: boolean; } export declare enum OtelNetworkAttrs { METHOD = "http.method", URL = "http.url", STATUS_CODE = "http.status_code", HOST = "http.host", SCHEME = "http.scheme", STATUS_TEXT = "http.status_text", RESPONSE_CONTENT_LENGTH = "http.response_content_length" } export type Browser = 'Chrome' | 'Edge' | 'Firefox' | 'Safari' | 'Opera' | 'IE' | 'Unknown'; export type OS = 'Windows' | 'MacOS' | 'Linux' | 'iOS' | 'Android' | 'Unknown'; export type Device = 'Mobile' | 'Tablet' | 'Desktop' | 'Unknown'; export type EventName = keyof HTMLElementEventMap; export interface PatternReplacement { pattern: RegExp; replacement: string; } export declare enum UrlType { PAGE = "page", NETWORK_REQUEST = "network_request" } export type LabelProviderLabels = Record<string, string | undefined>; export interface GenericLabelProvider { urlType?: UrlType; providerFunc: (url: string, event: CxRumEvent) => LabelProviderLabels; } export type LabelProvider = UrlBasedLabelProvider | GenericLabelProvider; export type InputType = 'button' | 'checkbox' | 'color' | 'date' | 'datetime-local' | 'email' | 'file' | 'hidden' | 'image' | 'month' | 'number' | 'password' | 'radio' | 'range' | 'reset' | 'search' | 'submit' | 'tel' | 'text' | 'time' | 'url' | 'week'; export interface EditableCxRumEvent extends Omit<CxRumEvent, 'session_context' | 'browser_sdk' | 'timestamp'> { session_context: Pick<SessionContext, keyof UserMetadata>; } export {};