• Version 7.104.0
  • Published
  • 1.28 MB
  • 1 dependency
  • MIT license


npm i @sentry/utils
yarn add @sentry/utils
pnpm add @sentry/utils


Utilities for all Sentry JavaScript SDKs






Type Aliases



const BAGGAGE_HEADER_NAME: string;

    variable browserPerformanceTimeOrigin

    const browserPerformanceTimeOrigin: number;
    • The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the performance API is available.

    variable CONSOLE_LEVELS

    const CONSOLE_LEVELS: readonly ConsoleLevel[];

      variable DEFAULT_RETRY_AFTER

      const DEFAULT_RETRY_AFTER: number;

        variable DEFAULT_USER_INCLUDES

        const DEFAULT_USER_INCLUDES: string[];

          variable GLOBAL_OBJ

          const GLOBAL_OBJ: InternalGlobal;
          • Get's the global object for the current JavaScript runtime

          variable logger

          const logger: Logger;

            variable MAX_BAGGAGE_STRING_LENGTH

            const MAX_BAGGAGE_STRING_LENGTH: number;
            • Max length of a serialized baggage string


            variable originalConsoleMethods

            const originalConsoleMethods: { [x: string]: (...args: any[]) => void };
            • This may be mutated by the console instrumentation.

            variable SENTRY_BAGGAGE_KEY_PREFIX

            const SENTRY_BAGGAGE_KEY_PREFIX: string;

              variable SENTRY_BAGGAGE_KEY_PREFIX_REGEX

              const SENTRY_BAGGAGE_KEY_PREFIX_REGEX: RegExp;

                variable SENTRY_XHR_DATA_KEY

                const SENTRY_XHR_DATA_KEY: string;

                  variable TRACEPARENT_REGEXP

                  const TRACEPARENT_REGEXP: RegExp;

                    variable validSeverityLevels

                    const validSeverityLevels: string[];


                      function addClickKeypressInstrumentationHandler

                      addClickKeypressInstrumentationHandler: (
                      handler: (data: HandlerDataDom) => void
                      ) => void;
                      • Add an instrumentation handler for when a click or a keypress happens.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addConsoleInstrumentationHandler

                      addConsoleInstrumentationHandler: (
                      handler: (data: HandlerDataConsole) => void
                      ) => void;
                      • Add an instrumentation handler for when a console.xxx method is called.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addContextToFrame

                      addContextToFrame: (
                      lines: string[],
                      frame: StackFrame,
                      linesOfContext?: number
                      ) => void;
                      • This function adds context (pre/post/line) lines to the provided frame

                        Parameter lines

                        string[] containing all lines

                        Parameter frame

                        StackFrame that will be mutated

                        Parameter linesOfContext

                        number of context lines we want to add pre/post

                      function addExceptionMechanism

                      addExceptionMechanism: (event: Event, newMechanism?: Mechanism) => void;
                      • Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.

                        Parameter event

                        The event to modify.

                        Parameter newMechanism

                        Mechanism data to add to the event.

                      function addExceptionTypeValue

                      addExceptionTypeValue: (event: Event, value?: string, type?: string) => void;
                      • Adds exception values, type and value to an synthetic Exception.

                        Parameter event

                        The event to modify.

                        Parameter value

                        Value of the exception.

                        Parameter type

                        Type of the exception.

                      function addFetchInstrumentationHandler

                      addFetchInstrumentationHandler: (
                      handler: (data: HandlerDataFetch) => void
                      ) => void;
                      • Add an instrumentation handler for when a fetch request happens. The handler function is called once when the request starts and once when it ends, which can be identified by checking if it has an endTimestamp.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addGlobalErrorInstrumentationHandler

                      addGlobalErrorInstrumentationHandler: (
                      handler: (data: HandlerDataError) => void
                      ) => void;
                      • Add an instrumentation handler for when an error is captured by the global error handler.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addGlobalUnhandledRejectionInstrumentationHandler

                      addGlobalUnhandledRejectionInstrumentationHandler: (
                      handler: (data: HandlerDataUnhandledRejection) => void
                      ) => void;
                      • Add an instrumentation handler for when an unhandled promise rejection is captured.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addHistoryInstrumentationHandler

                      addHistoryInstrumentationHandler: (
                      handler: (data: HandlerDataHistory) => void
                      ) => void;
                      • Add an instrumentation handler for when a fetch request happens. The handler function is called once when the request starts and once when it ends, which can be identified by checking if it has an endTimestamp.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function addInstrumentationHandler

                      addInstrumentationHandler: (
                      type: _InstrumentHandlerType,
                      callback: _InstrumentHandlerCallback
                      ) => void;
                      • Add handler that will be called when given type of instrumentation triggers. Use at your own risk, this might break without changelog notice, only used internally.


                        Use the proper function per instrumentation type instead!

                      function addItemToEnvelope

                      addItemToEnvelope: <E extends Envelope>(envelope: E, newItem: E[1][number]) => E;
                      • Add an item to an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.

                      function addNonEnumerableProperty

                      addNonEnumerableProperty: (obj: object, name: string, value: unknown) => void;
                      • Defines a non-enumerable property on the given object.

                        Parameter obj

                        The object on which to set the property

                        Parameter name

                        The name of the property to be set

                        Parameter value

                        The value to which to set the property

                      function addOrUpdateIntegration

                      addOrUpdateIntegration: <T extends UserIntegrations>(
                      defaultIntegrationInstance: Integration,
                      userIntegrations: T,
                      forcedOptions?: ForcedIntegrationOptions
                      ) => T;
                      • Enforces inclusion of a given integration with specified options in an integration array originally determined by the user, by either including the given default instance or by patching an existing user instance with the given options.

                        Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging options from a default integration instance with those from a user-provided instance of the same integration, only for allowing the user to override a default instance entirely. (TODO: Fix that.)

                        Parameter defaultIntegrationInstance

                        An instance of the integration with the correct options already set

                        Parameter userIntegrations

                        Integrations defined by the user.

                        Parameter forcedOptions

                        Options with which to patch an existing user-derived instance on the integration.


                        A final integrations array.


                        This will be removed in v8.

                      function addRequestDataToEvent

                      addRequestDataToEvent: (
                      event: Event,
                      req: PolymorphicRequest,
                      options?: AddRequestDataToEventOptions
                      ) => Event;
                      • Add data from the given request to the given event

                        Parameter event

                        The event to which the request data will be added

                        Parameter req

                        Request object


                        options.include Flags to control what data is included


                        options.deps Injected platform-specific dependencies


                        The mutated Event object

                      function addRequestDataToTransaction

                      addRequestDataToTransaction: (
                      transaction: Transaction | undefined,
                      req: PolymorphicRequest,
                      deps?: InjectedNodeDeps
                      ) => void;
                      • Sets parameterized route as transaction name e.g.: GET /users/:id Also adds more context data on the transaction from the request

                      function addXhrInstrumentationHandler

                      addXhrInstrumentationHandler: (handler: (data: HandlerDataXhr) => void) => void;
                      • Add an instrumentation handler for when an XHR request happens. The handler function is called once when the request starts and once when it ends, which can be identified by checking if it has an endTimestamp.

                        Use at your own risk, this might break without changelog notice, only used internally.

                      function applyAggregateErrorsToEvent

                      applyAggregateErrorsToEvent: (
                      exceptionFromErrorImplementation: (
                      stackParser: StackParser,
                      ex: Error
                      ) => Exception,
                      parser: StackParser,
                      maxValueLimit: number | undefined,
                      key: string,
                      limit: number,
                      event: Event,
                      hint?: EventHint
                      ) => void;
                      • Creates exceptions inside event.exception.values for errors that are nested on properties based on the key parameter.

                      function arrayify

                      arrayify: <T = unknown>(maybeArray: T | T[]) => T[];
                      • Checks whether the given input is already an array, and if it isn't, wraps it in one.

                        Parameter maybeArray

                        Input to turn into an array, if necessary


                        The input, if already an array, or an array with the input as the only element, if not

                      function baggageHeaderToDynamicSamplingContext

                      baggageHeaderToDynamicSamplingContext: (
                      baggageHeader: string | string[] | number | null | undefined | boolean
                      ) => Partial<DynamicSamplingContext> | undefined;
                      • Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values from it.

                        Parameter baggageHeader

                        A very bread definition of a baggage header as it might appear in various frameworks.


                        The Dynamic Sampling Context that was found on baggageHeader, if there was any, undefined otherwise.

                      function basename

                      basename: (path: string, ext?: string) => string;
                      • JSDoc

                      function callFrameToStackFrame

                      callFrameToStackFrame: (
                      frame: CallFrame,
                      url: string | undefined,
                      getModuleFromFilename: (filename: string | undefined) => string | undefined
                      ) => StackFrame;
                      • Converts Debugger.CallFrame to Sentry StackFrame

                      function checkOrSetAlreadyCaught

                      checkOrSetAlreadyCaught: (exception: unknown) => boolean;
                      • Checks whether or not we've already captured the given exception (note: not an identical exception - the very object in question), and marks it captured if not.

                        This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This function helps us ensure that even if we encounter the same error more than once, we only record it the first time we see it.

                        Note: It will ignore primitives (always return false and not mark them as seen), as properties can't be set on them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent object wrapper forms so that this check will always work. However, because we need to flag the exact object which will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification must be done before the exception captured.

                        Parameter A

                        thrown exception to check or flag as having been seen


                        true if the exception has already been captured, false if not (with the side effect of marking it seen)

                      function consoleSandbox

                      consoleSandbox: <T>(callback: () => T) => T;
                      • Temporarily disable sentry console instrumentations.

                        Parameter callback

                        The function to run against the original console messages


                        The results of the callback

                      function convertToPlainObject

                      convertToPlainObject: <V>(
                      value: V
                      ) =>
                      | V
                      | {
                      [ownProps: string]: unknown;
                      type: string;
                      target: string;
                      currentTarget: string;
                      detail?: unknown;
                      | { [ownProps: string]: unknown; message: string; name: string; stack?: string };
                      • Transforms any Error or Event into a plain object with all of their enumerable properties, and some of their non-enumerable properties attached.

                        Parameter value

                        Initial source that we have to transform in order for it to be usable by the serializer


                        An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor an Error.

                      function createAttachmentEnvelopeItem

                      createAttachmentEnvelopeItem: (
                      attachment: Attachment,
                      textEncoder?: TextEncoderInternal
                      ) => AttachmentItem;
                      • Creates attachment envelope items

                      function createClientReportEnvelope

                      createClientReportEnvelope: (
                      discarded_events: ClientReport,
                      dsn?: string,
                      timestamp?: number
                      ) => ClientReportEnvelope;
                      • Creates client report envelope

                        Parameter discarded_events

                        An array of discard events

                        Parameter dsn

                        A DSN that can be set on the header. Optional.

                      function createEnvelope

                      createEnvelope: <E extends Envelope>(headers: E[0], items?: E[1]) => E;
                      • Creates an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.

                      function createEventEnvelopeHeaders

                      createEventEnvelopeHeaders: (
                      event: Event,
                      sdkInfo: SdkInfo | undefined,
                      tunnel: string | undefined,
                      dsn?: DsnComponents
                      ) => EventEnvelopeHeaders;
                      • Creates event envelope headers, based on event, sdk info and tunnel Note: This function was extracted from the core package to make it available in Replay

                      function createStackParser

                      createStackParser: (...parsers: StackLineParser[]) => StackParser;
                      • Creates a stack parser with the supplied line parsers

                        StackFrames are returned in the correct order for Sentry Exception frames and with Sentry SDK internal frames removed from the top and bottom

                      function dateTimestampInSeconds

                      dateTimestampInSeconds: () => number;
                      • Returns a timestamp in seconds since the UNIX epoch using the Date API.

                        TODO(v8): Return type should be rounded.

                      function dirname

                      dirname: (path: string) => string;
                      • JSDoc

                      function disabledUntil

                      disabledUntil: (limits: RateLimits, category: string) => number;
                      • Gets the time that the given category is disabled until for rate limiting. In case no category-specific limit is set but a general rate limit across all categories is active, that time is returned.

                        the time in ms that the category is disabled until or 0 if there's no active rate limit.

                      function dropUndefinedKeys

                      dropUndefinedKeys: <T>(inputValue: T) => T;
                      • Given any object, return a new object having removed all fields whose value was undefined. Works recursively on objects and arrays.

                        Attention: This function keeps circular references in the returned object.

                      function dsnFromString

                      dsnFromString: (str: string) => DsnComponents | undefined;
                      • Parses a Dsn from a given string.

                        Parameter str

                        A Dsn as string

                        Parameter str

                        is not a valid DSN string


                        Dsn as DsnComponents or undefined if

                      function dsnToString

                      dsnToString: (dsn: DsnComponents, withPassword?: boolean) => string;
                      • Renders the string representation of this Dsn.

                        By default, this will render the public representation without the password component. To get the deprecated private representation, set withPassword to true.

                        Parameter withPassword

                        When set to true, the password will be included.

                      function dynamicRequire

                      dynamicRequire: (mod: any, request: string) => any;
                      • Requires a module which is protected against bundler minification.

                        Parameter request

                        The module path to resolve

                      function dynamicSamplingContextToSentryBaggageHeader

                      dynamicSamplingContextToSentryBaggageHeader: (
                      dynamicSamplingContext?: DynamicSamplingContext
                      ) => string | undefined;
                      • Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-".

                        Parameter dynamicSamplingContext

                        The Dynamic Sampling Context to turn into a header. For convenience and compatibility with the getDynamicSamplingContext method on the Transaction class ,this argument can also be undefined. If it is undefined the function will return undefined.


                        a baggage header, created from dynamicSamplingContext, or undefined either if dynamicSamplingContext was undefined, or if dynamicSamplingContext didn't contain any values.

                      function envelopeContainsItemType

                      envelopeContainsItemType: (
                      envelope: Envelope,
                      types: EnvelopeItemType[]
                      ) => boolean;
                      • Returns true if the envelope contains any of the given envelope item types

                      function envelopeItemTypeToDataCategory

                      envelopeItemTypeToDataCategory: (type: EnvelopeItemType) => DataCategory;
                      • Maps the type of an envelope item to a data category.

                      function escapeStringForRegex

                      escapeStringForRegex: (regexString: string) => string;
                      • Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to new RegExp().

                        Parameter regexString

                        The string to escape


                        An version of the string with all special regex characters escaped

                      function eventFromMessage

                      eventFromMessage: (
                      stackParser: StackParser,
                      message: ParameterizedString,
                      level?: Severity | SeverityLevel,
                      hint?: EventHint,
                      attachStacktrace?: boolean
                      ) => Event;
                      • Builds and Event from a Message

                      function eventFromUnknownInput

                      eventFromUnknownInput: (
                      getHubOrClient: (() => Hub) | Client | undefined,
                      stackParser: StackParser,
                      exception: unknown,
                      hint?: EventHint
                      ) => Event;
                      • Builds and Event from a Exception

                        TODO(v8): Remove getHub fallback

                      function exceptionFromError

                      exceptionFromError: (stackParser: StackParser, error: Error) => Exception;
                      • Extracts stack frames from the error and builds a Sentry Exception

                      function extractExceptionKeysForMessage

                      extractExceptionKeysForMessage: (
                      exception: Record<string, unknown>,
                      maxLength?: number
                      ) => string;
                      • Given any captured exception, extract its keys and create a sorted and truncated list that will be used inside the event message. eg. Non-error exception captured with keys: foo, bar, baz

                      function extractPathForTransaction

                      extractPathForTransaction: (
                      req: PolymorphicRequest,
                      options?: { path?: boolean; method?: boolean; customRoute?: string }
                      ) => [string, TransactionSource];
                      • Extracts a complete and parameterized path from the request object and uses it to construct transaction name. If the parameterized transaction name cannot be extracted, we fall back to the raw URL.

                        Additionally, this function determines and returns the transaction name source

                        eg. GET /mountpoint/user/:id

                        Parameter req

                        A request object

                        Parameter options

                        What to include in the transaction name (method, path, or a custom route name to be used instead of the request's route)


                        A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')

                      function extractRequestData

                      extractRequestData: (
                      req: PolymorphicRequest,
                      options?: { include?: string[]; deps?: InjectedNodeDeps }
                      ) => ExtractedNodeRequestData;
                      • Normalize data from the request object, accounting for framework differences.

                        Parameter req

                        The request object from which to extract data


                        options.include An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_INCLUDES if not provided.


                        options.deps Injected, platform-specific dependencies


                        An object containing normalized request data

                      function extractTraceparentData

                      extractTraceparentData: (traceparent?: string) => TraceparentData | undefined;
                      • Extract transaction context data from a sentry-trace header.

                        Parameter traceparent

                        Traceparent string


                        Object containing data from the header, or undefined if traceparent string is malformed

                      function filenameIsInApp

                      filenameIsInApp: (filename: string, isNative?: boolean) => boolean;
                      • Does this filename look like it's part of the app code?

                      function fill

                      fill: (
                      source: { [key: string]: any },
                      name: string,
                      replacementFactory: (...args: any[]) => any
                      ) => void;
                      • Replace a method in an object with a wrapped version of itself.

                        Parameter source

                        An object that contains a method to be wrapped.

                        Parameter name

                        The name of the method to be wrapped.

                        Parameter replacementFactory

                        A higher-order function that takes the original version of the given method and returns a wrapped version. Note: The function returned by replacementFactory needs to be a non-arrow function, in order to preserve the correct value of this, and the original method must be called using `origMethod.call(this, <other args>) or origMethod.apply(this, [<other args>]) (rather than being called directly), again to preserve this`.



                      function forEachEnvelopeItem

                      forEachEnvelopeItem: <E extends Envelope>(
                      envelope: Envelope,
                      callback: (
                      envelopeItem: E[1][number],
                      envelopeItemType: E[1][number][0]['type']
                      ) => boolean | void
                      ) => boolean;
                      • Convenience function to loop through the items and item types of an envelope. (This function was mostly created because working with envelope types is painful at the moment)

                        If the callback returns true, the rest of the items will be skipped.

                      function generateSentryTraceHeader

                      generateSentryTraceHeader: (
                      traceId?: string,
                      spanId?: string,
                      sampled?: boolean
                      ) => string;
                      • Create sentry-trace header from span context values.

                      function getComponentName

                      getComponentName: (elem: unknown) => string | null;
                      • Given a DOM element, traverses up the tree until it finds the first ancestor node that has the data-sentry-component attribute. This attribute is added at build-time by projects that have the component name annotation plugin installed.


                        a string representation of the component for the provided DOM element, or null if not found

                      function getDomElement

                      getDomElement: <E = any>(selector: string) => E | null;
                      • Gets a DOM element by using document.querySelector.

                        This wrapper will first check for the existance of the function before actually calling it so that we don't have to take care of this check, every time we want to access the DOM.

                        Reason: DOM/querySelector is not available in all environments.

                        We have to cast to any because utils can be consumed by a variety of environments, and we don't want to break TS users. If you know what element will be selected by document.querySelector, specify it as part of the generic call. For example, const element = getDomElement<Element>('selector');

                        Parameter selector

                        the selector string passed on to document.querySelector

                      function getEventDescription

                      getEventDescription: (event: Event) => string;
                      • Extracts either message or type+value from an event that can be used for user-facing logs


                        event's description

                      function getFunctionName

                      getFunctionName: (fn: unknown) => string;
                      • Safely extract function name from itself

                      function getGlobalObject

                      getGlobalObject: <T>() => T & InternalGlobal;
                      • Deprecated

                        Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8

                      function getGlobalSingleton

                      getGlobalSingleton: <T>(
                      name: keyof InternalGlobal['__SENTRY__'],
                      creator: () => T,
                      obj?: unknown
                      ) => T;
                      • Returns a global singleton contained in the global __SENTRY__ object.

                        If the singleton doesn't already exist in __SENTRY__, it will be created using the given factory function and added to the __SENTRY__ object.

                        Parameter name

                        name of the global singleton on __SENTRY__

                        Parameter creator

                        creator Factory function to create the singleton if it doesn't already exist on __SENTRY__

                        Parameter obj

                        (Optional) The global object on which to look for __SENTRY__, if not GLOBAL_OBJ's return value


                        the singleton

                      function getLocationHref

                      getLocationHref: () => string;
                      • A safe form of location.href

                      function getNumberOfUrlSegments

                      getNumberOfUrlSegments: (url: string) => number;
                      • Returns number of URL segments of a passed string URL.

                      function getOriginalFunction

                      getOriginalFunction: (func: WrappedFunction) => WrappedFunction | undefined;
                      • This extracts the original function if available. See markFunctionWrapped for more information.

                        Parameter func

                        the function to unwrap


                        the unwrapped version of the function if available.

                      function getSanitizedUrlString

                      getSanitizedUrlString: (url: PartialURL) => string;
                      • Takes a URL object and returns a sanitized string which is safe to use as span description see: https://develop.sentry.dev/sdk/data-handling/#structuring-data

                      function getSdkMetadataForEnvelopeHeader

                      getSdkMetadataForEnvelopeHeader: (
                      metadataOrEvent?: SdkMetadata | Event
                      ) => SdkInfo | undefined;
                      • Extracts the minimal SDK info from from the metadata or an events

                      function getSDKSource

                      getSDKSource: () => SdkSource;
                      • Get source of SDK.

                      function htmlTreeAsString

                      htmlTreeAsString: (
                      elem: unknown,
                      options?: string[] | { keyAttrs?: string[]; maxStringLength?: number }
                      ) => string;
                      • Given a child DOM element, returns a query-selector statement describing that and its ancestors e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]


                        generated DOM path

                      function isAbsolute

                      isAbsolute: (path: string) => boolean;
                      • JSDoc

                      function isBrowser

                      isBrowser: () => boolean;
                      • Returns true if we are in the browser.

                      function isBrowserBundle

                      isBrowserBundle: () => boolean;
                      • Figures out if we're building a browser bundle.


                        true if this is a browser bundle build.

                      function isDOMError

                      isDOMError: (wat: unknown) => boolean;
                      • Checks whether given value's type is DOMError isDOMError.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isDOMException

                      isDOMException: (wat: unknown) => boolean;
                      • Checks whether given value's type is DOMException isDOMException.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isElement

                      isElement: (wat: unknown) => boolean;
                      • Checks whether given value's type is an Element instance isElement.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isError

                      isError: (wat: unknown) => wat is Error;
                      • Checks whether given value's type is one of a few Error or Error-like isError.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isErrorEvent

                      isErrorEvent: (wat: unknown) => boolean;
                      • Checks whether given value's type is ErrorEvent isErrorEvent.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isEvent

                      isEvent: (wat: unknown) => wat is PolymorphicEvent;
                      • Checks whether given value's type is an Event instance isEvent.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isInstanceOf

                      isInstanceOf: (wat: any, base: any) => boolean;
                      • Checks whether given value's type is an instance of provided constructor. isInstanceOf.

                        Parameter wat

                        A value to be checked.

                        Parameter base

                        A constructor to be used in a check.


                        A boolean representing the result.

                      function isMatchingPattern

                      isMatchingPattern: (
                      value: string,
                      pattern: RegExp | string,
                      requireExactStringMatch?: boolean
                      ) => boolean;
                      • Checks if the given value matches a regex or string

                        Parameter value

                        The string to test

                        Parameter pattern

                        Either a regex or a string against which value will be matched

                        Parameter requireExactStringMatch

                        If true, value must match pattern exactly. If false, value will match pattern if it contains pattern. Only applies to string-type patterns.

                      function isNaN

                      isNaN: (wat: unknown) => boolean;
                      • Checks whether given value is NaN isNaN.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isNativeFetch

                      isNativeFetch: (func: Function) => boolean;
                      • isNativeFetch checks if the given function is a native implementation of fetch()

                      function isNodeEnv

                      isNodeEnv: () => boolean;
                      • Checks whether we're in the Node.js or Browser environment


                        Answer to given question

                      function isParameterizedString

                      isParameterizedString: (wat: unknown) => wat is ParameterizedString;
                      • Checks whether given string is parameterized isParameterizedString.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isPlainObject

                      isPlainObject: (wat: unknown) => wat is Record<string, unknown>;
                      • Checks whether given value's type is an object literal, or a class instance. isPlainObject.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isPrimitive

                      isPrimitive: (wat: unknown) => wat is Primitive;
                      • Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) isPrimitive.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isRateLimited

                      isRateLimited: (limits: RateLimits, category: string, now?: number) => boolean;
                      • Checks if a category is rate limited

                      function isRegExp

                      isRegExp: (wat: unknown) => wat is RegExp;
                      • Checks whether given value's type is an regexp isRegExp.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isString

                      isString: (wat: unknown) => wat is string;
                      • Checks whether given value's type is a string isString.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isSyntheticEvent

                      isSyntheticEvent: (wat: unknown) => boolean;
                      • Checks whether given value's type is a SyntheticEvent isSyntheticEvent.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function isThenable

                      isThenable: (wat: any) => wat is PromiseLike<any>;
                      • Checks whether given value has a then function.

                        Parameter wat

                        A value to be checked.

                      function isVueViewModel

                      isVueViewModel: (wat: unknown) => boolean;
                      • Checks whether given value's type is a Vue ViewModel.

                        Parameter wat

                        A value to be checked.


                        A boolean representing the result.

                      function join

                      join: (...args: string[]) => string;
                      • JSDoc

                      function loadModule

                      loadModule: <T>(moduleName: string) => T | undefined;
                      • Helper for dynamically loading module that should work with linked dependencies. The problem is that we _should_ be using require(require.resolve(moduleName, { paths: [cwd()] })) However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during build time. require.resolve is also not available in any other way, so we cannot create, a fake helper like we do with dynamicRequire.

                        We always prefer to use local package, thus the value is not returned early from each try/catch block. That is to mimic the behavior of require.resolve exactly.

                        Parameter moduleName

                        module name to require


                        possibly required module

                      function makeDsn

                      makeDsn: (from: DsnLike) => DsnComponents | undefined;
                      • Creates a valid Sentry Dsn object, identifying a Sentry instance and project.

                        Parameter from

                        is an invalid DSN source


                        a valid DsnComponents object or undefined if

                      function makeFifoCache

                      makeFifoCache: <Key extends string, Value>(
                      size: number
                      ) => {
                      get: (key: Key) => Value | undefined;
                      add: (key: Key, value: Value) => void;
                      delete: (key: Key) => boolean;
                      clear: () => void;
                      size: () => number;
                      • Creates a cache that evicts keys in fifo order

                        Parameter size

                      function makePromiseBuffer

                      makePromiseBuffer: <T>(limit?: number) => PromiseBuffer<T>;
                      • Creates an new PromiseBuffer object with the specified limit

                        Parameter limit

                        max number of promises that can be stored in the buffer

                      function markFunctionWrapped

                      markFunctionWrapped: (
                      wrapped: WrappedFunction,
                      original: WrappedFunction
                      ) => void;
                      • Remembers the original function on the wrapped function and patches up the prototype.

                        Parameter wrapped

                        the wrapper function

                        Parameter original

                        the original function that gets wrapped

                      function memoBuilder

                      memoBuilder: () => MemoFunc;
                      • Helper to decycle json objects

                      function nodeStackLineParser

                      nodeStackLineParser: (getModule?: GetModuleFn) => StackLineParser;
                      • Node.js stack line parser

                        This is in @sentry/utils so it can be used from the Electron SDK in the browser for when nodeIntegration == true. This allows it to be used without referencing or importing any node specific code which causes bundlers to complain

                      function normalize

                      normalize: (input: unknown, depth?: number, maxProperties?: number) => any;
                      • Recursively normalizes the given object.

                        - Creates a copy to prevent original input mutation - Skips non-enumerable properties - When stringifying, calls toJSON if implemented - Removes circular references - Translates non-serializable values (undefined/NaN/functions) to serializable format - Translates known global objects/classes to a string representations - Takes care of Error object serialization - Optionally limits depth of final output - Optionally limits number of properties/elements included in any single object/array

                        Parameter input

                        The object to be normalized.

                        Parameter depth

                        The max depth to which to normalize the object. (Anything deeper stringified whole.)

                        Parameter maxProperties

                        The max number of elements or properties to be included in any single array or object in the normallized output.


                        A normalized version of the object, or "**non-serializable**" if any errors are thrown during normalization.

                      function normalizePath

                      normalizePath: (path: string) => string;
                      • JSDoc

                      function normalizeToSize

                      normalizeToSize: <T>(
                      object: { [key: string]: any },
                      depth?: number,
                      maxSize?: number
                      ) => T;
                      • JSDoc

                      function normalizeUrlToBase

                      normalizeUrlToBase: (url: string, basePath: string) => string;
                      • Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint across platforms and working directory.

                        Parameter url

                        The URL to be normalized.

                        Parameter basePath

                        The application base path.


                        The normalized URL.

                      function objectify

                      objectify: (wat: unknown) => typeof Object;
                      • Ensure that something is an object.

                        Turns undefined and null into Strings and all other primitives into instances of their respective wrapper classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.

                        Parameter wat

                        The subject of the objectification


                        A version of wat which can safely be used with Object class methods

                      function parseEnvelope

                      parseEnvelope: (
                      env: string | Uint8Array,
                      textEncoder: TextEncoderInternal,
                      textDecoder: TextDecoderInternal
                      ) => Envelope;
                      • Parses an envelope

                      function parseRetryAfterHeader

                      parseRetryAfterHeader: (header: string, now?: number) => number;
                      • Extracts Retry-After value from the request header or returns default value

                        Parameter header

                        string representation of 'Retry-After' header

                        Parameter now

                        current unix timestamp

                      function parseSemver

                      parseSemver: (input: string) => SemVer;
                      • Parses input into a SemVer interface

                        Parameter input

                        string representation of a semver version

                      function parseStackFrames

                      parseStackFrames: (stackParser: StackParser, error: Error) => StackFrame[];
                      • Extracts stack frames from the error.stack string

                      function parseUrl

                      parseUrl: (url: string) => PartialURL;
                      • Parses string form of URL into an object // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B // intentionally using regex and not href parsing trick because React Native and other // environments where DOM might not be available


                        parsed URL object

                      function propagationContextFromHeaders

                      propagationContextFromHeaders: (
                      sentryTrace: string | undefined,
                      baggage: string | number | boolean | string[] | null | undefined
                      ) => PropagationContext;
                      • Create a propagation context from incoming headers.

                      function rejectedSyncPromise

                      rejectedSyncPromise: <T = never>(reason?: any) => PromiseLike<T>;
                      • Creates a rejected sync promise.

                        Parameter value

                        the value to reject the promise with


                        the rejected sync promise

                      function relative

                      relative: (from: string, to: string) => string;
                      • JSDoc

                      function resetInstrumentationHandlers

                      resetInstrumentationHandlers: () => void;
                      • Reset all instrumentation handlers. This can be used by tests to ensure we have a clean slate of instrumentation handlers.

                      function resolve

                      resolve: (...args: string[]) => string;
                      • JSDoc

                      function resolvedSyncPromise

                      resolvedSyncPromise: {
                      (): PromiseLike<void>;
                      <T>(value: T | PromiseLike<T>): PromiseLike<T>;

                        function safeJoin

                        safeJoin: (input: any[], delimiter?: string) => string;
                        • Join values in array

                          Parameter input

                          array of values to be joined together

                          Parameter delimiter

                          string to be placed in-between values


                          Joined values

                        function serializeEnvelope

                        serializeEnvelope: (
                        envelope: Envelope,
                        textEncoder?: TextEncoderInternal
                        ) => string | Uint8Array;
                        • Serializes an envelope.

                        function severityFromString

                        severityFromString: (level: Severity | SeverityLevel | string) => Severity;
                        • Converts a string-based level into a member of the deprecated Severity enum.

                          Parameter level

                          String representation of Severity




                          severityFromString is deprecated. Please use severityLevelFromString instead.

                        function severityLevelFromString

                        severityLevelFromString: (level: SeverityLevel | string) => SeverityLevel;
                        • Converts a string-based level into a SeverityLevel, normalizing it along the way.

                          Parameter level

                          String representation of desired SeverityLevel.


                          The SeverityLevel corresponding to the given string, or 'log' if the string isn't a valid level.

                        function snipLine

                        snipLine: (line: string, colno: number) => string;
                        • This is basically just trim_line from https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67

                          Parameter str

                          An object that contains serializable values

                          Parameter max

                          Maximum number of characters in truncated string


                          string Encoded

                        function stackParserFromStackParserOptions

                        stackParserFromStackParserOptions: (
                        stackParser: StackParser | StackLineParser[]
                        ) => StackParser;
                        • Gets a stack parser implementation from Options.stackParser

                          See Also

                          • Options

                            If options contains an array of line parsers, it is converted into a parser

                        function stringMatchesSomePattern

                        stringMatchesSomePattern: (
                        testString: string,
                        patterns?: Array<string | RegExp>,
                        requireExactStringMatch?: boolean
                        ) => boolean;
                        • Test the given string against an array of strings and regexes. By default, string matching is done on a substring-inclusion basis rather than a strict equality basis

                          Parameter testString

                          The string to test

                          Parameter patterns

                          The patterns against which to test the string

                          Parameter requireExactStringMatch

                          If true, testString must match one of the given string patterns exactly in order to count. If false, testString will match a string pattern if it contains that pattern.


                        function stripSentryFramesAndReverse

                        stripSentryFramesAndReverse: (stack: ReadonlyArray<StackFrame>) => StackFrame[];
                        • Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the function that caused the crash is the last frame in the array.

                        function stripUrlQueryAndFragment

                        stripUrlQueryAndFragment: (urlPath: string) => string;
                        • Strip the query string and fragment off of a given URL or path (if present)

                          Parameter urlPath

                          Full URL or path, including possible query string and/or fragment


                          URL or path without query string or fragment

                        function supportsDOMError

                        supportsDOMError: () => boolean;
                        • Tells whether current environment supports DOMError objects supportsDOMError.


                          Answer to the given question.

                        function supportsDOMException

                        supportsDOMException: () => boolean;
                        • Tells whether current environment supports DOMException objects supportsDOMException.


                          Answer to the given question.

                        function supportsErrorEvent

                        supportsErrorEvent: () => boolean;
                        • Tells whether current environment supports ErrorEvent objects supportsErrorEvent.


                          Answer to the given question.

                        function supportsFetch

                        supportsFetch: () => boolean;
                        • Tells whether current environment supports Fetch API supportsFetch.


                          Answer to the given question.

                        function supportsHistory

                        supportsHistory: () => boolean;
                        • Tells whether current environment supports History API supportsHistory.


                          Answer to the given question.

                        function supportsNativeFetch

                        supportsNativeFetch: () => boolean;
                        • Tells whether current environment supports Fetch API natively supportsNativeFetch.


                          true if window.fetch is natively implemented, false otherwise

                        function supportsReferrerPolicy

                        supportsReferrerPolicy: () => boolean;
                        • Tells whether current environment supports Referrer Policy API supportsReferrerPolicy.


                          Answer to the given question.

                        function supportsReportingObserver

                        supportsReportingObserver: () => boolean;
                        • Tells whether current environment supports ReportingObserver API supportsReportingObserver.


                          Answer to the given question.

                        function timestampInSeconds

                        timestampInSeconds: () => number;
                        • Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the availability of the Performance API.

                          BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is asleep. This creates a skew between dateTimestampInSeconds and timestampInSeconds. The skew can grow to arbitrary amounts like days, weeks or months. See https://github.com/getsentry/sentry-javascript/issues/2590.

                        function timestampWithMs

                        timestampWithMs: () => number;
                        • Re-exported with an old name for backwards-compatibility. TODO (v8): Remove this


                          Use timestampInSeconds instead.

                        function tracingContextFromHeaders

                        tracingContextFromHeaders: (
                        sentryTrace: Parameters<typeof extractTraceparentData>[0],
                        baggage: Parameters<typeof baggageHeaderToDynamicSamplingContext>[0]
                        ) => {
                        traceparentData: ReturnType<typeof extractTraceparentData>;
                        dynamicSamplingContext: ReturnType<typeof baggageHeaderToDynamicSamplingContext>;
                        propagationContext: PropagationContext;
                        • Create tracing context from incoming headers.


                          Use propagationContextFromHeaders instead.

                        function truncate

                        truncate: (str: string, max?: number) => string;
                        • Truncates given string to the maximum characters count

                          Parameter str

                          An object that contains serializable values

                          Parameter max

                          Maximum number of characters in truncated string (0 = unlimited)


                          string Encoded

                        function updateRateLimits

                        updateRateLimits: (
                        limits: RateLimits,
                        { statusCode, headers }: TransportMakeRequestResponse,
                        now?: number
                        ) => RateLimits;
                        • Update ratelimits from incoming headers.

                          the updated RateLimits object.

                        function urlEncode

                        urlEncode: (object: { [key: string]: any }) => string;
                        • Encodes given object into url-friendly format

                          Parameter object

                          An object that contains serializable values


                          string Encoded

                        function uuid4

                        uuid4: () => string;
                        • UUID4 generator


                          string Generated UUID4.

                        function walk

                        walk: (
                        key: string,
                        value: unknown,
                        depth?: number,
                        maxProperties?: number,
                        memo?: MemoFunc
                        ) => Primitive | ObjOrArray<unknown>;
                        • Visits a node to perform normalization on it

                          Parameter key

                          The key corresponding to the given node

                          Parameter value

                          The node to be visited

                          Parameter depth

                          Optional number indicating the maximum recursion depth

                          Parameter maxProperties

                          Optional maximum number of properties/elements included in any single object/array

                          Parameter memo

                          Optional Memo class handling decycling

                        function watchdogTimer

                        watchdogTimer: (
                        createTimer: CreateTimerImpl,
                        pollInterval: number,
                        anrThreshold: number,
                        callback: () => void
                        ) => WatchdogReturn;
                        • A node.js watchdog timer

                          Parameter pollInterval

                          The interval that we expect to get polled at

                          Parameter anrThreshold

                          The threshold for when we consider ANR

                          Parameter callback

                          The callback to call for ANR


                          An object with poll and enabled functions WatchdogReturn

                        function winterCGHeadersToDict

                        winterCGHeadersToDict: (
                        winterCGHeaders: WebFetchHeaders
                        ) => Record<string, string>;
                        • Transforms a Headers object that implements the Web Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict. The header keys will be lower case: e.g. A "Content-Type" header will be stored as "content-type".

                        function winterCGRequestToRequestData

                        winterCGRequestToRequestData: (req: WebFetchRequest) => PolymorphicRequest;
                        • Converts a Request object that implements the Web Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the RequestData integration understands.


                        class LRUMap

                        class LRUMap<K, V> {}
                        • A simple Least Recently Used map


                        constructor(_maxSize: number);

                          property size

                          readonly size: number;
                          • Get the current size of the cache

                          method clear

                          clear: () => void;
                          • Clear all entries

                          method get

                          get: (key: K) => V | undefined;
                          • Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order

                          method keys

                          keys: () => Array<K>;
                          • Get all the keys

                          method remove

                          remove: (key: K) => V | undefined;
                          • Remove an entry and return the entry if it was in the cache

                          method set

                          set: (key: K, value: V) => void;
                          • Insert an entry and evict an older entry if we've reached maxSize

                          method values

                          values: () => Array<V>;
                          • Get all the values

                          class SentryError

                          class SentryError extends Error {}
                          • An error emitted by Sentry SDKs and related utilities.


                          constructor(message: string, logLevel?: ConsoleLevel);

                            property logLevel

                            logLevel: ConsoleLevel;

                              property message

                              message: string;

                                property name

                                name: string;
                                • Display name of this error instance.

                                class SyncPromise

                                class SyncPromise<T> implements PromiseLike<T> {}
                                • Thenable class that behaves like a Promise and follows it's interface but is not async internally


                                executor: (
                                resolve: (value?: T | PromiseLike<T> | null) => void,
                                reject: (reason?: any) => void
                                ) => void

                                  method catch

                                  catch: <TResult = never>(
                                  onrejected?: (reason: any) => TResult | PromiseLike<TResult>
                                  ) => PromiseLike<T | TResult>;
                                  • JSDoc

                                  method finally

                                  finally: <TResult>(onfinally?: (() => void) | null) => PromiseLike<TResult>;
                                  • JSDoc

                                  method then

                                  then: <TResult1 = T, TResult2 = never>(
                                  onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>,
                                  onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
                                  ) => PromiseLike<TResult1 | TResult2>;
                                  • JSDoc


                                  interface InternalGlobal

                                  interface InternalGlobal {}
                                  • Internal global with common properties and Sentry extensions

                                  property console

                                  console: Console;

                                    property navigator

                                    navigator?: {
                                    userAgent?: string;

                                      property onerror

                                      onerror?: {
                                      event: object | string,
                                      source?: string,
                                      lineno?: number,
                                      colno?: number,
                                      error?: Error
                                      ): any;
                                      __SENTRY_INSTRUMENTED__?: true;
                                      __SENTRY_LOADER__?: true;

                                        property onunhandledrejection

                                        onunhandledrejection?: {
                                        (event: unknown): boolean;
                                        __SENTRY_INSTRUMENTED__?: true;
                                        __SENTRY_LOADER__?: true;

                                          property Sentry

                                          Sentry?: {
                                          Integrations?: Integration[];

                                            property SENTRY_DSN

                                            SENTRY_DSN?: string;

                                              property SENTRY_ENVIRONMENT

                                              SENTRY_ENVIRONMENT?: string;

                                                property SENTRY_RELEASE

                                                SENTRY_RELEASE?: {
                                                id?: string;

                                                  property SENTRY_SDK_SOURCE

                                                  SENTRY_SDK_SOURCE?: SdkSource;

                                                    interface PromiseBuffer

                                                    interface PromiseBuffer<T> {}

                                                      property $

                                                      $: Array<PromiseLike<T>>;

                                                        method add

                                                        add: (taskProducer: () => PromiseLike<T>) => PromiseLike<T>;

                                                          method drain

                                                          drain: (timeout?: number) => PromiseLike<boolean>;

                                                            interface TextDecoderInternal

                                                            interface TextDecoderInternal {}

                                                              method decode

                                                              decode: (input?: Uint8Array) => string;

                                                                Type Aliases

                                                                type AddRequestDataToEventOptions

                                                                type AddRequestDataToEventOptions = {
                                                                /** Flags controlling whether each type of data should be added to the event */
                                                                include?: {
                                                                ip?: boolean;
                                                                request?: boolean | Array<(typeof DEFAULT_REQUEST_INCLUDES)[number]>;
                                                                transaction?: boolean | TransactionNamingScheme;
                                                                user?: boolean | Array<(typeof DEFAULT_USER_INCLUDES)[number]>;
                                                                /** Injected platform-specific dependencies */
                                                                deps?: {
                                                                cookie: {
                                                                parse: (cookieStr: string) => Record<string, string>;
                                                                url: {
                                                                parse: (urlStr: string) => {
                                                                query: string | null;
                                                                • Options deciding what parts of the request to use when enhancing an event

                                                                type InstrumentHandlerCallback

                                                                type InstrumentHandlerCallback = _InstrumentHandlerCallback;
                                                                • Deprecated

                                                                  Use the specific handler data types from @sentry/types instead, e.g. HandlerDataFetch, HandlerDataConsole, ...

                                                                type InstrumentHandlerType

                                                                type InstrumentHandlerType = _InstrumentHandlerType;
                                                                • Deprecated

                                                                  Use the specific handler functions instead, e.g. addConsoleInstrumentationHandler, ...

                                                                type IntegrationWithExclusionOption

                                                                type IntegrationWithExclusionOption = Integration & {
                                                                * Allow the user to exclude this integration by not returning it from a function provided as the `integrations` option
                                                                * in `Sentry.init()`. Meant to be used with default integrations, the idea being that if a user has actively filtered
                                                                * an integration out, we should be able to respect that choice if we wish.
                                                                allowExclusionByUser?: boolean;

                                                                  type MemoFunc

                                                                  type MemoFunc = [(obj: any) => boolean, (obj: any) => void];

                                                                    type RateLimits

                                                                    type RateLimits = Record<string, number>;

                                                                      type SdkSource

                                                                      type SdkSource = 'npm' | 'cdn' | 'loader';

                                                                        type TransactionNamingScheme

                                                                        type TransactionNamingScheme = 'path' | 'methodPath' | 'handler';

                                                                          type UserIntegrations

                                                                          type UserIntegrations = Integration[] | UserIntegrationsFunction;

                                                                            type UserIntegrationsFunction

                                                                            type UserIntegrationsFunction = (integrations: Integration[]) => Integration[];

                                                                              Package Files (47)

                                                                              Dependencies (1)

                                                                              Dev Dependencies (3)

                                                                              Peer Dependencies (0)

                                                                              No peer dependencies.


                                                                              To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                              You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@sentry/utils.

                                                                              • Markdown
                                                                              • HTML
                                                                                <a href="https://www.jsdocs.io/package/@sentry/utils"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>