@sentry/utils

  • Version 8.20.0
  • Published
  • 1.14 MB
  • 1 dependency
  • MIT license

Install

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

Overview

Utilities for all Sentry JavaScript SDKs

Index

Variables

Functions

Classes

Interfaces

Type Aliases

Variables

variable BAGGAGE_HEADER_NAME

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

              https://www.w3.org/TR/baggage/#limits

            variable originalConsoleMethods

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

            variable SDK_VERSION

            const SDK_VERSION: string;

              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 TRACEPARENT_REGEXP

                  const TRACEPARENT_REGEXP: RegExp;

                    variable UNKNOWN_FUNCTION

                    const UNKNOWN_FUNCTION: string;

                      variable validSeverityLevels

                      const validSeverityLevels: string[];

                        Functions

                        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 addHandler

                        addHandler: (
                        type: InstrumentHandlerType,
                        handler: InstrumentHandlerCallback
                        ) => void;
                        • Add a handler function.

                        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 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

                          Parameter

                          options.include Flags to control what data is included

                          Parameter

                          options.deps Injected platform-specific dependencies

                          Returns

                          The mutated Event object

                        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

                          Returns

                          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.

                          Returns

                          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

                          Returns

                          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

                          Returns

                          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

                          Returns

                          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) => 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 createSpanEnvelopeItem

                        createSpanEnvelopeItem: (spanJson: SpanJSON) => SpanItem;
                        • Creates envelope item for a single span

                        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, dataCategory: DataCategory) => 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

                          Returns

                          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.

                          Returns

                          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

                          Returns

                          An version of the string with all special regex characters escaped

                        function eventFromMessage

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

                        function eventFromUnknownInput

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

                        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)

                          Returns

                          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[] }
                        ) => ExtractedNodeRequestData;
                        • Normalize data from the request object, accounting for framework differences.

                          Parameter req

                          The request object from which to extract data

                          Parameter

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

                          Parameter

                          options.deps Injected, platform-specific dependencies

                          Returns

                          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

                          Returns

                          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`.

                          Returns

                          void

                        function flatten

                        flatten: <T>(input: NestedArray<T>) => T[];
                        • Flattens a multi-dimensional array

                        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 generatePropagationContext

                        generatePropagationContext: () => PropagationContext;
                        • Returns a new minimal propagation context

                        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 or data-sentry-element attribute with data-sentry-component taking precendence. This attribute is added at build-time by projects that have the component name annotation plugin installed.

                          Returns

                          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

                          Returns

                          event's description

                        function getFramesFromEvent

                        getFramesFromEvent: (event: Event) => StackFrame[] | undefined;
                        • Get's stack frames from an event without needing to check for undefined properties.

                        function getFunctionName

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

                        function getGlobalSingleton

                        getGlobalSingleton: <T>(
                        name: keyof SentryCarrier,
                        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

                          Returns

                          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

                          Returns

                          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 name see: https://develop.sentry.dev/sdk/data-handling/#structuring-data

                        function getSdkMetadataForEnvelopeHeader

                        getSdkMetadataForEnvelopeHeader: (
                        metadataOrEvent?: SdkMetadata | Event
                        ) => SdkInfo | undefined;
                        • Extracts the minimal SDK info 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]

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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 isNativeFunction

                        isNativeFunction: (func: Function) => boolean;
                        • isNative checks if the given function is a native implementation

                        function isNodeEnv

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

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          A boolean representing the result.

                        function isRateLimited

                        isRateLimited: (
                        limits: RateLimits,
                        dataCategory: DataCategory,
                        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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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.

                          Returns

                          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

                          Returns

                          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

                          Returns

                          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 maybeInstrument

                        maybeInstrument: (type: InstrumentHandlerType, instrumentFn: () => void) => void;
                        • Maybe run an instrumentation function, unless it was already called.

                        function memoBuilder

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

                        function node

                        node: (getModule?: GetModuleFn) => StackLineParserFn;
                        • Node Stack line parser

                        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.

                          Returns

                          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.

                          Returns

                          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

                          Returns

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

                        function parseBaggageHeader

                        parseBaggageHeader: (
                        baggageHeader: string | string[] | number | null | undefined | boolean
                        ) => Record<string, string> | undefined;
                        • Take a baggage header and parse it into an object.

                        function parseEnvelope

                        parseEnvelope: (env: string | Uint8Array) => 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

                          Returns

                          parsed URL object

                        function propagationContextFromHeaders

                        propagationContextFromHeaders: (
                        sentryTrace: string | undefined,
                        baggage: string | number | boolean | string[] | null | undefined
                        ) => PropagationContext;
                        • Create a propagation context from incoming headers or creates a minimal new one if the headers are undefined.

                        function rejectedSyncPromise

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

                          Parameter value

                          the value to reject the promise with

                          Returns

                          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

                            Returns

                            Joined values

                          function serializeEnvelope

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

                          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.

                            Returns

                            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

                            Returns

                            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.

                            Returns

                          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

                            Returns

                            URL or path without query string or fragment

                          function supportsDOMError

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

                            Returns

                            Answer to the given question.

                          function supportsDOMException

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

                            Returns

                            Answer to the given question.

                          function supportsErrorEvent

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

                            Returns

                            Answer to the given question.

                          function supportsFetch

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

                            Returns

                            Answer to the given question.

                          function supportsHistory

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

                            Returns

                            Answer to the given question.

                          function supportsNativeFetch

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

                            Returns

                            true if window.fetch is natively implemented, false otherwise

                          function supportsReferrerPolicy

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

                            Returns

                            Answer to the given question.

                          function supportsReportingObserver

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

                            Returns

                            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 triggerHandlers

                          triggerHandlers: (type: InstrumentHandlerType, data: unknown) => void;
                          • Trigger handlers for a given instrumentation type.

                          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)

                            Returns

                            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

                            Returns

                            string Encoded

                          function uuid4

                          uuid4: () => string;
                          • UUID4 generator

                            Returns

                            string Generated UUID4.

                          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

                            Returns

                            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.

                          Classes

                          class LRUMap

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

                          constructor

                          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

                            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

                                  constructor

                                  constructor(
                                  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

                                    Interfaces

                                    interface PromiseBuffer

                                    interface PromiseBuffer<T> {}

                                      property $

                                      $: Array<PromiseLike<T>>;

                                        method add

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

                                          method drain

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

                                            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 GetModuleFn

                                            type GetModuleFn = (filename: string | undefined) => string | undefined;

                                              type InternalGlobal

                                              type InternalGlobal = {
                                              navigator?: {
                                              userAgent?: string;
                                              };
                                              console: Console;
                                              Sentry?: any;
                                              onerror?: {
                                              (
                                              event: object | string,
                                              source?: string,
                                              lineno?: number,
                                              colno?: number,
                                              error?: Error
                                              ): any;
                                              __SENTRY_INSTRUMENTED__?: true;
                                              __SENTRY_LOADER__?: true;
                                              };
                                              onunhandledrejection?: {
                                              (event: unknown): boolean;
                                              __SENTRY_INSTRUMENTED__?: true;
                                              __SENTRY_LOADER__?: true;
                                              };
                                              SENTRY_ENVIRONMENT?: string;
                                              SENTRY_DSN?: string;
                                              SENTRY_RELEASE?: {
                                              id?: string;
                                              };
                                              SENTRY_SDK_SOURCE?: SdkSource;
                                              /**
                                              * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map
                                              * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS
                                              * file.
                                              */
                                              _sentryDebugIds?: Record<string, string>;
                                              __SENTRY__: Record<Exclude<string, 'version'>, SentryCarrier> & {
                                              version?: string;
                                              } & BackwardsCompatibleSentryCarrier;
                                              /**
                                              * Raw module metadata that is injected by bundler plugins.
                                              *
                                              * Keys are `error.stack` strings, values are the metadata.
                                              */
                                              _sentryModuleMetadata?: Record<string, any>;
                                              _sentryEsmLoaderHookRegistered?: boolean;
                                              };
                                              • Internal global with common properties and Sentry extensions

                                              type MemoFunc

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

                                                type NestedArray

                                                type NestedArray<T> = Array<NestedArray<T> | T>;

                                                  type RateLimits

                                                  type RateLimits = Record<string, number>;

                                                    type SdkSource

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

                                                      type TransactionNamingScheme

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

                                                        Package Files (45)

                                                        Dependencies (1)

                                                        Dev Dependencies (2)

                                                        Peer Dependencies (0)

                                                        No peer dependencies.

                                                        Badge

                                                        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
                                                          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@sentry/utils)
                                                        • 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>