import type { AttributeObject, RawAttribute, RawAttributes } from './attributes'; import { getClient, getCurrentScope, getIsolationScope } from './currentScopes'; import { DEBUG_BUILD } from './debug-build'; import type { CaptureContext } from './scope'; import { closeSession, makeSession, updateSession } from './session'; import type { Event, EventHint } from './types/event'; import type { EventProcessor } from './types/eventprocessor'; import type { Extra, Extras } from './types/extra'; import type { Primitive } from './types/misc'; import type { Session, SessionContext } from './types/session'; import type { SeverityLevel } from './types/severity'; import type { User } from './types/user'; import { filterKeyValueData } from './utils/data-collection/filterKeyValueData'; import { debug } from './utils/debug-logger'; import type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent'; import { parseEventHintOrCaptureContext } from './utils/prepareEvent'; import { getCombinedScopeData } from './utils/scopeData'; import { GLOBAL_OBJ } from './utils/worldwide'; /** * Captures an exception event and sends it to Sentry. * * @param exception The exception to capture. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured Sentry event. */ export function captureException(exception: unknown, hint?: ExclusiveEventHintOrCaptureContext): string { return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); } /** * Captures a message event and sends it to Sentry. * * @param message The message to send to Sentry. * @param captureContext Define the level of the message or pass in additional data to attach to the message. * @returns the id of the captured message. */ export function captureMessage(message: string, captureContext?: CaptureContext | SeverityLevel): string { // This is necessary to provide explicit scopes upgrade, without changing the original // arity of the `captureMessage(message, level)` method. const level = typeof captureContext === 'string' ? captureContext : undefined; const hint = typeof captureContext !== 'string' ? { captureContext } : undefined; return getCurrentScope().captureMessage(message, level, hint); } /** * Captures a manually created event and sends it to Sentry. * * @param event The event to send to Sentry. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured event. */ export function captureEvent(event: Event, hint?: EventHint): string { return getCurrentScope().captureEvent(event, hint); } /** * Sets context data with the given name. * @param name of the context * @param context Any kind of data. This data will be normalized. */ export function setContext(name: string, context: { [key: string]: unknown } | null): void { getIsolationScope().setContext(name, context); } /** * Set an object that will be merged sent as extra data with the event. * @param extras Extras object to merge into current context. */ export function setExtras(extras: Extras): void { getIsolationScope().setExtras(extras); } /** * Set key:value that will be sent as extra data with the event. * @param key String of extra * @param extra Any kind of data. This data will be normalized. */ export function setExtra(key: string, extra: Extra): void { getIsolationScope().setExtra(key, extra); } /** * Set an object that will be merged sent as tags data with the event. * @param tags Tags context object to merge into current context. */ export function setTags(tags: { [key: string]: Primitive }): void { getIsolationScope().setTags(tags); } /** * Set key:value that will be sent as tags data with the event. * * Can also be used to unset a tag, by passing `undefined`. * * @param key String key of tag * @param value Value of tag */ export function setTag(key: string, value: Primitive): void { getIsolationScope().setTag(key, value); } /** * Sets attributes on the isolation scope. * * These attributes are applied to logs, metrics and streamed spans. * * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`. * * @param attributes - The attributes to set on the scope, as key-value pairs. * * @example * ```typescript * Sentry.setAttributes({ * is_admin: true, * payment_selection: 'credit_card', * render_duration: 150, * }); * ``` */ export function setAttributes>(attributes: RawAttributes): void { getIsolationScope().setAttributes(attributes); } /** * Sets an attribute on the isolation scope. * * These attributes are applied to logs, metrics and streamed spans. * * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`. * * @param key - The attribute key. * @param value - The attribute value. * * @example * ```typescript * Sentry.setAttribute('is_admin', true); * Sentry.setAttribute('render_duration', 150); * ``` */ export function setAttribute< // oxlint-disable-next-line typescript-eslint/no-explicit-any T extends (RawAttribute extends { value: any } | { unit: any } ? AttributeObject : unknown), >(key: string, value: RawAttribute): void { getIsolationScope().setAttribute(key, value); } /** * Updates user context information for future events. * * @param user User context object to be set in the current context. Pass `null` to unset the user. */ export function setUser(user: User | null): void { getIsolationScope().setUser(user); } /** * Sets the conversation ID for the current isolation scope. * * @param conversationId The conversation ID to set. Pass `null` or `undefined` to unset the conversation ID. */ export function setConversationId(conversationId: string | null | undefined): void { getIsolationScope().setConversationId(conversationId); } /** * The last error event id of the isolation scope. * * Warning: This function really returns the last recorded error event id on the current * isolation scope. If you call this function after handling a certain error and another error * is captured in between, the last one is returned instead of the one you might expect. * Also, ids of events that were never sent to Sentry (for example because * they were dropped by sampling or `beforeSend`) could be returned. * * @returns The last event id of the isolation scope. */ export function lastEventId(): string | undefined { return getIsolationScope().lastEventId(); } /** * Call `flush()` on the current client, if there is one. See {@link Client.flush}. * * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause * the client to wait until all events are sent before resolving the promise. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it * doesn't (or if there's no client defined). */ export async function flush(timeout?: number): Promise { const client = getClient(); if (client) { return client.flush(timeout); } DEBUG_BUILD && debug.warn('Cannot flush events. No client defined.'); return Promise.resolve(false); } /** * Call `close()` on the current client, if there is one, and unbind it from the current scope. * See {@link Client.close}. * * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this * parameter will cause the client to wait until all events are sent before disabling itself. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it * doesn't (or if there's no client defined). */ export async function close(timeout?: number): Promise { const scope = getCurrentScope(); const client = scope.getClient(); if (client) { const result = await client.close(timeout); // Unbind the client, so a later `init()` sets up a new one. if (scope.getClient() === client) { scope.setClient(undefined); } return result; } DEBUG_BUILD && debug.warn('Cannot flush events and disable SDK. No client defined.'); return Promise.resolve(false); } /** * Returns true if Sentry has been properly initialized. */ export function isInitialized(): boolean { return !!getClient(); } /** If the SDK is initialized & enabled. */ export function isEnabled(): boolean { const client = getClient(); return client?.getOptions().enabled !== false && !!client?.getTransport(); } /** * Add an event processor. * This will be added to the current isolation scope, ensuring any event that is processed in the current execution * context will have the processor applied. */ export function addEventProcessor(callback: EventProcessor): void { getIsolationScope().addEventProcessor(callback); } /** * Start a session on the current isolation scope. * * @param context (optional) additional properties to be applied to the returned session object * * @returns the new active session */ export function startSession(context?: SessionContext): Session { const isolationScope = getIsolationScope(); const { user } = getCombinedScopeData(isolationScope, getCurrentScope()); let userAgent = GLOBAL_OBJ.navigator?.userAgent; if (userAgent) { const headerCollection = getClient()?.getDataCollectionOptions().httpHeaders.request ?? true; userAgent = filterKeyValueData({ 'User-Agent': userAgent }, headerCollection)['User-Agent']; } const session = makeSession({ user, userAgent, ...context, }); // End existing session if there's one const currentSession = isolationScope.getSession(); if (currentSession?.status === 'ok') { updateSession(currentSession, { status: 'exited' }); } endSession(); // Afterwards we set the new session on the scope isolationScope.setSession(session); return session; } /** * End the session on the current isolation scope. */ export function endSession(): void { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const session = currentScope.getSession() || isolationScope.getSession(); if (session) { closeSession(session); } _sendSessionUpdate(); // the session is over; take it off of the scope isolationScope.setSession(); } /** * Sends the current Session on the scope */ function _sendSessionUpdate(): void { const isolationScope = getIsolationScope(); const client = getClient(); const session = isolationScope.getSession(); if (session && client) { client.captureSession(session); } } /** * Sends the current session on the scope to Sentry * * @param end If set the session will be marked as exited and removed from the scope. * Defaults to `false`. */ export function captureSession(end: boolean = false): void { // both send the update and pull the session from the scope if (end) { endSession(); return; } // only send the update _sendSessionUpdate(); }