import { JsonType, PostHogCaptureOptions, PostHogCore, PostHogCoreOptions, PostHogEventProperties, PostHogFetchOptions, PostHogFetchResponse, PostHogPersistedProperty, PostHogRemoteConfig, SurveyResponse } from '@posthog/core'; import { PostHogAutocaptureOptions, PostHogCustomAppProperties, PostHogCustomStorage, PostHogSessionReplayConfig } from './types'; import { OptionalReactNativeSessionReplay } from './optional/OptionalSessionReplay'; import { ErrorTrackingOptions } from './error-tracking'; export { PostHogPersistedProperty }; export interface PostHogOptions extends PostHogCoreOptions { /** Allows you to provide the storage type. By default 'file'. * 'file' will try to load the best available storage, the provided 'customStorage', 'customAsyncStorage' or in-memory storage. */ persistence?: 'memory' | 'file'; /** Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated */ customAppProperties?: PostHogCustomAppProperties | ((properties: PostHogCustomAppProperties) => PostHogCustomAppProperties); /** Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system or a synchronous storage such as mmkv. * If not provided, PostHog will attempt to use the best available storage via optional peer dependencies (async-storage, expo-file-system). * If `persistence` is set to 'memory', this option will be ignored. */ customStorage?: PostHogCustomStorage; /** Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active and Application Backgrounded. * By default is false. * Application Installed and Application Updated events are not supported with persistence set to 'memory'. */ captureAppLifecycleEvents?: boolean; /** * Enable Recording of Session Replays for Android and iOS * Requires Record user sessions to be enabled in the PostHog Project Settings * Defaults to false */ enableSessionReplay?: boolean; /** * Configuration for Session Replay */ sessionReplayConfig?: PostHogSessionReplayConfig; /** * If enabled, the session id ($session_id) will be persisted across app restarts. * This is an option for back compatibility, so your current data isn't skewed with the new version of the SDK. * If this is false, the session id will be always reset on app restart. * Defaults to false */ enablePersistSessionIdAcrossRestart?: boolean; /** * Error Tracking Configuration */ errorTracking?: ErrorTrackingOptions; /** * Automatically include common device and app properties in feature flag evaluation. * * When enabled, the following properties are sent with every /flags request: * - $app_version: App version * - $app_build: App build number * - $app_namespace: App bundle identifier / namespace * - $os_name: Operating system name * - $os_version: Operating system version * - $device_type: Device type (Mobile, Desktop) * - $lib: Name of the SDK library * - $lib_version: Version of the SDK library * * This ensures feature flags that rely on these properties work correctly * without waiting for server-side processing of identify() calls. * * @default true */ setDefaultPersonProperties?: boolean; } export declare class PostHog extends PostHogCore { private _persistence; private _storage; private _appProperties; private _currentSessionId?; private _enableSessionReplay?; private _sessionReplayNativeInitialized; private _sessionReplayOptions?; private _disableSurveys; private _disableRemoteConfig; private _errorTracking; private _surveysReadyPromise; private _surveysReady; private _setDefaultPersonProperties; /** * Creates a new PostHog instance for React Native. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options). * * If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there. * * {@label Initialization} * * @example * ```ts * // posthog.ts * import PostHog from 'posthog-react-native' * * export const posthog = new PostHog('', { * host: '' * }) * * // Then you can access PostHog by importing your instance * // Another file: * import { posthog } from './posthog' * * export function MyApp1() { * useEffect(async () => { * posthog.capture('event_name') * }, [posthog]) * * return Your app code * } * ``` * * @public * * @param apiKey - Your PostHog API key * @param options - PostHog configuration options */ constructor(apiKey: string, options?: PostHogOptions); /** * * @internal * */ ready(): Promise; /** * Called when remote config has been loaded (from either the remote config endpoint or the flags endpoint). * Gates error tracking autocapture based on the remote config response. * * Session replay config (consoleLogRecordingEnabled, sampleRate, capturePerformance.network_timing) is already * cached via PostHogPersistedProperty.RemoteConfig and applied at startup in startSessionReplay(). * * @internal */ protected onRemoteConfig(response: PostHogRemoteConfig): void; getPersistedProperty(key: PostHogPersistedProperty): T | undefined; setPersistedProperty(key: PostHogPersistedProperty, value: T | null): void; /** * Waits for any pending storage operations to complete. * This ensures data has been safely written to async storage before * considering events as sent, preventing duplicate events on app crash/restart. */ protected flushStorage(): Promise; fetch(url: string, options: PostHogFetchOptions): Promise; getLibraryId(): string; getLibraryVersion(): string; getCustomUserAgent(): string; getCommonEventProperties(): PostHogEventProperties; /** * Registers super properties that are sent with every event. * * Super properties are properties associated with events that are set once and then sent with every capture call. * They persist across sessions and are stored locally. * * {@label Capture} * * @example * ```js * // register super properties * posthog.register({ * 'icecream pref': 'vanilla', * team_id: 22, * }) * ``` * * @public * * @param properties An associative array of properties to store about the user */ register(properties: PostHogEventProperties): Promise; /** * Removes a super property so it won't be sent with future events. * * Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. * * {@label Capture} * * @example * ```js * // remove a super property * posthog.unregister('icecream pref') * ``` * * @public * * @param property The name of the super property to remove */ unregister(property: string): Promise; /** * Resets the user's ID and anonymous ID after logout. * * To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out. * This also clears all stored super properties and more. * * {@label Identification} * * @example * ```js * // reset after logout * posthog.reset() * ``` * * @example * ```js * // reset but keep feature flag overrides * posthog.reset([PostHogPersistedProperty.OverrideFeatureFlags]) * ``` * * @param propertiesToKeep - Optional array of persisted properties to preserve during reset * * @public */ reset(propertiesToKeep?: PostHogPersistedProperty[]): void; /** * Helper to extract and set default person properties from app properties * * @private * * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true. */ private _setDefaultPersonPropertiesForFlags; /** * Manually flushes the event queue. * * You can set the number of events in the configuration that should queue before flushing. * Setting this to 1 will send events immediately and will use more battery. This is set to 20 by default. * You can also manually flush the queue. If a flush is already in progress it returns a promise for the existing flush. * * {@label Capture} * * @example * ```js * // manually flush the queue * await posthog.flush() * ``` * * @public * * @returns Promise that resolves when the flush is complete */ flush(): Promise; /** * Opts the user in to data capture. * * By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }. * Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called. * * {@label Privacy} * * @example * ```js * // opt in to tracking * posthog.optIn() * ``` * * @public */ optIn(): Promise; /** * Opts the user out of data capture. * * You can completely opt-out users from data capture. Once this has been called it is persisted and will be respected until optIn is called again or the reset function is called. * * {@label Privacy} * * @example * ```js * // opt out of tracking * posthog.optOut() * ``` * * @public */ optOut(): Promise; /** * Checks if a feature flag is enabled for the current user. * * Defaults to undefined if not loaded yet or if there was a problem loading. * * {@label Feature flags} * * @example * ```js * // check if feature flag is enabled * const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag') * ``` * * @public * * @param key The feature flag key * @returns True if enabled, false if disabled, undefined if not loaded */ isFeatureEnabled(key: string): boolean | undefined; /** * Gets the value of a feature flag for the current user. * * Defaults to undefined if not loaded yet or if there was a problem loading. * Multivariant feature flags are returned as a string. * * {@label Feature flags} * * @example * ```js * // get feature flag value * const value = posthog.getFeatureFlag('key-for-your-boolean-flag') * ``` * * @public * * @param key The feature flag key * @returns The feature flag value or undefined if not loaded */ getFeatureFlag(key: string): boolean | string | undefined; /** * Gets the payload of a feature flag for the current user. * * Returns JsonType or undefined if not loaded yet or if there was a problem loading. * * {@label Feature flags} * * @example * ```js * // get feature flag payload * const payload = posthog.getFeatureFlagPayload('key-for-your-multivariate-flag') * ``` * * @public * * @param key The feature flag key * @returns The feature flag payload or undefined if not loaded */ getFeatureFlagPayload(key: string): JsonType | undefined; /** * Reloads feature flags from the server. * * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. * If you want to manually trigger a refresh, you can call this method. * * {@label Feature flags} * * @example * ```js * // reload feature flags * posthog.reloadFeatureFlags() * ``` * * @public */ reloadFeatureFlags(): void; /** * Reloads feature flags from the server asynchronously. * * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. * If you want to manually trigger a refresh and get the result, you can call this method. * * {@label Feature flags} * * @example * ```js * // reload feature flags and get result * posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags)) * ``` * * @public * * @returns Promise that resolves with the refreshed flags */ reloadFeatureFlagsAsync(): Promise | undefined>; /** * Associates the current user with a group. * * Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). * This is a paid feature and is not available on the open-source or free cloud plan. * * {@label Group analytics} * * @example * ```js * // associate with a group * posthog.group('company', 'company_id_in_your_db') * ``` * * @example * ```js * // associate with a group and update properties * posthog.group('company', 'company_id_in_your_db', { * name: 'Awesome Inc.', * employees: 11, * }) * ``` * * @public * * @param groupType The type of group (e.g. 'company', 'team') * @param groupKey The unique identifier for the group * @param properties Optional properties to set for the group */ group(groupType: string, groupKey: string, properties?: PostHogEventProperties): void; /** * Assigns an alias to the current user. * * Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. * For example, if a distinct ID used on the frontend is not available in your backend. * * {@label Identification} * * @example * ```js * // set alias for current user * posthog.alias('distinct_id') * ``` * * @public * * @param alias The alias to assign to the current user */ alias(alias: string): void; /** * Gets the current user's distinct ID. * * You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify for a user or not. * This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify(). * * {@label Identification} * * @example * ```js * // get current distinct ID * const distinctId = posthog.getDistinctId() * ``` * * @public * * @returns The current user's distinct ID */ getDistinctId(): string; /** * Sets person properties for feature flag evaluation. * * Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. * You can do so by setting properties the flag depends on with this call. These are set for the entire session. * Successive calls are additive: all properties you set are combined together and sent for flag evaluation. * * {@label Feature flags} * * @example * ```js * // set person properties for flags * posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}) * ``` * * @public * * @param properties The person properties to set for flag evaluation * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true. */ setPersonPropertiesForFlags(properties: Record, reloadFeatureFlags?: boolean): void; /** * Resets person properties for feature flag evaluation. * * * {@label Feature flags} * * @example * ```js * // reset person properties for flags * posthog.resetPersonPropertiesForFlags() * ``` * * @public * * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true. */ resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): void; /** * Sets group properties for feature flag evaluation. * * These properties are automatically attached to the current group (set via posthog.group()). * When you change the group, these properties are reset. * * {@label Feature flags} * * @example * ```js * // set group properties for flags * posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}}) * ``` * * @public * * @param properties The group properties to set for flag evaluation * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true. */ setGroupPropertiesForFlags(properties: Record>, reloadFeatureFlags?: boolean): void; /** * Resets group properties for feature flag evaluation. * * {@label Feature flags} * * @example * ```js * // reset group properties for flags * posthog.resetGroupPropertiesForFlags() * ``` * * @public * * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true. */ resetGroupPropertiesForFlags(reloadFeatureFlags?: boolean): void; /** * Captures a screen view event. * * @remarks * This function requires a name. You may also pass in an optional properties object. * Screen name is automatically registered for the session and will be included in subsequent events. * * {@label Capture} * * @example * ```js * // Basic screen capture * posthog.screen('dashboard') * ``` * * @example * ```js * // Screen capture with properties * posthog.screen('dashboard', { * background: 'blue', * hero: 'superhog', * }) * ``` * * @public * * @param name - The name of the screen * @param properties - Optional properties to include with the screen event * @param options - Optional capture options */ screen(name: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise; _isEnableSessionReplay(): boolean; _resetSessionId(reactNativeSessionReplay: typeof OptionalReactNativeSessionReplay | undefined, sessionId: string): void; getSessionId(): string; resetSessionId(): void; /** * Starts session recording. * This method will have no effect if PostHog is not enabled, or if session replay is disabled in your project settings. * * Note: This is only available on iOS and Android. On web/macOS, this is a no-op. * * Requires `posthog-react-native-session-replay` version 1.3.0 or higher. * * {@label Session Replay} * * @example * ```js * // Resume the current session recording * await posthog.startSessionRecording() * ``` * * @example * ```js * // Start a new session recording * await posthog.startSessionRecording(false) * ``` * * @public * * @param resumeCurrent - Whether to resume recording of current session (true) or start a new session (false). Defaults to true. */ startSessionRecording(resumeCurrent?: boolean): Promise; /** * Stops the current session recording if one is in progress. * * Note: This is only available on iOS and Android. On web/macOS, this is a no-op. * * Requires `posthog-react-native-session-replay` version 1.3.0 or higher. * * {@label Session Replay} * * @example * ```js * await posthog.stopSessionRecording() * ``` * @public */ stopSessionRecording(): Promise; /** * Returns whether session replay is currently active. * * Note: This is only available on iOS and Android. On web/macOS, this always returns false. * * {@label Session Replay} * * @example * ```js * const isActive = await posthog.isSessionReplayActive() * ``` * * @public * * @returns Whether session replay is currently active */ isSessionReplayActive(): Promise; /** * Associates events with a specific user. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) * * {@label Identification} * * @example * ```js * // Basic identify * posthog.identify('distinctID', { * email: 'user@posthog.com', * name: 'My Name' * }) * ``` * * @example * ```js * // Using $set and $set_once * posthog.identify('distinctID', { * $set: { * email: 'user@posthog.com', * name: 'My Name' * }, * $set_once: { * date_of_first_log_in: '2024-03-01' * } * }) * ``` * * @public * * @param distinctId - A unique identifier for your user. Typically either their email or database ID. * @param properties - Optional dictionary with key:value pairs to set the person properties * @param options - Optional capture options */ identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void; /** * Capture a caught exception manually * * {@label Error tracking} * * @public * * @example * ```js * // Capture a caught exception * try { * // something that might throw * } catch (error) { * posthog.captureException(error) * } * ``` * * @example * ```js * // With additional properties * posthog.captureException(error, { * customProperty: 'value', * anotherProperty: ['I', 'can be a list'], * ... * }) * ``` * * @param {Error} error The error to capture * @param {Object} [additionalProperties] Any additional properties to add to the error event * @returns {void} */ captureException(error: Error | unknown, additionalProperties?: PostHogEventProperties): void; initReactNativeNavigation(options: PostHogAutocaptureOptions): boolean; /** * Creates a person profile for the current user, if they don't already have one. * * This is useful when using `personProfiles: 'identified_only'` mode and you want to * explicitly create a profile for an anonymous user before they identify. * * If `personProfiles` is 'identified_only' and no profile exists, this will create one. * If `personProfiles` is 'never', this will log an error and do nothing. * If `personProfiles` is 'always' or a profile already exists, this is a no-op. * * {@label Identification} * * @example * ```js * // Create a person profile for an anonymous user * posthog.createPersonProfile() * ``` * * @public */ createPersonProfile(): void; /** * Sets properties on the person profile associated with the current `distinct_id`. * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) * * {@label Identification} * * @remarks * Updates user properties that are stored with the person profile in PostHog. * If `personProfiles` is set to `identified_only` and no profile exists, this will create one. * * @example * ```js * // set user properties * posthog.setPersonProperties({ * email: 'user@example.com', * plan: 'premium' * }) * ``` * * @example * ```js * // set properties with $set_once * posthog.setPersonProperties( * { name: 'Max Hedgehog' }, // $set properties * { initial_url: '/blog' } // $set_once properties * ) * ``` * * @example * ```js * // set properties without reloading feature flags * posthog.setPersonProperties({ plan: 'premium' }, undefined, false) * ``` * * @public * * @param userPropertiesToSet - Optional: An object of properties to store about the user. * These properties will overwrite any existing values for the same keys. * @param userPropertiesToSetOnce - Optional: An object of properties to store about the user. * If a property is previously set, this does not override that value. * @param reloadFeatureFlags - Whether to reload feature flags after setting the properties. Defaults to true. */ setPersonProperties(userPropertiesToSet?: { [key: string]: JsonType; }, userPropertiesToSetOnce?: { [key: string]: JsonType; }, reloadFeatureFlags?: boolean): void; getSurveys(): Promise; /** * Returns a promise that resolves when surveys are ready to be loaded. * If surveys are already loaded and ready to go, returns a resolved promise instead. * @internal */ _onSurveysReady(): Promise; private _surveysReadyResolve; /** * Helper function to cache surveys to storage with consistent logging */ private _cacheSurveys; /** * Internal method to notify that surveys are ready */ private _notifySurveysReady; /** * Handle surveys from remote config response */ private _handleSurveysFromRemoteConfig; /** * Load flags AND handle surveys from the flags response (only when remote config is disabled) */ private _flagsAsyncWithSurveys; /** * Internal method to load surveys from API (when remote config is disabled) */ private _loadSurveysFromAPI; /** * Initializes the native session replay SDK if not already initialized. * This is called automatically by startSessionReplay() or lazily by startSessionRecording(). * * @returns true if the native SDK is ready (initialized or already was), false otherwise */ private initializeSessionReplayNative; private startSessionReplay; private captureAppLifecycleEvents; private persistAppVersion; }