@dynatrace/dtrum-api-types
Version:
Typescript types for the Dynatrace RUM JavaScript dtrum.* API
750 lines (703 loc) • 31.4 kB
TypeScript
/**
* @inline
* @ignore
*/
export interface ActionLeaveListener {
(actionId: number, stoptime: number, isRootAction: boolean): void;
}
/**
* @inline
* @ignore
*/
export type ActionEnterListener = (actionId: number, starttime: number, isRootAction: boolean, element?: EventTarget | string) => void;
/**
* @inline
* @ignore
*/
export interface APIPage {
/**
* The name of the new view, typically matching the location.pathname or location.hash.
*/
name: string;
/**
* The group of the new view, recommended to include dynamic placeholders of the view name.
* For example, if the view name is "/books/123", the view group should be "books/:bookId" or similar.
* If null or undefined, the Dynatrace server calculates the group based on the name.
*/
group?: string;
}
/**
* @ignore
* @inline
*/
export type PageLeaveListener = (unloadRunning: boolean) => void;
/**
* @ignore
* @inline
*/
export type AllowedMapTypes = Date | string | number;
// this is used for dtrum doc
/**
* @category API
*/
// eslint-disable-next-line @typescript-eslint/naming-convention -- dtrum is fine here
export type dtrum = DtrumApi;
/**
* @category API
*/
// eslint-disable-next-line @typescript-eslint/naming-convention -- dynatrace is fine here
export type dynatrace = DynatraceApi;
/**
* @category Custom Reporting
* @typeParam S - The type of the captured property.
*/
export interface Property<S> {
/** The value of the property. */
value: S;
/** Indicates if the property is public. If not set to true, the value will be sent as masked (dT_pv) in doNotTrack
* mode. */
public?: boolean;
}
/**
* @category Custom Reporting
*/
export interface PropertyMap<S extends AllowedMapTypes> {
/** A map of properties, keyed by string. */
[key: string]: Property<S> | S;
}
/**
* @category Custom Reporting
*/
export interface FailedProperty {
/** The key of the failed property. */
key: string;
/** The reason for the failure. */
reason: string;
}
/**
* @category Custom Reporting
*/
export interface SuccessfulProperty {
/** The key of the successfully collected property. */
key: string;
/** The value of the successfully collected property. */
value: AllowedMapTypes;
}
/**
* @category Custom Reporting
*/
export interface PropertiesSendingReport {
/** A list of properties that failed to send, with reasons. */
failedProperties: FailedProperty[];
/** A list of properties that were successfully sent. */
sentProperties: SuccessfulProperty[];
/** Additional information about the sending process. */
info: string;
}
/**
* @category Custom Reporting
*/
export interface PropertyObject {
/** A map of Java long properties. */
javaLong?: PropertyMap<number>;
/** A map of date properties. */
date?: PropertyMap<Date>;
/** A map of short string properties. */
shortString?: PropertyMap<string>;
/** A map of Java double properties. */
javaDouble?: PropertyMap<number>;
}
/**
* @category Actions
*/
export interface DtRumUserInput {
/** The target element or string that initiated the input. */
target: EventTarget | string | undefined;
/** The name of the user input. */
name: string;
/** Additional information about the input. */
info: string;
/** The title of the current document. */
title: string;
}
/**
* Provides information about call results to {@link dtrum.actionName}.
*
* @category Actions
*/
export const enum ActionNameResult {
/** Action naming was successful with the provided name. */
SUCCESS = 0,
/** The action with the provided ID was not found, or there was no currently active action. */
ACTION_NOT_FOUND = 1,
/** The provided action name was not of type string. */
INVALID_ACTION_NAME = 2,
/** The provided action ID was provided, not of type number. */
INVALID_ACTION_ID = 3
}
/**
* @category Custom Reporting
*/
export interface MetaData {
/**
* An internally used id
*
* @ignore
*/
id: string;
/**
* Specifies where the metadata is collected from, such as:
* - CSS Selector
* - JavaScript Variable
* - Cookie
* - Query String
* - JavaScript Function
*/
type: string;
/**
* Describes how the metadata can be retrieved (e.g., cookie name, CSS selector, JavaScript variable name).
*/
expression: string;
/**
* The current value for the given expression.
*/
value: string | null;
/**
* Additional information about the captured value.
*/
info?: string;
}
/**
* @inline
* @ignore
*/
export interface DtrumApi {
/**
* Enables or disables automatic action detection. Use this method when you want to manually instrument your application.
*
* @group Actions
* @see {@link enterAction}
* @see {@link leaveAction}
* @param enabled Specifies whether automatic action detection should be enabled or disabled.
*/
setAutomaticActionDetection(enabled: boolean): void;
/**
* Prevents RUM JavaScript from automatically detecting the load end event.
* The load end event must be explicitly set using {@link signalLoadEnd}.
* Call this method immediately after injecting RUM JavaScript.
*
* @group Actions
*/
setLoadEndManually(): void;
/**
* Signals that the page has finished loading.
* Use in combination with {@link setLoadEndManually} to define your own load end times.
*
* @group Actions
* @see {@link setLoadEndManually}
*/
signalLoadEnd(): void;
/**
* Reports the HTTP status code and a custom message for the response of the current page.
* For example, use this method to mark your 404 pages that respond with an HTTP status code of 200.
* This method must be called before the page's onload event finishes; otherwise, the information will be discarded.
*
* @group Custom Reporting
* @param responseCode The HTTP status code to set.
* @param message An additional informational message.
* @returns Returns false if the values were incorrect or the method was called too late; otherwise, returns true.
*/
markAsErrorPage(responseCode: number, message: string): boolean;
/**
* Reports the HTTP status code and an additional message for the response of the current XHR action.
* For example, use this method when the HTTP status code of your XHR response is 200, but the server's result indicates a failed request.
* This method must be called before the XHR action finishes and all listeners have been invoked.
*
* @group Custom Reporting
* @param responseCode The HTTP status code of the current XHR action.
* @param message An additional informational message.
* @param parentActionId The optional ID of the action to mark as failed. If not provided, the currently open action is used.
* @returns Returns false if the values were incorrect or the method was called too late; otherwise, returns true.
*/
markXHRFailed(responseCode: number, message: string, parentActionId?: number): boolean;
/**
* Forces the sending of a beacon to ensure actions are not lost.
* For example, use this method before a window unload event by adding a {@link addPageLeavingListener}.
*
* @group Lifecycle
* @see {@link addPageLeavingListener}
* @param forceSync DEPRECATED: This parameter is not used anymore and has no effect if provided.
* @param sendPreview Forces the sending of preview beacons containing actions that have not yet been closed.
* @param killUnfinished Terminates unfinished actions and sends them immediately. Handle with care, as actions might be inaccurate.
*/
sendBeacon(forceSync: boolean, sendPreview: boolean, killUnfinished: boolean): void;
/**
* Enters a new custom action. Use this method to create a custom action.<br />
* This method must be called before {@link leaveAction}, which closes the custom action.
*
* @group Actions
* @see {@link leaveAction}
* @param actionName The name of the action.
* @param actionType DEPRECATED: This parameter is not used anymore and has no effect if provided.
* @param startTime The timestamp in milliseconds. If falsy, the current time is used.
* @param sourceUrl The source URL for the action.
* @returns The ID of the created action, or 0 if the action was not created.
*/
enterAction(actionName: string, actionType?: string, startTime?: number, sourceUrl?: string): number;
/**
* Attaches a listener that is called while entering an action.<br />
* Remove the listener if not needed, or filter actions using {@link addActionProperties} to prevent sending the
* same action property for every action. Use this method to hook into the automatic action creation event to
* influence related concepts such as action naming or action properties.
*
* @group Actions
* @see {@link removeEnterActionListener}
* @see {@link actionName}
* @see {@link addActionProperties}
*/
addEnterActionListener(
/**
* The callback function to be triggered when an action is entered.
*
* @param actionId The ID of the action being entered.
* @param starttime The start time of the action.
* @param isRootAction Indicates if the action is a root action.
* @param element The element that initiated the event.
*/
listener: ActionEnterListener
): void;
/**
* Removes a previously attached listener that detects the enter action event.
*
* @group Actions
* @see {@link addEnterActionListener}
* @param listener The reference to the listener to be removed.
*/
removeEnterActionListener(
/**
* The callback function to be triggered when an action is entered.
*
* @param actionId The ID of the action being entered.
* @param starttime The start time of the action.
* @param isRootAction Indicates if the action is a root action.
* @param element The element that initiated the event.
*/
listener: ActionEnterListener
): void;
/**
* Leaves an action that was previously created using {@link enterAction}. Use this method to set the load end event
* for a custom action and complete its creation. This method must be called after {@link enterAction}.
*
* @group Actions
* @see {@link enterAction}
* @param actionId The ID of the action to leave. This must be the value returned by {@link enterAction}.
* @param stopTime The timestamp in milliseconds. Providing a stop time will force the action to stop and prevent
* the visually complete module from extending it.
* @param startTime Optional start time in milliseconds (necessary if the start time should be modified). Note that
* the start time must not be more than an hour in the past; otherwise it is ignored.
*/
leaveAction(actionId: number, stopTime?: number, startTime?: number): void;
/**
* Attaches a listener that is called when leaving an action.<br />
* Remove the listener if not needed, or filter actions using {@link addActionProperties} to prevent sending the
* same action property for every action. Use this method to hook into the out-of-the-box action closing event.
*
* @group Actions
* @see {@link removeLeaveActionListener}
* @see {@link addActionProperties}
*/
addLeaveActionListener(
/**
* The callback function to be triggered when an action is left.
*
* @param actionId The ID of the action being left.
* @param stoptime The end time of the action.
* @param isRootAction Indicates if the action is a root action.
*/
listener: ActionLeaveListener
): void;
/**
* Removes a previously attached listener that detects the leave action event.
*
* @group Actions
* @see {@link addLeaveActionListener}
*/
removeLeaveActionListener(
/**
* The callback function to be removed.
*
* @param actionId The ID of the action being left.
* @param stoptime The end time of the action.
* @param isRootAction Indicates if the action is a root action.
*/
listener: ActionLeaveListener
): void;
/**
* Adds custom {@link https://www.dynatrace.com/support/help/shortlink/user-session-properties | action properties}
* to the currently active action. <br />
* Only accepts valid java long, java double (as a string representation), Date objects, and short strings with a
* maximum length of 100-1000 characters (as configured under Application Settings). <br />
* Action properties must be defined under Application settings and use a lowercase key.
*
* @group Custom Reporting
* @see {@link sendSessionProperties}
* @param parentActionId The ID of the action.
* @param javaLong A JSON object containing key-value pairs of valid numbers.
* The values must be within the range -9223372036854776000 to 9223372036854776000.
* @param date A JSON object containing key-value pairs of JavaScript Date objects.
* @param shortString A JSON object containing key-value pairs of strings. Each string must be less than 100 characters.
* @param javaDouble A JSON object containing key-value pairs of valid floating point numbers.
* The values must be within the range -1.7976931348623157e+308 to 1.7976931348623157e+308.
* @returns A status report about the properties passed to the function. This report contains information about any
* failed properties with the reason for failure, as well as details of properties that were sent successfully,
* and a summary message regarding the total number of failed properties.
*/
addActionProperties(
parentActionId: number,
javaLong?: PropertyMap<number>,
date?: PropertyMap<Date>,
shortString?: PropertyMap<string>,
javaDouble?: PropertyMap<number>
): PropertiesSendingReport | undefined;
/**
* Reports an error to Dynatrace. Use this method when you catch errors in your application code and want to
* propagate them to Dynatrace, rather than handling them solely with your own logging. If the error is managed by
* your application, it will not be handled by the global JavaScript
* {@link https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror | onerror event handler},
* which Dynatrace uses to automatically capture JavaScript errors.
*
* @group Custom Reporting
* @param error The error to report. Any standard browser error object is supported. If the error does not
* include a stack trace, the RUM JavaScript monitoring code will attempt to generate one.
* Alternatively, you can provide your own object with the following properties: 'message',
* 'file', 'line', 'column', and 'stack'. The 'message' property is required; all other
* properties are optional.
* @param parentActionId The parent action ID. If not provided or null, the error is added to the current action.
*/
reportError(error: Error | string, parentActionId?: number): void;
/**
* Sets the
* {@link https://www.dynatrace.com/support/help/shortlink/user-tagging#user-tagging-via-javascript-api | user tag},
* which is used to identify individual users across different browsers, devices, and sessions.
*
* @group Custom Reporting
* @param value The username. This can be a name, user ID, or email address.
*/
identifyUser(value: string): void;
/**
* Adds a listener that is called when the user is leaving the page, before the RUM monitoring beacon is sent.
* Use this method to hook into the page unload event.
*
* @group Lifecycle
*/
addPageLeavingListener(
/**
* A function that will be called in case the user leaves the page.
*
* @param unloadRunning A boolean that is true if the page is currently being dismissed.
*/
listener: PageLeaveListener
): void;
/**
* Indicates the start of a user input. Every user input must be concluded by calling {@link endUserInput}.
* RUM JavaScript checks for an active user input when an XHR call or a page load occurs. If a user input is active,
* that input is marked as having triggered the user action. Use this method when a user input is not automatically detected by RUM JavaScript.
*
* @group Actions
* @see {@link endUserInput}
* @param domNode The DOM node (or a string identifier) that triggered the action (e.g., a button). Determines the
* caption for the resulting action.
* @param type The type of action (e.g., 'click', 'keypress', 'scroll').
* @param addInfo Optional additional information about the user input (e.g., key, mouse button, etc.).
* @param validTime The duration (in milliseconds) for which this user input should remain valid.
* @returns An object containing information about the user input.
*/
beginUserInput(domNode: HTMLElement | string, type: string, addInfo?: string, validTime?: number): DtRumUserInput;
/**
* Ends a user input that was started with {@link beginUserInput}.
*
* @group Actions
* @param userInputObject The user input object returned by {@link beginUserInput}.
*/
endUserInput(userInputObject: DtRumUserInput): void;
/**
* Extends or initiates actions. Use this method when you want to extend an active Load or XHR action with an unlinked XHR call, i.e., an action.
* It is particularly useful when the XHR call is asynchronous and cannot be automatically correlated with an action,
* which might otherwise cause the action to close prematurely, leading to inaccurate metrics (such as user action duration).
* This method must be called before {@link leaveXhrAction}.
*
* @group Actions
* @see {@link leaveXhrAction}
* @param type Optional information about the type of XHR (e.g., framework name).
* @param xmode XHR action creation mode:<br />
* 0 ... Extend only running XHR actions.<br />
* 1 ... Extend any running action.<br />
* 3 ... Start an action if a user input is present.
* @param xhrUrl The URL of the requested resource. This argument should always be provided. If omitted, the request will appear as "/undefined" in the waterfall.
* @returns The ID of the XHR action.
*/
enterXhrAction(type: string, xmode?: 0 | 1 | 3, xhrUrl?: string): number;
/**
* Indicates the end of an XHR action.
*
* @group Actions
* @see {@link enterXhrAction}
* @param actionId The ID of the XHR action.
* @param stopTime The stop time of the XHR action in milliseconds.
*/
leaveXhrAction(actionId: number, stopTime?: number): void;
/**
* Indicates that an XHR callback is active (e.g., XMLHttpRequest onreadystatechange) and links subsequently triggered
* XHR actions to this callback.
* For example, if an XHR callback adds a script tag to your page and triggers another XHR call, that call
* would not automatically be added to the current action. Calling this method allows the subsequent XHR call
* to be linked to its initial action. The XHR callback must be concluded with {@link leaveXhrCallback}.
*
* @group Actions
* @param actionId The ID of the action to which the callback belongs.
*/
enterXhrCallback(actionId: number): void;
/**
* Indicates the end of an XHR callback.
*
* @group Actions
* @see {@link enterXhrCallback}
* @param actionId The ID of the action to which the callback belongs.
*/
leaveXhrCallback(actionId: number): void;
/**
* Indicates the start of a load action. Frameworks often have their own load callback functions, and this method
* can be used when a framework begins loading before the 'DOMContentLoaded' event.
*
* @group Actions
*/
signalOnLoadStart(): void;
/**
* Instructs RUM JavaScript to wait for an additional call to {@link signalOnLoadEnd} before closing the 'onload'
* action. Note: The load action will only use the provided load end event correctly if {@link signalOnLoadEnd} is
* called afterward.
*
* @group Actions
* @see {@link setLoadEndManually}
*/
incrementOnLoadEndMarkers(): void;
/**
* Indicates the end of a load action. This method requires that {@link incrementOnLoadEndMarkers} has been called beforehand.
* The action is closed after the final call to {@link signalOnLoadEnd}.
*
* @group Actions
* @see {@link signalOnLoadStart}
*/
signalOnLoadEnd(): void;
/**
* Sets the name of the currently active action, or the action corresponding to the provided ID.
*
* @group Actions
* @param actionName The new name for the action.
* @param actionId The ID of the action to update. If omitted, the currently active action is updated.
* @returns An {@link ActionNameResult} indicating whether the update was successful.
*/
actionName(actionName: string, actionId?: number): ActionNameResult;
/**
* Immediately ends the current session.
*
* @group Lifecycle
*/
endSession(): void;
/**
* Returns the current time in milliseconds using the most accurate method available.
*
* @group Utilities
* @returns The current time in milliseconds.
*/
now(): number;
/**
* Enables RUM JavaScript if it was previously disabled via the
* {@link https://www.dynatrace.com/support/help/shortlink/configure-rum-privacy#opt-in-mode | opt-in mode}.
* Use this method in conjunction with a user consent tool to enable RUM monitoring once consent has been provided.
*
* @group Lifecycle
* @see {@link disable}
*/
enable(): void;
/**
* Disables RUM JavaScript and removes all cookies if it was previously enabled with {@link enable}, thereby activating
* the {@link https://www.dynatrace.com/support/help/shortlink/configure-rum-privacy#opt-in-mode | opt-in mode}.
* Use this method along with a user consent tool to disable RUM monitoring when consent is not provided.
*
* @group Lifecycle
* @see {@link enable}
*/
disable(): void;
/**
* Adds a listener that is triggered when the current visit times out and before a new visit ID is generated.
*
* @group Lifecycle
* @param listener The listener function to add, which receives the current visit ID and a boolean indicating if a
* new visit will start due to timeout.
*/
addVisitTimeoutListener(listener: (
/**
* The timed out visit ID.
*/
visitId: string,
/**
* True if a new visit will start due to timeout.
*/
newVisitAfterTimeout: boolean
) => void): void;
/**
* Enables session replay.
*
* @group Lifecycle
* @param ignoreCostControl If true, enables session replay regardless of the cost control configuration.
*/
enableSessionReplay(ignoreCostControl: boolean): void;
/**
* Disables session replay.
*
* @group Lifecycle
*/
disableSessionReplay(): void;
/**
* Retrieves and evaluates metadata for the page, which can be used for troubleshooting RUM monitoring.
*
* @group Custom Reporting
* @returns An array of metadata objects, each containing an id, type, expression, the captured value, and an
* optional failure reason.
*/
getAndEvaluateMetaData(): MetaData[];
/**
* Re-enables persistent values if they were previously disabled by calling {@link disablePersistentValues}.
* Use this method when you want to resume monitoring returning users.
*
* @group Lifecycle
*/
enablePersistentValues(): void;
/**
* Removes all persistent values and disables any functionality that would recreate them. Note that this must be
* called on every page, as it erases persistent RUM monitoring data, including the information that prevents
* persistent data from being stored.<br />
* Use this method when you want to disable monitoring of returning users.
* For more information, see {@link https://www.dynatrace.com/support/help/shortlink/cookies#cookie-storage | cookie storage}.
*
* @group Lifecycle
* @param remember If true, the configuration state is saved in local storage so that it persists across page loads.
*/
disablePersistentValues(remember: boolean): void;
// eslint-disable-next-line @dynatrace/dem-eslint-rules/jsagent-changelog-sprint-annotation -- apparently unused since 2018
/**
* @deprecated
* @ignore
*/
registerPreDiffMethod(method: (diff: string) => string): void;
/**
* Sends {@link https://www.dynatrace.com/support/help/shortlink/user-session-properties | session properties} on a beacon
* currently only accepts valid java long, java double (as a string representation), Date objects, and short strings of
* a maximum length of 100-1000 characters (as configured under Application Settings). <br />
* NOTE: session properties need to have a lower case key! <br />
*
* Make sure to first define session properties under Application settings before making this API call.
*
* @group Custom Reporting
* @see {@link addActionProperties} is related and works similarly.
* @param javaLongOrObject A JSON object containing key-value pairs of valid numbers.
* The values must be within the range -9223372036854776000 to 9223372036854776000.
* @param date A JSON object containing key-value pairs of JavaScript Date objects.
* @param shortString A JSON object containing key-value pairs of strings. Each string must be less than 100 characters.
* @param javaDouble A JSON object containing key-value pairs of valid floating point numbers.
* The values must be within the range -1.7976931348623157e+308 to 1.7976931348623157e+308.
* @returns A status report about the properties passed to the function. This report contains information about any
* failed properties with the reason for failure, as well as details of properties that were sent successfully,
* and a summary message regarding the total number of failed properties.
*/
sendSessionProperties(
javaLongOrObject?: PropertyMap<number> | PropertyObject,
date?: PropertyMap<Date>,
shortString?: PropertyMap<string>,
javaDouble?: PropertyMap<number>
): PropertiesSendingReport | undefined;
/**
* Reports {@link https://www.dynatrace.com/support/help/shortlink/configure-application-errors#configure-custom-errors | custom errors}
* to Dynatrace. Use this method to capture custom errors, such as form validation errors, that are defined in Application settings.
*
* @group Custom Reporting
* @param key The key of the error (e.g., 'validation error').
* @param value The error value (e.g., 'Email validation failed').
* @param hint An optional hint to identify the issue, such as the content of the input element that triggered the error.
* @param parentingInfo Defines how the custom error should be attached. When a number is provided, the error is attached
* to the specified open action. When a boolean is provided and true, it is attached to the currently active action.
*/
reportCustomError(key: string, value: string, hint?: string, parentingInfo?: number | boolean): void;
/**
* Enables manual page detection. Once this method is called, RUM JavaScript will stop automatically detecting page and page group names
* and will only use the values provided via {@link setPage}.
* It is recommended to call this as early as possible.
*
* @group Custom Reporting
*/
enableManualPageDetection(): void;
/**
* Starts a new page view and reports it to the Dynatrace server.
*
* @group Custom Reporting
* @returns A negative number if starting the new page failed, or a positive number if the new page was started successfully.
* * -2: The page is being set while manual page detection is inactive (perhaps {@link enableManualPageDetection} was not called).
* * -1: The new page is the same as the previous one.
* * 1: The new page started successfully.
* * 2: The new page started during onload, meaning it is cached and will be sent with the load action.
*/
setPage(newPage: APIPage): number;
}
/**
* A valid json object which does not contain functions, undefined, Infinity or NaN as values.
* A JSONValue may only be:
* 1. primitive (string, number, boolean, null)
* 2. an array of JSONValues
* 3. another valid JSONObject
*
* @category Utilities
*/
export type JSONObject = { [k: string]: JSONValue };
/**
* @category Utilities
*/
export type Primitive = string | number | boolean | null;
/**
* @category Utilities
*/
export type JSONArray = JSONValue[];
/**
* @category Utilities
*/
export type JSONValue = JSONArray | JSONObject | Primitive;
/**
* @inline
* @ignore
*/
export interface DynatraceApi {
/**
* Send a Business Event
*
* With sendBizEvent, you can report a business event. These standalone events are being sent detached from user actions or sessions.
* Note: Business events are only supported on Dynatrace SaaS deployments currently.
*
* @example
* ```typescript
* dynatrace.sendBizEvent("type", {
* prop: "value",
* name: "biz event name",
* timestamp: 123,
* url: "www.dynatrace.com",
* "page_id": "123456789",
* "window.orientation": "diagonal"
* });
*```
*
* @param type Mandatory event type
* @param fields Must be a valid JSON object and cannot contain functions, undefined, Infinity and NaN as values, otherwise they will be replaced with null.
* `Attributes` need to be serializable using JSON.stringify.
* The resulting event will be populated with `attributes` parameter, and enriched with additional properties, thus also empty objects are valid.
*/
sendBizEvent(type: string, fields: JSONObject): void;
}