@rudderstack/analytics-js
Version:
RudderStack JavaScript SDK
1,421 lines (1,386 loc) • 46.4 kB
text/typescript
type LoggerProvider$1 = Record<Exclude<Lowercase<LogLevel>, Lowercase<'NONE'>>, (...data: any[]) => void>;
interface ILogger {
minLogLevel: number;
scope?: string;
logProvider: LoggerProvider$1;
log(...data: any[]): void;
info(...data: any[]): void;
debug(...data: any[]): void;
warn(...data: any[]): void;
error(...data: any[]): void;
setScope(scopeVal: string): void;
setMinLogLevel(logLevel: LogLevel): void;
}
type LogLevel = 'LOG' | 'INFO' | 'DEBUG' | 'WARN' | 'ERROR' | 'NONE';
type RSALogger = Pick<ILogger, 'log' | 'info' | 'debug' | 'warn' | 'error' | 'setMinLogLevel'>;
type LoggerProvider = Record<Exclude<Lowercase<LogLevel>, Lowercase<'NONE'>>, (...data: any[]) => void>;
/**
* Service to log messages/data to output provider, default is console
*/
declare class Logger implements ILogger {
minLogLevel: number;
scope?: string;
logProvider: LoggerProvider;
constructor(minLogLevel?: LogLevel, scope?: string, logProvider?: Console);
log(...data: any[]): void;
info(...data: any[]): void;
debug(...data: any[]): void;
warn(...data: any[]): void;
error(...data: any[]): void;
outputLog(logMethod: LogLevel, data: any[]): void;
setScope(scopeVal: string): void;
setMinLogLevel(logLevel: LogLevel): void;
/**
* Formats the console message using `scope` and styles
*/
formatLogData(data: any[]): any[];
}//# sourceMappingURL=Logger.d.ts.map
type Nullable<T> = T | null;
/**
* Represents a generic object in the APIs
* Use for parameters like properties, traits etc.
*/
type ApiObject = {
[index: string]: string | number | boolean | ApiObject | null | Date | (string | number | boolean | null | Date | ApiObject | undefined)[] | undefined;
};
type DestinationIntgConfig = boolean | undefined | ApiObject;
/**
* Represents the integration options object
* Example usages:
* integrationOptions { All: false, "Google Analytics": true, "Braze": true}
* integrationOptions { All: true, "Chartbeat": false, "Customer.io": false}
* integrationOptions { All: true, "GA4": { "clientId": "1234" }, "Google Analytics": false }
*/
type IntegrationOpts = {
All?: boolean;
[index: string]: DestinationIntgConfig;
};
type Traits = Nullable<ApiObject>;
type ApiCallback = (data?: any) => void;
/**
* Represents the options parameter in the APIs
*/
type ApiOptions = {
integrations?: IntegrationOpts;
anonymousId?: string;
originalTimestamp?: string;
[index: string]: string | number | boolean | ApiObject | null | Date | (string | number | boolean | ApiObject)[] | undefined;
};
type APIEvent = {
type: RudderEventType;
category?: string;
name?: string;
properties?: Nullable<ApiObject>;
options?: Nullable<ApiOptions>;
callback?: () => void;
userId?: Nullable<string>;
traits?: Nullable<ApiObject>;
to?: string;
from?: string;
groupId?: Nullable<string>;
};
type RudderEventType = 'page' | 'track' | 'identify' | 'alias' | 'group';
interface ExtensionPoint {
[lifeCycleName: string]: (...args: any[]) => unknown;
}
/**
* ExtensionPoint can be nested, e.g. 'sdk.initialize.phase1'
* When index signature is provided, every key have to match the type, the types
* for 'name', 'deps', and 'initialize' is added as index signature.
*/
interface ExtensionPlugin {
name: string;
initialize?: (state?: any) => void;
deps?: string[];
[key: string]: string | (() => void) | ExtensionPoint | ((...args: any[]) => unknown) | string[] | undefined;
}
type PluginEngineConfig = {
throws?: boolean | RegExp;
};
interface IPluginEngine {
plugins: ExtensionPlugin[];
byName: Record<string, ExtensionPlugin>;
cache: Record<string, ExtensionPlugin[]>;
config: PluginEngineConfig;
register: (plugin: ExtensionPlugin, state?: Record<string, any>) => void;
unregister: (name: string) => void;
getPlugin: (name: string) => ExtensionPlugin | undefined;
getPlugins: (extPoint?: string) => ExtensionPlugin[];
invoke: <T = any>(extPoint?: string, allowMultiple?: boolean, ...args: any[]) => Nullable<T>[];
invokeSingle: <T = any>(extPoint?: string, ...args: any[]) => Nullable<T>;
invokeMultiple: <T = any>(extPoint?: string, ...args: any[]) => Nullable<T>[];
}
interface IPluginsManager {
engine: IPluginEngine;
init(): void;
attachEffects(): void;
setActivePlugins(): void;
invokeMultiple<T = any>(extPoint?: string, ...args: any[]): Nullable<T>[];
invokeSingle<T = any>(extPoint?: string, ...args: any[]): Nullable<T>;
register(plugins: ExtensionPlugin[]): void;
}
type PluginName = 'BeaconQueue' | 'CustomConsentManager' | 'DeviceModeDestinations' | 'DeviceModeTransformation' | 'ExternalAnonymousId' | 'GoogleLinker' | 'IubendaConsentManager' | 'KetchConsentManager' | 'NativeDestinationQueue' | 'OneTrustConsentManager' | 'StorageEncryption' | 'StorageEncryptionLegacy' | 'StorageMigrator' | 'XhrQueue';
type UserSessionKey = 'userId' | 'userTraits' | 'anonymousId' | 'groupId' | 'groupTraits' | 'initialReferrer' | 'initialReferringDomain' | 'sessionInfo' | 'authToken';
type StorageEncryptionVersion = 'legacy' | 'v3';
type StorageType = 'cookieStorage' | 'localStorage' | 'memoryStorage' | 'sessionStorage' | 'none';
type StorageEncryption = {
version: StorageEncryptionVersion;
};
type LoadOptionStorageEntry = {
type: StorageType;
};
type StorageOpts = {
encryption?: StorageEncryption;
migrate?: boolean;
type?: StorageType;
cookie?: CookieOptions;
entries?: {
[key in UserSessionKey]?: LoadOptionStorageEntry;
};
};
type CookieOptions = {
maxage?: number;
expires?: Date;
path?: string;
domain?: string;
samesite?: string;
secure?: boolean;
};
type CookieSameSite = 'Strict' | 'Lax' | 'None';
type OneTrustCookieCategory = {
oneTrustCookieCategory: string;
};
type ConsentManagement = {
deniedConsentIds: Consents;
allowedConsentIds: Consents;
provider: ConsentManagementProvider;
};
type ConsentManagementMetadata = {
providers: ConsentManagementProviderMetadata[];
};
type ConsentManagementProviderMetadata = {
provider: ConsentManagementProvider;
resolutionStrategy: ConsentResolutionStrategy;
};
type ConsentManagementProvider = 'iubenda' | 'oneTrust' | 'ketch' | 'custom';
type ConsentResolutionStrategy = 'and' | 'or';
type Consents = string[];
type ConsentManagementOptions = {
enabled?: boolean;
provider?: ConsentManagementProvider;
allowedConsentIds?: Consents;
deniedConsentIds?: Consents;
};
type KetchConsentPurpose = {
purpose: string;
};
type IubendaConsentPurpose = {
purpose: string;
};
type ConsentOptions = {
storage?: StorageOpts;
consentManagement?: ConsentManagementOptions;
integrations?: IntegrationOpts;
discardPreConsentEvents?: boolean;
sendPageEvent?: boolean;
trackConsent?: boolean;
};
type UaChTrackLevel = 'none' | 'default' | 'full';
/**
* Represents the options parameter for anonymousId
*/
type AnonymousIdOptions = {
autoCapture?: {
enabled?: boolean;
source?: string;
};
};
type SessionCutOffOptions = {
enabled: boolean;
duration?: number;
};
type SessionOpts = {
autoTrack?: boolean;
timeout?: number;
cutOff?: SessionCutOffOptions;
};
type EventMapping = {
from: string;
to: string;
};
type Conversion = {
conversionLabel: string;
name: string;
};
type EventFilteringOption = 'disable' | 'whitelistedEvents' | 'blacklistedEvents';
/**
* Represents the beacon queue options parameter in loadOptions type
*/
type BeaconQueueOpts = {
maxItems?: number;
flushQueueInterval?: number;
};
type EventsTransportMode = 'xhr' | 'beacon';
type BatchOpts = {
enabled: boolean;
maxItems?: number;
maxSize?: number;
flushInterval?: number;
};
/**
* Represents the queue options parameter in loadOptions type
*/
type QueueOpts = {
maxRetryDelay?: number;
minRetryDelay?: number;
backoffFactor?: number;
backoffJitter?: number;
maxAttempts?: number;
maxItems?: number;
batch?: BatchOpts;
timerScaleFactor?: number;
};
/**
* Represents the destinations queue options parameter in loadOptions type
*/
type DestinationsQueueOpts = {
maxItems?: number;
};
type OnLoadedCallback = (analytics: any) => void;
type DeliveryType = 'immediate' | 'buffer';
type StorageStrategy = 'none' | 'session' | 'anonymousId';
type PreConsentStorageOptions = {
strategy: StorageStrategy;
};
type PreConsentEventsOptions = {
delivery: DeliveryType;
};
type PreConsentOptions = {
enabled: boolean;
storage?: PreConsentStorageOptions;
events?: PreConsentEventsOptions;
};
declare enum PageLifecycleEvents {
UNLOADED = "Page Unloaded"
}
type PageLifecycleOptions = {
enabled: boolean;
events?: PageLifecycleEvents[];
options?: ApiOptions;
};
type AutoTrackOptions = {
enabled?: boolean;
options?: ApiOptions;
pageLifecycle?: PageLifecycleOptions;
};
/**
* Represents the source configuration override options for destinations
*/
type SourceConfigurationOverrideDestination = {
id: string;
enabled?: boolean;
config?: Record<string, any>;
};
type SourceConfigurationOverride = {
destinations: SourceConfigurationOverrideDestination[];
};
/**
* Represents the options parameter in the load API
*/
type LoadOptions = {
logLevel?: LogLevel;
integrations?: IntegrationOpts;
configUrl?: string;
queueOptions?: QueueOpts;
loadIntegration?: boolean;
sessions?: SessionOpts;
secureCookie?: boolean;
destSDKBaseURL?: string;
pluginsSDKBaseURL?: string;
useBeacon?: boolean;
beaconQueueOptions?: BeaconQueueOpts;
destinationsQueueOptions?: DestinationsQueueOpts;
anonymousIdOptions?: AnonymousIdOptions;
setCookieDomain?: string;
sameSiteCookie?: CookieSameSite;
/**
* @deprecated Integrations version are locked by default. We do not recommend using this option.
*/
lockIntegrationsVersion?: boolean;
/**
* @deprecated Plugins version are locked by default. We do not recommend using this option.
*/
lockPluginsVersion?: boolean;
polyfillIfRequired?: boolean;
onLoaded?: OnLoadedCallback;
uaChTrackLevel?: UaChTrackLevel;
getSourceConfig?: () => string | ApiObject | Promise<ApiObject> | Promise<string>;
sendAdblockPage?: boolean;
sendAdblockPageOptions?: ApiOptions;
plugins?: Nullable<PluginName[]>;
polyfillURL?: string;
useGlobalIntegrationsConfigInEvents?: boolean;
bufferDataPlaneEventsUntilReady?: boolean;
dataPlaneEventsBufferTimeout?: number;
storage?: StorageOpts;
preConsent?: PreConsentOptions;
transportMode?: EventsTransportMode;
consentManagement?: ConsentManagementOptions;
sameDomainCookiesOnly?: boolean;
externalAnonymousIdCookieName?: string;
useServerSideCookies?: boolean;
dataServiceEndpoint?: string;
autoTrack?: AutoTrackOptions;
sourceConfigurationOverride?: SourceConfigurationOverride;
};
type Address = {
city?: string;
City?: string;
country?: string;
Country?: string;
postalCode?: string;
state?: string;
State?: string;
street?: string;
};
type Company = {
name?: string;
id?: string;
industry?: string;
employee_count?: string;
plan?: string;
};
/**
* Represents a traits object in the Identify API
*/
type IdentifyTraits = {
id?: string;
userId?: string;
firstName?: string;
firstname?: string;
first_name?: string;
lastName?: string;
lastname?: string;
last_name?: string;
name?: string;
Name?: string;
age?: number;
email?: string;
Email?: string;
'E-mail'?: string;
phone?: string;
address?: string | Address;
birthday?: string;
company?: Company;
createdAt?: string;
description?: string;
gender?: string;
title?: string;
username?: string;
website?: string;
avatar?: string;
zip?: string | number;
state?: string;
State?: string;
dob?: string;
employed?: string | boolean;
education?: string;
married?: string | boolean;
customerType?: string | number;
euConsent?: string;
euConsentMessage?: string;
newEmail?: string;
tags?: string | string[];
removeTags?: string | string[];
prospect?: string | boolean;
doubleOptin?: string | boolean;
event_id?: string;
organization?: string;
region?: string;
anonymous?: string | boolean;
country?: string;
custom?: string;
ip?: string;
privateAttributeNames?: any;
secondary?: any;
customPageId?: string;
isRudderEvents?: boolean;
optOutType?: boolean | string | number;
groupType?: string | number;
anonymousId?: string | number;
ip_address?: string;
number?: string | number;
[index: string]: string | number | boolean | ApiObject | null | Date | (string | number | boolean | null | Date | ApiObject)[] | undefined;
};
type AppInfo = {
readonly name: string;
readonly version: string;
readonly namespace: string;
readonly installType: string;
};
type LibraryInfo = {
readonly name: string;
readonly version: string;
readonly snippetVersion?: string;
};
type OSInfo = {
readonly name: string;
readonly version: string;
};
type ScreenInfo = {
readonly density: number;
readonly width: number;
readonly height: number;
readonly innerWidth: number;
readonly innerHeight: number;
};
type UTMParameters = Record<string, string>;
type PageLifecycle = {
pageViewId: string;
};
type AutoTrack = {
page: PageLifecycle;
};
type RudderContext = {
[index: string]: string | number | boolean | ApiObject | UADataValues | Nullable<string> | (string | number | boolean | ApiObject)[] | undefined;
traits?: Nullable<ApiObject>;
sessionId?: number;
sessionStart?: boolean;
consentManagement?: ConsentManagement;
'ua-ch'?: UADataValues;
app: AppInfo;
library: LibraryInfo;
userAgent: Nullable<string>;
os: OSInfo;
locale: Nullable<string>;
screen: ScreenInfo;
campaign?: UTMParameters;
trulyAnonymousTracking?: boolean;
timezone: string;
autoTrack?: AutoTrack;
};
type RudderEvent = {
type: RudderEventType;
channel: string;
anonymousId: string;
context: RudderContext;
originalTimestamp: string;
integrations: IntegrationOpts;
messageId: string;
event: Nullable<string>;
previousId?: string;
userId?: Nullable<string>;
sentAt?: string;
properties?: Nullable<ApiObject>;
name?: Nullable<string>;
category?: Nullable<string>;
traits?: Traits;
groupId?: Nullable<string>;
};
type RSAEvent = {
message: RudderEvent;
};
type DestinationConnectionMode = 'hybrid' | 'cloud' | 'device';
type DestinationEvent = {
eventName: string;
};
type ConsentsConfig = {
consent: string;
};
type ConsentManagementProviderConfig = {
provider: ConsentManagementProvider;
consents: ConsentsConfig[];
resolutionStrategy: string | undefined;
};
/**
* The common configuration properties for all device
* and hybrid mode supported destinations.
*/
type BaseDestinationConfig = {
blacklistedEvents: DestinationEvent[];
whitelistedEvents: DestinationEvent[];
eventFilteringOption: EventFilteringOption;
consentManagement: ConsentManagementProviderConfig[];
connectionMode: DestinationConnectionMode;
};
type DestinationConfig = BaseDestinationConfig & {
iubendaConsentPurposes?: IubendaConsentPurpose[];
oneTrustCookieCategories?: OneTrustCookieCategory[];
ketchConsentPurposes?: KetchConsentPurpose[];
clickEventConversions?: Conversion[];
pageLoadConversions?: Conversion[];
conversionID?: string;
conversionLinker?: boolean;
disableAdPersonalization?: boolean;
dynamicRemarketing?: boolean;
sendPageView?: boolean;
defaultPageConversion?: string;
enableConversionEventsFiltering?: boolean;
trackConversions?: boolean;
trackDynamicRemarketing?: boolean;
tagID?: string;
advertiserId?: string;
partnerId?: string;
measurementId?: string;
capturePageView?: string;
useNativeSDKToSend?: boolean;
extendPageViewParams?: boolean;
eventMappingFromConfig?: EventMapping[];
appKey?: string;
dataCenter?: string;
enableBrazeLogging?: boolean;
enableNestedArrayOperations?: boolean;
enableSubscriptionGroupInGroupCall?: boolean;
supportDedup?: boolean;
trackAnonymousUser?: boolean;
serverUrl?: string;
containerID?: string;
fs_debug_mode?: boolean;
fs_org?: boolean;
siteID?: string;
[key: string]: any;
};
type AnalyticsIdentifyMethod = {
(userId: string, traits?: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(userId: string, traits?: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
(userId: string, callback?: ApiCallback): void;
(traits: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(traits: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
};
type AnalyticsPageMethod = {
(category: string, name: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(category: string, name: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
(category: string, name: string, callback?: ApiCallback): void;
(name: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(name: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
(name: string, callback?: ApiCallback): void;
(properties: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(properties: Nullable<ApiObject>, callback?: ApiCallback): void;
(callback?: ApiCallback): void;
};
type AnalyticsTrackMethod = {
(event: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(event: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
(event: string, callback?: ApiCallback): void;
};
type AnalyticsGroupMethod = {
(groupId: string, traits?: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(groupId: string, traits?: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
(groupId: string, callback?: ApiCallback): void;
(traits: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(traits: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
};
type AnalyticsAliasMethod = {
(to: string, from?: string, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(to: string, from?: string, callback?: ApiCallback): void;
(to: string, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
(to: string, callback?: ApiCallback): void;
};
interface IRudderAnalytics<T = any> {
analyticsInstances: Record<string, T>;
defaultAnalyticsKey: string;
logger: ILogger;
/**
* Set the writeKey of the analytics instance that should be default
*/
setDefaultInstanceKey(writeKey: string, autoSet: boolean): void;
/**
* Get the instance of Analytics that is set as default
*/
getAnalyticsInstance(writeKey?: string): T | undefined;
/**
* Trigger load event in buffer queue if exists
*/
triggerBufferedLoadEvent(): void;
/**
* Call control pane to get client configs
*/
load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial<LoadOptions>): void;
/**
* To register a callback for SDK ready state
*/
ready(callback: ApiCallback): void;
/**
* To record a page view event
*/
page: AnalyticsPageMethod;
/**
* To record a user track event
*/
track: AnalyticsTrackMethod;
/**
* To record a user identification event
*/
identify: AnalyticsIdentifyMethod;
/**
* To record a user alias event
*/
alias: AnalyticsAliasMethod;
/**
* To record a user group event
*/
group: AnalyticsGroupMethod;
/**
* Clear user information
*
* @param resetAnonymousId optionally clears anonymousId as well
*/
reset(resetAnonymousId?: boolean): void;
/**
* To get anonymousId set in the SDK
*
* @param options options for anonymousId
*/
getAnonymousId(options?: AnonymousIdOptions): string | undefined;
/**
* To set anonymousId
*
* @param anonymousId custom anonymousId value
* @param rudderAmpLinkerParam AMP Linker ID string
*/
setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string): void;
/**
* To get userId set in the SDK
*/
getUserId(): Nullable<string> | undefined;
/**
* To get user traits set in the SDK
*/
getUserTraits(): Nullable<ApiObject> | undefined;
/**
* To get groupId set in the SDK
*/
getGroupId(): Nullable<string> | undefined;
/**
* To get group traits set in the SDK
*/
getGroupTraits(): Nullable<ApiObject> | undefined;
/**
* To manually start user session in the SDK
*/
startSession(sessionId?: number): void;
/**
* To manually end user session in the SDK
*/
endSession(): void;
/**
* To set authorization token
* @param token token value
*/
setAuthToken(token: string): void;
/**
* To fetch the current sessionId
*/
getSessionId(): Nullable<number> | undefined;
/**
* To provide consent
* @param options Consent API options
*/
consent(options?: ConsentOptions): void;
/**
* To add a custom integration for a custom destination
* @param destinationId The ID of the custom destination from the RudderStack dashboard
* @param integration The custom integration object
*/
addCustomIntegration(destinationId: string, integration: RSACustomIntegration): void;
}
type RSAnalytics = Pick<IRudderAnalytics, 'track' | 'page' | 'identify' | 'group' | 'alias' | 'getAnonymousId' | 'getUserId' | 'getUserTraits' | 'getGroupId' | 'getGroupTraits' | 'getSessionId'>;
/**
* Type for the custom destination configuration object
* For now, it is the same as the base destination config
* but in the future, it can be extended to include more properties
*/
type CustomDestinationConfig = BaseDestinationConfig & {};
/**
* Type for the custom integration to be used in addCustomIntegration API
* Defines the contract that all custom integrations must implement
*/
type RSACustomIntegration = {
/**
* Initialize the integration
* @param destinationConfig - The custom destination configuration object
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @optional
*/
init?: (destinationConfig: CustomDestinationConfig, analytics: RSAnalytics, logger: RSALogger) => void;
/**
* Check if the integration is ready to process events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @returns boolean indicating whether the integration is ready
* @required
*/
isReady: (analytics: RSAnalytics, logger: RSALogger) => boolean;
/**
* Process track events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @param event - The track event payload to process
* @optional
*/
track?: (analytics: RSAnalytics, logger: RSALogger, event: RSAEvent) => void;
/**
* Process page events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @param event - The page event payload to process
* @optional
*/
page?: (analytics: RSAnalytics, logger: RSALogger, event: RSAEvent) => void;
/**
* Process identify events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @param event - The identify event payload to process
* @optional
*/
identify?: (analytics: RSAnalytics, logger: RSALogger, event: RSAEvent) => void;
/**
* Process group events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @param event - The group event payload to process
* @optional
*/
group?: (analytics: RSAnalytics, logger: RSALogger, event: RSAEvent) => void;
/**
* Process alias events
* @param analytics - The RudderStack analytics instance
* @param logger - The logger instance for this integration
* @param event - The alias event payload to process
* @optional
*/
alias?: (analytics: RSAnalytics, logger: RSALogger, event: RSAEvent) => void;
};
type SDKError = unknown | Error | ErrorEvent | Event | PromiseRejectionEvent;
type ErrorInfo = {
error: SDKError;
context: string;
customMessage?: string;
errorType?: ErrorType;
groupingHash?: string | SDKError;
category?: 'sdk' | 'integrations';
};
interface IErrorHandler {
httpClient: IHttpClient;
logger: ILogger;
init(): void;
onError(errorInfo: ErrorInfo): Promise<void>;
leaveBreadcrumb(breadcrumb: string): void;
}
declare enum ErrorType {
HANDLEDEXCEPTION = "handledException",
UNHANDLEDEXCEPTION = "unhandledException",
UNHANDLEDREJECTION = "unhandledPromiseRejection"
}
interface IRequestConfig {
url: string;
options?: Partial<IXHRRequestOptions>;
isRawResponse?: boolean;
timeout?: number;
}
type ResponseDetails = {
response: string;
error?: Error;
timedOut?: boolean;
xhr?: XMLHttpRequest;
options: IXHRRequestOptions;
};
type AsyncRequestCallback<T> = (data?: T | string | undefined, details?: ResponseDetails) => void;
interface IAsyncRequestConfig<T> extends IRequestConfig {
callback?: AsyncRequestCallback<T>;
}
interface IXHRRequestOptions {
method: HTTPClientMethod;
url: string;
headers: Record<string, string | undefined>;
data?: XMLHttpRequestBodyInit;
sendRawData?: boolean;
withCredentials?: boolean;
}
type HTTPClientMethod = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';
interface IHttpClient {
errorHandler?: IErrorHandler;
logger: ILogger;
basicAuthHeader?: string;
getData<T = any>(config: IRequestConfig): Promise<{
data: T | string | undefined;
details?: ResponseDetails;
}>;
getAsyncData<T = any>(config: IAsyncRequestConfig<T>): void;
setAuthHeader(value: string, noBto?: boolean): void;
resetAuthHeader(): void;
init(errorHandler: IErrorHandler): void;
}
interface IExternalSourceLoadConfig {
url: string;
id: string;
callback?(id: string, error?: SDKError): void;
async?: boolean;
timeout?: number;
extraAttributes?: Record<string, string>;
}
interface IExternalSrcLoader {
logger: ILogger;
timeout: number;
loadJSFile(config: IExternalSourceLoadConfig): void;
}
type StoreId = string;
interface IStoreConfig {
name: string;
id: StoreId;
isEncrypted?: boolean;
validKeys?: Record<string, string>;
noCompoundKey?: boolean;
errorHandler: IErrorHandler;
logger: ILogger;
type?: StorageType;
}
interface IStoreManager {
stores?: Record<StoreId, IStore>;
isInitialized?: boolean;
errorHandler: IErrorHandler;
logger: ILogger;
init(): void;
initializeStorageState(): void;
setStore(storeConfig: IStoreConfig): IStore;
getStore(id: StoreId): IStore | undefined;
}
interface IStore {
id: string;
name: string;
isEncrypted: boolean;
validKeys: Record<string, string>;
engine: IStorage;
originalEngine: IStorage;
noKeyValidation?: boolean;
noCompoundKey?: boolean;
errorHandler: IErrorHandler;
logger: ILogger;
pluginsManager: IPluginsManager;
createValidKey(key: string): string | undefined;
swapQueueStoreToInMemoryEngine(): void;
set(key: string, value: any): void;
get<T = any>(key: string): Nullable<T>;
remove(key: string): void;
getOriginalEngine(): IStorage;
decrypt(value?: Nullable<string>): Nullable<string>;
encrypt(value: any): string;
crypto(value: string, mode: 'encrypt' | 'decrypt'): string;
onError(error: unknown): void;
}
interface IStorage extends Storage {
configure?(options?: StorageOptions): void;
keys(): string[];
isEnabled?: boolean;
}
type StorageOptions = Partial<ICookieStorageOptions | ILocalStorageOptions | IInMemoryStorageOptions>;
interface ICookieStorageOptions extends CookieOptions {
samesite?: CookieSameSite;
domain?: string;
secure?: boolean;
enabled?: boolean;
sameDomainCookiesOnly?: boolean;
}
interface ILocalStorageOptions {
enabled?: boolean;
}
interface IInMemoryStorageOptions {
enabled?: boolean;
}
type PageCallOptions = {
category?: string;
name?: string;
properties?: Nullable<ApiObject>;
options?: Nullable<ApiOptions>;
callback?: ApiCallback;
};
type TrackCallOptions = {
name: string;
properties?: Nullable<ApiObject>;
options?: Nullable<ApiOptions>;
callback?: ApiCallback;
};
type IdentifyCallOptions = {
userId?: Nullable<string>;
traits?: Nullable<IdentifyTraits>;
options?: Nullable<ApiOptions>;
callback?: ApiCallback;
};
type AliasCallOptions = {
to: string;
from?: string;
options?: Nullable<ApiOptions>;
callback?: ApiCallback;
};
type GroupCallOptions = {
groupId?: Nullable<string>;
traits?: Nullable<ApiObject>;
options?: Nullable<ApiOptions>;
callback?: ApiCallback;
};
/**
* A buffer queue to serve as a store for any type of data
*/
declare class BufferQueue<T = any> {
items: T[];
constructor();
enqueue(item: T): void;
dequeue(): Nullable<T> | undefined;
isEmpty(): boolean;
size(): number;
clear(): void;
}
//# sourceMappingURL=BufferQueue.d.ts.map
/**
* Store Implementation with dedicated storage
*/
declare class Store implements IStore {
id: string;
name: string;
isEncrypted: boolean;
validKeys: Record<string, string>;
engine: IStorage;
originalEngine: IStorage;
noKeyValidation?: boolean;
noCompoundKey?: boolean;
errorHandler: IErrorHandler;
logger: ILogger;
pluginsManager: IPluginsManager;
constructor(config: IStoreConfig, engine: IStorage, pluginsManager: IPluginsManager);
/**
* Ensure the key is valid and with correct format
*/
createValidKey(key: string): string | undefined;
/**
* Switch to inMemoryEngine, bringing any existing data with.
*/
swapQueueStoreToInMemoryEngine(): void;
/**
* Set value by key.
*/
set(key: string, value: any): void;
/**
* Get by Key.
*/
get<T = any>(key: string): Nullable<T>;
/**
* Remove by Key.
*/
remove(key: string): void;
/**
* Get original engine
*/
getOriginalEngine(): IStorage;
/**
* Decrypt values
*/
decrypt(value?: Nullable<string>): Nullable<string>;
/**
* Encrypt value
*/
encrypt(value: Nullable<any>): string;
/**
* Extension point to use with encryption plugins
*/
crypto(value: Nullable<any>, mode: 'encrypt' | 'decrypt'): string;
/**
* Handle errors
*/
onError(error: unknown, customMessage?: string, groupingHash?: string): void;
}
//# sourceMappingURL=Store.d.ts.map
interface IUserSessionManager {
storeManager?: IStoreManager;
init(): void;
setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string): void;
getAnonymousId(options?: AnonymousIdOptions): string;
refreshSession(): void;
getSessionId(): Nullable<number>;
getGroupId(): Nullable<string>;
getUserId(): Nullable<string>;
setUserId(userId?: null | string): void;
setUserTraits(traits?: Nullable<ApiObject>): void;
getUserTraits(): Nullable<ApiObject>;
getGroupTraits(): Nullable<ApiObject>;
setGroupId(groupId?: Nullable<string>): void;
setGroupTraits(traits?: Nullable<ApiObject>): void;
reset(resetAnonymousId?: boolean, noNewSessionStart?: boolean): void;
start(sessionId?: number): void;
end(): void;
syncStorageDataToState(): void;
setAuthToken(token: Nullable<string>): void;
}
type StatsCollection = {
errors: {
enabled: boolean;
provider?: string;
};
metrics: {
enabled: boolean;
};
};
type DestinationDefinition = {
name: string;
displayName: string;
updatedAt: string;
};
type ConfigResponseDestinationItem = {
shouldApplyDeviceModeTransformation: boolean;
propagateEventsUntransformedOnError: boolean;
config: DestinationConfig;
updatedAt: string;
destinationDefinition: DestinationDefinition;
enabled: boolean;
id: string;
name: string;
};
type Connection = {
createdAt: string;
deleted: boolean;
destinationId: string;
enabled: boolean;
id: string;
sourceId: string;
updatedAt: string;
};
type SourceDefinition = {
category: Nullable<any>;
config: Nullable<any>;
configSchema: Nullable<any>;
createdAt: string;
displayName: string;
id: string;
name: string;
options: Nullable<any>;
uiConfig: Nullable<any>;
updatedAt: string;
};
type SourceConfigResponse = {
consentManagementMetadata?: ConsentManagementMetadata;
source: {
destinations: ConfigResponseDestinationItem[];
sourceDefinitionId: string;
transient: boolean;
updatedAt: string;
workspaceId: string;
writeKey: string;
enabled: boolean;
id: string;
liveEventsConfig: {
eventUpload: boolean;
eventUploadTS: number;
};
name: string;
secretVersion: Nullable<string>;
sourceDefinition: SourceDefinition;
config: {
statsCollection: StatsCollection;
};
connections: Connection[];
createdAt: string;
createdBy: string;
deleted: boolean;
};
};
interface IConfigManager {
httpClient: IHttpClient;
errorHandler: IErrorHandler;
logger: ILogger;
init: () => void;
getConfig: () => void;
processConfig: (response: SourceConfigResponse | string | undefined, details?: ResponseDetails) => void;
}
interface IEventManager {
init(): void;
addEvent(event: APIEvent): void;
resume(): void;
}
interface ICapabilitiesManager {
httpClient: IHttpClient;
errorHandler: IErrorHandler;
logger: ILogger;
externalSrcLoader: IExternalSrcLoader;
init(): void;
detectBrowserCapabilities(): void;
prepareBrowserCapabilities(): void;
attachWindowListeners(): void;
onReady(): void;
}
type PreloadedEventCall = Array<string | any>;
type RudderAnalyticsPreloader = {
[index: string]: (...args: any[]) => any;
};
interface IAnalytics {
preloadBuffer: BufferQueue<PreloadedEventCall>;
initialized: boolean;
httpClient: IHttpClient;
logger: ILogger;
errorHandler: IErrorHandler;
externalSrcLoader: IExternalSrcLoader;
capabilitiesManager: ICapabilitiesManager;
storeManager?: IStoreManager;
configManager?: IConfigManager;
eventManager?: IEventManager;
userSessionManager?: IUserSessionManager;
pluginsManager?: IPluginsManager;
clientDataStore?: Store;
/**
* Start application lifecycle if not already started
*/
load(writeKey: string, dataPlaneUrl?: string | Partial<LoadOptions>, loadOptions?: Partial<LoadOptions>): void;
/**
* Orchestrate the lifecycle of the application phases/status
*/
startLifecycle(): void;
/**
* Load browser polyfill if required
*/
onMounted(): void;
/**
* Prepare internal services and load configuration
*/
onBrowserCapabilitiesReady(): void;
/**
* Enqueue in buffer the events that were triggered pre SDK initialization
*/
enqueuePreloadBufferEvents(bufferedEvents: PreloadedEventCall[]): void;
/**
* Start the process of consuming the buffered events that were triggered pre SDK initialization
*/
processDataInPreloadBuffer(): void;
/**
* Assign instances for the internal services
*/
prepareInternalServices(): void;
/**
* Load configuration
*/
loadConfig(): void;
/**
* Initialize the storage and event queue
*/
onPluginsReady(): void;
/**
* Load plugins
*/
onConfigured(): void;
/**
* Trigger onLoaded callback if any is provided in config & emit initialised event
*/
onInitialized(): void;
/**
* Emit ready event
*/
onReady(): void;
/**
* Consume preloaded events buffer
*/
processBufferedEvents(): void;
/**
* Load device mode destinations
*/
loadDestinations(): void;
/**
* Invoke the ready callbacks if any exist
*/
onDestinationsReady(): void;
/**
* To register a callback for SDK ready state
*/
ready(callback: ApiCallback, isBufferedInvocation?: boolean): void;
/**
* To record a page view event
*/
page(pageOptions: PageCallOptions, isBufferedInvocation?: boolean): void;
/**
* To record a user track event
*/
track(trackCallOptions: TrackCallOptions, isBufferedInvocation?: boolean): void;
/**
* To record a user identification event
*/
identify(identifyCallOptions: IdentifyCallOptions, isBufferedInvocation?: boolean): void;
/**
* To record a user alias event
*/
alias(aliasCallOptions: AliasCallOptions, isBufferedInvocation?: boolean): void;
/**
* To record a user group event
*/
group(groupCallOptions: GroupCallOptions, isBufferedInvocation?: boolean): void;
/**
* To get anonymousId set in the SDK
*/
getAnonymousId(options?: AnonymousIdOptions): string | undefined;
/**
* To set anonymousId
*/
setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string, isBufferedInvocation?: boolean): void;
/**
* Clear user information, optionally anonymousId as well
*/
reset(resetAnonymousId?: boolean, isBufferedInvocation?: boolean): void;
/**
* To get userId set in the SDK
*/
getUserId(): Nullable<string> | undefined;
/**
* To get user traits set in the SDK
*/
getUserTraits(): Nullable<ApiObject> | undefined;
/**
* To get groupId set in the SDK
*/
getGroupId(): Nullable<string> | undefined;
/**
* To get group traits set in the SDK
*/
getGroupTraits(): Nullable<ApiObject> | undefined;
/**
* To manually start user session in the SDK
*/
startSession(sessionId?: number, isBufferedInvocation?: boolean): void;
/**
* To manually end user session in the SDK
*/
endSession(isBufferedInvocation?: boolean): void;
/**
* To fetch the current sessionId
*/
getSessionId(): Nullable<number>;
/**
* To record consent
* @param options Consent API options
*/
consent(options?: ConsentOptions, isBufferedInvocation?: boolean): void;
/**
* To set auth token
*/
setAuthToken(token: string): void;
/**
* Add a custom integration for a custom destination
* @param destinationId - Unique ID for the custom destination from the RudderStack dashboard
* @param integration - The custom integration instance implementing RSACustomIntegration
* @param isBufferedInvocation - Internal flag to indicate if this is a buffered call
*/
addCustomIntegration(destinationId: string, integration: RSACustomIntegration, isBufferedInvocation?: boolean): void;
}
declare class RudderAnalytics implements IRudderAnalytics<IAnalytics> {
static globalSingleton: Nullable<RudderAnalytics>;
analyticsInstances: Record<string, IAnalytics>;
defaultAnalyticsKey: string;
logger: Logger;
constructor();
/**
* Create an instance of the current instance that can be used
* to call a subset of methods of the current instance.
* It is typically used to expose the analytics instance to the integrations (standard and custom)
*/
createSafeAnalyticsInstance(): void;
static initializeGlobalResources(): void;
/**
* Set instance to use if no specific writeKey is provided in methods
* automatically for the first created instance
* TODO: to support multiple analytics instances in the near future
*/
setDefaultInstanceKey(writeKey: string): void;
/**
* Retrieve an existing analytics instance
*/
getAnalyticsInstance(writeKey?: string): IAnalytics | undefined;
/**
* Loads the SDK
* @param writeKey Source write key
* @param dataPlaneUrl Data plane URL
* @param loadOptions Additional options for loading the SDK
* @returns none
*/
load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial<LoadOptions>): void;
/**
* A function to track page lifecycle events like page loaded and page unloaded
* @param loadOptions
* @returns
*/
trackPageLifecycleEvents(loadOptions?: Partial<LoadOptions>): void;
/**
* Setup page unload tracking if enabled
* @param events
* @param useBeacon
* @param options
*/
setupPageUnloadTracking(events: PageLifecycleEvents[], useBeacon: boolean | undefined, options: ApiOptions): void;
/**
* Trigger load event in buffer queue if exists and stores the
* remaining preloaded events array in global object
*/
triggerBufferedLoadEvent(): void;
/**
* Get ready callback arguments and forward to ready call
*/
ready(callback: ApiCallback): void;
/**
* Process page arguments and forward to page call
*/
page(category: string, name: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
page(category: string, name: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
page(category: string, name: string, callback?: ApiCallback): void;
page(name: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
page(name: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
page(name: string, callback?: ApiCallback): void;
page(properties: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
page(properties: Nullable<ApiObject>, callback?: ApiCallback): void;
page(callback?: ApiCallback): void;
/**
* Process track arguments and forward to page call
*/
track(event: string, properties?: Nullable<ApiObject>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
track(event: string, properties?: Nullable<ApiObject>, callback?: ApiCallback): void;
track(event: string, callback?: ApiCallback): void;
/**
* Process identify arguments and forward to page call
*/
identify(userId: string, traits?: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
identify(userId: string, traits?: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
identify(userId: string, callback?: ApiCallback): void;
identify(traits: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
identify(traits: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
/**
* Process alias arguments and forward to page call
*/
alias(to: string, from?: string, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
alias(to: string, from?: string, callback?: ApiCallback): void;
alias(to: string, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
alias(to: string, callback?: ApiCallback): void;
/**
* Process group arguments and forward to page call
*/
group(groupId: string, traits?: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
group(groupId: string, traits?: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
group(groupId: string, callback?: ApiCallback): void;
group(traits: Nullable<IdentifyTraits>, options?: Nullable<ApiOptions>, callback?: ApiCallback): void;
group(traits: Nullable<IdentifyTraits>, callback?: ApiCallback): void;
reset(resetAnonymousId?: boolean): void;
getAnonymousId(options?: AnonymousIdOptions): string | undefined;
setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string): void;
getUserId(): Nullable<string> | undefined;
getUserTraits(): Nullable<ApiObject> | undefined;
getGroupId(): Nullable<string> | undefined;
getGroupTraits(): Nullable<ApiObject> | undefined;
startSession(sessionId?: number): void;
endSession(): void;
getSessionId(): Nullable<number> | undefined;
setAuthToken(token: string): void;
consent(options?: ConsentOptions): void;
addCustomIntegration(destinationId: string, integration: RSACustomIntegration): void;
}
//# sourceMappingURL=RudderAnalytics.d.ts.map
declare global {
interface Window {
rudderanalytics: RudderAnalytics | RudderAnalyticsPreloader | undefined;
}
}
//# sourceMappingURL=index.d.ts.map
export { RudderAnalytics };
export type { AnonymousIdOptions, ApiCallback, ApiObject, ApiOptions, BeaconQueueOpts, ConsentOptions, CookieSameSite, CustomDestinationConfig, DestinationsQueueOpts, IdentifyTraits, IntegrationOpts, LoadOptions, LogLevel, PluginName, PreloadedEventCall, QueueOpts, RSACustomIntegration, RSAEvent, RSALogger, RSAnalytics, RudderAnalyticsPreloader, SessionOpts, UaChTrackLevel };