posthog-js
Version:
Posthog-js allows you to automatically capture usage and send events to PostHog.
230 lines (229 loc) • 11.3 kB
TypeScript
import type { Client } from '@posthog/browser-common';
import type { DeferredStylesheetStats, MutationCost, SnapshotCost } from '@posthog/rrweb-record';
import type { ErrorTracking } from '@posthog/core';
import type { PostHog } from '../posthog-core';
import type { BufferedConsoleEntry } from '../logs-types';
import type { SessionIdManager } from '../sessionid';
import type { DeadClicksAutoCaptureConfig, ExternalIntegrationKind, Properties, RemoteConfig, SiteAppLoader, SessionStartReason } from '../types';
import type { ConversationsRemoteConfig, GetMessagesResponse, GetTicketsOptions, GetTicketsResponse, MarkAsReadResponse, RestoreFromTokenResponse, RequestRestoreLinkResponse, SendMessageResponse, UserProvidedTraits } from '../posthog-conversations-types';
import type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching';
import type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types';
import type { eventWithTime } from '../extensions/replay/types/rrweb-types';
export type AssignableWindow = Window & typeof globalThis & {
posthog: any;
__PosthogExtensions__?: PostHogExtensions;
/**
* When loading remote config, we assign it to this global configuration
* for ease of sharing it with the rest of the SDK
*/
_POSTHOG_REMOTE_CONFIG?: Record<string, {
config: RemoteConfig;
siteApps: SiteAppLoader[];
}>;
/**
* If this is set on the window, our logger will log to the console
* for ease of debugging. Used for testing purposes only.
*
* @see {Config.DEBUG} from config.ts
*/
POSTHOG_DEBUG: any;
doNotTrack: any;
posthogCustomizations: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/exception-autocapture.ts
*
* @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead
*/
posthogErrorWrappingFunctions: any;
/**
* Legacy exception autocapture entrypoint names used by posthog-js <= 1.141.0.
* Both spellings are required because those clients checked one and called the other.
*
* See entrypoints/exception-autocapture.ts
*
* @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead
*/
extendPostHogWithExceptionAutoCapture: any;
extendPostHogWithExceptionAutocapture: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/posthog-recorder.ts
*
* @deprecated use `__PosthogExtensions__.rrweb` instead
*/
rrweb: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/posthog-recorder.ts
*
* @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead
*/
rrwebConsoleRecord: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/posthog-recorder.ts
*
* @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead
*/
getRecordNetworkPlugin: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/web-vitals.ts
*
* @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead
*/
postHogWebVitalsCallbacks: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/tracing-headers.ts
*
* @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead
*/
postHogTracingHeadersPatchFns: any;
/**
* This is a legacy way to expose these functions, but we still need to support it for backwards compatibility
* Can be removed once we drop support for 1.161.1
*
* See entrypoints/surveys.ts
*
* @deprecated use `__PosthogExtensions__.generateSurveys` instead
*/
extendPostHogWithSurveys: any;
ph_load_toolbar: any;
ph_load_editor: any;
ph_toolbar_state: any;
} & Record<`__$$ph_site_app_${string}`, any>;
/**
* This is our contract between (potentially) lazily loaded extensions and the SDK
* changes to this interface can be breaking changes for users of the SDK
*/
export type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration';
/** Subset of the web-vitals library's `ReportOpts` passed to metric observers. */
export interface WebVitalsReportOpts {
reportAllChanges?: boolean;
reportSoftNavs?: boolean;
}
/**
* Options only the attribution build understands, so they are passed to attributed
* observers and never to the observers in the default bundle.
*/
export interface WebVitalsAttributionReportOpts extends WebVitalsReportOpts {
includeProcessedEventEntries?: boolean;
}
export type WebVitalsCallbackFlavor = 'web-vitals' | 'web-vitals-with-attribution' | 'web-vitals-soft-navs' | 'web-vitals-with-attribution-soft-navs';
export type WebVitalsMetricCallbacks = {
onLCP: (onReport: (metric: any) => void, opts?: WebVitalsReportOpts) => void;
onCLS: (onReport: (metric: any) => void, opts?: WebVitalsReportOpts) => void;
onFCP: (onReport: (metric: any) => void, opts?: WebVitalsReportOpts) => void;
onINP: (onReport: (metric: any) => void, opts?: WebVitalsReportOpts) => void;
};
export type WebVitalsCallbacks = WebVitalsMetricCallbacks & {
withoutAttribution?: WebVitalsMetricCallbacks;
};
export type PostHogExtensionKind = 'toolbar' | 'exception-autocapture' | 'web-vitals' | 'web-vitals-with-attribution' | 'web-vitals-soft-navs' | 'web-vitals-with-attribution-soft-navs' | 'recorder' | 'lazy-recorder' | 'tracing-headers' | 'surveys' | 'logs' | 'conversations' | 'product-tours' | 'dead-clicks-autocapture' | 'remote-config' | ExternalExtensionKind;
export interface LazyLoadedSessionRecordingInterface {
start: (startReason?: SessionStartReason) => void;
stop: () => void;
discard: (options?: {
discardProducerEvents?: boolean;
}) => void;
sessionId: string;
status: SessionRecordingStatus;
onRRwebEmit: (rawEvent: eventWithTime) => void;
log: (message: string, level: 'log' | 'warn' | 'error') => void;
sdkDebugProperties: Properties;
overrideLinkedFlag: () => void;
overrideSampling: () => void;
overrideTrigger: (triggerType: TriggerType) => void;
isStarted: boolean;
tryAddCustomEvent(tag: string, payload: any): boolean;
setDocumentWasEverVisible?: (documentWasEverVisible: boolean) => void;
}
export interface LazyLoadedDeadClicksAutocaptureInterface {
start: (observerTarget: Node) => void;
stop: () => void;
}
export interface LazyLoadedConversationsInterface {
show: () => void;
hide: () => void;
isVisible: () => boolean;
reset: () => void;
setIdentity: () => void;
clearIdentity: () => void;
sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>;
getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>;
markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>;
getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>;
requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>;
restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>;
restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>;
getCurrentTicketId: () => string | null;
getWidgetSessionId: () => string;
}
interface PostHogExtensions {
loadExternalDependency?: (posthog: PostHog, kind: PostHogExtensionKind, callback: (error?: string | Event, event?: Event) => void) => void;
loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void;
errorWrappingFunctions?: {
wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void;
wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void;
wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void;
};
rrweb?: {
record: any;
version: string;
wasMaxDepthReached?: () => boolean;
resetMaxDepthState?: () => void;
getLastSnapshotCost?: () => SnapshotCost | null;
getMutationCost?: () => MutationCost;
getDeferredStylesheetStats?: () => DeferredStylesheetStats;
getDiscardedDurationSamples?: () => number;
resetSnapshotCostState?: () => void;
};
rrwebPlugins?: {
getRecordConsolePlugin: any;
getRecordNetworkPlugin?: any;
};
generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined;
generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined;
logs?: {
initializeLogs?: (host: PostHog | Client) => (() => void) | undefined;
replayConsoleBuffer?: (host: PostHog | Client, entries: BufferedConsoleEntry[]) => void;
};
/** @deprecated Use `postHogWebVitalsCallbacksByFlavor` to select callbacks explicitly. */
postHogWebVitalsCallbacks?: WebVitalsCallbacks;
postHogWebVitalsCallbacksByFlavor?: Partial<Record<WebVitalsCallbackFlavor, WebVitalsCallbacks>>;
/**
* @deprecated
*
* this was introduced briefly, it is now always a no-op and only kept for backwards compatibility
*/
loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks'];
tracingHeadersPatchFns?: {
_patchFetch: (hostnames: TracingHeadersHostnames, distinctId: TracingHeadersDistinctId, sessionManager?: SessionIdManager) => () => void;
_patchXHR: (hostnames: TracingHeadersHostnames, distinctId: TracingHeadersDistinctId, sessionManager?: SessionIdManager) => () => void;
};
initDeadClicksAutocapture?: (ph: PostHog, config: DeadClicksAutoCaptureConfig) => LazyLoadedDeadClicksAutocaptureInterface;
integrations?: {
[K in ExternalIntegrationKind]?: {
start: (posthog: PostHog) => void;
stop: () => void;
};
};
initSessionRecording?: (ph: PostHog, documentWasEverVisible?: boolean) => LazyLoadedSessionRecordingInterface;
initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface;
}
export { AbortController, CompressionStream, document, fetch, isBrowserOnline, location, navigator, userAgent, window, XMLHttpRequest, } from '@posthog/browser-common/utils/globals';
export declare const assignableWindow: AssignableWindow;