posthog-react-native 4.79.0 → 4.79.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/posthog-rn.d.ts +4 -1
- package/dist/posthog-rn.js +1 -1
- package/dist/posthog-rn.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +5 -5
- package/tooling/posthog-xcode.sh +6 -2
package/dist/posthog-rn.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog-rn.js","names":["_reactNative","require","_core","_storage","_surveyProgress","_logsDefaults","_version","_nativeDeps","_utils","_wixNavigation","_OptionalPlugin","_errorTracking","_exceptionContext","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","_callSuper","_getPrototypeOf2","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","Boolean","prototype","valueOf","call","_superPropGet","p","_get2","mapAppStateForLogs","state","undefined","NATIVE_CALL_TIMEOUT_MS","MANUAL_RECORDING_START_RETRY_DELAYS_MS","PostHog","exports","_PostHogCore","apiKey","options","_this","_classCallCheck2","normalizedApiKey","trim","console","error","_appProperties","_sessionReplayNativeInitialized","_nativeErrorTrackingInitialized","_androidNdkCrashesUnsupportedWarned","_pushNativeInitialized","_fatalJsCaptureNativeInitialized","_pushNativeUnsupported","_sessionReplayMacOSWarned","_sessionReplayEvalChain","Promise","resolve","_nativeChain","_sessionReplayEventTriggers","_eventsStoragePreloadSucceeded","_surveysReadyPromise","_surveysReady","_requestHeaders","_surveysReadyResolve","_isInitialized","_persistence","_b","persistence","_disableSurveys","_c","disableSurveys","ErrorTracking","errorTracking","_logger","captureFatalException","hint","eventUuid","timestamp","prepareNativeCapture","_captureFatalAndChooseOwner","captureExceptionInternal","$exception_level","uuid","waitForJSPersist","_waitForJSPersist","_asyncToGenerator2","_regenerator","mark","_callee","wrap","_context","prev","next","_initPromise","abrupt","_eventsStorage","waitForPersistSuccess","stop","getPersistenceMode","waitForStorageReady","_waitForStorageReady","_callee2","_context2","isNativeCaptureReady","_isNativePluginInitialized","_setDefaultPersonProperties","_d","setDefaultPersonProperties","_overrideDisplayLanguage","_a","overrideDisplayLanguage","_e","requestHeaders","customAppProperties","getAppProperties","storagePromise","theStorage","_f","customStorage","buildOptimisticAsyncStorage","createEventsStorage","_logsStorage","createLogsStorage","preloads","preloadPromise","allSettled","map","_ref","_ref2","_slicedToArray2","then","results","i","status","concat","reason","createEventsMemoryStorage","createLogsMemoryStorage","_currentAppState","AppState","currentState","_resolvedLogsConfig","resolveLogsConfig","logs","_logs","PostHogLogs","flags","getFeatureFlags","flagKeys","distinctId","getDistinctId","sessionId","getSessionId","screenName","sessionProps","$screen_name","appState","activeFeatureFlags","fn","waitForPersist","addEventListener","mapped","flush","_ref3","_callee3","err","_context3","logFlushError","_x3","isBackgrounding","logsFlushPromise","flushWithTimeout","backgroundFlushBudgetMs","_ref4","_callee4","_context4","_x4","initAfterStorage","enablePersistSessionIdAcrossRestart","setPersistedProperty","PostHogPersistedProperty","SessionId","SessionLastTimestamp","SessionStartTimestamp","setupBootstrap","getPersistedProperty","DeviceId","anonId","getAnonymousId","_setDefaultPersonPropertiesForFlags","isDisabled","cachedRemoteConfig","RemoteConfig","onRemoteConfig","reloadRemoteConfigAsync","response","_handleSurveysFromRemoteConfig","_notifySurveysReady","captureAppLifecycleEvents","persistAppVersion","startSessionReplay","onFeatureFlags","_isEnableSessionReplay","_manualRecordingStartRequest","pending","_evaluateAndStartSessionReplay","addTracingHeaders","patchFetchForTracingHeaders","_inherits2","_createClass2","key","value","_ready","_callee5","_context5","ready","_storageForKey","LogsQueue","getItem","storage","SurveysInProgress","otherProjects","getOtherProjectSurveyProgress","setItem","removeItem","_events","emit","PersonProperties","_flushStorage","_callee6","_context6","flushStorage","_shutdown2","_callee7","shutdownTimeoutMs","start","remainingMs","logsBudgetMs","_remainingMs","drain","_args7","_context7","_cancelManualRecordingStart","Date","now","Math","max","min","terminationFlushBudgetMs","all","shutdown","raceWithTimeout","finish","_shutdown","_fetch","fetch","_x","_x2","toString","url","getLibraryId","getLibraryVersion","version","getCustomUserAgent","Platform","OS","getCustomHeaders","getCommonEventProperties","_Dimensions$get","Dimensions","get","width","height","$screen_height","$screen_width","getSurveyDisplayLanguageOverride","register","properties","unregister","property","reset","propertiesToKeep","_this2","effectivePropertiesToKeep","InstalledAppBuild","InstalledAppVersion","SessionReplay","Surveys","PushRegistered","_toConsumableArray2","OptionalReactNativePlugin","_enqueueNative","plugin","String","_propagateNativeOptOut","_this3","reloadFeatureFlags","defaultProps","relevantKeys","commonProps","$lib","$lib_version","setPersonPropertiesForFlags","captureLog","flushLogs","_this4","_captureLogger","trace","body","attributes","level","debug","info","warn","fatal","optIn","result","optOut","_this5","coreOptOut","persistOptOut","unregisterPushNotificationToken","_this6","setOptOut","optedOut","_isPushNativeEnabled","_sessionReplayOptions","_ensureNativeInitialized","isFeatureEnabled","getFeatureFlag","getFeatureFlagPayload","reloadFeatureFlagsAsync","updateFlags","payloads","group","groupType","groupKey","propsToCache","setGroupPropertiesForFlags","alias","getDeviceId","deviceId","resetPersonPropertiesForFlags","resetGroupPropertiesForFlags","_screen","_callee8","name","_context8","registerForSession","capture","screen","_x5","_x6","_x7","isMacOS","_enableSessionReplay","_resetSessionId","reactNativeSessionReplay","endSession","startSession","_currentSessionId","resetSessionId","_startSessionRecording2","_callee0","_this7","resumeCurrent","request","_args0","_context0","retryCount","_callee9","_context9","_attemptManualRecordingStart","startSessionRecording","clearTimeout","timer","_attemptManualRecordingStart2","_callee1","started","_context1","_startSessionRecording","sent","_stopSessionRecording","_scheduleManualRecordingStartRetry","_x8","_x9","_this8","delay","startRecording","safeSetTimeout","_callee10","_context10","_startSessionRecording3","_callee11","_this9","initialized","newSessionId","_t","_context11","initializeNativePlugin","isEnabled","_x0","_stopSessionRecording2","_callee13","_this0","_context13","_callee12","_context12","stopSessionRecording","_stopSessionRecording3","_callee14","_t2","_context14","stopRecording","_isSessionReplayActive","_callee15","_t3","_context15","isSessionReplayActive","identify","_this1","previousDistinctId","userProps","$set","userPropsOnce","$set_once","_typeof2","Array","isArray","entries","_ref8","_ref9","propsOnceToCache","_ref0","_ref1","nativeDistinctId","anonymousId","identified","captureException","additionalProperties","resolvedHint","mechanism","handled","type","syntheticException","Error","merged","getExceptionContext","finalAdditional","attachExceptionSteps","captureOptions","_originatedFromCaptureException","buildExceptionProperties","toISOString","builder","getErrorPropertiesBuilder","exceptionProperties","buildFromUnknown","addExceptionStep","message","createErrorPropertiesBuilder","CoreErrorTracking","ErrorPropertiesBuilder","PromiseRejectionEventCoercer","ErrorCoercer","ErrorEventCoercer","ObjectCoercer","StringCoercer","PrimitiveCoercer","createStackParser","isHermes","chromeStackLineParser","geckoStackLineParser","initReactNativeNavigation","withReactNativeNavigation","createPersonProfile","setPersonProperties","userPropertiesToSet","userPropertiesToSetOnce","unsetPersonProperties","propertyNames","_getSurveys","_callee16","surveys","_context16","_cacheSurveys","JSON","stringify","getSurveys","_onSurveysReady","_this10","source","_registerPushNotificationToken","_callee17","deviceToken","_this11","_context17","_callPushPlugin","allowMacOS","requireInit","noop","registerPushNotificationToken","appId","_x1","_x10","_unregisterPushNotificationToken","_callee18","_this12","_context18","allowWhenOptedOut","_capturePushNotificationOpened","_callee19","_i","_arr","_context19","capturePushNotificationOpened","_x11","_callPushPlugin2","_callee20","method","behavior","invoke","_this13","_context20","isWeb","_x12","_x13","_x14","label","run","_this14","_callee21","_context21","_this15","_callee22","_context22","_pluginVersionAtLeast","major","minor","OptionalReactNativePluginVersion","match","_ref12","Number","installedMajor","installedMinor","_nativeErrorAutocapture","autocapture","nativeCrashes","androidNdkCrashes","_isAutocaptureNativeErrors","_this$_nativeErrorAut","_isFatalJsCaptureNativeEnabled","isUncaughtExceptionAutocaptureEnabled","force","capturePushNotificationSubscriptions","pushIdentityProvider","_initializeSessionReplayNative","_callee23","_context23","initializeSessionReplayNative","_x15","_x16","_initializeNativePlugin","_callee24","enableSessionReplay","forcePush","_g","_h","_j","nativeErrorAutocapture","enableNativeErrorTracking","enablePush","enableFatalJsCapture","defaultThrottleDelayMs","_ref13","_ref13$maskAllTextInp","maskAllTextInputs","_ref13$maskAllImages","maskAllImages","_ref13$maskAllSandbox","maskAllSandboxedViews","_ref13$captureTouches","captureTouches","_ref13$captureLog","localCaptureLog","_ref13$captureNetwork","localCaptureNetworkTelemetry","_ref13$verifyScreensh","verifyScreenshotMaskAlignment","screenshotScale","screenshotCompressionQuality","screenshotColorMode","_ref13$screenshotMode","screenshotModeBackgroundCapture","localSampleRate","_ref13$iOSdebouncerDe","iOSdebouncerDelayMs","_ref13$androidDebounc","androidDebouncerDelayMs","throttleDelayMs","remoteConsoleLogEnabled","remoteNetworkTimingEnabled","remoteSampleRateRaw","captureNetworkTelemetry","localSampleRateValid","remoteSampleRateValid","sampleRate","sdkReplayConfig","sessionReplay","cachedSessionReplayConfig","pushOnlyInit","sdkOptions","loggableSdkOptions","wasSessionReplayEnabled","pushIdentityProviderEnabled","pluginConfig","_args24","_t4","_t5","_context24","sessionReplayConfig","getRemoteConfigBool","sessionRecording","capturePerformance","getRemoteConfigNumber","isValidSampleRate","isFinite","host","isDebug","sdkVersion","flushAt","preloadFeatureFlags","setup","setPushIdentityProvider","enabled","decideReplayConfig","nativeAutocapture","exceptionSteps","getNativePluginExceptionStepsConfig","rageClickConfig","rageClick","onNativeErrorTrackingReady","_x17","_x18","_startSessionReplay","_callee25","_context25","_x19","_x20","_this16","_evaluateAndStartSessionReplayInternal","_evaluateAndStartSessionReplayInternal2","_callee26","remoteConfig","featureFlags","cachedFeatureFlags","recordingActive","linkedFlag","flag","variant","_value","eventTriggers","activated","_t6","_context26","getKnownFeatureFlags","_parseEventTriggers","_isEventTriggerActivatedForSession","_sessionReplayRecordingActive","_x21","processBeforeEnqueue","observation","_fatalCaptureObservation","isObservedFatal","event","processed","suppress","nativeCapture","queued","_maybeActivateEventTrigger","previousObservation","eventName","includes","SessionReplayEventTriggerActivatedSession","entry","_captureAppLifecycleEvents","_callee27","_this17","appBuild","appVersion","isMemoryPersistence","prevAppBuild","prevAppVersion","initialUrl","_t7","_t8","_t9","_context27","$app_build","$app_version","maybeAdd","Linking","getInitialURL","_persistAppVersion","_callee28","_context28","PostHogCore"],"sources":["../src/posthog-rn.ts"],"sourcesContent":["import { AppState, type AppStateStatus, Dimensions, Linking, Platform } from 'react-native'\n\nimport {\n CaptureLogOptions,\n CaptureLogger,\n JsonType,\n PostHogCaptureOptions,\n PostHogCore,\n PostHogCoreOptions,\n PostHogEventProperties,\n PostHogFetchOptions,\n PostHogFetchResponse,\n PostHogLogs,\n PostHogLogsConfig,\n PostHogPersistedProperty,\n PostHogRemoteConfig,\n Survey,\n SurveyResponse,\n allSettled,\n logFlushError,\n maybeAdd,\n patchFetchForTracingHeaders,\n raceWithTimeout,\n safeSetTimeout,\n FeatureFlagValue,\n FeatureFlagResultOptions,\n IsFeatureEnabledOptions,\n ErrorTracking as CoreErrorTracking,\n isObject,\n uuidv7,\n} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport {\n PostHogRNStorage,\n createEventsStorage,\n createLogsStorage,\n createEventsMemoryStorage,\n createLogsMemoryStorage,\n} from './storage'\nimport { getOtherProjectSurveyProgress } from './surveys/survey-progress'\nimport { resolveLogsConfig } from './logs-defaults'\nimport { version } from './version'\nimport { buildOptimisticAsyncStorage, getAppProperties } from './native-deps'\nimport {\n PostHogAutocaptureOptions,\n PostHogCustomAppProperties,\n PostHogCustomStorage,\n PostHogPushIdentityProvider,\n PostHogRageClickConfig,\n PostHogSessionReplayConfig,\n} from './types'\nimport { getRemoteConfigBool, getRemoteConfigNumber, isHermes, isMacOS, isValidSampleRate, isWeb } from './utils'\nimport { withReactNativeNavigation } from './frameworks/wix-navigation'\nimport { OptionalReactNativePlugin, OptionalReactNativePluginVersion } from './optional/OptionalPlugin'\nimport { ErrorTracking, ErrorTrackingOptions } from './error-tracking'\nimport { getExceptionContext } from './error-tracking/exception-context'\n\nexport { PostHogPersistedProperty }\n\n/**\n * Collapses RN's broader AppState status set into the OTLP `app.state`\n * enum (foreground|background). 'inactive' (iOS transition) and 'extension'\n * are treated as foreground — the app is still running JS, just not the\n * primary scene. 'unknown' returns undefined so the attribute is omitted\n * rather than guessed.\n */\nfunction mapAppStateForLogs(state: AppStateStatus | undefined): 'foreground' | 'background' | undefined {\n if (state === 'background') {\n return 'background'\n }\n if (!state || state === 'unknown') {\n return undefined\n }\n return 'foreground'\n}\n\n// Upper bound on a single JS->native bridge call. Only bounds the call itself — waiting for\n// native setup happens before it — so it can be tight enough that a stuck call doesn't strand\n// the queue for the process lifetime.\nconst NATIVE_CALL_TIMEOUT_MS = 10_000\n// Native config readiness has no bridge notification, so manual starts need bounded timer\n// retries as well as flags-driven retries. JS flags can finish loading before native config.\nconst MANUAL_RECORDING_START_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 16000]\n\ntype ManualRecordingStartRequest = {\n pending: boolean\n retryCount: number\n timer?: ReturnType<typeof setTimeout>\n}\n\nexport interface PostHogOptions extends PostHogCoreOptions {\n /**\n * Allows you to provide the storage type.\n * 'file' will try to load the best available storage, the provided 'customStorage', 'customAsyncStorage' or in-memory storage.\n *\n * @default 'file'\n */\n persistence?: 'memory' | 'file'\n /** Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated */\n customAppProperties?:\n | PostHogCustomAppProperties\n | ((properties: PostHogCustomAppProperties) => PostHogCustomAppProperties)\n /**\n * Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system or a synchronous storage such as mmkv.\n * If not provided, PostHog will attempt to use the best available storage via optional peer dependencies (async-storage, expo-file-system).\n * If `persistence` is set to 'memory', this option will be ignored.\n */\n customStorage?: PostHogCustomStorage\n\n /**\n * A list of headers that should be sent with requests to the PostHog API.\n */\n requestHeaders?: { [header_name: string]: string }\n\n /**\n * Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active and Application Backgrounded.\n * Application Installed and Application Updated events are not supported with persistence set to 'memory'.\n *\n * @default true\n */\n captureAppLifecycleEvents?: boolean\n\n /**\n * Enable Recording of Session Replays for Android and iOS\n * Requires Record user sessions to be enabled in the PostHog Project Settings\n *\n * This option is read once, at setup. To record only some sessions, either gate recording\n * from your project settings (sampling, a linked flag, or event triggers), or leave this\n * option off and drive the recorder from your app with `startSessionRecording()` and\n * `stopSessionRecording()`.\n *\n * @default false\n */\n enableSessionReplay?: boolean\n\n /**\n * Configuration for Session Replay\n */\n sessionReplayConfig?: PostHogSessionReplayConfig\n\n /**\n * If enabled, the session id ($session_id) will be persisted across app restarts.\n * This is an option for back compatibility, so your current data isn't skewed with the new version of the SDK.\n * If this is false, the session id will be always reset on app restart.\n *\n * @default false\n */\n enablePersistSessionIdAcrossRestart?: boolean\n\n /**\n * Error Tracking Configuration\n */\n errorTracking?: ErrorTrackingOptions\n\n /**\n * Configure rage click (rage tap) detection on iOS.\n *\n * The native iOS SDK fires a `$rageclick` event when a user taps the same\n * area repeatedly in quick succession. The default thresholds (3 taps,\n * 30 points, 1 second) were tuned for web and frequently produce false\n * positives on mobile. Raise the thresholds or set `enabled: false` to\n * suppress them.\n *\n * Android is unaffected — posthog-android does not have native rage click\n * detection.\n *\n * Requires `@posthog/react-native-plugin` version 2.7.0 or newer.\n */\n rageClickConfig?: PostHogRageClickConfig\n\n /**\n * Automatically include common device and app properties in feature flag evaluation.\n *\n * When enabled, the following properties are sent with every /flags request:\n * - $app_version: App version\n * - $app_build: App build number\n * - $app_namespace: App bundle identifier / namespace\n * - $os_name: Operating system name\n * - $os_version: Operating system version\n * - $device_type: Device type (Mobile, Desktop)\n * - $lib: Name of the SDK library\n * - $lib_version: Version of the SDK library\n *\n * This ensures feature flags that rely on these properties work correctly\n * without waiting for server-side processing of identify() calls.\n *\n * @default true\n */\n setDefaultPersonProperties?: boolean\n\n /**\n * Logs feature configuration. Enables structured log capture via\n * `posthog.captureLog(...)` or `posthog.logger.info(...)`. Records ship to\n * PostHog's logs product (`/i/v1/logs`) in OTLP format, batched on a timer,\n * AppState change, buffer fill, or manual `flushLogs()`.\n *\n * Capture is **unconditional** — calling the API ships records as long as\n * the SDK is initialized and the user hasn't opted out. The only blockers\n * are `optedOut`, missing/empty `body`, and missing API key.\n *\n * All fields below are optional; per-SDK defaults apply (mobile defaults\n * are tuned for cellular bandwidth and battery, ~50 logs/sec ceiling).\n *\n * @example Minimal — just service tagging, defaults for everything else\n * ```ts\n * new PostHog(key, {\n * logs: { serviceName: 'my-app', environment: 'production' }\n * })\n * ```\n *\n * @example Tune for higher-volume logging\n * ```ts\n * new PostHog(key, {\n * logs: {\n * serviceName: 'my-app',\n * rateCap: { maxLogs: 5000, windowMs: 60000 },\n * maxBufferSize: 500,\n * beforeSend: (r) => r.body.includes('secret') ? null : r,\n * }\n * })\n * ```\n */\n logs?: PostHogLogsConfig\n\n /**\n * Overrides the language used when rendering translated survey copy.\n * When unset, the SDK falls back to the persisted person property `language`\n * and then the device locale.\n */\n overrideDisplayLanguage?: string | null\n\n /**\n * Whether to automatically register this device's push token so PostHog\n * Workflows can target it. Requires `@posthog/react-native-plugin`.\n *\n * Your app still owns permission — PostHog only observes the token the OS hands\n * back, and never sees later refreshes. Forward those to\n * {@link PostHog.registerPushNotificationToken} yourself.\n *\n * Not supported on web or macOS.\n *\n * @default true\n */\n capturePushNotificationSubscriptions?: boolean\n\n /**\n * Whether to automatically capture `$push_notification_opened` on a notification\n * tap. Requires `@posthog/react-native-plugin`.\n *\n * Fires for pushes from any provider, not just PostHog's — but title and body are\n * attached only for PostHog's own, so third-party notification text never reaches\n * analytics. On Android, taps that launch the app and taps while it's running are both\n * captured from `@posthog/react-native-plugin` 2.6.0 (earlier versions: cold starts\n * only); call {@link PostHog.capturePushNotificationOpened} for the taps it misses.\n *\n * The native SDK builds and sends this event, so JS `before_send` never sees it.\n *\n * On iOS a tap can reach the app before your JS runs, so the SDK installs a hook at launch to\n * catch a tap that cold-launches the app. Two switches gate automatic capture there, and\n * `false` on either one means the SDK sends no `$push_notification_opened` of its own (an\n * explicit {@link PostHog.capturePushNotificationOpened} call still captures):\n *\n * - This option set to `false` turns capture off when `setup()` runs and releases the launch\n * hook, dropping the tap it was holding. The hook is still installed for the window between\n * launch and `setup()`.\n * - `com.posthog.posthog.CAPTURE_PUSH_NOTIFICATION_OPENED` set to `false` in `Info.plist`\n * (Expo: `ios.infoPlist`) skips the launch hook entirely, so nothing is installed before your\n * JS runs, and forces capture off at `setup()` even when this option is `true`. It is the\n * same key posthog-flutter reads.\n *\n * Not supported on web.\n *\n * @default true\n */\n capturePushNotificationOpened?: boolean\n\n /**\n * Mints a signed identity-verification token for push subscription requests.\n * Only needed when your PostHog project requires identity verification for push.\n * Requires `@posthog/react-native-plugin`.\n *\n * Called with the current `distinctId` and `appId`. Mint on your backend (HS256,\n * `sub` = distinctId, an `app_id` claim, `aud` = `posthog:push_identity`), never\n * in the app. Return `null` to send the request unauthenticated; a slow or\n * throwing implementation does the same after 10 seconds.\n */\n pushIdentityProvider?: PostHogPushIdentityProvider\n}\n\nexport class PostHog extends PostHogCore {\n private _persistence: PostHogOptions['persistence']\n private _eventsStorage: PostHogRNStorage\n private _logsStorage: PostHogRNStorage\n private _appProperties: PostHogCustomAppProperties = {}\n private _currentSessionId?: string | undefined\n private _enableSessionReplay?: boolean\n private _sessionReplayNativeInitialized: boolean = false\n private _nativeErrorTrackingInitialized: boolean = false\n private _androidNdkCrashesUnsupportedWarned: boolean = false\n // Initialized: setup() ran carrying push config, so a live native instance exists.\n // Unsupported: this plugin can never do push — latched so the enable check stops\n // recomputing, without claiming an instance that isn't there.\n private _pushNativeInitialized: boolean = false\n private _fatalJsCaptureNativeInitialized: boolean = false\n private _pushNativeUnsupported: boolean = false\n private _sessionReplayMacOSWarned: boolean = false\n // Last applied recording state; the native bridge is only crossed on a change.\n private _sessionReplayRecordingActive?: boolean\n private _manualRecordingStartRequest?: ManualRecordingStartRequest\n // Serializes re-arm evaluations so concurrent flags reloads don't interleave.\n private _sessionReplayEvalChain: Promise<void> = Promise.resolve()\n // Serializes every JS->native command (identity, consent, push) so they reach native in\n // call order. See _enqueueNative.\n private _nativeChain: Promise<void> = Promise.resolve()\n private _sessionReplayOptions?: PostHogOptions\n // Event names that gate session replay (remote `sessionRecording.eventTriggers`). Cached in\n // memory so the capture hot path never reads storage. Empty when replay is off or unconfigured.\n private _sessionReplayEventTriggers: string[] = []\n private _eventsStoragePreloadSucceeded = true\n private _fatalCaptureObservation?: {\n eventUuid: string\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n queued: boolean\n nativeCapture?: () => Promise<void>\n }\n private _disableSurveys: boolean\n private _errorTracking: ErrorTracking\n private _logs: PostHogLogs\n // Resolved logs config — kept around so lifecycle handlers (AppState\n // background, _shutdown) can read the configured flush-time budgets without\n // reaching back into the user's options object.\n private _resolvedLogsConfig: ReturnType<typeof resolveLogsConfig>\n // Cached, foreground/background view of the app's lifecycle. Read on the\n // log-capture hot path (per record) so we tag every log with whether it\n // happened in foreground or background. Updated by the AppState listener\n // and seeded from `AppState.currentState` at construction.\n private _currentAppState?: 'foreground' | 'background'\n private _surveysReadyPromise: Promise<void> | null = null\n private _surveysReady: boolean = false\n private _setDefaultPersonProperties: boolean\n private _overrideDisplayLanguage: string | null\n private _requestHeaders: { [header_name: string]: string } = {}\n\n /**\n * 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).\n *\n * If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there.\n *\n * {@label Initialization}\n *\n * @example\n * ```ts\n * // posthog.ts\n * import PostHog from 'posthog-react-native'\n *\n * export const posthog = new PostHog('<ph_project_api_key>', {\n * host: '<ph_client_api_host>'\n * })\n *\n * // Then you can access PostHog by importing your instance\n * // Another file:\n * import { posthog } from './posthog'\n *\n * export function MyApp1() {\n * useEffect(async () => {\n * posthog.capture('event_name')\n * }, [posthog])\n *\n * return <View>Your app code</View>\n * }\n * ```\n *\n * @public\n *\n * @param apiKey - Your PostHog API key\n * @param options - PostHog configuration options\n */\n constructor(apiKey: string, options?: PostHogOptions) {\n const normalizedApiKey = typeof apiKey === 'string' ? apiKey.trim() : ''\n if (!normalizedApiKey) {\n console.error(\"You must pass your PostHog project's api key. The client will be disabled.\")\n }\n\n super(normalizedApiKey, options)\n this._isInitialized = false\n this._persistence = options?.persistence ?? 'file'\n this._disableSurveys = options?.disableSurveys ?? false\n this._errorTracking = new ErrorTracking(this, options?.errorTracking, this._logger, {\n captureFatalException: (error, hint, eventUuid, timestamp, prepareNativeCapture) =>\n this._captureFatalAndChooseOwner(eventUuid, prepareNativeCapture, () =>\n this.captureExceptionInternal(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint, {\n uuid: eventUuid,\n timestamp,\n })\n ),\n // Other events may still be queued behind the exception, so the fatal path waits for\n // the JS store to land even when native owns the exception itself.\n waitForJSPersist: async () => {\n await this._initPromise\n return this._eventsStorage.waitForPersistSuccess()\n },\n // Memory-mode apps don't have AsyncStorage, and the native SDK's queue is disk-backed:\n // handing it the exception would land data the rest of the SDK promises never to touch\n // disk. Keep the event in the JS queue there instead.\n getPersistenceMode: () => this._persistence || 'file',\n waitForStorageReady: async () => {\n await this._initPromise\n return this._eventsStoragePreloadSucceeded\n },\n isNativeCaptureReady: () => this._isNativePluginInitialized(),\n })\n this._setDefaultPersonProperties = options?.setDefaultPersonProperties ?? true\n this._overrideDisplayLanguage = options?.overrideDisplayLanguage?.trim() || null\n this._requestHeaders = options?.requestHeaders ?? {}\n\n // Either build the app properties from the existing ones\n this._appProperties =\n typeof options?.customAppProperties === 'function'\n ? options.customAppProperties(getAppProperties())\n : options?.customAppProperties || getAppProperties()\n\n // Resolve storage and construct the logs module BEFORE registering the\n // AppState listener — the listener body references `this._logs` and\n // `this._eventsStorage`, and while AppState.addEventListener('change')\n // only fires on changes (not at registration), the dependency direction\n // should be explicit: dependencies first, callbacks that use them second.\n let storagePromise: Promise<void> | undefined\n\n let theStorage: PostHogCustomStorage | undefined\n if (this._persistence === 'file') {\n theStorage = options?.customStorage ?? buildOptimisticAsyncStorage()\n }\n\n if (theStorage) {\n this._eventsStorage = createEventsStorage(theStorage)\n this._logsStorage = createLogsStorage(theStorage)\n // `allSettled` so one pipeline's preload failure doesn't block the other. The failing\n // cache starts empty; future writes still target its configured storage backend.\n const preloads: Array<['events' | 'logs', Promise<void>]> = []\n if (this._eventsStorage.preloadPromise) {\n void this._eventsStorage.preloadPromise.catch(() => {\n this._eventsStoragePreloadSucceeded = false\n })\n preloads.push(['events', this._eventsStorage.preloadPromise])\n }\n if (this._logsStorage.preloadPromise) {\n preloads.push(['logs', this._logsStorage.preloadPromise])\n }\n if (preloads.length > 0) {\n storagePromise = allSettled(preloads.map(([, p]) => p)).then((results) => {\n results.forEach((r, i) => {\n if (r.status === 'rejected') {\n this._logger.error(`PostHog ${preloads[i][0]} storage preload failed:`, r.reason)\n }\n })\n })\n }\n } else {\n this._eventsStorage = createEventsMemoryStorage()\n this._logsStorage = createLogsMemoryStorage()\n }\n\n // Seed from sync `AppState.currentState` so the very first capture (which\n // can happen before any 'change' event fires) is already tagged. Maps\n // RN's broader status set into the OTLP `app.state` enum's\n // foreground/background dichotomy.\n this._currentAppState = mapAppStateForLogs(AppState.currentState)\n\n this._resolvedLogsConfig = resolveLogsConfig(options?.logs)\n this._logs = new PostHogLogs(\n this,\n this._resolvedLogsConfig,\n this._logger,\n () => {\n // Pulled at capture time so each tag reflects state at the moment\n // the log was fired, not at flush.\n const flags = this.getFeatureFlags()\n const flagKeys = flags ? Object.keys(flags) : undefined\n return {\n distinctId: this.getDistinctId() || undefined,\n sessionId: this.getSessionId() || undefined,\n screenName: (this.sessionProps?.$screen_name as string | undefined) || undefined,\n appState: this._currentAppState,\n activeFeatureFlags: flagKeys && flagKeys.length > 0 ? flagKeys : undefined,\n }\n },\n (fn) => this.wrap(fn),\n // Block between batches on the logs-storage disk write so a crash can't\n // replay an already-sent batch. Events do the equivalent via\n // `flushStorage()` (events-storage side). Mirror per-pipeline so one\n // pipeline's slow disk doesn't stall the other.\n () => this._logsStorage.waitForPersist()\n )\n\n // NOTE: this listener is registered for the lifetime of the PostHog\n // instance and is never explicitly removed. RN apps typically construct\n // a single long-lived PostHog and keep it until process exit, so a leak\n // doesn't matter in practice; just be aware that constructing many\n // instances (e.g. in tests without an explicit teardown) would\n // accumulate listeners.\n AppState.addEventListener('change', (state) => {\n // ignore unknown state (usually initial state, the app might not be ready yet)\n if (state === 'unknown') {\n return\n }\n\n // Update before kicking off the flush — captures that race the flush\n // (e.g. fired in a `componentWillUnmount` triggered by backgrounding)\n // should already see the new state.\n const mapped = mapAppStateForLogs(state)\n if (mapped) {\n this._currentAppState = mapped\n }\n\n // Flush on every transition, including foreground→active. Foreground\n // flush is technically redundant (the timer would catch up shortly),\n // but it's cheap and keeps the lifecycle handler symmetric — no\n // special-casing of which transitions should drain.\n void this.flush().catch(async (err) => {\n await logFlushError(err)\n })\n // Flush buffered logs alongside events — OS may suspend or terminate the\n // process next, and anything left in the queue won't get a second chance\n // until the app is next foregrounded. On background, race the flush\n // against `backgroundFlushBudgetMs` so a slow network can't run past\n // the OS-imposed background window (~30s on iOS). Foreground/active\n // transitions don't need a budget — the app is staying alive.\n const isBackgrounding = mapped === 'background'\n const logsFlushPromise = isBackgrounding\n ? this._logs.flushWithTimeout(this._resolvedLogsConfig.backgroundFlushBudgetMs)\n : this._logs.flush()\n void logsFlushPromise.catch(async (err) => {\n await logFlushError(err)\n })\n // Persist pending writes before the OS may suspend the process.\n void this._eventsStorage.waitForPersist()\n void this._logsStorage.waitForPersist()\n\n if (state === 'active') {\n this.getSessionId()\n }\n })\n\n const initAfterStorage = (): void => {\n // reset session id on app restart\n const enablePersistSessionIdAcrossRestart = options?.enablePersistSessionIdAcrossRestart\n if (!enablePersistSessionIdAcrossRestart) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, null)\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null)\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null)\n }\n\n this.setupBootstrap(options)\n\n // Seed device_id from the anonymous id at init time so existing installs\n // get a stable device-level identifier; once set, it survives identify()\n // and reset() independently of anonymous_id.\n if (!this.getPersistedProperty(PostHogPersistedProperty.DeviceId)) {\n const anonId = this.getAnonymousId()\n if (anonId) {\n this.setPersistedProperty(PostHogPersistedProperty.DeviceId, anonId)\n }\n }\n\n // Set default person properties for flags if enabled\n if (this._setDefaultPersonProperties) {\n this._setDefaultPersonPropertiesForFlags(false)\n }\n\n this._isInitialized = true\n\n if (this.isDisabled) {\n return\n }\n\n // Preload error tracking state from cached remote config.\n // This gates error tracking autocapture before the fresh remote config is fetched.\n const cachedRemoteConfig = this.getPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(\n PostHogPersistedProperty.RemoteConfig\n )\n if (cachedRemoteConfig) {\n this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking)\n }\n\n this.reloadRemoteConfigAsync()\n .then((response) => {\n if (response) {\n // Applies the remote autocapture kill-switch at the earliest authoritative\n // point; the flags response may apply it again later.\n this._errorTracking.onRemoteConfig(response.errorTracking)\n this._handleSurveysFromRemoteConfig(response)\n }\n })\n .catch((error) => {\n this._logger.error('Error loading remote config:', error)\n })\n .finally(() => {\n this._notifySurveysReady()\n })\n\n // captureAppLifecycleEvents defaults to true; only skip if explicitly set to false\n if (options?.captureAppLifecycleEvents !== false) {\n void this.captureAppLifecycleEvents()\n }\n\n void this.persistAppVersion()\n\n void this.startSessionReplay(options, cachedRemoteConfig ?? undefined)\n\n // Re-evaluate session replay on every flags load/reload so the linked flag\n // gates recording without an app restart. A pending manual start can also retry here,\n // even when replay was disabled at setup.\n this.onFeatureFlags(() => {\n if (this._isEnableSessionReplay() || this._manualRecordingStartRequest?.pending) {\n void this._evaluateAndStartSessionReplay()\n }\n })\n\n if (options?.addTracingHeaders && options.addTracingHeaders.length > 0) {\n patchFetchForTracingHeaders(this, options.addTracingHeaders)\n }\n }\n\n // For async storage, we wait for the storage to be ready before we start the SDK\n // For sync storage we can start the SDK immediately\n if (storagePromise) {\n this._initPromise = storagePromise.then(initAfterStorage)\n } else {\n this._initPromise = Promise.resolve()\n initAfterStorage()\n }\n }\n\n /**\n *\n * @internal\n *\n */\n public async ready(): Promise<void> {\n await this._initPromise\n }\n\n /**\n * Called when remote config has been loaded (from either the remote config endpoint or the flags endpoint).\n * Gates error tracking autocapture based on the remote config response.\n *\n * Session replay config (consoleLogRecordingEnabled, sampleRate, capturePerformance.network_timing) is already\n * cached via PostHogPersistedProperty.RemoteConfig and applied at startup in startSessionReplay().\n *\n * @internal\n */\n protected onRemoteConfig(response: PostHogRemoteConfig): void {\n this._errorTracking.onRemoteConfig(response.errorTracking)\n }\n\n /**\n * Resolves the storage instance for a given persisted-property key.\n * `LogsQueue` routes to `_logsStorage` (dedicated `.posthog-rn-logs.json`\n * file); every other key routes to `_eventsStorage`. Single source of\n * truth for routing — extending to new logs-scoped keys is a one-line\n * edit here.\n */\n private _storageForKey(key: PostHogPersistedProperty): PostHogRNStorage {\n return key === PostHogPersistedProperty.LogsQueue ? this._logsStorage : this._eventsStorage\n }\n\n getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined {\n return this._storageForKey(key).getItem(key) as T | undefined\n }\n\n setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void {\n const storage = this._storageForKey(key)\n if (key === PostHogPersistedProperty.SurveysInProgress && value === null) {\n const otherProjects = getOtherProjectSurveyProgress(this)\n otherProjects.length ? storage.setItem(key, otherProjects) : storage.removeItem(key)\n this._events.emit('surveysReset', undefined)\n } else {\n value !== null ? storage.setItem(key, value) : storage.removeItem(key)\n }\n if (key === PostHogPersistedProperty.PersonProperties) {\n // Notify surveys after the in-memory write, including unsets and resets,\n // without waiting for a feature flag reload.\n this._events.emit('personProperties', value)\n }\n }\n\n /**\n * Waits for any pending storage operations to complete.\n * This ensures data has been safely written to async storage before\n * considering events as sent, preventing duplicate events on app crash/restart.\n */\n protected async flushStorage(): Promise<void> {\n await this._eventsStorage.waitForPersist()\n }\n\n /**\n * Drain both pipelines on shutdown. Run in parallel so the logs final\n * flush + timer teardown doesn't serialize behind events (and vice-versa).\n * `_logs.shutdown()` swallows its own errors — a transient logs failure\n * must not break events shutdown.\n *\n * Logs use the smaller of `terminationFlushBudgetMs` and the caller's\n * `shutdownTimeoutMs` so a final flush can never run past the caller's\n * shutdown SLA, while still respecting the configured logs-specific\n * termination budget when it's tighter.\n *\n * After the flushes, drain any debounced storage writes that weren't already\n * persisted via the queue-advance path — `setPersistedProperty` calls for\n * distinctId, sessionId, deviceId, feature flag overrides, etc. only arm a\n * debounced write. The drain runs in `finally` so a timed-out flush still\n * persists them, and its await is bounded by the time left in the shutdown\n * SLA so a hung storage backend can't run past it.\n */\n async _shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {\n this._cancelManualRecordingStart()\n const start = Date.now()\n try {\n const remainingMs = Math.max(0, shutdownTimeoutMs - (Date.now() - start))\n const logsBudgetMs = Math.min(remainingMs, this._resolvedLogsConfig.terminationFlushBudgetMs)\n await Promise.all([this._logs.shutdown(logsBudgetMs), super._shutdown(remainingMs)])\n } finally {\n this._errorTracking.shutdown()\n // Sync drain runs inside waitForPersist before the race below; the race\n // only bounds the await for in-flight async writes.\n const remainingMs = Math.max(0, shutdownTimeoutMs - (Date.now() - start))\n const drain = Promise.all([this._eventsStorage.waitForPersist(), this._logsStorage.waitForPersist()])\n await raceWithTimeout(drain, remainingMs)\n }\n }\n\n fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {\n return fetch(url, options)\n }\n\n getLibraryId(): string {\n return 'posthog-react-native'\n }\n\n getLibraryVersion(): string {\n return version\n }\n\n getCustomUserAgent(): string {\n if (Platform.OS === 'web') {\n return ''\n }\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`\n }\n\n protected getCustomHeaders(): { [key: string]: string } {\n return { ...super.getCustomHeaders(), ...this._requestHeaders }\n }\n\n getCommonEventProperties(): PostHogEventProperties {\n // On iOS, 'screen' is UIScreen.main, which ignores resizable windows and stays the outer display on\n // foldables. 'window' is the app's window. Android's 'window' can exclude system bars, so keep 'screen' there.\n const { width, height } = Dimensions.get(Platform.OS === 'ios' ? 'window' : 'screen')\n return {\n ...super.getCommonEventProperties(),\n ...this._appProperties,\n $screen_height: height,\n $screen_width: width,\n }\n }\n\n getSurveyDisplayLanguageOverride(): string | null {\n return this._overrideDisplayLanguage\n }\n\n /**\n * Registers super properties that are sent with every event.\n *\n * Super properties are properties associated with events that are set once and then sent with every capture call.\n * They persist across sessions and are stored locally.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // register super properties\n * posthog.register({\n * 'icecream pref': 'vanilla',\n * team_id: 22,\n * })\n * ```\n *\n * @public\n *\n * @param properties An associative array of properties to store about the user\n */\n register(properties: PostHogEventProperties): Promise<void> {\n return super.register(properties)\n }\n\n /**\n * Removes a super property so it won't be sent with future events.\n *\n * Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // remove a super property\n * posthog.unregister('icecream pref')\n * ```\n *\n * @public\n *\n * @param property The name of the super property to remove\n */\n unregister(property: string): Promise<void> {\n return super.unregister(property)\n }\n\n /**\n * Resets the user's ID and anonymous ID after logout.\n *\n * To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.\n * This also clears all stored super properties and more.\n *\n * By default (when `propertiesToKeep` is not provided), the app lifecycle properties\n * (`InstalledAppBuild` and `InstalledAppVersion`) are automatically preserved to prevent\n * duplicate \"Application Installed\" events on the next app launch.\n *\n * If you pass `propertiesToKeep` explicitly, only the properties you specify will be preserved.\n * To keep the default app lifecycle behavior, include `PostHogPersistedProperty.InstalledAppBuild`\n * and `PostHogPersistedProperty.InstalledAppVersion` in your array.\n *\n * Note: The event queue (`PostHogPersistedProperty.Queue`) and logs queue\n * (`PostHogPersistedProperty.LogsQueue`) are always preserved regardless of\n * what is passed in `propertiesToKeep`, to ensure in-flight data is not lost.\n *\n * The project-level remote config (`PostHogPersistedProperty.RemoteConfig`,\n * `PostHogPersistedProperty.SessionReplay`, `PostHogPersistedProperty.Surveys`) is also\n * always preserved — it is not user data — so session replay and surveys keep working\n * after an identity change. The user-specific survey state (`SurveysSeen`,\n * `SurveyLastSeenDate`) is still cleared.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // reset after logout (preserves app lifecycle properties by default)\n * posthog.reset()\n * ```\n *\n * @example\n * ```js\n * // reset but keep feature flag overrides and app lifecycle properties\n * posthog.reset([\n * PostHogPersistedProperty.OverrideFeatureFlags,\n * PostHogPersistedProperty.InstalledAppBuild,\n * PostHogPersistedProperty.InstalledAppVersion,\n * ])\n * ```\n *\n * @param propertiesToKeep - Optional array of persisted properties to preserve during reset.\n * When not provided, app lifecycle and device bucketing properties are automatically preserved.\n * When provided, only the specified properties are preserved.\n * The event queue and logs queue are always preserved regardless.\n *\n * @public\n */\n reset(propertiesToKeep?: PostHogPersistedProperty[]): void {\n // When propertiesToKeep is not explicitly provided, automatically preserve app lifecycle\n // properties and device_id to prevent duplicate \"Application Installed\" events and\n // to maintain stable feature flag bucketing across identity changes.\n const effectivePropertiesToKeep = propertiesToKeep ?? [\n PostHogPersistedProperty.InstalledAppBuild,\n PostHogPersistedProperty.InstalledAppVersion,\n PostHogPersistedProperty.DeviceId,\n ]\n\n // Cancel before super.reset() emits flags for the next, anonymous user.\n this._cancelManualRecordingStart()\n\n // RemoteConfig, SessionReplay, and Surveys are project-level config, not user data:\n // always preserve them so replay can re-arm against the new user's flags. The\n // user-specific survey state (SurveysSeen, SurveyLastSeenDate) is still cleared.\n // Do NOT keep SessionReplayEventTriggerActivatedSession: it is user-session state, so the\n // base reset() must clear it to stop one user's activation leaking into the next.\n // PushRegistered is device-level subscription state, not user data: native reset()\n // re-binds the subscription rather than deleting it, so the device stays registered.\n super.reset([\n PostHogPersistedProperty.RemoteConfig,\n PostHogPersistedProperty.SessionReplay,\n PostHogPersistedProperty.Surveys,\n PostHogPersistedProperty.PushRegistered,\n ...effectivePropertiesToKeep,\n ])\n\n if (this._setDefaultPersonProperties) {\n // Reset reloads flags asyncrhonously, but doesn't wait for it.\n // As a result, we can synchronously set the default person properties without\n // reloading, and allow the super.reset() call to reload the flags.\n this._setDefaultPersonPropertiesForFlags(false)\n }\n\n // Native holds its own identity and a registered push token is bound to it, so without this\n // Workflows keep delivering to the logged-out user. identify() only writes native\n // preferences; reset() is what unregisters and re-registers the subscription.\n if (OptionalReactNativePlugin?.reset) {\n // Ids are read at dispatch, not here: a same-tick identify() shares this queue and\n // lands after, so native must converge on whichever identity is current by then.\n void this._enqueueNative(\n 'reset',\n (plugin) => plugin.reset?.(String(this.getDistinctId()), String(this.getAnonymousId())),\n // Boot native when a manual register persisted a subscription; skipping the rebind\n // would leave Workflows targeting the pre-reset identity.\n this.getPersistedProperty(PostHogPersistedProperty.PushRegistered) === true\n )\n }\n // super.reset() cleared the persisted opt-out, but native keeps its own copy and would\n // stay opted out for the rest of the process.\n this._propagateNativeOptOut()\n\n // Logout must be durable so a crash in the debounce window can't resurface the previous user.\n void this._eventsStorage.waitForPersist()\n }\n\n /**\n * Helper to extract and set default person properties from app properties\n *\n * @private\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n private _setDefaultPersonPropertiesForFlags(reloadFeatureFlags = true): void {\n const defaultProps: Record<string, JsonType> = {}\n const relevantKeys = [\n '$app_version',\n '$app_build',\n '$app_namespace',\n '$os_name',\n '$os_version',\n '$device_type',\n ] as const\n\n relevantKeys.forEach((key) => {\n const value = this._appProperties[key]\n if (value !== null && value !== undefined) {\n defaultProps[key] = value\n }\n })\n\n const commonProps = this.getCommonEventProperties()\n if (commonProps.$lib) {\n defaultProps.$lib = commonProps.$lib\n }\n if (commonProps.$lib_version) {\n defaultProps.$lib_version = commonProps.$lib_version\n }\n\n if (Object.keys(defaultProps).length > 0) {\n this.setPersonPropertiesForFlags(defaultProps, reloadFeatureFlags)\n }\n }\n\n /**\n * Manually flushes the event queue.\n *\n * You can set the number of events in the configuration that should queue before flushing.\n * Setting this to 1 will send events immediately and will use more battery. This is set to 20 by default.\n * You can also manually flush the queue. If a flush is already in progress it returns a promise for the existing flush.\n *\n * Note: this drains the **events** pipeline only. Logs are flushed via\n * {@link flushLogs}, and {@link shutdown} drains both before terminating.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // manually flush the queue\n * await posthog.flush()\n * ```\n *\n * @see flushLogs\n * @public\n *\n * @returns Promise that resolves when the flush is complete\n */\n flush(): Promise<void> {\n return super.flush()\n }\n\n /**\n * Captures a structured log record and sends it to PostHog's logs product\n * (`/i/v1/logs`). Low-level primitive — most callers will prefer\n * `posthog.logger.info(...)` / `.warn(...)` / `.error(...)` etc., which\n * wrap this with a level pre-set.\n *\n * Records are buffered per-session, rate-limited, batched into OTLP\n * payloads, and flushed on a timer, on AppState change, or when the\n * buffer reaches capacity. Configure flush cadence, rate cap, and a\n * `beforeSend` filter via the `logs` option on `new PostHog(...)`.\n *\n * Note — naming collision: `posthog.captureLog()` (this method) is the\n * **logs product** API. There is also a separate, pre-existing\n * `sessionReplayConfig.captureLog` boolean that controls whether\n * **session replay** records the device's `console.*` output. The two\n * are unrelated: this method emits structured records to the logs\n * pipeline regardless of whether session replay is on.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * posthog.captureLog({\n * body: 'checkout completed',\n * level: 'info',\n * attributes: { order_id: 'ord_789', amount_cents: 4999 },\n * })\n * ```\n *\n * @public\n *\n * @param options Log record. `body` is required; `level` defaults to\n * `'info'`. `attributes` are attached as OTLP key-value attributes\n * and will override auto-populated ones (distinctId, sessionId) on\n * key conflict.\n */\n captureLog(options: CaptureLogOptions): void {\n this._logs.captureLog(options)\n }\n\n /**\n * Manually flushes the logs queue.\n *\n * Logs flush automatically on a timer, when the buffer fills, or on\n * AppState change — most apps never need to call this. Use it when you\n * want a synchronous-style hand-off (e.g. before navigating away from a\n * critical screen, in a custom crash handler, or while testing locally).\n *\n * If a flush is already in progress, both callers join the same in-flight\n * promise — no double-send.\n *\n * Note: this drains the **logs** pipeline only. Events are flushed via\n * {@link flush}, and {@link shutdown} drains both before terminating.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * await posthog.flushLogs()\n * ```\n *\n * @see flush\n * @public\n *\n * @returns Promise that resolves when the flush is complete.\n */\n flushLogs(): Promise<void> {\n return this._logs.flush()\n }\n\n private _captureLogger?: CaptureLogger\n\n /**\n * Convenience per-level logger. Each method is shorthand for\n * `posthog.captureLog({ body, level, attributes })`. Lazily constructed\n * on first access, then reused.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * posthog.logger.info('checkout completed', { order_id: 'ord_789' })\n * posthog.logger.error('payment failed', { code: 'E001' })\n * ```\n *\n * @public\n */\n get logger(): CaptureLogger {\n if (!this._captureLogger) {\n this._captureLogger = {\n trace: (body, attributes) => this.captureLog({ body, level: 'trace', attributes }),\n debug: (body, attributes) => this.captureLog({ body, level: 'debug', attributes }),\n info: (body, attributes) => this.captureLog({ body, level: 'info', attributes }),\n warn: (body, attributes) => this.captureLog({ body, level: 'warn', attributes }),\n error: (body, attributes) => this.captureLog({ body, level: 'error', attributes }),\n fatal: (body, attributes) => this.captureLog({ body, level: 'fatal', attributes }),\n }\n }\n return this._captureLogger\n }\n\n /**\n * Opts the user in to data capture.\n *\n * By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }.\n * Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called.\n *\n * {@label Privacy}\n *\n * @example\n * ```js\n * // opt in to tracking\n * posthog.optIn()\n * ```\n *\n * @public\n */\n optIn(): Promise<void> {\n // Consent must be durable. See reset()/identify().\n const result = super.optIn()\n void this._eventsStorage.waitForPersist()\n // Native re-arms push on opt-in (iOS reinstalls its integrations, Android resumes deferred\n // work on the next flush), so the token unregistered by optOut() comes back without a restart.\n this._propagateNativeOptOut()\n return result\n }\n\n /**\n * Opts the user out of data capture.\n *\n * 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.\n *\n * {@label Privacy}\n *\n * @example\n * ```js\n * // opt out of tracking\n * posthog.optOut()\n * ```\n *\n * @public\n */\n optOut(): Promise<void> {\n this._cancelManualRecordingStart()\n // Consent must be durable. See reset()/identify().\n const coreOptOut = super.optOut()\n const persistOptOut = (): Promise<void> => {\n this.setPersistedProperty(PostHogPersistedProperty.SurveysInProgress, null)\n return this._eventsStorage.waitForPersist()\n }\n const result = Promise.all([\n coreOptOut,\n this._isInitialized ? persistOptOut() : this._initPromise.then(persistOptOut),\n ]).then(() => undefined)\n // A fatal exception captured before this point lives in the native SDK's own queue, so\n // there is nothing left on the JS side to clear. _propagateNativeOptOut() below stops\n // native capturing anything further.\n //\n // NOTE: neither native SDK drops what its queue already holds on optOut(), so an\n // exception captured while opted in can still be delivered after consent is withdrawn.\n // The JS journal this replaced rotated a generation to prevent exactly that. Delivery\n // usually happens on the relaunch flush, before a user can opt out, but the guarantee\n // is weaker than it was.\n // A device token registered before opt-out would otherwise survive consent withdrawal: the\n // native subscription handler keeps its own persisted record and retry loop. unregister is\n // deliberately allowed while opted out.\n // Native gates unregister sends on its own opt-out flag, so the unregister has to reach\n // native first; both share _nativeChain, so enqueueing it first is the ordering. A DELETE\n // that still loses the race natively is persisted there and replayed after opt-in.\n if (OptionalReactNativePlugin?.unregisterPushNotificationToken) {\n void this.unregisterPushNotificationToken()\n }\n this._propagateNativeOptOut()\n return result\n }\n\n // Native persists its own consent flag and only reads the JS one at setup(), so runtime\n // changes must cross the bridge or native's automatic push registration keeps running on\n // its setup-time snapshot (e.g. re-registering an OS-refreshed token after optOut()).\n private _propagateNativeOptOut(): void {\n if (!OptionalReactNativePlugin?.setOptOut) {\n // A plugin that predates push cannot auto-register tokens, so there is no consent to sync.\n return\n }\n // Consent is read at dispatch, so two queued writes converge on the current value however\n // they interleave — an unawaited optOut()/optIn() pair cannot strand native opted out.\n void this._enqueueNative('setOptOut', (plugin) => plugin.setOptOut?.(this.optedOut))\n // Nothing runs setup() while opted out, so consent granted at runtime has no native\n // instance to land on. The predicate is false when opted out, so optOut() self-excludes.\n if (this._isPushNativeEnabled(this._sessionReplayOptions)) {\n void this._ensureNativeInitialized()\n }\n }\n\n /**\n * Checks if a feature flag is enabled for the current user.\n *\n * A `false` return value means the SDK resolved the current value as off. If no evaluation is\n * available, this method returns `defaultValue` when provided. Without a default, it returns\n * `undefined` before flags load; for backwards compatibility, a missing key can resolve to\n * `false` after a non-empty response is stored.\n *\n * Globally inactive flags are omitted from remote responses, so they follow this missing-key\n * behavior rather than carrying an explicit off evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // check if feature flag is enabled\n * const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')\n * ```\n *\n * @example\n * ```js\n * // fall back to false while flags are not loaded\n * const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: false })\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @param options Optional per-call settings\n * @returns True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above\n */\n isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & { defaultValue: boolean }): boolean\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined {\n return super.isFeatureEnabled(key, options)\n }\n\n /**\n * Gets the value of a feature flag for the current user.\n *\n * Returns `true` or `false` for an evaluated boolean flag and a string for a multivariate flag.\n * Returns `undefined` before flags load or when loading fails. For backwards compatibility, a\n * missing key can resolve to `false` after a non-empty response is stored; use\n * `getFeatureFlagResult()` to distinguish an unavailable key from a conclusive off result.\n *\n * Globally inactive flags are omitted from remote responses, so they follow this missing-key\n * behavior rather than carrying an explicit off evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // get feature flag value\n * const value = posthog.getFeatureFlag('key-for-your-boolean-flag')\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @param options Optional per-call settings\n * @returns The current feature flag value, or undefined if flags are unavailable\n */\n getFeatureFlag(key: string, options?: FeatureFlagResultOptions): boolean | string | undefined {\n return super.getFeatureFlag(key, options)\n }\n\n /**\n * Gets the payload of a feature flag for the current user.\n *\n * Returns JsonType or undefined if not loaded yet or if there was a problem loading.\n *\n * {@label Feature flags}\n *\n * @deprecated Use `getFeatureFlagResult()` instead, which returns the flag value and payload from a single evaluation.\n *\n * @example\n * ```js\n * // get feature flag payload\n * const payload = posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @returns The feature flag payload or undefined if not loaded\n */\n getFeatureFlagPayload(key: string): JsonType | undefined {\n return super.getFeatureFlagPayload(key)\n }\n\n /**\n * Reloads feature flags from the server.\n *\n * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.\n * If you want to manually trigger a refresh, you can call this method.\n *\n * {@label Feature flags}\n *\n * @remarks\n * When the `disableRemoteFeatureFlags` option is set, this method is a no-op; supply\n * flag values via `updateFlags()` instead.\n *\n * @example\n * ```js\n * // reload feature flags\n * posthog.reloadFeatureFlags()\n * ```\n *\n * @public\n */\n reloadFeatureFlags(): void {\n super.reloadFeatureFlags()\n }\n\n /**\n * Reloads feature flags from the server asynchronously.\n *\n * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.\n * If you want to manually trigger a refresh and get the result, you can call this method.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reload feature flags and get result\n * posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))\n * ```\n *\n * @public\n *\n * @remarks\n * When the `disableRemoteFeatureFlags` option is set, no request is made and the\n * promise resolves with the currently stored flags (from `bootstrap` or `updateFlags()`).\n *\n * @returns Promise that resolves with the refreshed flags\n */\n reloadFeatureFlagsAsync(): Promise<Record<string, boolean | string> | undefined> {\n return super.reloadFeatureFlagsAsync()\n }\n\n /**\n * Replaces (or merges into) the stored feature flags and payloads with locally supplied\n * values, exactly as if they had been returned by the flags endpoint: the values are\n * persisted, `getFeatureFlag()`/`getFeatureFlagPayload()` read them back, and\n * `onFeatureFlags` listeners fire. Makes no network request.\n *\n * Intended for apps that evaluate flags outside the SDK (e.g. server-side local\n * evaluation) and push the results in at runtime, typically together with the\n * `disableRemoteFeatureFlags` option so the SDK never fetches flags itself.\n *\n * {@label Feature flags}\n *\n * @remarks\n * The values are cleared by `reset()`, so push them again after an identity change.\n *\n * @example\n * ```js\n * // replace all stored flags with locally evaluated ones\n * posthog.updateFlags({ 'my-flag': true, 'multivariate-flag': 'variant-1' })\n * ```\n *\n * @example\n * ```js\n * // include payloads\n * posthog.updateFlags({ 'my-flag': true }, { 'my-flag': { color: 'blue' } })\n * ```\n *\n * @example\n * ```js\n * // merge into the stored flags instead of replacing them\n * posthog.updateFlags({ 'my-flag': false }, undefined, { merge: true })\n * ```\n *\n * @public\n *\n * @param flags - Flag keys mapped to their values (boolean, or a variant string)\n * @param payloads - Optional flag keys mapped to their JSON payloads\n * @param options - Set `merge: true` to merge with the currently stored flags instead of replacing them\n */\n updateFlags(\n flags: Record<string, boolean | string>,\n payloads?: Record<string, JsonType>,\n options?: { merge?: boolean }\n ): void {\n super.updateFlags(flags, payloads, options)\n }\n\n /**\n * Associates the current user with a group.\n *\n * Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.).\n * This is a paid feature and is not available on the open-source or free cloud plan.\n *\n * {@label Group analytics}\n *\n * @example\n * ```js\n * // associate with a group\n * posthog.group('company', 'company_id_in_your_db')\n * ```\n *\n * @example\n * ```js\n * // associate with a group and update properties\n * posthog.group('company', 'company_id_in_your_db', {\n * name: 'Awesome Inc.',\n * employees: 11,\n * })\n * ```\n *\n * @public\n *\n * @param groupType The type of group (e.g. 'company', 'team')\n * @param groupKey The unique identifier for the group\n * @param properties Optional properties to set for the group\n */\n group(groupType: string, groupKey: string, properties?: PostHogEventProperties): void {\n super.group(groupType, groupKey, properties)\n\n // Automatically cache group properties for feature flag evaluation\n if (properties && Object.keys(properties).length > 0) {\n const propsToCache: Record<string, JsonType> = {}\n Object.keys(properties).forEach((key) => {\n const value = properties[key]\n if (value !== null && value !== undefined) {\n propsToCache[key] = value\n }\n })\n if (Object.keys(propsToCache).length > 0) {\n this.setGroupPropertiesForFlags({\n [groupType]: propsToCache,\n })\n }\n }\n }\n\n /**\n * Assigns an alias to the current user.\n *\n * Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible.\n * For example, if a distinct ID used on the frontend is not available in your backend.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // set alias for current user\n * posthog.alias('distinct_id')\n * ```\n *\n * @public\n *\n * @param alias The alias to assign to the current user\n */\n alias(alias: string): void {\n super.alias(alias)\n }\n\n /**\n * Gets the current user's distinct ID.\n *\n * 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.\n * This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // get current distinct ID\n * const distinctId = posthog.getDistinctId()\n * ```\n *\n * @public\n *\n * @returns The current user's distinct ID\n */\n getDistinctId(): string {\n return super.getDistinctId()\n }\n\n /**\n * Returns the stable device identifier used for device-level feature flag bucketing.\n * This ID persists across identify() and reset() calls, only changing on a fresh\n * app install, manual cache clearing, or OS-initiated storage cleanup.\n *\n * @returns The device ID, or an empty string if not yet initialized\n */\n getDeviceId(): string {\n const deviceId = this.getPersistedProperty<string>(PostHogPersistedProperty.DeviceId)\n if (!deviceId) {\n // Lazy init for upgrades: existing installs won't have a device_id yet\n const anonId = this.getAnonymousId()\n if (anonId) {\n this.setPersistedProperty(PostHogPersistedProperty.DeviceId, anonId)\n return anonId\n }\n return ''\n }\n return deviceId\n }\n\n /**\n * Sets person properties for feature flag evaluation.\n *\n * Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier.\n * You can do so by setting properties the flag depends on with this call. These are set for the entire session.\n * Successive calls are additive: all properties you set are combined together and sent for flag evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // set person properties for flags\n * posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})\n * ```\n *\n * @public\n *\n * @param properties The person properties to set for flag evaluation\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setPersonPropertiesForFlags(properties: Record<string, JsonType>, reloadFeatureFlags = true): void {\n super.setPersonPropertiesForFlags(properties, reloadFeatureFlags)\n }\n\n /**\n * Resets person properties for feature flag evaluation.\n *\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reset person properties for flags\n * posthog.resetPersonPropertiesForFlags()\n * ```\n *\n * @public\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n resetPersonPropertiesForFlags(reloadFeatureFlags = true): void {\n super.resetPersonPropertiesForFlags()\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Sets group properties for feature flag evaluation.\n *\n * These properties are automatically attached to the current group (set via posthog.group()).\n * When you change the group, these properties are reset.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // set group properties for flags\n * posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})\n * ```\n *\n * @public\n *\n * @param properties The group properties to set for flag evaluation\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setGroupPropertiesForFlags(properties: Record<string, Record<string, JsonType>>, reloadFeatureFlags = true): void {\n super.setGroupPropertiesForFlags(properties)\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Resets group properties for feature flag evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reset group properties for flags\n * posthog.resetGroupPropertiesForFlags()\n * ```\n *\n * @public\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n resetGroupPropertiesForFlags(reloadFeatureFlags = true): void {\n super.resetGroupPropertiesForFlags()\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Captures a screen view event.\n *\n * @remarks\n * This function requires a name. You may also pass in an optional properties object.\n * Once initialized, the screen name is registered immediately for subsequent events, including exceptions.\n * During initialization, screen registration and event capture retain their call order.\n * Exceptions use the last recorded screen, not a destination that has not yet been tracked.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // Basic screen capture\n * posthog.screen('dashboard')\n * ```\n *\n * @example\n * ```js\n * // Screen capture with properties\n * posthog.screen('dashboard', {\n * background: 'blue',\n * hero: 'superhog',\n * })\n * ```\n *\n * @public\n *\n * @param name - The name of the screen\n * @param properties - Optional properties to include with the screen event\n * @param options - Optional capture options\n */\n async screen(name: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void> {\n // Keep queued captures in order during initialization, without yielding once the client is ready.\n if (!this._isInitialized) {\n await this._initPromise\n }\n this.registerForSession({\n $screen_name: name,\n })\n\n return this.capture(\n '$screen',\n {\n ...properties,\n $screen_name: name,\n },\n options\n )\n }\n\n _isEnableSessionReplay(): boolean {\n // Session replay has no macOS backend, so it is never enabled there (crash tracking still is).\n return !this.isDisabled && !isMacOS() && (this._enableSessionReplay ?? false)\n }\n\n _resetSessionId(reactNativeSessionReplay: typeof OptionalReactNativePlugin | undefined, sessionId: string): void {\n // _resetSessionId is only called if reactNativeSessionReplay not undefined, but the linter wasn't happy\n if (reactNativeSessionReplay) {\n reactNativeSessionReplay.endSession()\n reactNativeSessionReplay.startSession(sessionId)\n }\n }\n\n getSessionId(): string {\n const sessionId = super.getSessionId()\n\n if (!this._isEnableSessionReplay() && !this._isNativePluginInitialized()) {\n return sessionId\n }\n\n // only rotate if there is a new sessionId and it is different from the current one\n if (sessionId.length > 0 && this._currentSessionId && sessionId !== this._currentSessionId) {\n if (OptionalReactNativePlugin) {\n try {\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n this._logger.info(`sessionId rotated from ${this._currentSessionId} to ${sessionId}.`)\n } catch (e) {\n this._logger.error(`Failed to rotate sessionId: ${e}.`)\n }\n }\n this._currentSessionId = sessionId\n\n // Event triggers are armed per session: the previous activation no longer matches the new\n // session id, so re-evaluate to stop recording until a fresh matching event fires.\n if (this._sessionReplayEventTriggers.length > 0) {\n void this._evaluateAndStartSessionReplay()\n }\n } else {\n this._logger.info(`sessionId not rotated, sessionId ${sessionId} and currentSessionId ${this._currentSessionId}.`)\n }\n\n return sessionId\n }\n\n resetSessionId(): void {\n super.resetSessionId()\n if ((this._isEnableSessionReplay() || this._isNativePluginInitialized()) && OptionalReactNativePlugin) {\n try {\n OptionalReactNativePlugin.endSession()\n this._logger.info(`Native PostHog session ended.`)\n } catch (e) {\n this._logger.error(`Native PostHog session failed to end: ${e}.`)\n }\n }\n }\n\n /**\n * Starts session recording.\n * This method will have no effect if PostHog is not enabled, or if session replay is disabled in your project settings.\n *\n * A refused manual start is retried with successive delays of 1, 2, 4, 8, and 16 seconds,\n * and on subsequent feature flags loads while pending. This promise resolves after the\n * initial attempt, without waiting for retries or guaranteeing recording is active.\n * A newer start supersedes an unfinished request. Stop, reset, opt-out, and shutdown\n * cancel pending starts. Use `isSessionReplayActive()` to check the current recording state.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this is a no-op.\n *\n * Requires `posthog-react-native-session-replay` version 1.3.0 or higher.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * // Resume the current session recording\n * await posthog.startSessionRecording()\n * ```\n *\n * @example\n * ```js\n * // Start a new session recording\n * await posthog.startSessionRecording(false)\n * ```\n *\n * @public\n *\n * @param resumeCurrent - Whether to resume recording of current session (true) or start a new session (false). Defaults to true.\n */\n async startSessionRecording(resumeCurrent: boolean = true): Promise<void> {\n this._cancelManualRecordingStart()\n const request: ManualRecordingStartRequest = { pending: false, retryCount: 0 }\n this._manualRecordingStartRequest = request\n // Chained here, not in _startSessionRecording (which _evaluateAndStartSessionReplayInternal\n // also calls from inside this chain — re-chaining there deadlocks), so two callers can't\n // both enter initializeNativePlugin() and race their pluginConfigs.\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n await this._attemptManualRecordingStart(request, resumeCurrent)\n })\n await this._sessionReplayEvalChain\n }\n\n private _cancelManualRecordingStart(): void {\n clearTimeout(this._manualRecordingStartRequest?.timer)\n this._manualRecordingStartRequest = undefined\n }\n\n private async _attemptManualRecordingStart(\n request: ManualRecordingStartRequest,\n resumeCurrent: boolean\n ): Promise<boolean> {\n if (this._manualRecordingStartRequest !== request) {\n return false\n }\n if (this.isDisabled || this.optedOut) {\n this._cancelManualRecordingStart()\n return false\n }\n\n const started = await this._startSessionRecording(resumeCurrent)\n // Cancellation is synchronous; a bridge call already in flight can still finish later.\n // Do not let its result revive the old request or leave its recorder running.\n if (this._manualRecordingStartRequest !== request) {\n if (started) {\n await this._stopSessionRecording()\n }\n return false\n }\n if (started) {\n this._cancelManualRecordingStart()\n } else {\n request.pending = true\n this._scheduleManualRecordingStartRetry(request)\n }\n return started\n }\n\n private _scheduleManualRecordingStartRetry(request: ManualRecordingStartRequest): void {\n const delay = MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount]\n if (\n request.timer !== undefined ||\n delay === undefined ||\n !this._sessionReplayNativeInitialized ||\n !OptionalReactNativePlugin?.startRecording\n ) {\n return\n }\n request.retryCount++\n request.timer = safeSetTimeout(() => {\n request.timer = undefined\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n // The original attempt already rotated the session if resumeCurrent was false.\n await this._attemptManualRecordingStart(request, true)\n })\n }, delay)\n }\n\n // Shared start path. Also called by the flags-driven evaluation, which runs inside\n // _sessionReplayEvalChain and so must not re-enter it.\n private async _startSessionRecording(resumeCurrent: boolean): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - nothing to do\n return false\n }\n\n try {\n // Check if the plugin supports startRecording\n if (!OptionalReactNativePlugin.startRecording) {\n this._logger.warn(\n 'startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n return false\n }\n\n // If only error tracking is active, add replay to the existing native instance\n // rather than re-initializing.\n if (!this._sessionReplayNativeInitialized) {\n this._logger.info('Native session replay SDK not initialized, initializing now...')\n const initialized = await this.initializeNativePlugin(this._sessionReplayOptions, undefined, true)\n if (!initialized) {\n this._logger.error('Failed to initialize native session replay SDK.')\n return false\n }\n }\n\n // Handle session ID if not resuming\n if (!resumeCurrent) {\n super.resetSessionId()\n const newSessionId = super.getSessionId()\n // sync native + rn sessionId\n this._resetSessionId(OptionalReactNativePlugin, String(newSessionId))\n this._currentSessionId = newSessionId\n }\n\n await OptionalReactNativePlugin.startRecording(resumeCurrent)\n\n // Both native SDKs refuse to start the recorder while their own remote config is not\n // loaded (PostHog.kt, PostHogSDK.swift) and resolve the call all the same, so ask the\n // recorder instead of reporting a success the caller cannot check.\n const started = await OptionalReactNativePlugin.isEnabled().catch((e) => {\n // Unknown state, so report the start rather than a failure nothing can act on.\n this._logger.warn(`Failed to confirm the session recording started: ${e}`)\n return true\n })\n\n if (!started) {\n this._logger.warn(\n 'The native SDK refused to start session recording, usually because its remote config is not loaded yet. ' +\n 'PostHog retries on the next feature flags load.'\n )\n return false\n }\n\n this._logger.info(`Session recording ${resumeCurrent ? 'resumed' : 'started'}.`)\n return true\n } catch (e) {\n this._logger.error(`Failed to start session recording: ${e}`)\n return false\n }\n }\n\n /**\n * Stops the current session recording if one is in progress.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this is a no-op.\n *\n * Requires `posthog-react-native-session-replay` version 1.3.0 or higher.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * await posthog.stopSessionRecording()\n * ```\n * @public\n */\n async stopSessionRecording(): Promise<void> {\n this._cancelManualRecordingStart()\n // Let an in-flight native start settle before stopping its recorder.\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n await this._stopSessionRecording()\n })\n await this._sessionReplayEvalChain\n }\n\n // Shared stop path, also called by the flags-driven evaluation.\n private async _stopSessionRecording(): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - nothing to do\n return false\n }\n\n try {\n // Check if the plugin supports stopRecording\n if (!OptionalReactNativePlugin.stopRecording) {\n this._logger.warn(\n 'stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n return false\n }\n\n await OptionalReactNativePlugin.stopRecording()\n this._logger.info('Session recording stopped.')\n return true\n } catch (e) {\n this._logger.error(`Failed to stop session recording: ${e}`)\n return false\n }\n }\n\n /**\n * Returns whether session replay is currently active.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this always returns false.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * const isActive = await posthog.isSessionReplayActive()\n * ```\n *\n * @public\n *\n * @returns Whether session replay is currently active\n */\n async isSessionReplayActive(): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - not active\n return false\n }\n\n try {\n return await OptionalReactNativePlugin.isEnabled()\n } catch (e) {\n this._logger.error(`Failed to check session replay status: ${e}`)\n return false\n }\n }\n\n /**\n * Associates events with a specific user. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // Basic identify\n * posthog.identify('distinctID', {\n * email: 'user@posthog.com',\n * name: 'My Name'\n * })\n * ```\n *\n * @example\n * ```js\n * // Using $set and $set_once\n * posthog.identify('distinctID', {\n * $set: {\n * email: 'user@posthog.com',\n * name: 'My Name'\n * },\n * $set_once: {\n * date_of_first_log_in: '2024-03-01'\n * }\n * })\n * ```\n *\n * @public\n *\n * @param distinctId - A unique identifier for your user. Typically either their email or database ID.\n * @param properties - Optional dictionary with key:value pairs to set the person properties\n * @param options - Optional capture options\n */\n identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {\n const previousDistinctId = this.getDistinctId()\n\n // Extract $set_once before super.identify() because core deletes it from the properties object\n const userProps = properties?.$set || properties\n const userPropsOnce = properties?.$set_once\n\n super.identify(distinctId, properties, options)\n\n // Automatically cache person properties for feature flag evaluation\n\n const propsToCache: Record<string, JsonType> = {}\n if (userProps && typeof userProps === 'object' && !Array.isArray(userProps)) {\n Object.entries(userProps).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n propsToCache[key] = value\n }\n })\n }\n\n const propsOnceToCache: Record<string, JsonType> = {}\n if (userPropsOnce && typeof userPropsOnce === 'object' && !Array.isArray(userPropsOnce)) {\n Object.entries(userPropsOnce).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n propsOnceToCache[key] = value\n }\n })\n }\n\n if (Object.keys(propsToCache).length > 0 || Object.keys(propsOnceToCache).length > 0) {\n // super.identify() already handles reloading flags in all cases:\n // - When distinctId changes: it calls reloadFeatureFlags() directly\n // - When distinctId is the same but properties change: it calls setPersonProperties() which reloads flags\n // So we only need to set the properties here without triggering another reload.\n this.setPersonPropertiesForFlags(\n {\n $set: propsToCache,\n ...(Object.keys(propsOnceToCache).length > 0 ? { $set_once: propsOnceToCache } : {}),\n },\n false\n )\n }\n\n if (OptionalReactNativePlugin) {\n // Queued, not inline: a same-tick reset() is already on _nativeChain and must land first,\n // or its post-reset anonymous id gets overwritten. No init check here — gating on\n // _isNativePluginInitialized() would lose every identify() issued while setup() is in\n // flight, which is most startup identifies.\n void this._enqueueNative('identify', (plugin) => {\n const nativeDistinctId = String(this.getDistinctId() || previousDistinctId)\n const anonymousId = String(this.getAnonymousId())\n const identified = plugin.identify(nativeDistinctId, anonymousId)\n this._logger.info(\n `Native PostHog identified with distinctId ${nativeDistinctId} and anonymousId ${anonymousId}.`\n )\n return identified\n })\n }\n\n // Account-switch safety — same as reset().\n void this._eventsStorage.waitForPersist()\n }\n\n /**\n * Capture a caught exception manually\n *\n * Exceptions also include capture-time `$app_state` (active, background, inactive or extension) on any\n * platform where React Native AppState provides a known value. On iOS and Android, optional\n * `expo-updates` (0.25.0 or newer) adds `$expo_update_id`, `$expo_runtime_version`, `$expo_channel`\n * and `$expo_is_embedded_launch` for enabled updates outside development mode. Unknown values\n * are omitted.\n * These exception-only fields are separate from the static app metadata controlled by\n * `customAppProperties`, including the existing `$app_version` and `$app_build`.\n * Override these fields with `additionalProperties`, or remove them using `before_send`.\n *\n * {@label Error tracking}\n *\n * @public\n *\n * @example\n * ```js\n * // Capture a caught exception\n * try {\n * // something that might throw\n * } catch (error) {\n * posthog.captureException(error)\n * }\n * ```\n *\n * @example\n * ```js\n * // With additional properties\n * posthog.captureException(error, {\n * customProperty: 'value',\n * anotherProperty: ['I', 'can be a list'],\n * ...\n * })\n * ```\n *\n * @param {Error} error The error to capture\n * @param {Object} [additionalProperties] Any additional properties to add to the error event\n * @returns {void}\n */\n captureException(\n error: Error | unknown,\n additionalProperties: PostHogEventProperties = {},\n hint?: CoreErrorTracking.EventHint\n ): void {\n try {\n const result = this.captureExceptionInternal(error, additionalProperties, hint)\n if (result?.additionalProperties?.$exception_level === 'fatal') {\n void this._eventsStorage.waitForPersist()\n void this._logsStorage.waitForPersist()\n }\n } catch (e) {\n this._logger.error('Error while capturing $exception:', e)\n }\n }\n\n private captureExceptionInternal(\n error: Error | unknown,\n additionalProperties: PostHogEventProperties = {},\n hint?: CoreErrorTracking.EventHint,\n options?: PostHogCaptureOptions\n ): {\n eventUuid: string\n timestamp: string\n additionalProperties: PostHogEventProperties\n } | null {\n const resolvedHint: CoreErrorTracking.EventHint = hint ?? {\n mechanism: { handled: true, type: 'generic' },\n syntheticException: new Error('Synthetic Error'),\n }\n\n const merged: PostHogEventProperties = { ...getExceptionContext(), ...additionalProperties }\n\n // Attach the rolling exception-steps buffer (no-op if the caller already provided their own).\n const finalAdditional = this._errorTracking.attachExceptionSteps(merged)\n\n const captureOptions: PostHogCaptureOptions = {\n ...(options || {}),\n _originatedFromCaptureException: true,\n }\n\n this.capture(\n '$exception',\n { ...this.buildExceptionProperties(error, resolvedHint), ...finalAdditional },\n captureOptions\n )\n\n const eventUuid = captureOptions.uuid ?? ''\n const timestamp = (captureOptions.timestamp ?? new Date()).toISOString()\n return {\n eventUuid,\n timestamp,\n additionalProperties: finalAdditional,\n }\n }\n\n private buildExceptionProperties(error: Error | unknown, hint: CoreErrorTracking.EventHint): PostHogEventProperties {\n try {\n const builder = this.getErrorPropertiesBuilder()\n const exceptionProperties = builder.buildFromUnknown(error, hint) as unknown as PostHogEventProperties\n return exceptionProperties\n } catch (e) {\n this._logger.error('Error while building exception properties:', e)\n return {}\n }\n }\n\n /**\n * Records a breadcrumb-style exception step. Steps accumulate in a rolling, byte-bounded buffer\n * and are attached to every captured `$exception` as `$exception_steps`, giving the error tracking\n * UI a timeline of recent activity before each error.\n *\n * The `$timestamp` is captured at call time. The reserved keys `$message` and `$timestamp` are\n * stripped from `properties` — the SDK sets the canonical values. This method never throws.\n *\n * @example\n * ```js\n * posthog.addExceptionStep('User tapped Checkout', { screen: 'cart' })\n * ```\n *\n * @param {string} message A non-empty description of the step\n * @param {Object} [properties] Optional additional context to attach to the step\n * @returns {void}\n */\n addExceptionStep(message: string, properties?: Properties): void {\n this._errorTracking.addExceptionStep(message, properties)\n }\n\n protected override createErrorPropertiesBuilder(): CoreErrorTracking.ErrorPropertiesBuilder {\n return new CoreErrorTracking.ErrorPropertiesBuilder(\n [\n new CoreErrorTracking.PromiseRejectionEventCoercer(),\n new CoreErrorTracking.ErrorCoercer(),\n new CoreErrorTracking.ErrorEventCoercer(),\n new CoreErrorTracking.ObjectCoercer(),\n new CoreErrorTracking.StringCoercer(),\n new CoreErrorTracking.PrimitiveCoercer(),\n ],\n CoreErrorTracking.createStackParser(\n isHermes() ? 'hermes' : 'web:javascript',\n CoreErrorTracking.chromeStackLineParser,\n CoreErrorTracking.geckoStackLineParser\n )\n )\n }\n\n initReactNativeNavigation(options: PostHogAutocaptureOptions): boolean {\n return withReactNativeNavigation(this, options)\n }\n\n /**\n * Creates a person profile for the current user, if they don't already have one.\n *\n * This is useful when using `personProfiles: 'identified_only'` mode and you want to\n * explicitly create a profile for an anonymous user before they identify.\n *\n * If `personProfiles` is 'identified_only' and no profile exists, this will create one.\n * If `personProfiles` is 'never', this will log an error and do nothing.\n * If `personProfiles` is 'always' or a profile already exists, this is a no-op.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // Create a person profile for an anonymous user\n * posthog.createPersonProfile()\n * ```\n *\n * @public\n */\n createPersonProfile(): void {\n super.createPersonProfile()\n }\n\n /**\n * Sets properties on the person profile associated with the current `distinct_id`.\n * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @remarks\n * Updates user properties that are stored with the person profile in PostHog.\n * If `personProfiles` is set to `identified_only` and no profile exists, this will create one.\n *\n * @example\n * ```js\n * // set user properties\n * posthog.setPersonProperties({\n * email: 'user@example.com',\n * plan: 'premium'\n * })\n * ```\n *\n * @example\n * ```js\n * // set properties with $set_once\n * posthog.setPersonProperties(\n * { name: 'Max Hedgehog' }, // $set properties\n * { initial_url: '/blog' } // $set_once properties\n * )\n * ```\n *\n * @example\n * ```js\n * // set properties without reloading feature flags\n * posthog.setPersonProperties({ plan: 'premium' }, undefined, false)\n * ```\n *\n * @public\n *\n * @param userPropertiesToSet - Optional: An object of properties to store about the user.\n * These properties will overwrite any existing values for the same keys.\n * @param userPropertiesToSetOnce - Optional: An object of properties to store about the user.\n * If a property is previously set, this does not override that value.\n * @param reloadFeatureFlags - Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setPersonProperties(\n userPropertiesToSet?: { [key: string]: JsonType },\n userPropertiesToSetOnce?: { [key: string]: JsonType },\n reloadFeatureFlags = true\n ): void {\n super.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce, reloadFeatureFlags)\n }\n\n /**\n * Removes properties from the person profile associated with the current `distinct_id`.\n * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @public\n *\n * @param propertyNames - The name (or names) of the person properties to remove.\n * @param reloadFeatureFlags - Whether to reload feature flags after removing the properties. Defaults to true.\n */\n unsetPersonProperties(propertyNames: string | string[], reloadFeatureFlags = true): void {\n super.unsetPersonProperties(propertyNames, reloadFeatureFlags)\n }\n\n public async getSurveys(): Promise<SurveyResponse['surveys']> {\n if (this._disableSurveys === true) {\n this._logger.info('Loading surveys is disabled.')\n this._cacheSurveys(null, 'disabled in config')\n return []\n }\n\n const surveys = this.getPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys)\n\n if (surveys && surveys.length > 0) {\n this._logger.info('Surveys fetched from storage: ', JSON.stringify(surveys))\n return surveys\n }\n\n this._logger.info('No surveys found in storage')\n return []\n }\n\n /**\n * Returns a promise that resolves when surveys are ready to be loaded.\n * If surveys are already loaded and ready to go, returns a resolved promise instead.\n * @internal\n */\n _onSurveysReady(): Promise<void> {\n if (this._surveysReady) {\n // If surveys are already ready, resolve immediately\n return Promise.resolve()\n }\n\n if (!this._surveysReadyPromise) {\n this._surveysReadyPromise = new Promise<void>((resolve) => {\n this._surveysReadyResolve = resolve\n })\n }\n\n return this._surveysReadyPromise\n }\n\n private _surveysReadyResolve: (() => void) | null = null\n\n /**\n * Helper function to cache surveys to storage with consistent logging\n */\n private _cacheSurveys(surveys: Survey[] | null, source: string): void {\n this.setPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys, surveys)\n\n if (surveys && surveys.length > 0) {\n this._logger.info(`Surveys cached from ${source}:`, JSON.stringify(surveys))\n } else if (surveys === null) {\n this._logger.info(`Surveys cleared (${source})`)\n } else {\n this._logger.info(`No surveys to cache from ${source})`)\n }\n }\n\n /**\n * Internal method to notify that surveys are ready\n */\n private _notifySurveysReady(): void {\n this._surveysReady = true\n if (this._surveysReadyResolve) {\n this._surveysReadyResolve()\n this._surveysReadyResolve = null\n this._surveysReadyPromise = null\n }\n }\n\n /**\n * Handle surveys from remote config response\n */\n private _handleSurveysFromRemoteConfig(response: any): void {\n if (this._disableSurveys === true) {\n this._logger.info('Loading surveys skipped, disabled.')\n this._cacheSurveys(null, 'remote config (disabled)')\n return\n }\n\n const surveys = response.surveys\n\n // Keep an authoritative empty list distinct from an unavailable survey cache.\n if (Array.isArray(surveys)) {\n this._cacheSurveys(surveys as Survey[], 'remote config')\n } else {\n this._cacheSurveys(null, 'remote config')\n }\n }\n\n /**\n * Registers this device's push token so PostHog Workflows can target it.\n * Requires `@posthog/react-native-plugin`.\n *\n * Registration happens at startup on its own when\n * {@link PostHogOptions.capturePushNotificationSubscriptions} is on, so call this for\n * token refreshes, which that startup fetch cannot see — on Android only, since a\n * refresh listener yields an FCM token and iOS defaults to APNs. Safe to call before\n * the native SDK is ready; the call queues rather than being dropped.\n *\n * `appId` says which provider delivers: the Firebase `project_id` for an FCM token, the\n * APNs bundle id for an APNs token. Unset, iOS uses the bundle id and Android the\n * default `FirebaseApp`'s project id, so pass it if you don't use Firebase or use a\n * non-default project. Registration fails server-side if your PostHog project has no\n * matching integration for `appId`.\n *\n * To use FCM on iOS too, pass the Firebase `project_id` as `appId` and set\n * {@link PostHogOptions.capturePushNotificationSubscriptions} to `false` first —\n * otherwise the device registers twice (APNs under the bundle id, FCM under the project\n * id), a Workflow with both integrations delivers twice, and\n * {@link unregisterPushNotificationToken} clears only the most recent.\n *\n * Not supported on web or macOS.\n */\n async registerPushNotificationToken(deviceToken: string, options?: { appId?: string }): Promise<void> {\n return this._callPushPlugin(\n 'registerPushNotificationToken',\n // requireInit: a host driving registration itself may have both capture flags off, so\n // nothing else would ever bring the native SDK up and the token would be dropped.\n { allowMacOS: false, requireInit: true, noop: 'token not registered' },\n (plugin) => {\n // Native persists the subscription across launches; remember that so a later\n // launch's cleanup knows to boot native (see unregister/reset).\n this.setPersistedProperty(PostHogPersistedProperty.PushRegistered, true)\n return plugin.registerPushNotificationToken?.(deviceToken, options?.appId ?? null)\n }\n )\n }\n\n /**\n * Unregisters this device's push token so Workflows stop targeting it — for example\n * from your logout flow. Requires `@posthog/react-native-plugin`.\n *\n * Durable: a failed or offline request retries on the next flush or launch. `reset()`\n * already moves a registered token to the new identity, so this is only needed if you\n * manage subscriptions yourself.\n *\n * Not supported on web or macOS.\n */\n async unregisterPushNotificationToken(): Promise<void> {\n return this._callPushPlugin(\n 'unregisterPushNotificationToken',\n // requireInit only when a manual register persisted a subscription: native keeps it\n // across launches, so cleanup must boot native even in a process where nothing else\n // initialized it. Without one, native never came up with anything to remove, and\n // booting it to delete nothing would defeat the opt-out this usually follows.\n {\n allowMacOS: false,\n allowWhenOptedOut: true,\n requireInit: this.getPersistedProperty(PostHogPersistedProperty.PushRegistered) === true,\n noop: 'nothing to unregister',\n },\n (plugin) => {\n // Clear on dispatch: both native SDKs persist the delete intent before their\n // consent/network gates and retry it on later launches, so the retry is native's\n // from here on.\n this.setPersistedProperty(PostHogPersistedProperty.PushRegistered, null)\n return plugin.unregisterPushNotificationToken?.()\n }\n )\n }\n\n /**\n * Captures `$push_notification_opened` when a user opens a push notification.\n * Requires `@posthog/react-native-plugin`.\n *\n * Only for taps {@link PostHogOptions.capturePushNotificationOpened} cannot see itself —\n * local notifications, plus Android taps while the app is running if\n * `@posthog/react-native-plugin` is older than 2.6.0. A notification PostHog sent is still\n * counted once when both paths report it (same `posthog.invocation_id` and action within\n * five minutes); one from another provider is counted twice.\n *\n * Keys of `payload`'s `posthog` entry become `$notification_<key>` properties. Leave\n * `action` unset for a plain tap; `subtitle` is iOS only. The native SDK builds and\n * sends the event, so JS `before_send` never sees it — redact anything sensitive first.\n *\n * Not supported on web.\n */\n async capturePushNotificationOpened(options: {\n title?: string\n subtitle?: string\n body?: string\n payload?: { [key: string]: JsonType }\n action?: string\n }): Promise<void> {\n const properties: { [key: string]: JsonType } = {}\n for (const key of ['title', 'subtitle', 'body', 'payload', 'action'] as const) {\n if (options[key] !== undefined) {\n properties[key] = options[key]\n }\n }\n return this._callPushPlugin(\n 'capturePushNotificationOpened',\n { allowMacOS: true, requireInit: true, noop: 'event not captured' },\n (plugin) => plugin.capturePushNotificationOpened?.(properties)\n )\n }\n\n // Shared guard skeleton for the push methods: disabled → unsupported platform →\n // plugin missing or outdated → queued behind native init → swallow-and-warn on rejection.\n private async _callPushPlugin(\n method: 'registerPushNotificationToken' | 'unregisterPushNotificationToken' | 'capturePushNotificationOpened',\n behavior: { allowMacOS: boolean; allowWhenOptedOut?: boolean; requireInit: boolean; noop: string },\n invoke: (plugin: NonNullable<typeof OptionalReactNativePlugin>) => Promise<void> | undefined\n ): Promise<void> {\n if (this.isDisabled) {\n return\n }\n // Unregistering removes a subscription, so it stays available after opt-out; the two that\n // send data do not.\n if (this.optedOut && !behavior.allowWhenOptedOut) {\n this._logger.warn(`${method} skipped: the user is opted out; ${behavior.noop}.`)\n return\n }\n if (isWeb() || (!behavior.allowMacOS && isMacOS())) {\n this._logger.warn(`${method} is not supported on ${isWeb() ? 'web' : 'macOS'}; ${behavior.noop}.`)\n return\n }\n if (!OptionalReactNativePlugin?.[method]) {\n this._logger.warn(`${method} requires @posthog/react-native-plugin; install or update it.`)\n return\n }\n return this._enqueueNative(\n method,\n (plugin) => {\n // Re-check consent: it may have been withdrawn while this waited its turn.\n if (this.optedOut && !behavior.allowWhenOptedOut) {\n this._logger.warn(`${method} skipped: the user is opted out; ${behavior.noop}.`)\n return\n }\n return invoke(plugin)\n },\n behavior.requireInit\n )\n }\n\n /**\n * The one channel for JS->native commands (identity, consent, push):\n *\n * - ordered: commands reach native in call order, so a reset() can't be overtaken by an\n * identify() issued after it.\n * - late-bound: `run` reads live state at dispatch, so the newest identity/consent wins.\n * - init-gated: nothing runs before native setup(). `requireInit` brings a native SDK that\n * was never set up all the way up rather than dropping the command.\n *\n * Never rejects — failures are logged.\n */\n private _enqueueNative(\n label: string,\n run: (plugin: NonNullable<typeof OptionalReactNativePlugin>) => Promise<void> | void,\n requireInit: boolean = false\n ): Promise<void> {\n const next = this._nativeChain\n .catch(() => {})\n .then(async () => {\n if (this.isDisabled || isWeb() || !OptionalReactNativePlugin) {\n return\n }\n // ready() doesn't cover native setup — it's kicked off fire-and-forget, and the native\n // SDK resolves a call it dropped for not being initialized, so the caller sees a\n // success that registered nothing. _initPromise first: it is what assigns the eval\n // chain, so until it settles the chain is still its initial resolved value.\n await this._initPromise.catch(() => {})\n await this._sessionReplayEvalChain.catch(() => {})\n if (!this._isNativePluginInitialized()) {\n if (!requireInit) {\n return\n }\n await this._ensureNativeInitialized()\n if (!this._isNativePluginInitialized()) {\n this._logger.warn(`${label} skipped: the native plugin is not initialized.`)\n return\n }\n }\n // A call that never settles (bridge torn down mid-call, or a native hang) would own\n // _nativeChain for the rest of the process, silently blocking every later\n // identify/reset/consent/push. Timing out doesn't cancel the native work, just stops\n // it blocking the queue.\n await raceWithTimeout(Promise.resolve(run(OptionalReactNativePlugin)), NATIVE_CALL_TIMEOUT_MS, () =>\n this._logger.warn(`Native PostHog ${label} timed out after ${NATIVE_CALL_TIMEOUT_MS}ms; continuing.`)\n )\n })\n .catch((e) => this._logger.warn(`Native PostHog ${label} failed: ${e}.`))\n this._nativeChain = next\n return next\n }\n\n // Brings native up on demand (push call, or late consent). Runs on the replay eval chain\n // to avoid racing a flags-driven evaluation. Callers re-check _isNativePluginInitialized\n // since the return value is also true on the nothing-to-do path.\n private _ensureNativeInitialized(): Promise<void> {\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n if (!this._isNativePluginInitialized()) {\n // enableSessionReplay: false — only replay's own evaluation may start it; this just\n // brings the instance up. forcePush: true — needed even with both auto-capture flags\n // off, the one config nothing else would create an instance for.\n await this.initializeNativePlugin(this._sessionReplayOptions, undefined, false, true)\n }\n })\n return this._sessionReplayEvalChain\n }\n\n private _pluginVersionAtLeast(major: number, minor: number): boolean {\n const version = OptionalReactNativePluginVersion?.match(/^(\\d+)\\.(\\d+)\\.\\d+(?:\\+[\\w.-]+)?$/)\n if (!version) {\n return false\n }\n const [installedMajor, installedMinor] = [Number(version[1]), Number(version[2])]\n return installedMajor > major || (installedMajor === major && installedMinor >= minor)\n }\n\n // Two native opt-ins: nativeCrashes covers the platform's own crash handler, while Android\n // NDK crashes are a separate posthog-android toggle (its tombstone scanner).\n private _nativeErrorAutocapture(options?: PostHogOptions): { nativeCrashes: boolean; androidNdkCrashes: boolean } {\n const autocapture = options?.errorTracking?.autocapture\n if (this.isDisabled || typeof autocapture !== 'object') {\n return { nativeCrashes: false, androidNdkCrashes: false }\n }\n // Android-only, so it must not bring up the native SDK on other platforms.\n let androidNdkCrashes = Platform.OS === 'android' && autocapture.androidNdkCrashes === true\n // Older plugins ignore the key, so it would start the native SDK with nothing to capture.\n if (androidNdkCrashes && !this._pluginVersionAtLeast(2, 12)) {\n if (!this._androidNdkCrashesUnsupportedWarned) {\n this._androidNdkCrashesUnsupportedWarned = true\n this._logger.warn(\n `errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later ` +\n `(installed: ${OptionalReactNativePluginVersion ?? 'unknown'}); ignoring.`\n )\n }\n androidNdkCrashes = false\n }\n return { nativeCrashes: autocapture.nativeCrashes === true, androidNdkCrashes }\n }\n\n private _isAutocaptureNativeErrors(options?: PostHogOptions): boolean {\n const { nativeCrashes, androidNdkCrashes } = this._nativeErrorAutocapture(options)\n return nativeCrashes || androidNdkCrashes\n }\n\n /**\n * Fatal JavaScript exceptions are handed to the native SDK, which persists them to its own\n * disk queue synchronously before the process dies. That only works if the native SDK is\n * set up, so JS uncaught-exception autocapture now warrants native init on its own — an app\n * that enabled neither replay, native crashes nor push would otherwise have no durable\n * fatal path at all.\n */\n private _isFatalJsCaptureNativeEnabled(): boolean {\n if (this.isDisabled || this.optedOut || isWeb() || this._persistence === 'memory') {\n return false\n }\n return this._errorTracking.isUncaughtExceptionAutocaptureEnabled()\n }\n\n private _isNativePluginInitialized(): boolean {\n return (\n this._sessionReplayNativeInitialized ||\n this._nativeErrorTrackingInitialized ||\n this._pushNativeInitialized ||\n this._fatalJsCaptureNativeInitialized\n )\n }\n\n // Push is enabled unless everything push-related is switched off: both auto-capture\n // flags default to true, matching the native SDKs.\n //\n // `force` covers a host that disabled both auto-capture flags to drive registration itself —\n // the native SDK still must exist. It bypasses only the auto-capture test; consent/platform/\n // plugin-support still gate, and the config built from `options` means forcing never\n // re-enables auto-capture.\n private _isPushNativeEnabled(options?: PostHogOptions, force: boolean = false): boolean {\n // optedOut is the persisted consent state; isDisabled is the static `disabled` option.\n // Push registers a durable device token, so it must respect consent, not just `disabled`.\n if (this.isDisabled || this.optedOut || isWeb() || this._pushNativeUnsupported) {\n return false\n }\n return (\n force ||\n options?.capturePushNotificationSubscriptions !== false ||\n options?.capturePushNotificationOpened !== false ||\n !!options?.pushIdentityProvider\n )\n }\n\n /**\n * Initializes the native session replay SDK if not already initialized.\n * This is called automatically by startSessionReplay() or lazily by startSessionRecording().\n *\n * @returns true if the native SDK is ready (initialized or already was), false otherwise\n */\n private async initializeSessionReplayNative(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<boolean> {\n return this.initializeNativePlugin(options, cachedRemoteConfig, true)\n }\n\n private async initializeNativePlugin(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>,\n enableSessionReplay: boolean = this._isEnableSessionReplay(),\n forcePush: boolean = false\n ): Promise<boolean> {\n const nativeErrorAutocapture = this._nativeErrorAutocapture(options)\n let enableNativeErrorTracking = nativeErrorAutocapture.nativeCrashes || nativeErrorAutocapture.androidNdkCrashes\n let enablePush = this._isPushNativeEnabled(options, forcePush)\n const enableFatalJsCapture = this._isFatalJsCaptureNativeEnabled()\n\n // Session replay has no macOS backend — the native plugin no-ops its recording controls there.\n // Skip it in JS so we don't mark replay initialized or log a false \"started\" while nothing records.\n if (enableSessionReplay && isMacOS()) {\n if (!this._sessionReplayMacOSWarned) {\n this._sessionReplayMacOSWarned = true\n this._logger.warn('Session replay is not supported on macOS; ignoring.')\n }\n enableSessionReplay = false\n }\n\n if (!enableSessionReplay && !enableNativeErrorTracking && !enablePush && !enableFatalJsCapture) {\n return true\n }\n\n if (!OptionalReactNativePlugin) {\n // Only replay and error tracking warrant a warning: they are explicit opt-ins,\n // while push is on by default and shouldn't nag every plugin-less app.\n if (enableSessionReplay || enableNativeErrorTracking) {\n this._logger.warn(\n enableSessionReplay\n ? 'Session replay enabled but not installed.'\n : 'Native error tracking enabled but not installed.'\n )\n }\n // Push is on by default, so latch it unsupported or every flags reload re-enters this\n // method just to return here.\n this._pushNativeUnsupported = true\n return false\n }\n\n if (\n (!enableSessionReplay || this._sessionReplayNativeInitialized) &&\n (!enableNativeErrorTracking || this._nativeErrorTrackingInitialized) &&\n (!enablePush || this._pushNativeInitialized) &&\n (!enableFatalJsCapture || this._fatalJsCaptureNativeInitialized)\n ) {\n return true\n }\n\n // Both native SDKs ignore a second setup() once running (PostHogSDK.swift:139,\n // PostHog.kt:150), so whatever brought the instance up first — replay, error tracking, or\n // push — replay must resume on it instead of calling setup() again. Reaching here with\n // enableSessionReplay true already means sampling/event-trigger evaluation decided\n // recording may start.\n if (this._isNativePluginInitialized() && enableSessionReplay && !this._sessionReplayNativeInitialized) {\n this._sessionReplayNativeInitialized = true\n await OptionalReactNativePlugin.startRecording?.(true)\n return true\n }\n\n const sessionId = this.getSessionId()\n if (sessionId.length === 0) {\n this._logger.warn(`Native PostHog plugin enabled but no sessionId found.`)\n return false\n }\n\n const defaultThrottleDelayMs = 1000\n\n const {\n maskAllTextInputs = true,\n maskAllImages = true,\n maskAllSandboxedViews = true,\n captureTouches = true,\n captureLog: localCaptureLog = true,\n captureNetworkTelemetry: localCaptureNetworkTelemetry = true,\n verifyScreenshotMaskAlignment = false,\n screenshotScale,\n screenshotCompressionQuality,\n screenshotColorMode,\n screenshotModeBackgroundCapture = false,\n sampleRate: localSampleRate,\n iOSdebouncerDelayMs = defaultThrottleDelayMs,\n androidDebouncerDelayMs = defaultThrottleDelayMs,\n } = options?.sessionReplayConfig ?? {}\n\n if (captureTouches === false && !isMacOS()) {\n if (!this._pluginVersionAtLeast(2, 9)) {\n this._logger.warn(\n `sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. ` +\n `The installed plugin (version ${OptionalReactNativePluginVersion ?? 'unknown'}) may still record touch coordinates. ` +\n `Upgrade the plugin and rebuild your app before relying on this setting.`\n )\n }\n }\n\n let throttleDelayMs = options?.sessionReplayConfig?.throttleDelayMs ?? defaultThrottleDelayMs\n\n // if deprecated values are set, we use the higher one for back compatibility\n if (\n throttleDelayMs === defaultThrottleDelayMs &&\n (iOSdebouncerDelayMs !== defaultThrottleDelayMs || androidDebouncerDelayMs !== defaultThrottleDelayMs)\n ) {\n throttleDelayMs = Math.max(iOSdebouncerDelayMs, androidDebouncerDelayMs)\n }\n\n // Gate captureLog and captureNetworkTelemetry using cached remote config.\n // The effective state is: localEnabled AND remoteEnabled.\n // If remote config hasn't loaded yet (no cached value), defaults to true (don't block locally enabled capture).\n const remoteConsoleLogEnabled = getRemoteConfigBool(\n cachedRemoteConfig?.sessionRecording,\n 'consoleLogRecordingEnabled',\n true\n )\n const remoteNetworkTimingEnabled = getRemoteConfigBool(\n cachedRemoteConfig?.capturePerformance,\n 'network_timing',\n true\n )\n const remoteSampleRateRaw = getRemoteConfigNumber(cachedRemoteConfig?.sessionRecording, 'sampleRate')\n\n const captureLog = localCaptureLog && remoteConsoleLogEnabled\n const captureNetworkTelemetry = localCaptureNetworkTelemetry && remoteNetworkTimingEnabled\n\n const localSampleRateValid =\n localSampleRate === undefined ? undefined : isValidSampleRate(localSampleRate) ? localSampleRate : undefined\n const remoteSampleRateValid =\n remoteSampleRateRaw === undefined\n ? undefined\n : isValidSampleRate(remoteSampleRateRaw)\n ? remoteSampleRateRaw\n : undefined\n\n const sampleRate = localSampleRateValid ?? remoteSampleRateValid\n\n if (localCaptureLog && !remoteConsoleLogEnabled) {\n this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).')\n }\n if (localCaptureNetworkTelemetry && !remoteNetworkTimingEnabled) {\n this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).')\n }\n if (localSampleRate !== undefined && localSampleRateValid === undefined) {\n this._logger.warn(\n `Ignoring invalid sessionReplayConfig.sampleRate '${localSampleRate}'. Expected a number between 0 and 1.`\n )\n }\n if (remoteSampleRateRaw !== undefined && remoteSampleRateValid === undefined) {\n this._logger.warn(\n `Ignoring invalid remote config sessionRecording.sampleRate '${remoteSampleRateRaw}'. Expected a number between 0 and 1.`\n )\n }\n if (localSampleRateValid !== undefined && remoteSampleRateValid !== undefined) {\n this._logger.warn(\n `Local sessionReplayConfig.sampleRate (${localSampleRateValid}) overrides the remote sampleRate ` +\n `(${remoteSampleRateValid}). The project setting is ignored while the local option is set. ` +\n `Remove sessionReplayConfig.sampleRate to follow the project setting.`\n )\n } else if (typeof sampleRate === 'number') {\n const source = localSampleRateValid !== undefined ? 'local config' : 'remote config'\n this._logger.info(`sampleRate set from ${source} (${sampleRate}).`)\n } else if (cachedRemoteConfig === undefined) {\n this._logger.warn(\n 'Session replay starts with no sampleRate because no remote config is cached yet. ' +\n 'Any project sample rate applies from the next launch.'\n )\n }\n\n const sdkReplayConfig = {\n maskAllTextInputs,\n maskAllImages,\n maskAllSandboxedViews,\n captureTouches,\n captureLog,\n captureNetworkTelemetry,\n verifyScreenshotMaskAlignment,\n ...(Number.isFinite(screenshotScale) ? { screenshotScale } : {}),\n ...(Number.isFinite(screenshotCompressionQuality) ? { screenshotCompressionQuality } : {}),\n ...(screenshotColorMode !== undefined ? { screenshotColorMode } : {}),\n screenshotModeBackgroundCapture,\n sampleRate,\n iOSdebouncerDelayMs,\n androidDebouncerDelayMs,\n throttleDelayMs,\n }\n\n this._logger.info(\n `Native PostHog plugin (version ${OptionalReactNativePluginVersion ?? 'unknown'}) replay config: ${JSON.stringify(\n sdkReplayConfig\n )}`\n )\n\n // if Flags API has not returned yet, we will start session replay with default config.\n const sessionReplay = this.getPersistedProperty(PostHogPersistedProperty.SessionReplay) ?? {}\n const cachedSessionReplayConfig = (sessionReplay as { [key: string]: JsonType }) ?? {}\n\n this._logger.info(\n `Session replay session recording from flags cached config: ${JSON.stringify(cachedSessionReplayConfig)}`\n )\n\n // Neither push nor fatal-JS capture needs native's own feature-flag preload — JS already\n // owns flags, and the fatal path only uses native as a durable queue. Native error\n // tracking's autocapture kill-switch does need it, as does replay, so only skip when\n // those two are not why we are here. Remote config isn't skippable: both native SDKs\n // deprecated that option to a no-op.\n const pushOnlyInit = (enablePush || enableFatalJsCapture) && !enableSessionReplay && !enableNativeErrorTracking\n\n const sdkOptions = {\n apiKey: this.apiKey,\n host: this.host,\n debug: this.isDebug,\n distinctId: this.getDistinctId(),\n anonymousId: this.getAnonymousId(),\n sdkVersion: this.getLibraryVersion(),\n flushAt: this.flushAt,\n // Consent is persisted JS-side; without this the native SDK defaults to opted-in and\n // would keep registering a device token after optOut().\n optOut: this.optedOut,\n preloadFeatureFlags: !pushOnlyInit,\n // Native-sent requests (session replay, crash uploads) bypass the JS request path,\n // so the configured headers are passed through to the native plugin as well.\n requestHeaders: this._requestHeaders,\n }\n\n // Log header names only: requestHeaders values can carry secrets (e.g. an Authorization token).\n const loggableSdkOptions = { ...sdkOptions, requestHeaders: Object.keys(this._requestHeaders) }\n this._logger.info(`Native PostHog plugin sdk options: ${JSON.stringify(loggableSdkOptions)}`)\n\n try {\n const wasSessionReplayEnabled = enableSessionReplay\n ? await OptionalReactNativePlugin.isEnabled().catch(() => false)\n : false\n\n if (OptionalReactNativePlugin.setup) {\n // The provider can't cross the bridge, so only an enabled marker goes into the\n // setup map; the JS listener itself must be installed here, before setup() captures it.\n // Installed regardless of enablePush: an opted-out app's only setup() call comes from\n // replay/error-tracking, and native ignores a second — skip here and subscriptions stay\n // unauthenticated for the process. Inert while opted out, since native only mints on a\n // subscription request, which its own opt-out flag blocks.\n let pushIdentityProviderEnabled = false\n if (options?.pushIdentityProvider) {\n if (OptionalReactNativePlugin.setPushIdentityProvider) {\n OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider)\n pushIdentityProviderEnabled = true\n } else {\n this._logger.warn(\n 'pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.'\n )\n }\n }\n\n const pluginConfig = {\n sessionReplay: {\n enabled: enableSessionReplay,\n sdkReplayConfig,\n decideReplayConfig: cachedSessionReplayConfig,\n },\n errorTracking: {\n nativeAutocapture: nativeErrorAutocapture.nativeCrashes,\n androidNdkCrashes: nativeErrorAutocapture.androidNdkCrashes,\n exceptionSteps: this._errorTracking.getNativePluginExceptionStepsConfig(),\n },\n // Always sent, even when push init isn't the reason we're here: the native\n // defaults are true, so an explicit opt-out must reach the native config.\n push: {\n capturePushNotificationSubscriptions: options?.capturePushNotificationSubscriptions ?? true,\n capturePushNotificationOpened: options?.capturePushNotificationOpened ?? true,\n pushIdentityProviderEnabled,\n },\n ...(options?.rageClickConfig && { rageClick: options.rageClickConfig }),\n }\n await OptionalReactNativePlugin.setup(String(sessionId), sdkOptions, pluginConfig)\n // Native resolves its own persisted opt-out over the config value passed above, so an\n // earlier optIn() keeps winning and sdkOptions.optOut alone can't opt a user back out.\n // Only an explicit optOut()/optIn() overwrites it, so re-assert JS consent every setup.\n await OptionalReactNativePlugin.setOptOut?.(this.optedOut)\n if (wasSessionReplayEnabled) {\n // if somehow the SDK is already enabled with a different sessionId, we reset it\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n }\n } else {\n if (enableNativeErrorTracking) {\n this._logger.warn(\n 'Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n // The legacy plugin can't do native crash capture, so don't mark it initialized below.\n enableNativeErrorTracking = false\n }\n // start() carries no push config, so the legacy plugin can never do push. Unsupported,\n // not initialized: the latch stops enablePush recomputing true on every flags reload,\n // while claiming initialized would assert a native instance setup() never created.\n if (enablePush) {\n this._logger.warn(\n 'Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.'\n )\n }\n enablePush = false\n this._pushNativeUnsupported = true\n if (!enableSessionReplay) {\n return false\n }\n if (!(await OptionalReactNativePlugin.isEnabled())) {\n await OptionalReactNativePlugin.start(\n String(sessionId),\n sdkOptions,\n sdkReplayConfig,\n cachedSessionReplayConfig\n )\n } else {\n // if somehow the SDK is already enabled with a different sessionId, we reset it\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n }\n }\n this._currentSessionId = sessionId\n if (enableSessionReplay) {\n this._sessionReplayNativeInitialized = true\n this._logger.info(`Session replay started with sessionId ${sessionId}.`)\n }\n if (enableNativeErrorTracking) {\n this._nativeErrorTrackingInitialized = true\n this._errorTracking.onNativeErrorTrackingReady()\n this._logger.info('Native error tracking started.')\n }\n if (enablePush) {\n this._pushNativeInitialized = true\n this._logger.info('Push notification native support started.')\n }\n if (enableFatalJsCapture) {\n this._fatalJsCaptureNativeInitialized = true\n this._logger.info('Native durable capture for fatal JavaScript exceptions started.')\n }\n return true\n } catch (e) {\n this._logger.error(`Native PostHog plugin failed to start: ${e}.`)\n return false\n }\n }\n\n private async startSessionReplay(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<void> {\n this._enableSessionReplay = options?.enableSessionReplay\n this._sessionReplayOptions = options\n\n await this._evaluateAndStartSessionReplay(cachedRemoteConfig)\n }\n\n /**\n * Decides whether session replay should be recording (replay enabled AND the linked\n * flag, if any, on for the current user) and arms or pauses the native recorder to match.\n *\n * Runs at startup and on every feature flags load/reload (identify(), reset(),\n * reloadFeatureFlags()), so recording starts, resumes, or pauses on identity changes\n * without an app restart. `_sessionReplayRecordingActive` dedups repeated answers, and\n * the init guards prevent double-starts. When replay is off, the native plugin is still\n * initialized for native error tracking (both share one native instance).\n *\n * Pausing requires a real \"flag off\": core keeps the previous flag values across\n * quota-limited/failed reloads, so a transient error never pauses a recording. Right\n * after reset() the flags are genuinely unknown and pausing is the intended outcome.\n *\n * Evaluations are serialized so concurrent flags reloads run one at a time.\n */\n private _evaluateAndStartSessionReplay(cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>): Promise<void> {\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(() => this._evaluateAndStartSessionReplayInternal(cachedRemoteConfig))\n return this._sessionReplayEvalChain\n }\n\n private async _evaluateAndStartSessionReplayInternal(\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<void> {\n const options = this._sessionReplayOptions\n const enableNativeErrorTracking = this._isAutocaptureNativeErrors(options)\n const enablePush = this._isPushNativeEnabled(options)\n const enableFatalJsCapture = this._isFatalJsCaptureNativeEnabled()\n // On the re-arm path (flags reloaded after identify/reset) cachedRemoteConfig\n // isn't passed in, so fall back to the persisted remote config for capture gating.\n const remoteConfig =\n cachedRemoteConfig ??\n this.getPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(PostHogPersistedProperty.RemoteConfig)\n\n if (!this._isEnableSessionReplay()) {\n this._logger.info('Session replay is not enabled.')\n // Replay off — disarm event triggers so the capture hook stays inert.\n this._sessionReplayEventTriggers = []\n if (enableNativeErrorTracking || enablePush || enableFatalJsCapture) {\n await this.initializeNativePlugin(options, remoteConfig, false)\n }\n const request = this._manualRecordingStartRequest\n if (request?.pending) {\n await this._attemptManualRecordingStart(request, true)\n }\n return\n }\n\n // if Flags API has not returned yet, we will start session replay with default config.\n const sessionReplay = this.getPersistedProperty(PostHogPersistedProperty.SessionReplay) ?? {}\n const featureFlags = this.getKnownFeatureFlags() ?? {}\n const cachedFeatureFlags = (featureFlags as { [key: string]: FeatureFlagValue }) ?? {}\n const cachedSessionReplayConfig = (sessionReplay as { [key: string]: JsonType }) ?? {}\n\n this._logger.info('Session replay feature flags from flags cached config:', JSON.stringify(cachedFeatureFlags))\n\n let recordingActive = true\n const linkedFlag = cachedSessionReplayConfig['linkedFlag'] as\n | string\n | { [key: string]: JsonType }\n | null\n | undefined\n\n if (typeof linkedFlag === 'string') {\n const value = cachedFeatureFlags[linkedFlag]\n if (typeof value === 'boolean') {\n recordingActive = value\n } else if (typeof value === 'string') {\n // if its a multi-variant flag linked to \"any\"\n recordingActive = true\n } else {\n // disable recording if the flag does not exist/quota limited\n recordingActive = false\n }\n\n this._logger.info(`Session replay '${linkedFlag}' linked flag value: '${value}'`)\n } else if (linkedFlag && typeof linkedFlag === 'object') {\n const flag = linkedFlag['flag'] as string | undefined\n const variant = linkedFlag['variant'] as string | undefined\n if (flag && variant) {\n const value = cachedFeatureFlags[flag]\n recordingActive = value === variant\n this._logger.info(`Session replay '${flag}' linked flag variant '${variant}' and value '${value}'`)\n } else {\n // disable recording if the flag does not exist/quota limited\n this._logger.info(`Session replay '${flag}' linked flag variant: '${variant}' does not exist/quota limited.`)\n recordingActive = false\n }\n } else {\n this._logger.info(`Session replay has no cached linkedFlag.`)\n }\n\n // Event triggers: replay records only once the client captures an event whose name matches a\n // configured trigger, and stays active for the rest of that session. Cache the armed triggers in\n // memory for the capture hot path (processBeforeEnqueue), then AND the activation into the gate —\n // an unfired trigger blocks recording exactly like an unsatisfied linked flag (restrictive AND).\n const eventTriggers = this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers'])\n this._sessionReplayEventTriggers = eventTriggers\n\n if (eventTriggers.length > 0) {\n const activated = this._isEventTriggerActivatedForSession(super.getSessionId())\n if (!activated) {\n recordingActive = false\n }\n this._logger.info(`Session replay event triggers configured (${eventTriggers.length}); activated: ${activated}.`)\n }\n\n if (recordingActive) {\n if (this._sessionReplayRecordingActive === true) {\n // Already recording — nothing to do.\n return\n }\n // Record the actual outcome; on failure it stays false so the next reload retries.\n // (Already initialized means replay was paused by an earlier flag-off, so resume it.)\n this._sessionReplayRecordingActive = this._sessionReplayNativeInitialized\n ? await this._startSessionRecording(true)\n : await this.initializeNativePlugin(options, remoteConfig, true)\n } else {\n this._logger.info('Session replay disabled.')\n\n if (this._sessionReplayRecordingActive === true) {\n // Linked flag turned off — pause so a gated-off user isn't recorded. Keep the flag\n // set if the native stop fails, so the next reload retries instead of giving up.\n this._sessionReplayRecordingActive = !(await this._stopSessionRecording())\n } else {\n this._sessionReplayRecordingActive = false\n }\n\n if (enableNativeErrorTracking || enablePush) {\n await this.initializeNativePlugin(options, remoteConfig, false)\n }\n }\n }\n\n /**\n * Capture chokepoint for session-replay event triggers. Every captured event (capture, $screen,\n * autocapture, lifecycle) passes through here. Chains to super first so `before_send` still runs;\n * when a surviving event's name matches an armed trigger and the session hasn't activated yet, it\n * activates replay for the session and kicks a re-evaluation that starts native recording. The\n * trigger check never drops an event or throws into the capture path.\n */\n protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null {\n const observation = this._fatalCaptureObservation\n const isObservedFatal =\n observation !== undefined && message.uuid === observation.eventUuid && message.event === '$exception'\n const processed = super.processBeforeEnqueue(message)\n let suppress = false\n if (isObservedFatal && processed && observation) {\n // The final, before_send-accepted payload. Offer it to the native SDK here rather than\n // after enqueueing: if native takes ownership the JS copy must never reach the queue,\n // and if the payload cannot be built we must still fall through to the JS queue. Both\n // outcomes have to be decided in this one step or the exception can end up in neither\n // queue, or in both.\n try {\n observation.nativeCapture = observation.prepareNativeCapture(processed)\n } catch (e) {\n this._logger.warn(`Fatal exception payload could not be prepared for native capture: ${e}`)\n observation.nativeCapture = undefined\n }\n suppress = observation.nativeCapture !== undefined\n observation.queued = !suppress\n }\n try {\n this._maybeActivateEventTrigger(processed?.['event'])\n } catch (e) {\n this._logger.error(`Session replay event trigger check failed: ${e}.`)\n }\n return suppress ? null : processed\n }\n\n /**\n * Capture a fatal exception and decide which queue owns it. The native SDK persists a\n * fatal `$exception` synchronously, so when it is available it takes the event and the JS\n * queue copy is dropped; otherwise the event stays in the JS queue as usual.\n */\n private _captureFatalAndChooseOwner(\n eventUuid: string,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined,\n capture: () => unknown\n ): { queued: boolean; nativeCapture?: () => Promise<void> } {\n const observation: NonNullable<PostHog['_fatalCaptureObservation']> = {\n eventUuid,\n prepareNativeCapture,\n queued: false,\n }\n const previousObservation = this._fatalCaptureObservation\n this._fatalCaptureObservation = observation\n try {\n capture()\n } finally {\n this._fatalCaptureObservation = previousObservation\n }\n return { queued: observation.queued, nativeCapture: observation.nativeCapture }\n }\n\n private _maybeActivateEventTrigger(eventName: unknown): void {\n if (this._sessionReplayEventTriggers.length === 0 || typeof eventName !== 'string') {\n return\n }\n if (!this._sessionReplayEventTriggers.includes(eventName)) {\n return\n }\n // Use super.getSessionId() (not this.getSessionId()) deliberately: the capture path already ran the\n // overriding getSessionId() during enrichProperties, so rotation handling has fired and the id is\n // synced. Calling the override again here would re-enter rotation logic from inside capture.\n const sessionId = super.getSessionId()\n if (!sessionId) {\n return\n }\n // Already activated AND the native recorder is confirmed running — nothing to do. If activation\n // was persisted but a prior start failed (recording still inactive), fall through to re-kick the\n // evaluation so a later matching event retries the native start instead of staying stuck.\n if (this._isEventTriggerActivatedForSession(sessionId) && this._sessionReplayRecordingActive === true) {\n return\n }\n if (!this._isEventTriggerActivatedForSession(sessionId)) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession, sessionId)\n this._logger.info(`Session replay event trigger '${eventName}' activated for session ${sessionId}.`)\n }\n // Re-evaluate so the native recorder starts; fire-and-forget keeps the capture path synchronous.\n // Serialized through _sessionReplayEvalChain, so this never races a concurrent evaluation.\n void this._evaluateAndStartSessionReplay()\n }\n\n private _parseEventTriggers(value: JsonType | undefined): string[] {\n if (!Array.isArray(value)) {\n return []\n }\n return value.filter((entry): entry is string => typeof entry === 'string')\n }\n\n private _isEventTriggerActivatedForSession(sessionId: string): boolean {\n return this.getPersistedProperty(PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession) === sessionId\n }\n\n private async captureAppLifecycleEvents(): Promise<void> {\n const appBuild = this._appProperties.$app_build\n const appVersion = this._appProperties.$app_version\n\n const isMemoryPersistence = this._persistence === 'memory'\n\n const properties: PostHogEventProperties = {}\n\n if (!isMemoryPersistence) {\n const prevAppBuild = this.getPersistedProperty(PostHogPersistedProperty.InstalledAppBuild) as string | undefined\n const prevAppVersion = this.getPersistedProperty(PostHogPersistedProperty.InstalledAppVersion) as\n | string\n | undefined\n\n if (!appBuild || !appVersion) {\n this._logger.warn(\n 'PostHog could not track installation/update/open, as the build and version were not set. ' +\n 'This can happen if some dependencies are not installed correctly, or if you have provided' +\n 'customAppProperties but not included $app_build or $app_version.'\n )\n }\n if (appBuild) {\n if (!prevAppBuild) {\n // new app install\n this.capture('Application Installed', properties)\n } else if (prevAppBuild !== appBuild) {\n // $app_version and $app_build are already added in the common event properties\n // app updated\n this.capture('Application Updated', {\n ...maybeAdd('previous_version', prevAppVersion),\n ...maybeAdd('previous_build', prevAppBuild),\n ...properties,\n })\n }\n }\n } else {\n this._logger.warn(\n 'PostHog was initialised with persistence set to \"memory\", capturing native app events (Application Installed and Application Updated) is not supported.'\n )\n }\n\n const initialUrl = (await Linking.getInitialURL()) ?? undefined\n\n this.capture('Application Opened', {\n ...properties,\n ...maybeAdd('url', initialUrl),\n })\n\n AppState.addEventListener('change', (state) => {\n if (state === 'active') {\n this.capture('Application Became Active')\n } else if (state === 'background') {\n this.capture('Application Backgrounded')\n }\n })\n }\n\n private async persistAppVersion(): Promise<void> {\n const appBuild = this._appProperties.$app_build\n const appVersion = this._appProperties.$app_version\n this.setPersistedProperty(PostHogPersistedProperty.InstalledAppBuild, appBuild)\n this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,"file":"posthog-rn.js","names":["_reactNative","require","_core","_storage","_surveyProgress","_logsDefaults","_version","_nativeDeps","_utils","_wixNavigation","_OptionalPlugin","_errorTracking","_exceptionContext","ownKeys","e","r","t","Object","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","_callSuper","_getPrototypeOf2","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","Boolean","prototype","valueOf","call","_superPropGet","p","_get2","mapAppStateForLogs","state","undefined","NATIVE_CALL_TIMEOUT_MS","MANUAL_RECORDING_START_RETRY_DELAYS_MS","PostHog","exports","_PostHogCore","apiKey","options","_this","_classCallCheck2","normalizedApiKey","trim","console","error","_appProperties","_sessionReplayNativeInitialized","_nativeErrorTrackingInitialized","_androidNdkCrashesUnsupportedWarned","_pushNativeInitialized","_fatalJsCaptureNativeInitialized","_pushNativeUnsupported","_sessionReplayMacOSWarned","_sessionReplayEvalChain","Promise","resolve","_nativeChain","_sessionReplayEventTriggers","_eventsStoragePreloadSucceeded","_surveysReadyPromise","_surveysReady","_requestHeaders","_surveysReadyResolve","_isInitialized","_persistence","_b","persistence","_disableSurveys","_c","disableSurveys","ErrorTracking","errorTracking","_logger","captureFatalException","hint","eventUuid","timestamp","prepareNativeCapture","_captureFatalAndChooseOwner","captureExceptionInternal","$exception_level","uuid","waitForJSPersist","_waitForJSPersist","_asyncToGenerator2","_regenerator","mark","_callee","wrap","_context","prev","next","_initPromise","abrupt","_eventsStorage","waitForPersistSuccess","stop","getPersistenceMode","waitForStorageReady","_waitForStorageReady","_callee2","_context2","isNativeCaptureReady","_isNativePluginInitialized","_setDefaultPersonProperties","_d","setDefaultPersonProperties","_overrideDisplayLanguage","_a","overrideDisplayLanguage","_e","requestHeaders","customAppProperties","getAppProperties","reactNativeVersion","getReactNativeVersion","$react_native_version","storagePromise","theStorage","_f","customStorage","buildOptimisticAsyncStorage","createEventsStorage","_logsStorage","createLogsStorage","preloads","preloadPromise","allSettled","map","_ref","_ref2","_slicedToArray2","then","results","i","status","concat","reason","createEventsMemoryStorage","createLogsMemoryStorage","_currentAppState","AppState","currentState","_resolvedLogsConfig","resolveLogsConfig","logs","_logs","PostHogLogs","flags","getFeatureFlags","flagKeys","distinctId","getDistinctId","sessionId","getSessionId","screenName","sessionProps","$screen_name","appState","activeFeatureFlags","fn","waitForPersist","addEventListener","mapped","flush","_ref3","_callee3","err","_context3","logFlushError","_x3","isBackgrounding","logsFlushPromise","flushWithTimeout","backgroundFlushBudgetMs","_ref4","_callee4","_context4","_x4","initAfterStorage","enablePersistSessionIdAcrossRestart","setPersistedProperty","PostHogPersistedProperty","SessionId","SessionLastTimestamp","SessionStartTimestamp","setupBootstrap","getPersistedProperty","DeviceId","anonId","getAnonymousId","_setDefaultPersonPropertiesForFlags","isDisabled","cachedRemoteConfig","RemoteConfig","onRemoteConfig","reloadRemoteConfigAsync","response","_handleSurveysFromRemoteConfig","_notifySurveysReady","captureAppLifecycleEvents","persistAppVersion","startSessionReplay","onFeatureFlags","_isEnableSessionReplay","_manualRecordingStartRequest","pending","_evaluateAndStartSessionReplay","addTracingHeaders","patchFetchForTracingHeaders","_inherits2","_createClass2","key","value","_ready","_callee5","_context5","ready","_storageForKey","LogsQueue","getItem","storage","SurveysInProgress","otherProjects","getOtherProjectSurveyProgress","setItem","removeItem","_events","emit","PersonProperties","_flushStorage","_callee6","_context6","flushStorage","_shutdown2","_callee7","shutdownTimeoutMs","start","remainingMs","logsBudgetMs","_remainingMs","drain","_args7","_context7","_cancelManualRecordingStart","Date","now","Math","max","min","terminationFlushBudgetMs","all","shutdown","raceWithTimeout","finish","_shutdown","_fetch","fetch","_x","_x2","toString","url","getLibraryId","getLibraryVersion","version","getCustomUserAgent","Platform","OS","getCustomHeaders","getCommonEventProperties","_Dimensions$get","Dimensions","get","width","height","$screen_height","$screen_width","getSurveyDisplayLanguageOverride","register","properties","unregister","property","reset","propertiesToKeep","_this2","effectivePropertiesToKeep","InstalledAppBuild","InstalledAppVersion","SessionReplay","Surveys","PushRegistered","_toConsumableArray2","OptionalReactNativePlugin","_enqueueNative","plugin","String","_propagateNativeOptOut","_this3","reloadFeatureFlags","defaultProps","relevantKeys","commonProps","$lib","$lib_version","setPersonPropertiesForFlags","captureLog","flushLogs","_this4","_captureLogger","trace","body","attributes","level","debug","info","warn","fatal","optIn","result","optOut","_this5","coreOptOut","persistOptOut","unregisterPushNotificationToken","_this6","setOptOut","optedOut","_isPushNativeEnabled","_sessionReplayOptions","_ensureNativeInitialized","isFeatureEnabled","getFeatureFlag","getFeatureFlagPayload","reloadFeatureFlagsAsync","updateFlags","payloads","group","groupType","groupKey","propsToCache","setGroupPropertiesForFlags","alias","getDeviceId","deviceId","resetPersonPropertiesForFlags","resetGroupPropertiesForFlags","_screen","_callee8","name","_context8","registerForSession","capture","screen","_x5","_x6","_x7","isMacOS","_enableSessionReplay","_resetSessionId","reactNativeSessionReplay","endSession","startSession","_currentSessionId","resetSessionId","_startSessionRecording2","_callee0","_this7","resumeCurrent","request","_args0","_context0","retryCount","_callee9","_context9","_attemptManualRecordingStart","startSessionRecording","clearTimeout","timer","_attemptManualRecordingStart2","_callee1","started","_context1","_startSessionRecording","sent","_stopSessionRecording","_scheduleManualRecordingStartRetry","_x8","_x9","_this8","delay","startRecording","safeSetTimeout","_callee10","_context10","_startSessionRecording3","_callee11","_this9","initialized","newSessionId","_t","_context11","initializeNativePlugin","isEnabled","_x0","_stopSessionRecording2","_callee13","_this0","_context13","_callee12","_context12","stopSessionRecording","_stopSessionRecording3","_callee14","_t2","_context14","stopRecording","_isSessionReplayActive","_callee15","_t3","_context15","isSessionReplayActive","identify","_this1","previousDistinctId","userProps","$set","userPropsOnce","$set_once","_typeof2","Array","isArray","entries","_ref8","_ref9","propsOnceToCache","_ref0","_ref1","nativeDistinctId","anonymousId","identified","captureException","additionalProperties","resolvedHint","mechanism","handled","type","syntheticException","Error","merged","getExceptionContext","finalAdditional","attachExceptionSteps","captureOptions","_originatedFromCaptureException","buildExceptionProperties","toISOString","builder","getErrorPropertiesBuilder","exceptionProperties","buildFromUnknown","addExceptionStep","message","createErrorPropertiesBuilder","CoreErrorTracking","ErrorPropertiesBuilder","PromiseRejectionEventCoercer","ErrorCoercer","ErrorEventCoercer","ObjectCoercer","StringCoercer","PrimitiveCoercer","createStackParser","isHermes","chromeStackLineParser","geckoStackLineParser","initReactNativeNavigation","withReactNativeNavigation","createPersonProfile","setPersonProperties","userPropertiesToSet","userPropertiesToSetOnce","unsetPersonProperties","propertyNames","_getSurveys","_callee16","surveys","_context16","_cacheSurveys","JSON","stringify","getSurveys","_onSurveysReady","_this10","source","_registerPushNotificationToken","_callee17","deviceToken","_this11","_context17","_callPushPlugin","allowMacOS","requireInit","noop","registerPushNotificationToken","appId","_x1","_x10","_unregisterPushNotificationToken","_callee18","_this12","_context18","allowWhenOptedOut","_capturePushNotificationOpened","_callee19","_i","_arr","_context19","capturePushNotificationOpened","_x11","_callPushPlugin2","_callee20","method","behavior","invoke","_this13","_context20","isWeb","_x12","_x13","_x14","label","run","_this14","_callee21","_context21","_this15","_callee22","_context22","_pluginVersionAtLeast","major","minor","OptionalReactNativePluginVersion","match","_ref12","Number","installedMajor","installedMinor","_nativeErrorAutocapture","autocapture","nativeCrashes","androidNdkCrashes","_isAutocaptureNativeErrors","_this$_nativeErrorAut","_isFatalJsCaptureNativeEnabled","isUncaughtExceptionAutocaptureEnabled","force","capturePushNotificationSubscriptions","pushIdentityProvider","_initializeSessionReplayNative","_callee23","_context23","initializeSessionReplayNative","_x15","_x16","_initializeNativePlugin","_callee24","enableSessionReplay","forcePush","_g","_h","_j","nativeErrorAutocapture","enableNativeErrorTracking","enablePush","enableFatalJsCapture","defaultThrottleDelayMs","_ref13","_ref13$maskAllTextInp","maskAllTextInputs","_ref13$maskAllImages","maskAllImages","_ref13$maskAllSandbox","maskAllSandboxedViews","_ref13$captureTouches","captureTouches","_ref13$captureLog","localCaptureLog","_ref13$captureNetwork","localCaptureNetworkTelemetry","_ref13$verifyScreensh","verifyScreenshotMaskAlignment","screenshotScale","screenshotCompressionQuality","screenshotColorMode","_ref13$screenshotMode","screenshotModeBackgroundCapture","localSampleRate","_ref13$iOSdebouncerDe","iOSdebouncerDelayMs","_ref13$androidDebounc","androidDebouncerDelayMs","throttleDelayMs","remoteConsoleLogEnabled","remoteNetworkTimingEnabled","remoteSampleRateRaw","captureNetworkTelemetry","localSampleRateValid","remoteSampleRateValid","sampleRate","sdkReplayConfig","sessionReplay","cachedSessionReplayConfig","pushOnlyInit","sdkOptions","loggableSdkOptions","wasSessionReplayEnabled","pushIdentityProviderEnabled","pluginConfig","_args24","_t4","_t5","_context24","sessionReplayConfig","getRemoteConfigBool","sessionRecording","capturePerformance","getRemoteConfigNumber","isValidSampleRate","isFinite","host","isDebug","sdkVersion","flushAt","preloadFeatureFlags","setup","setPushIdentityProvider","enabled","decideReplayConfig","nativeAutocapture","exceptionSteps","getNativePluginExceptionStepsConfig","rageClickConfig","rageClick","onNativeErrorTrackingReady","_x17","_x18","_startSessionReplay","_callee25","_context25","_x19","_x20","_this16","_evaluateAndStartSessionReplayInternal","_evaluateAndStartSessionReplayInternal2","_callee26","remoteConfig","featureFlags","cachedFeatureFlags","recordingActive","linkedFlag","flag","variant","_value","eventTriggers","activated","_t6","_context26","getKnownFeatureFlags","_parseEventTriggers","_isEventTriggerActivatedForSession","_sessionReplayRecordingActive","_x21","processBeforeEnqueue","observation","_fatalCaptureObservation","isObservedFatal","event","processed","suppress","nativeCapture","queued","_maybeActivateEventTrigger","previousObservation","eventName","includes","SessionReplayEventTriggerActivatedSession","entry","_captureAppLifecycleEvents","_callee27","_this17","appBuild","appVersion","isMemoryPersistence","prevAppBuild","prevAppVersion","initialUrl","_t7","_t8","_t9","_context27","$app_build","$app_version","maybeAdd","Linking","getInitialURL","_persistAppVersion","_callee28","_context28","PostHogCore"],"sources":["../src/posthog-rn.ts"],"sourcesContent":["import { AppState, type AppStateStatus, Dimensions, Linking, Platform } from 'react-native'\n\nimport {\n CaptureLogOptions,\n CaptureLogger,\n JsonType,\n PostHogCaptureOptions,\n PostHogCore,\n PostHogCoreOptions,\n PostHogEventProperties,\n PostHogFetchOptions,\n PostHogFetchResponse,\n PostHogLogs,\n PostHogLogsConfig,\n PostHogPersistedProperty,\n PostHogRemoteConfig,\n Survey,\n SurveyResponse,\n allSettled,\n logFlushError,\n maybeAdd,\n patchFetchForTracingHeaders,\n raceWithTimeout,\n safeSetTimeout,\n FeatureFlagValue,\n FeatureFlagResultOptions,\n IsFeatureEnabledOptions,\n ErrorTracking as CoreErrorTracking,\n isObject,\n uuidv7,\n} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport {\n PostHogRNStorage,\n createEventsStorage,\n createLogsStorage,\n createEventsMemoryStorage,\n createLogsMemoryStorage,\n} from './storage'\nimport { getOtherProjectSurveyProgress } from './surveys/survey-progress'\nimport { resolveLogsConfig } from './logs-defaults'\nimport { version } from './version'\nimport { buildOptimisticAsyncStorage, getAppProperties } from './native-deps'\nimport {\n PostHogAutocaptureOptions,\n PostHogCustomAppProperties,\n PostHogCustomStorage,\n PostHogPushIdentityProvider,\n PostHogRageClickConfig,\n PostHogSessionReplayConfig,\n} from './types'\nimport {\n getReactNativeVersion,\n getRemoteConfigBool,\n getRemoteConfigNumber,\n isHermes,\n isMacOS,\n isValidSampleRate,\n isWeb,\n} from './utils'\nimport { withReactNativeNavigation } from './frameworks/wix-navigation'\nimport { OptionalReactNativePlugin, OptionalReactNativePluginVersion } from './optional/OptionalPlugin'\nimport { ErrorTracking, ErrorTrackingOptions } from './error-tracking'\nimport { getExceptionContext } from './error-tracking/exception-context'\n\nexport { PostHogPersistedProperty }\n\n/**\n * Collapses RN's broader AppState status set into the OTLP `app.state`\n * enum (foreground|background). 'inactive' (iOS transition) and 'extension'\n * are treated as foreground — the app is still running JS, just not the\n * primary scene. 'unknown' returns undefined so the attribute is omitted\n * rather than guessed.\n */\nfunction mapAppStateForLogs(state: AppStateStatus | undefined): 'foreground' | 'background' | undefined {\n if (state === 'background') {\n return 'background'\n }\n if (!state || state === 'unknown') {\n return undefined\n }\n return 'foreground'\n}\n\n// Upper bound on a single JS->native bridge call. Only bounds the call itself — waiting for\n// native setup happens before it — so it can be tight enough that a stuck call doesn't strand\n// the queue for the process lifetime.\nconst NATIVE_CALL_TIMEOUT_MS = 10_000\n// Native config readiness has no bridge notification, so manual starts need bounded timer\n// retries as well as flags-driven retries. JS flags can finish loading before native config.\nconst MANUAL_RECORDING_START_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 16000]\n\ntype ManualRecordingStartRequest = {\n pending: boolean\n retryCount: number\n timer?: ReturnType<typeof setTimeout>\n}\n\nexport interface PostHogOptions extends PostHogCoreOptions {\n /**\n * Allows you to provide the storage type.\n * 'file' will try to load the best available storage, the provided 'customStorage', 'customAsyncStorage' or in-memory storage.\n *\n * @default 'file'\n */\n persistence?: 'memory' | 'file'\n /**\n * Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated.\n * An object replaces the default App properties except `$react_native_version`, which is kept unless the object sets it (set it to `undefined` to remove it).\n */\n customAppProperties?:\n | PostHogCustomAppProperties\n | ((properties: PostHogCustomAppProperties) => PostHogCustomAppProperties)\n /**\n * Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system or a synchronous storage such as mmkv.\n * If not provided, PostHog will attempt to use the best available storage via optional peer dependencies (async-storage, expo-file-system).\n * If `persistence` is set to 'memory', this option will be ignored.\n */\n customStorage?: PostHogCustomStorage\n\n /**\n * A list of headers that should be sent with requests to the PostHog API.\n */\n requestHeaders?: { [header_name: string]: string }\n\n /**\n * Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active and Application Backgrounded.\n * Application Installed and Application Updated events are not supported with persistence set to 'memory'.\n *\n * @default true\n */\n captureAppLifecycleEvents?: boolean\n\n /**\n * Enable Recording of Session Replays for Android and iOS\n * Requires Record user sessions to be enabled in the PostHog Project Settings\n *\n * This option is read once, at setup. To record only some sessions, either gate recording\n * from your project settings (sampling, a linked flag, or event triggers), or leave this\n * option off and drive the recorder from your app with `startSessionRecording()` and\n * `stopSessionRecording()`.\n *\n * @default false\n */\n enableSessionReplay?: boolean\n\n /**\n * Configuration for Session Replay\n */\n sessionReplayConfig?: PostHogSessionReplayConfig\n\n /**\n * If enabled, the session id ($session_id) will be persisted across app restarts.\n * This is an option for back compatibility, so your current data isn't skewed with the new version of the SDK.\n * If this is false, the session id will be always reset on app restart.\n *\n * @default false\n */\n enablePersistSessionIdAcrossRestart?: boolean\n\n /**\n * Error Tracking Configuration\n */\n errorTracking?: ErrorTrackingOptions\n\n /**\n * Configure rage click (rage tap) detection on iOS.\n *\n * The native iOS SDK fires a `$rageclick` event when a user taps the same\n * area repeatedly in quick succession. The default thresholds (3 taps,\n * 30 points, 1 second) were tuned for web and frequently produce false\n * positives on mobile. Raise the thresholds or set `enabled: false` to\n * suppress them.\n *\n * Android is unaffected — posthog-android does not have native rage click\n * detection.\n *\n * Requires `@posthog/react-native-plugin` version 2.7.0 or newer.\n */\n rageClickConfig?: PostHogRageClickConfig\n\n /**\n * Automatically include common device and app properties in feature flag evaluation.\n *\n * When enabled, the following properties are sent with every /flags request:\n * - $app_version: App version\n * - $app_build: App build number\n * - $app_namespace: App bundle identifier / namespace\n * - $os_name: Operating system name\n * - $os_version: Operating system version\n * - $device_type: Device type (Mobile, Desktop)\n * - $lib: Name of the SDK library\n * - $lib_version: Version of the SDK library\n *\n * This ensures feature flags that rely on these properties work correctly\n * without waiting for server-side processing of identify() calls.\n *\n * @default true\n */\n setDefaultPersonProperties?: boolean\n\n /**\n * Logs feature configuration. Enables structured log capture via\n * `posthog.captureLog(...)` or `posthog.logger.info(...)`. Records ship to\n * PostHog's logs product (`/i/v1/logs`) in OTLP format, batched on a timer,\n * AppState change, buffer fill, or manual `flushLogs()`.\n *\n * Capture is **unconditional** — calling the API ships records as long as\n * the SDK is initialized and the user hasn't opted out. The only blockers\n * are `optedOut`, missing/empty `body`, and missing API key.\n *\n * All fields below are optional; per-SDK defaults apply (mobile defaults\n * are tuned for cellular bandwidth and battery, ~50 logs/sec ceiling).\n *\n * @example Minimal — just service tagging, defaults for everything else\n * ```ts\n * new PostHog(key, {\n * logs: { serviceName: 'my-app', environment: 'production' }\n * })\n * ```\n *\n * @example Tune for higher-volume logging\n * ```ts\n * new PostHog(key, {\n * logs: {\n * serviceName: 'my-app',\n * rateCap: { maxLogs: 5000, windowMs: 60000 },\n * maxBufferSize: 500,\n * beforeSend: (r) => r.body.includes('secret') ? null : r,\n * }\n * })\n * ```\n */\n logs?: PostHogLogsConfig\n\n /**\n * Overrides the language used when rendering translated survey copy.\n * When unset, the SDK falls back to the persisted person property `language`\n * and then the device locale.\n */\n overrideDisplayLanguage?: string | null\n\n /**\n * Whether to automatically register this device's push token so PostHog\n * Workflows can target it. Requires `@posthog/react-native-plugin`.\n *\n * Your app still owns permission — PostHog only observes the token the OS hands\n * back, and never sees later refreshes. Forward those to\n * {@link PostHog.registerPushNotificationToken} yourself.\n *\n * Not supported on web or macOS.\n *\n * @default true\n */\n capturePushNotificationSubscriptions?: boolean\n\n /**\n * Whether to automatically capture `$push_notification_opened` on a notification\n * tap. Requires `@posthog/react-native-plugin`.\n *\n * Fires for pushes from any provider, not just PostHog's — but title and body are\n * attached only for PostHog's own, so third-party notification text never reaches\n * analytics. On Android, taps that launch the app and taps while it's running are both\n * captured from `@posthog/react-native-plugin` 2.6.0 (earlier versions: cold starts\n * only); call {@link PostHog.capturePushNotificationOpened} for the taps it misses.\n *\n * The native SDK builds and sends this event, so JS `before_send` never sees it.\n *\n * On iOS a tap can reach the app before your JS runs, so the SDK installs a hook at launch to\n * catch a tap that cold-launches the app. Two switches gate automatic capture there, and\n * `false` on either one means the SDK sends no `$push_notification_opened` of its own (an\n * explicit {@link PostHog.capturePushNotificationOpened} call still captures):\n *\n * - This option set to `false` turns capture off when `setup()` runs and releases the launch\n * hook, dropping the tap it was holding. The hook is still installed for the window between\n * launch and `setup()`.\n * - `com.posthog.posthog.CAPTURE_PUSH_NOTIFICATION_OPENED` set to `false` in `Info.plist`\n * (Expo: `ios.infoPlist`) skips the launch hook entirely, so nothing is installed before your\n * JS runs, and forces capture off at `setup()` even when this option is `true`. It is the\n * same key posthog-flutter reads.\n *\n * Not supported on web.\n *\n * @default true\n */\n capturePushNotificationOpened?: boolean\n\n /**\n * Mints a signed identity-verification token for push subscription requests.\n * Only needed when your PostHog project requires identity verification for push.\n * Requires `@posthog/react-native-plugin`.\n *\n * Called with the current `distinctId` and `appId`. Mint on your backend (HS256,\n * `sub` = distinctId, an `app_id` claim, `aud` = `posthog:push_identity`), never\n * in the app. Return `null` to send the request unauthenticated; a slow or\n * throwing implementation does the same after 10 seconds.\n */\n pushIdentityProvider?: PostHogPushIdentityProvider\n}\n\nexport class PostHog extends PostHogCore {\n private _persistence: PostHogOptions['persistence']\n private _eventsStorage: PostHogRNStorage\n private _logsStorage: PostHogRNStorage\n private _appProperties: PostHogCustomAppProperties = {}\n private _currentSessionId?: string | undefined\n private _enableSessionReplay?: boolean\n private _sessionReplayNativeInitialized: boolean = false\n private _nativeErrorTrackingInitialized: boolean = false\n private _androidNdkCrashesUnsupportedWarned: boolean = false\n // Initialized: setup() ran carrying push config, so a live native instance exists.\n // Unsupported: this plugin can never do push — latched so the enable check stops\n // recomputing, without claiming an instance that isn't there.\n private _pushNativeInitialized: boolean = false\n private _fatalJsCaptureNativeInitialized: boolean = false\n private _pushNativeUnsupported: boolean = false\n private _sessionReplayMacOSWarned: boolean = false\n // Last applied recording state; the native bridge is only crossed on a change.\n private _sessionReplayRecordingActive?: boolean\n private _manualRecordingStartRequest?: ManualRecordingStartRequest\n // Serializes re-arm evaluations so concurrent flags reloads don't interleave.\n private _sessionReplayEvalChain: Promise<void> = Promise.resolve()\n // Serializes every JS->native command (identity, consent, push) so they reach native in\n // call order. See _enqueueNative.\n private _nativeChain: Promise<void> = Promise.resolve()\n private _sessionReplayOptions?: PostHogOptions\n // Event names that gate session replay (remote `sessionRecording.eventTriggers`). Cached in\n // memory so the capture hot path never reads storage. Empty when replay is off or unconfigured.\n private _sessionReplayEventTriggers: string[] = []\n private _eventsStoragePreloadSucceeded = true\n private _fatalCaptureObservation?: {\n eventUuid: string\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n queued: boolean\n nativeCapture?: () => Promise<void>\n }\n private _disableSurveys: boolean\n private _errorTracking: ErrorTracking\n private _logs: PostHogLogs\n // Resolved logs config — kept around so lifecycle handlers (AppState\n // background, _shutdown) can read the configured flush-time budgets without\n // reaching back into the user's options object.\n private _resolvedLogsConfig: ReturnType<typeof resolveLogsConfig>\n // Cached, foreground/background view of the app's lifecycle. Read on the\n // log-capture hot path (per record) so we tag every log with whether it\n // happened in foreground or background. Updated by the AppState listener\n // and seeded from `AppState.currentState` at construction.\n private _currentAppState?: 'foreground' | 'background'\n private _surveysReadyPromise: Promise<void> | null = null\n private _surveysReady: boolean = false\n private _setDefaultPersonProperties: boolean\n private _overrideDisplayLanguage: string | null\n private _requestHeaders: { [header_name: string]: string } = {}\n\n /**\n * 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).\n *\n * If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there.\n *\n * {@label Initialization}\n *\n * @example\n * ```ts\n * // posthog.ts\n * import PostHog from 'posthog-react-native'\n *\n * export const posthog = new PostHog('<ph_project_api_key>', {\n * host: '<ph_client_api_host>'\n * })\n *\n * // Then you can access PostHog by importing your instance\n * // Another file:\n * import { posthog } from './posthog'\n *\n * export function MyApp1() {\n * useEffect(async () => {\n * posthog.capture('event_name')\n * }, [posthog])\n *\n * return <View>Your app code</View>\n * }\n * ```\n *\n * @public\n *\n * @param apiKey - Your PostHog API key\n * @param options - PostHog configuration options\n */\n constructor(apiKey: string, options?: PostHogOptions) {\n const normalizedApiKey = typeof apiKey === 'string' ? apiKey.trim() : ''\n if (!normalizedApiKey) {\n console.error(\"You must pass your PostHog project's api key. The client will be disabled.\")\n }\n\n super(normalizedApiKey, options)\n this._isInitialized = false\n this._persistence = options?.persistence ?? 'file'\n this._disableSurveys = options?.disableSurveys ?? false\n this._errorTracking = new ErrorTracking(this, options?.errorTracking, this._logger, {\n captureFatalException: (error, hint, eventUuid, timestamp, prepareNativeCapture) =>\n this._captureFatalAndChooseOwner(eventUuid, prepareNativeCapture, () =>\n this.captureExceptionInternal(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint, {\n uuid: eventUuid,\n timestamp,\n })\n ),\n // Other events may still be queued behind the exception, so the fatal path waits for\n // the JS store to land even when native owns the exception itself.\n waitForJSPersist: async () => {\n await this._initPromise\n return this._eventsStorage.waitForPersistSuccess()\n },\n // Memory-mode apps don't have AsyncStorage, and the native SDK's queue is disk-backed:\n // handing it the exception would land data the rest of the SDK promises never to touch\n // disk. Keep the event in the JS queue there instead.\n getPersistenceMode: () => this._persistence || 'file',\n waitForStorageReady: async () => {\n await this._initPromise\n return this._eventsStoragePreloadSucceeded\n },\n isNativeCaptureReady: () => this._isNativePluginInitialized(),\n })\n this._setDefaultPersonProperties = options?.setDefaultPersonProperties ?? true\n this._overrideDisplayLanguage = options?.overrideDisplayLanguage?.trim() || null\n this._requestHeaders = options?.requestHeaders ?? {}\n\n // Either build the app properties from the existing ones\n if (typeof options?.customAppProperties === 'function') {\n this._appProperties = options.customAppProperties(getAppProperties())\n } else if (options?.customAppProperties) {\n // An object replaces the defaults but keeps $react_native_version unless it sets that key itself\n const reactNativeVersion = getReactNativeVersion()\n this._appProperties = {\n ...(reactNativeVersion ? { $react_native_version: reactNativeVersion } : {}),\n ...options.customAppProperties,\n }\n } else {\n this._appProperties = getAppProperties()\n }\n\n // Resolve storage and construct the logs module BEFORE registering the\n // AppState listener — the listener body references `this._logs` and\n // `this._eventsStorage`, and while AppState.addEventListener('change')\n // only fires on changes (not at registration), the dependency direction\n // should be explicit: dependencies first, callbacks that use them second.\n let storagePromise: Promise<void> | undefined\n\n let theStorage: PostHogCustomStorage | undefined\n if (this._persistence === 'file') {\n theStorage = options?.customStorage ?? buildOptimisticAsyncStorage()\n }\n\n if (theStorage) {\n this._eventsStorage = createEventsStorage(theStorage)\n this._logsStorage = createLogsStorage(theStorage)\n // `allSettled` so one pipeline's preload failure doesn't block the other. The failing\n // cache starts empty; future writes still target its configured storage backend.\n const preloads: Array<['events' | 'logs', Promise<void>]> = []\n if (this._eventsStorage.preloadPromise) {\n void this._eventsStorage.preloadPromise.catch(() => {\n this._eventsStoragePreloadSucceeded = false\n })\n preloads.push(['events', this._eventsStorage.preloadPromise])\n }\n if (this._logsStorage.preloadPromise) {\n preloads.push(['logs', this._logsStorage.preloadPromise])\n }\n if (preloads.length > 0) {\n storagePromise = allSettled(preloads.map(([, p]) => p)).then((results) => {\n results.forEach((r, i) => {\n if (r.status === 'rejected') {\n this._logger.error(`PostHog ${preloads[i][0]} storage preload failed:`, r.reason)\n }\n })\n })\n }\n } else {\n this._eventsStorage = createEventsMemoryStorage()\n this._logsStorage = createLogsMemoryStorage()\n }\n\n // Seed from sync `AppState.currentState` so the very first capture (which\n // can happen before any 'change' event fires) is already tagged. Maps\n // RN's broader status set into the OTLP `app.state` enum's\n // foreground/background dichotomy.\n this._currentAppState = mapAppStateForLogs(AppState.currentState)\n\n this._resolvedLogsConfig = resolveLogsConfig(options?.logs)\n this._logs = new PostHogLogs(\n this,\n this._resolvedLogsConfig,\n this._logger,\n () => {\n // Pulled at capture time so each tag reflects state at the moment\n // the log was fired, not at flush.\n const flags = this.getFeatureFlags()\n const flagKeys = flags ? Object.keys(flags) : undefined\n return {\n distinctId: this.getDistinctId() || undefined,\n sessionId: this.getSessionId() || undefined,\n screenName: (this.sessionProps?.$screen_name as string | undefined) || undefined,\n appState: this._currentAppState,\n activeFeatureFlags: flagKeys && flagKeys.length > 0 ? flagKeys : undefined,\n }\n },\n (fn) => this.wrap(fn),\n // Block between batches on the logs-storage disk write so a crash can't\n // replay an already-sent batch. Events do the equivalent via\n // `flushStorage()` (events-storage side). Mirror per-pipeline so one\n // pipeline's slow disk doesn't stall the other.\n () => this._logsStorage.waitForPersist()\n )\n\n // NOTE: this listener is registered for the lifetime of the PostHog\n // instance and is never explicitly removed. RN apps typically construct\n // a single long-lived PostHog and keep it until process exit, so a leak\n // doesn't matter in practice; just be aware that constructing many\n // instances (e.g. in tests without an explicit teardown) would\n // accumulate listeners.\n AppState.addEventListener('change', (state) => {\n // ignore unknown state (usually initial state, the app might not be ready yet)\n if (state === 'unknown') {\n return\n }\n\n // Update before kicking off the flush — captures that race the flush\n // (e.g. fired in a `componentWillUnmount` triggered by backgrounding)\n // should already see the new state.\n const mapped = mapAppStateForLogs(state)\n if (mapped) {\n this._currentAppState = mapped\n }\n\n // Flush on every transition, including foreground→active. Foreground\n // flush is technically redundant (the timer would catch up shortly),\n // but it's cheap and keeps the lifecycle handler symmetric — no\n // special-casing of which transitions should drain.\n void this.flush().catch(async (err) => {\n await logFlushError(err)\n })\n // Flush buffered logs alongside events — OS may suspend or terminate the\n // process next, and anything left in the queue won't get a second chance\n // until the app is next foregrounded. On background, race the flush\n // against `backgroundFlushBudgetMs` so a slow network can't run past\n // the OS-imposed background window (~30s on iOS). Foreground/active\n // transitions don't need a budget — the app is staying alive.\n const isBackgrounding = mapped === 'background'\n const logsFlushPromise = isBackgrounding\n ? this._logs.flushWithTimeout(this._resolvedLogsConfig.backgroundFlushBudgetMs)\n : this._logs.flush()\n void logsFlushPromise.catch(async (err) => {\n await logFlushError(err)\n })\n // Persist pending writes before the OS may suspend the process.\n void this._eventsStorage.waitForPersist()\n void this._logsStorage.waitForPersist()\n\n if (state === 'active') {\n this.getSessionId()\n }\n })\n\n const initAfterStorage = (): void => {\n // reset session id on app restart\n const enablePersistSessionIdAcrossRestart = options?.enablePersistSessionIdAcrossRestart\n if (!enablePersistSessionIdAcrossRestart) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, null)\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null)\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null)\n }\n\n this.setupBootstrap(options)\n\n // Seed device_id from the anonymous id at init time so existing installs\n // get a stable device-level identifier; once set, it survives identify()\n // and reset() independently of anonymous_id.\n if (!this.getPersistedProperty(PostHogPersistedProperty.DeviceId)) {\n const anonId = this.getAnonymousId()\n if (anonId) {\n this.setPersistedProperty(PostHogPersistedProperty.DeviceId, anonId)\n }\n }\n\n // Set default person properties for flags if enabled\n if (this._setDefaultPersonProperties) {\n this._setDefaultPersonPropertiesForFlags(false)\n }\n\n this._isInitialized = true\n\n if (this.isDisabled) {\n return\n }\n\n // Preload error tracking state from cached remote config.\n // This gates error tracking autocapture before the fresh remote config is fetched.\n const cachedRemoteConfig = this.getPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(\n PostHogPersistedProperty.RemoteConfig\n )\n if (cachedRemoteConfig) {\n this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking)\n }\n\n this.reloadRemoteConfigAsync()\n .then((response) => {\n if (response) {\n // Applies the remote autocapture kill-switch at the earliest authoritative\n // point; the flags response may apply it again later.\n this._errorTracking.onRemoteConfig(response.errorTracking)\n this._handleSurveysFromRemoteConfig(response)\n }\n })\n .catch((error) => {\n this._logger.error('Error loading remote config:', error)\n })\n .finally(() => {\n this._notifySurveysReady()\n })\n\n // captureAppLifecycleEvents defaults to true; only skip if explicitly set to false\n if (options?.captureAppLifecycleEvents !== false) {\n void this.captureAppLifecycleEvents()\n }\n\n void this.persistAppVersion()\n\n void this.startSessionReplay(options, cachedRemoteConfig ?? undefined)\n\n // Re-evaluate session replay on every flags load/reload so the linked flag\n // gates recording without an app restart. A pending manual start can also retry here,\n // even when replay was disabled at setup.\n this.onFeatureFlags(() => {\n if (this._isEnableSessionReplay() || this._manualRecordingStartRequest?.pending) {\n void this._evaluateAndStartSessionReplay()\n }\n })\n\n if (options?.addTracingHeaders && options.addTracingHeaders.length > 0) {\n patchFetchForTracingHeaders(this, options.addTracingHeaders)\n }\n }\n\n // For async storage, we wait for the storage to be ready before we start the SDK\n // For sync storage we can start the SDK immediately\n if (storagePromise) {\n this._initPromise = storagePromise.then(initAfterStorage)\n } else {\n this._initPromise = Promise.resolve()\n initAfterStorage()\n }\n }\n\n /**\n *\n * @internal\n *\n */\n public async ready(): Promise<void> {\n await this._initPromise\n }\n\n /**\n * Called when remote config has been loaded (from either the remote config endpoint or the flags endpoint).\n * Gates error tracking autocapture based on the remote config response.\n *\n * Session replay config (consoleLogRecordingEnabled, sampleRate, capturePerformance.network_timing) is already\n * cached via PostHogPersistedProperty.RemoteConfig and applied at startup in startSessionReplay().\n *\n * @internal\n */\n protected onRemoteConfig(response: PostHogRemoteConfig): void {\n this._errorTracking.onRemoteConfig(response.errorTracking)\n }\n\n /**\n * Resolves the storage instance for a given persisted-property key.\n * `LogsQueue` routes to `_logsStorage` (dedicated `.posthog-rn-logs.json`\n * file); every other key routes to `_eventsStorage`. Single source of\n * truth for routing — extending to new logs-scoped keys is a one-line\n * edit here.\n */\n private _storageForKey(key: PostHogPersistedProperty): PostHogRNStorage {\n return key === PostHogPersistedProperty.LogsQueue ? this._logsStorage : this._eventsStorage\n }\n\n getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined {\n return this._storageForKey(key).getItem(key) as T | undefined\n }\n\n setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void {\n const storage = this._storageForKey(key)\n if (key === PostHogPersistedProperty.SurveysInProgress && value === null) {\n const otherProjects = getOtherProjectSurveyProgress(this)\n otherProjects.length ? storage.setItem(key, otherProjects) : storage.removeItem(key)\n this._events.emit('surveysReset', undefined)\n } else {\n value !== null ? storage.setItem(key, value) : storage.removeItem(key)\n }\n if (key === PostHogPersistedProperty.PersonProperties) {\n // Notify surveys after the in-memory write, including unsets and resets,\n // without waiting for a feature flag reload.\n this._events.emit('personProperties', value)\n }\n }\n\n /**\n * Waits for any pending storage operations to complete.\n * This ensures data has been safely written to async storage before\n * considering events as sent, preventing duplicate events on app crash/restart.\n */\n protected async flushStorage(): Promise<void> {\n await this._eventsStorage.waitForPersist()\n }\n\n /**\n * Drain both pipelines on shutdown. Run in parallel so the logs final\n * flush + timer teardown doesn't serialize behind events (and vice-versa).\n * `_logs.shutdown()` swallows its own errors — a transient logs failure\n * must not break events shutdown.\n *\n * Logs use the smaller of `terminationFlushBudgetMs` and the caller's\n * `shutdownTimeoutMs` so a final flush can never run past the caller's\n * shutdown SLA, while still respecting the configured logs-specific\n * termination budget when it's tighter.\n *\n * After the flushes, drain any debounced storage writes that weren't already\n * persisted via the queue-advance path — `setPersistedProperty` calls for\n * distinctId, sessionId, deviceId, feature flag overrides, etc. only arm a\n * debounced write. The drain runs in `finally` so a timed-out flush still\n * persists them, and its await is bounded by the time left in the shutdown\n * SLA so a hung storage backend can't run past it.\n */\n async _shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {\n this._cancelManualRecordingStart()\n const start = Date.now()\n try {\n const remainingMs = Math.max(0, shutdownTimeoutMs - (Date.now() - start))\n const logsBudgetMs = Math.min(remainingMs, this._resolvedLogsConfig.terminationFlushBudgetMs)\n await Promise.all([this._logs.shutdown(logsBudgetMs), super._shutdown(remainingMs)])\n } finally {\n this._errorTracking.shutdown()\n // Sync drain runs inside waitForPersist before the race below; the race\n // only bounds the await for in-flight async writes.\n const remainingMs = Math.max(0, shutdownTimeoutMs - (Date.now() - start))\n const drain = Promise.all([this._eventsStorage.waitForPersist(), this._logsStorage.waitForPersist()])\n await raceWithTimeout(drain, remainingMs)\n }\n }\n\n fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {\n return fetch(url, options)\n }\n\n getLibraryId(): string {\n return 'posthog-react-native'\n }\n\n getLibraryVersion(): string {\n return version\n }\n\n getCustomUserAgent(): string {\n if (Platform.OS === 'web') {\n return ''\n }\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`\n }\n\n protected getCustomHeaders(): { [key: string]: string } {\n return { ...super.getCustomHeaders(), ...this._requestHeaders }\n }\n\n getCommonEventProperties(): PostHogEventProperties {\n // On iOS, 'screen' is UIScreen.main, which ignores resizable windows and stays the outer display on\n // foldables. 'window' is the app's window. Android's 'window' can exclude system bars, so keep 'screen' there.\n const { width, height } = Dimensions.get(Platform.OS === 'ios' ? 'window' : 'screen')\n return {\n ...super.getCommonEventProperties(),\n ...this._appProperties,\n $screen_height: height,\n $screen_width: width,\n }\n }\n\n getSurveyDisplayLanguageOverride(): string | null {\n return this._overrideDisplayLanguage\n }\n\n /**\n * Registers super properties that are sent with every event.\n *\n * Super properties are properties associated with events that are set once and then sent with every capture call.\n * They persist across sessions and are stored locally.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // register super properties\n * posthog.register({\n * 'icecream pref': 'vanilla',\n * team_id: 22,\n * })\n * ```\n *\n * @public\n *\n * @param properties An associative array of properties to store about the user\n */\n register(properties: PostHogEventProperties): Promise<void> {\n return super.register(properties)\n }\n\n /**\n * Removes a super property so it won't be sent with future events.\n *\n * Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // remove a super property\n * posthog.unregister('icecream pref')\n * ```\n *\n * @public\n *\n * @param property The name of the super property to remove\n */\n unregister(property: string): Promise<void> {\n return super.unregister(property)\n }\n\n /**\n * Resets the user's ID and anonymous ID after logout.\n *\n * To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.\n * This also clears all stored super properties and more.\n *\n * By default (when `propertiesToKeep` is not provided), the app lifecycle properties\n * (`InstalledAppBuild` and `InstalledAppVersion`) are automatically preserved to prevent\n * duplicate \"Application Installed\" events on the next app launch.\n *\n * If you pass `propertiesToKeep` explicitly, only the properties you specify will be preserved.\n * To keep the default app lifecycle behavior, include `PostHogPersistedProperty.InstalledAppBuild`\n * and `PostHogPersistedProperty.InstalledAppVersion` in your array.\n *\n * Note: The event queue (`PostHogPersistedProperty.Queue`) and logs queue\n * (`PostHogPersistedProperty.LogsQueue`) are always preserved regardless of\n * what is passed in `propertiesToKeep`, to ensure in-flight data is not lost.\n *\n * The project-level remote config (`PostHogPersistedProperty.RemoteConfig`,\n * `PostHogPersistedProperty.SessionReplay`, `PostHogPersistedProperty.Surveys`) is also\n * always preserved — it is not user data — so session replay and surveys keep working\n * after an identity change. The user-specific survey state (`SurveysSeen`,\n * `SurveyLastSeenDate`) is still cleared.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // reset after logout (preserves app lifecycle properties by default)\n * posthog.reset()\n * ```\n *\n * @example\n * ```js\n * // reset but keep feature flag overrides and app lifecycle properties\n * posthog.reset([\n * PostHogPersistedProperty.OverrideFeatureFlags,\n * PostHogPersistedProperty.InstalledAppBuild,\n * PostHogPersistedProperty.InstalledAppVersion,\n * ])\n * ```\n *\n * @param propertiesToKeep - Optional array of persisted properties to preserve during reset.\n * When not provided, app lifecycle and device bucketing properties are automatically preserved.\n * When provided, only the specified properties are preserved.\n * The event queue and logs queue are always preserved regardless.\n *\n * @public\n */\n reset(propertiesToKeep?: PostHogPersistedProperty[]): void {\n // When propertiesToKeep is not explicitly provided, automatically preserve app lifecycle\n // properties and device_id to prevent duplicate \"Application Installed\" events and\n // to maintain stable feature flag bucketing across identity changes.\n const effectivePropertiesToKeep = propertiesToKeep ?? [\n PostHogPersistedProperty.InstalledAppBuild,\n PostHogPersistedProperty.InstalledAppVersion,\n PostHogPersistedProperty.DeviceId,\n ]\n\n // Cancel before super.reset() emits flags for the next, anonymous user.\n this._cancelManualRecordingStart()\n\n // RemoteConfig, SessionReplay, and Surveys are project-level config, not user data:\n // always preserve them so replay can re-arm against the new user's flags. The\n // user-specific survey state (SurveysSeen, SurveyLastSeenDate) is still cleared.\n // Do NOT keep SessionReplayEventTriggerActivatedSession: it is user-session state, so the\n // base reset() must clear it to stop one user's activation leaking into the next.\n // PushRegistered is device-level subscription state, not user data: native reset()\n // re-binds the subscription rather than deleting it, so the device stays registered.\n super.reset([\n PostHogPersistedProperty.RemoteConfig,\n PostHogPersistedProperty.SessionReplay,\n PostHogPersistedProperty.Surveys,\n PostHogPersistedProperty.PushRegistered,\n ...effectivePropertiesToKeep,\n ])\n\n if (this._setDefaultPersonProperties) {\n // Reset reloads flags asyncrhonously, but doesn't wait for it.\n // As a result, we can synchronously set the default person properties without\n // reloading, and allow the super.reset() call to reload the flags.\n this._setDefaultPersonPropertiesForFlags(false)\n }\n\n // Native holds its own identity and a registered push token is bound to it, so without this\n // Workflows keep delivering to the logged-out user. identify() only writes native\n // preferences; reset() is what unregisters and re-registers the subscription.\n if (OptionalReactNativePlugin?.reset) {\n // Ids are read at dispatch, not here: a same-tick identify() shares this queue and\n // lands after, so native must converge on whichever identity is current by then.\n void this._enqueueNative(\n 'reset',\n (plugin) => plugin.reset?.(String(this.getDistinctId()), String(this.getAnonymousId())),\n // Boot native when a manual register persisted a subscription; skipping the rebind\n // would leave Workflows targeting the pre-reset identity.\n this.getPersistedProperty(PostHogPersistedProperty.PushRegistered) === true\n )\n }\n // super.reset() cleared the persisted opt-out, but native keeps its own copy and would\n // stay opted out for the rest of the process.\n this._propagateNativeOptOut()\n\n // Logout must be durable so a crash in the debounce window can't resurface the previous user.\n void this._eventsStorage.waitForPersist()\n }\n\n /**\n * Helper to extract and set default person properties from app properties\n *\n * @private\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n private _setDefaultPersonPropertiesForFlags(reloadFeatureFlags = true): void {\n const defaultProps: Record<string, JsonType> = {}\n const relevantKeys = [\n '$app_version',\n '$app_build',\n '$app_namespace',\n '$os_name',\n '$os_version',\n '$device_type',\n ] as const\n\n relevantKeys.forEach((key) => {\n const value = this._appProperties[key]\n if (value !== null && value !== undefined) {\n defaultProps[key] = value\n }\n })\n\n const commonProps = this.getCommonEventProperties()\n if (commonProps.$lib) {\n defaultProps.$lib = commonProps.$lib\n }\n if (commonProps.$lib_version) {\n defaultProps.$lib_version = commonProps.$lib_version\n }\n\n if (Object.keys(defaultProps).length > 0) {\n this.setPersonPropertiesForFlags(defaultProps, reloadFeatureFlags)\n }\n }\n\n /**\n * Manually flushes the event queue.\n *\n * You can set the number of events in the configuration that should queue before flushing.\n * Setting this to 1 will send events immediately and will use more battery. This is set to 20 by default.\n * You can also manually flush the queue. If a flush is already in progress it returns a promise for the existing flush.\n *\n * Note: this drains the **events** pipeline only. Logs are flushed via\n * {@link flushLogs}, and {@link shutdown} drains both before terminating.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // manually flush the queue\n * await posthog.flush()\n * ```\n *\n * @see flushLogs\n * @public\n *\n * @returns Promise that resolves when the flush is complete\n */\n flush(): Promise<void> {\n return super.flush()\n }\n\n /**\n * Captures a structured log record and sends it to PostHog's logs product\n * (`/i/v1/logs`). Low-level primitive — most callers will prefer\n * `posthog.logger.info(...)` / `.warn(...)` / `.error(...)` etc., which\n * wrap this with a level pre-set.\n *\n * Records are buffered per-session, rate-limited, batched into OTLP\n * payloads, and flushed on a timer, on AppState change, or when the\n * buffer reaches capacity. Configure flush cadence, rate cap, and a\n * `beforeSend` filter via the `logs` option on `new PostHog(...)`.\n *\n * Note — naming collision: `posthog.captureLog()` (this method) is the\n * **logs product** API. There is also a separate, pre-existing\n * `sessionReplayConfig.captureLog` boolean that controls whether\n * **session replay** records the device's `console.*` output. The two\n * are unrelated: this method emits structured records to the logs\n * pipeline regardless of whether session replay is on.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * posthog.captureLog({\n * body: 'checkout completed',\n * level: 'info',\n * attributes: { order_id: 'ord_789', amount_cents: 4999 },\n * })\n * ```\n *\n * @public\n *\n * @param options Log record. `body` is required; `level` defaults to\n * `'info'`. `attributes` are attached as OTLP key-value attributes\n * and will override auto-populated ones (distinctId, sessionId) on\n * key conflict.\n */\n captureLog(options: CaptureLogOptions): void {\n this._logs.captureLog(options)\n }\n\n /**\n * Manually flushes the logs queue.\n *\n * Logs flush automatically on a timer, when the buffer fills, or on\n * AppState change — most apps never need to call this. Use it when you\n * want a synchronous-style hand-off (e.g. before navigating away from a\n * critical screen, in a custom crash handler, or while testing locally).\n *\n * If a flush is already in progress, both callers join the same in-flight\n * promise — no double-send.\n *\n * Note: this drains the **logs** pipeline only. Events are flushed via\n * {@link flush}, and {@link shutdown} drains both before terminating.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * await posthog.flushLogs()\n * ```\n *\n * @see flush\n * @public\n *\n * @returns Promise that resolves when the flush is complete.\n */\n flushLogs(): Promise<void> {\n return this._logs.flush()\n }\n\n private _captureLogger?: CaptureLogger\n\n /**\n * Convenience per-level logger. Each method is shorthand for\n * `posthog.captureLog({ body, level, attributes })`. Lazily constructed\n * on first access, then reused.\n *\n * {@label Capture}\n *\n * @example\n * ```ts\n * posthog.logger.info('checkout completed', { order_id: 'ord_789' })\n * posthog.logger.error('payment failed', { code: 'E001' })\n * ```\n *\n * @public\n */\n get logger(): CaptureLogger {\n if (!this._captureLogger) {\n this._captureLogger = {\n trace: (body, attributes) => this.captureLog({ body, level: 'trace', attributes }),\n debug: (body, attributes) => this.captureLog({ body, level: 'debug', attributes }),\n info: (body, attributes) => this.captureLog({ body, level: 'info', attributes }),\n warn: (body, attributes) => this.captureLog({ body, level: 'warn', attributes }),\n error: (body, attributes) => this.captureLog({ body, level: 'error', attributes }),\n fatal: (body, attributes) => this.captureLog({ body, level: 'fatal', attributes }),\n }\n }\n return this._captureLogger\n }\n\n /**\n * Opts the user in to data capture.\n *\n * By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { defaultOptIn: false }.\n * Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called.\n *\n * {@label Privacy}\n *\n * @example\n * ```js\n * // opt in to tracking\n * posthog.optIn()\n * ```\n *\n * @public\n */\n optIn(): Promise<void> {\n // Consent must be durable. See reset()/identify().\n const result = super.optIn()\n void this._eventsStorage.waitForPersist()\n // Native re-arms push on opt-in (iOS reinstalls its integrations, Android resumes deferred\n // work on the next flush), so the token unregistered by optOut() comes back without a restart.\n this._propagateNativeOptOut()\n return result\n }\n\n /**\n * Opts the user out of data capture.\n *\n * 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.\n *\n * {@label Privacy}\n *\n * @example\n * ```js\n * // opt out of tracking\n * posthog.optOut()\n * ```\n *\n * @public\n */\n optOut(): Promise<void> {\n this._cancelManualRecordingStart()\n // Consent must be durable. See reset()/identify().\n const coreOptOut = super.optOut()\n const persistOptOut = (): Promise<void> => {\n this.setPersistedProperty(PostHogPersistedProperty.SurveysInProgress, null)\n return this._eventsStorage.waitForPersist()\n }\n const result = Promise.all([\n coreOptOut,\n this._isInitialized ? persistOptOut() : this._initPromise.then(persistOptOut),\n ]).then(() => undefined)\n // A fatal exception captured before this point lives in the native SDK's own queue, so\n // there is nothing left on the JS side to clear. _propagateNativeOptOut() below stops\n // native capturing anything further.\n //\n // NOTE: neither native SDK drops what its queue already holds on optOut(), so an\n // exception captured while opted in can still be delivered after consent is withdrawn.\n // The JS journal this replaced rotated a generation to prevent exactly that. Delivery\n // usually happens on the relaunch flush, before a user can opt out, but the guarantee\n // is weaker than it was.\n // A device token registered before opt-out would otherwise survive consent withdrawal: the\n // native subscription handler keeps its own persisted record and retry loop. unregister is\n // deliberately allowed while opted out.\n // Native gates unregister sends on its own opt-out flag, so the unregister has to reach\n // native first; both share _nativeChain, so enqueueing it first is the ordering. A DELETE\n // that still loses the race natively is persisted there and replayed after opt-in.\n if (OptionalReactNativePlugin?.unregisterPushNotificationToken) {\n void this.unregisterPushNotificationToken()\n }\n this._propagateNativeOptOut()\n return result\n }\n\n // Native persists its own consent flag and only reads the JS one at setup(), so runtime\n // changes must cross the bridge or native's automatic push registration keeps running on\n // its setup-time snapshot (e.g. re-registering an OS-refreshed token after optOut()).\n private _propagateNativeOptOut(): void {\n if (!OptionalReactNativePlugin?.setOptOut) {\n // A plugin that predates push cannot auto-register tokens, so there is no consent to sync.\n return\n }\n // Consent is read at dispatch, so two queued writes converge on the current value however\n // they interleave — an unawaited optOut()/optIn() pair cannot strand native opted out.\n void this._enqueueNative('setOptOut', (plugin) => plugin.setOptOut?.(this.optedOut))\n // Nothing runs setup() while opted out, so consent granted at runtime has no native\n // instance to land on. The predicate is false when opted out, so optOut() self-excludes.\n if (this._isPushNativeEnabled(this._sessionReplayOptions)) {\n void this._ensureNativeInitialized()\n }\n }\n\n /**\n * Checks if a feature flag is enabled for the current user.\n *\n * A `false` return value means the SDK resolved the current value as off. If no evaluation is\n * available, this method returns `defaultValue` when provided. Without a default, it returns\n * `undefined` before flags load; for backwards compatibility, a missing key can resolve to\n * `false` after a non-empty response is stored.\n *\n * Globally inactive flags are omitted from remote responses, so they follow this missing-key\n * behavior rather than carrying an explicit off evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // check if feature flag is enabled\n * const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')\n * ```\n *\n * @example\n * ```js\n * // fall back to false while flags are not loaded\n * const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: false })\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @param options Optional per-call settings\n * @returns True if the flag evaluates on, false if it evaluates off, or the missing-value fallback described above\n */\n isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & { defaultValue: boolean }): boolean\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined {\n return super.isFeatureEnabled(key, options)\n }\n\n /**\n * Gets the value of a feature flag for the current user.\n *\n * Returns `true` or `false` for an evaluated boolean flag and a string for a multivariate flag.\n * Returns `undefined` before flags load or when loading fails. For backwards compatibility, a\n * missing key can resolve to `false` after a non-empty response is stored; use\n * `getFeatureFlagResult()` to distinguish an unavailable key from a conclusive off result.\n *\n * Globally inactive flags are omitted from remote responses, so they follow this missing-key\n * behavior rather than carrying an explicit off evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // get feature flag value\n * const value = posthog.getFeatureFlag('key-for-your-boolean-flag')\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @param options Optional per-call settings\n * @returns The current feature flag value, or undefined if flags are unavailable\n */\n getFeatureFlag(key: string, options?: FeatureFlagResultOptions): boolean | string | undefined {\n return super.getFeatureFlag(key, options)\n }\n\n /**\n * Gets the payload of a feature flag for the current user.\n *\n * Returns JsonType or undefined if not loaded yet or if there was a problem loading.\n *\n * {@label Feature flags}\n *\n * @deprecated Use `getFeatureFlagResult()` instead, which returns the flag value and payload from a single evaluation.\n *\n * @example\n * ```js\n * // get feature flag payload\n * const payload = posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload\n * ```\n *\n * @public\n *\n * @param key The feature flag key\n * @returns The feature flag payload or undefined if not loaded\n */\n getFeatureFlagPayload(key: string): JsonType | undefined {\n return super.getFeatureFlagPayload(key)\n }\n\n /**\n * Reloads feature flags from the server.\n *\n * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.\n * If you want to manually trigger a refresh, you can call this method.\n *\n * {@label Feature flags}\n *\n * @remarks\n * When the `disableRemoteFeatureFlags` option is set, this method is a no-op; supply\n * flag values via `updateFlags()` instead.\n *\n * @example\n * ```js\n * // reload feature flags\n * posthog.reloadFeatureFlags()\n * ```\n *\n * @public\n */\n reloadFeatureFlags(): void {\n super.reloadFeatureFlags()\n }\n\n /**\n * Reloads feature flags from the server asynchronously.\n *\n * PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag.\n * If you want to manually trigger a refresh and get the result, you can call this method.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reload feature flags and get result\n * posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))\n * ```\n *\n * @public\n *\n * @remarks\n * When the `disableRemoteFeatureFlags` option is set, no request is made and the\n * promise resolves with the currently stored flags (from `bootstrap` or `updateFlags()`).\n *\n * @returns Promise that resolves with the refreshed flags\n */\n reloadFeatureFlagsAsync(): Promise<Record<string, boolean | string> | undefined> {\n return super.reloadFeatureFlagsAsync()\n }\n\n /**\n * Replaces (or merges into) the stored feature flags and payloads with locally supplied\n * values, exactly as if they had been returned by the flags endpoint: the values are\n * persisted, `getFeatureFlag()`/`getFeatureFlagPayload()` read them back, and\n * `onFeatureFlags` listeners fire. Makes no network request.\n *\n * Intended for apps that evaluate flags outside the SDK (e.g. server-side local\n * evaluation) and push the results in at runtime, typically together with the\n * `disableRemoteFeatureFlags` option so the SDK never fetches flags itself.\n *\n * {@label Feature flags}\n *\n * @remarks\n * The values are cleared by `reset()`, so push them again after an identity change.\n *\n * @example\n * ```js\n * // replace all stored flags with locally evaluated ones\n * posthog.updateFlags({ 'my-flag': true, 'multivariate-flag': 'variant-1' })\n * ```\n *\n * @example\n * ```js\n * // include payloads\n * posthog.updateFlags({ 'my-flag': true }, { 'my-flag': { color: 'blue' } })\n * ```\n *\n * @example\n * ```js\n * // merge into the stored flags instead of replacing them\n * posthog.updateFlags({ 'my-flag': false }, undefined, { merge: true })\n * ```\n *\n * @public\n *\n * @param flags - Flag keys mapped to their values (boolean, or a variant string)\n * @param payloads - Optional flag keys mapped to their JSON payloads\n * @param options - Set `merge: true` to merge with the currently stored flags instead of replacing them\n */\n updateFlags(\n flags: Record<string, boolean | string>,\n payloads?: Record<string, JsonType>,\n options?: { merge?: boolean }\n ): void {\n super.updateFlags(flags, payloads, options)\n }\n\n /**\n * Associates the current user with a group.\n *\n * Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.).\n * This is a paid feature and is not available on the open-source or free cloud plan.\n *\n * {@label Group analytics}\n *\n * @example\n * ```js\n * // associate with a group\n * posthog.group('company', 'company_id_in_your_db')\n * ```\n *\n * @example\n * ```js\n * // associate with a group and update properties\n * posthog.group('company', 'company_id_in_your_db', {\n * name: 'Awesome Inc.',\n * employees: 11,\n * })\n * ```\n *\n * @public\n *\n * @param groupType The type of group (e.g. 'company', 'team')\n * @param groupKey The unique identifier for the group\n * @param properties Optional properties to set for the group\n */\n group(groupType: string, groupKey: string, properties?: PostHogEventProperties): void {\n super.group(groupType, groupKey, properties)\n\n // Automatically cache group properties for feature flag evaluation\n if (properties && Object.keys(properties).length > 0) {\n const propsToCache: Record<string, JsonType> = {}\n Object.keys(properties).forEach((key) => {\n const value = properties[key]\n if (value !== null && value !== undefined) {\n propsToCache[key] = value\n }\n })\n if (Object.keys(propsToCache).length > 0) {\n this.setGroupPropertiesForFlags({\n [groupType]: propsToCache,\n })\n }\n }\n }\n\n /**\n * Assigns an alias to the current user.\n *\n * Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible.\n * For example, if a distinct ID used on the frontend is not available in your backend.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // set alias for current user\n * posthog.alias('distinct_id')\n * ```\n *\n * @public\n *\n * @param alias The alias to assign to the current user\n */\n alias(alias: string): void {\n super.alias(alias)\n }\n\n /**\n * Gets the current user's distinct ID.\n *\n * 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.\n * This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // get current distinct ID\n * const distinctId = posthog.getDistinctId()\n * ```\n *\n * @public\n *\n * @returns The current user's distinct ID\n */\n getDistinctId(): string {\n return super.getDistinctId()\n }\n\n /**\n * Returns the stable device identifier used for device-level feature flag bucketing.\n * This ID persists across identify() and reset() calls, only changing on a fresh\n * app install, manual cache clearing, or OS-initiated storage cleanup.\n *\n * @returns The device ID, or an empty string if not yet initialized\n */\n getDeviceId(): string {\n const deviceId = this.getPersistedProperty<string>(PostHogPersistedProperty.DeviceId)\n if (!deviceId) {\n // Lazy init for upgrades: existing installs won't have a device_id yet\n const anonId = this.getAnonymousId()\n if (anonId) {\n this.setPersistedProperty(PostHogPersistedProperty.DeviceId, anonId)\n return anonId\n }\n return ''\n }\n return deviceId\n }\n\n /**\n * Sets person properties for feature flag evaluation.\n *\n * Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier.\n * You can do so by setting properties the flag depends on with this call. These are set for the entire session.\n * Successive calls are additive: all properties you set are combined together and sent for flag evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // set person properties for flags\n * posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})\n * ```\n *\n * @public\n *\n * @param properties The person properties to set for flag evaluation\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setPersonPropertiesForFlags(properties: Record<string, JsonType>, reloadFeatureFlags = true): void {\n super.setPersonPropertiesForFlags(properties, reloadFeatureFlags)\n }\n\n /**\n * Resets person properties for feature flag evaluation.\n *\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reset person properties for flags\n * posthog.resetPersonPropertiesForFlags()\n * ```\n *\n * @public\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n resetPersonPropertiesForFlags(reloadFeatureFlags = true): void {\n super.resetPersonPropertiesForFlags()\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Sets group properties for feature flag evaluation.\n *\n * These properties are automatically attached to the current group (set via posthog.group()).\n * When you change the group, these properties are reset.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // set group properties for flags\n * posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})\n * ```\n *\n * @public\n *\n * @param properties The group properties to set for flag evaluation\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setGroupPropertiesForFlags(properties: Record<string, Record<string, JsonType>>, reloadFeatureFlags = true): void {\n super.setGroupPropertiesForFlags(properties)\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Resets group properties for feature flag evaluation.\n *\n * {@label Feature flags}\n *\n * @example\n * ```js\n * // reset group properties for flags\n * posthog.resetGroupPropertiesForFlags()\n * ```\n *\n * @public\n *\n * @param reloadFeatureFlags Whether to reload feature flags after setting the properties. Defaults to true.\n */\n resetGroupPropertiesForFlags(reloadFeatureFlags = true): void {\n super.resetGroupPropertiesForFlags()\n\n if (reloadFeatureFlags) {\n this.reloadFeatureFlags()\n }\n }\n\n /**\n * Captures a screen view event.\n *\n * @remarks\n * This function requires a name. You may also pass in an optional properties object.\n * Once initialized, the screen name is registered immediately for subsequent events, including exceptions.\n * During initialization, screen registration and event capture retain their call order.\n * Exceptions use the last recorded screen, not a destination that has not yet been tracked.\n *\n * {@label Capture}\n *\n * @example\n * ```js\n * // Basic screen capture\n * posthog.screen('dashboard')\n * ```\n *\n * @example\n * ```js\n * // Screen capture with properties\n * posthog.screen('dashboard', {\n * background: 'blue',\n * hero: 'superhog',\n * })\n * ```\n *\n * @public\n *\n * @param name - The name of the screen\n * @param properties - Optional properties to include with the screen event\n * @param options - Optional capture options\n */\n async screen(name: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void> {\n // Keep queued captures in order during initialization, without yielding once the client is ready.\n if (!this._isInitialized) {\n await this._initPromise\n }\n this.registerForSession({\n $screen_name: name,\n })\n\n return this.capture(\n '$screen',\n {\n ...properties,\n $screen_name: name,\n },\n options\n )\n }\n\n _isEnableSessionReplay(): boolean {\n // Session replay has no macOS backend, so it is never enabled there (crash tracking still is).\n return !this.isDisabled && !isMacOS() && (this._enableSessionReplay ?? false)\n }\n\n _resetSessionId(reactNativeSessionReplay: typeof OptionalReactNativePlugin | undefined, sessionId: string): void {\n // _resetSessionId is only called if reactNativeSessionReplay not undefined, but the linter wasn't happy\n if (reactNativeSessionReplay) {\n reactNativeSessionReplay.endSession()\n reactNativeSessionReplay.startSession(sessionId)\n }\n }\n\n getSessionId(): string {\n const sessionId = super.getSessionId()\n\n if (!this._isEnableSessionReplay() && !this._isNativePluginInitialized()) {\n return sessionId\n }\n\n // only rotate if there is a new sessionId and it is different from the current one\n if (sessionId.length > 0 && this._currentSessionId && sessionId !== this._currentSessionId) {\n if (OptionalReactNativePlugin) {\n try {\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n this._logger.info(`sessionId rotated from ${this._currentSessionId} to ${sessionId}.`)\n } catch (e) {\n this._logger.error(`Failed to rotate sessionId: ${e}.`)\n }\n }\n this._currentSessionId = sessionId\n\n // Event triggers are armed per session: the previous activation no longer matches the new\n // session id, so re-evaluate to stop recording until a fresh matching event fires.\n if (this._sessionReplayEventTriggers.length > 0) {\n void this._evaluateAndStartSessionReplay()\n }\n } else {\n this._logger.info(`sessionId not rotated, sessionId ${sessionId} and currentSessionId ${this._currentSessionId}.`)\n }\n\n return sessionId\n }\n\n resetSessionId(): void {\n super.resetSessionId()\n if ((this._isEnableSessionReplay() || this._isNativePluginInitialized()) && OptionalReactNativePlugin) {\n try {\n OptionalReactNativePlugin.endSession()\n this._logger.info(`Native PostHog session ended.`)\n } catch (e) {\n this._logger.error(`Native PostHog session failed to end: ${e}.`)\n }\n }\n }\n\n /**\n * Starts session recording.\n * This method will have no effect if PostHog is not enabled, or if session replay is disabled in your project settings.\n *\n * A refused manual start is retried with successive delays of 1, 2, 4, 8, and 16 seconds,\n * and on subsequent feature flags loads while pending. This promise resolves after the\n * initial attempt, without waiting for retries or guaranteeing recording is active.\n * A newer start supersedes an unfinished request. Stop, reset, opt-out, and shutdown\n * cancel pending starts. Use `isSessionReplayActive()` to check the current recording state.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this is a no-op.\n *\n * Requires `posthog-react-native-session-replay` version 1.3.0 or higher.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * // Resume the current session recording\n * await posthog.startSessionRecording()\n * ```\n *\n * @example\n * ```js\n * // Start a new session recording\n * await posthog.startSessionRecording(false)\n * ```\n *\n * @public\n *\n * @param resumeCurrent - Whether to resume recording of current session (true) or start a new session (false). Defaults to true.\n */\n async startSessionRecording(resumeCurrent: boolean = true): Promise<void> {\n this._cancelManualRecordingStart()\n const request: ManualRecordingStartRequest = { pending: false, retryCount: 0 }\n this._manualRecordingStartRequest = request\n // Chained here, not in _startSessionRecording (which _evaluateAndStartSessionReplayInternal\n // also calls from inside this chain — re-chaining there deadlocks), so two callers can't\n // both enter initializeNativePlugin() and race their pluginConfigs.\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n await this._attemptManualRecordingStart(request, resumeCurrent)\n })\n await this._sessionReplayEvalChain\n }\n\n private _cancelManualRecordingStart(): void {\n clearTimeout(this._manualRecordingStartRequest?.timer)\n this._manualRecordingStartRequest = undefined\n }\n\n private async _attemptManualRecordingStart(\n request: ManualRecordingStartRequest,\n resumeCurrent: boolean\n ): Promise<boolean> {\n if (this._manualRecordingStartRequest !== request) {\n return false\n }\n if (this.isDisabled || this.optedOut) {\n this._cancelManualRecordingStart()\n return false\n }\n\n const started = await this._startSessionRecording(resumeCurrent)\n // Cancellation is synchronous; a bridge call already in flight can still finish later.\n // Do not let its result revive the old request or leave its recorder running.\n if (this._manualRecordingStartRequest !== request) {\n if (started) {\n await this._stopSessionRecording()\n }\n return false\n }\n if (started) {\n this._cancelManualRecordingStart()\n } else {\n request.pending = true\n this._scheduleManualRecordingStartRetry(request)\n }\n return started\n }\n\n private _scheduleManualRecordingStartRetry(request: ManualRecordingStartRequest): void {\n const delay = MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount]\n if (\n request.timer !== undefined ||\n delay === undefined ||\n !this._sessionReplayNativeInitialized ||\n !OptionalReactNativePlugin?.startRecording\n ) {\n return\n }\n request.retryCount++\n request.timer = safeSetTimeout(() => {\n request.timer = undefined\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n // The original attempt already rotated the session if resumeCurrent was false.\n await this._attemptManualRecordingStart(request, true)\n })\n }, delay)\n }\n\n // Shared start path. Also called by the flags-driven evaluation, which runs inside\n // _sessionReplayEvalChain and so must not re-enter it.\n private async _startSessionRecording(resumeCurrent: boolean): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - nothing to do\n return false\n }\n\n try {\n // Check if the plugin supports startRecording\n if (!OptionalReactNativePlugin.startRecording) {\n this._logger.warn(\n 'startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n return false\n }\n\n // If only error tracking is active, add replay to the existing native instance\n // rather than re-initializing.\n if (!this._sessionReplayNativeInitialized) {\n this._logger.info('Native session replay SDK not initialized, initializing now...')\n const initialized = await this.initializeNativePlugin(this._sessionReplayOptions, undefined, true)\n if (!initialized) {\n this._logger.error('Failed to initialize native session replay SDK.')\n return false\n }\n }\n\n // Handle session ID if not resuming\n if (!resumeCurrent) {\n super.resetSessionId()\n const newSessionId = super.getSessionId()\n // sync native + rn sessionId\n this._resetSessionId(OptionalReactNativePlugin, String(newSessionId))\n this._currentSessionId = newSessionId\n }\n\n await OptionalReactNativePlugin.startRecording(resumeCurrent)\n\n // Both native SDKs refuse to start the recorder while their own remote config is not\n // loaded (PostHog.kt, PostHogSDK.swift) and resolve the call all the same, so ask the\n // recorder instead of reporting a success the caller cannot check.\n const started = await OptionalReactNativePlugin.isEnabled().catch((e) => {\n // Unknown state, so report the start rather than a failure nothing can act on.\n this._logger.warn(`Failed to confirm the session recording started: ${e}`)\n return true\n })\n\n if (!started) {\n this._logger.warn(\n 'The native SDK refused to start session recording, usually because its remote config is not loaded yet. ' +\n 'PostHog retries on the next feature flags load.'\n )\n return false\n }\n\n this._logger.info(`Session recording ${resumeCurrent ? 'resumed' : 'started'}.`)\n return true\n } catch (e) {\n this._logger.error(`Failed to start session recording: ${e}`)\n return false\n }\n }\n\n /**\n * Stops the current session recording if one is in progress.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this is a no-op.\n *\n * Requires `posthog-react-native-session-replay` version 1.3.0 or higher.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * await posthog.stopSessionRecording()\n * ```\n * @public\n */\n async stopSessionRecording(): Promise<void> {\n this._cancelManualRecordingStart()\n // Let an in-flight native start settle before stopping its recorder.\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n await this._stopSessionRecording()\n })\n await this._sessionReplayEvalChain\n }\n\n // Shared stop path, also called by the flags-driven evaluation.\n private async _stopSessionRecording(): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - nothing to do\n return false\n }\n\n try {\n // Check if the plugin supports stopRecording\n if (!OptionalReactNativePlugin.stopRecording) {\n this._logger.warn(\n 'stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n return false\n }\n\n await OptionalReactNativePlugin.stopRecording()\n this._logger.info('Session recording stopped.')\n return true\n } catch (e) {\n this._logger.error(`Failed to stop session recording: ${e}`)\n return false\n }\n }\n\n /**\n * Returns whether session replay is currently active.\n *\n * Note: This is only available on iOS and Android. On web/macOS, this always returns false.\n *\n * {@label Session Replay}\n *\n * @example\n * ```js\n * const isActive = await posthog.isSessionReplayActive()\n * ```\n *\n * @public\n *\n * @returns Whether session replay is currently active\n */\n async isSessionReplayActive(): Promise<boolean> {\n await this._initPromise\n\n if (this.isDisabled) {\n return false\n }\n\n if (!OptionalReactNativePlugin) {\n // No native plugin loaded (web, or plugin not installed) - not active\n return false\n }\n\n try {\n return await OptionalReactNativePlugin.isEnabled()\n } catch (e) {\n this._logger.error(`Failed to check session replay status: ${e}`)\n return false\n }\n }\n\n /**\n * Associates events with a specific user. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // Basic identify\n * posthog.identify('distinctID', {\n * email: 'user@posthog.com',\n * name: 'My Name'\n * })\n * ```\n *\n * @example\n * ```js\n * // Using $set and $set_once\n * posthog.identify('distinctID', {\n * $set: {\n * email: 'user@posthog.com',\n * name: 'My Name'\n * },\n * $set_once: {\n * date_of_first_log_in: '2024-03-01'\n * }\n * })\n * ```\n *\n * @public\n *\n * @param distinctId - A unique identifier for your user. Typically either their email or database ID.\n * @param properties - Optional dictionary with key:value pairs to set the person properties\n * @param options - Optional capture options\n */\n identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {\n const previousDistinctId = this.getDistinctId()\n\n // Extract $set_once before super.identify() because core deletes it from the properties object\n const userProps = properties?.$set || properties\n const userPropsOnce = properties?.$set_once\n\n super.identify(distinctId, properties, options)\n\n // Automatically cache person properties for feature flag evaluation\n\n const propsToCache: Record<string, JsonType> = {}\n if (userProps && typeof userProps === 'object' && !Array.isArray(userProps)) {\n Object.entries(userProps).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n propsToCache[key] = value\n }\n })\n }\n\n const propsOnceToCache: Record<string, JsonType> = {}\n if (userPropsOnce && typeof userPropsOnce === 'object' && !Array.isArray(userPropsOnce)) {\n Object.entries(userPropsOnce).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n propsOnceToCache[key] = value\n }\n })\n }\n\n if (Object.keys(propsToCache).length > 0 || Object.keys(propsOnceToCache).length > 0) {\n // super.identify() already handles reloading flags in all cases:\n // - When distinctId changes: it calls reloadFeatureFlags() directly\n // - When distinctId is the same but properties change: it calls setPersonProperties() which reloads flags\n // So we only need to set the properties here without triggering another reload.\n this.setPersonPropertiesForFlags(\n {\n $set: propsToCache,\n ...(Object.keys(propsOnceToCache).length > 0 ? { $set_once: propsOnceToCache } : {}),\n },\n false\n )\n }\n\n if (OptionalReactNativePlugin) {\n // Queued, not inline: a same-tick reset() is already on _nativeChain and must land first,\n // or its post-reset anonymous id gets overwritten. No init check here — gating on\n // _isNativePluginInitialized() would lose every identify() issued while setup() is in\n // flight, which is most startup identifies.\n void this._enqueueNative('identify', (plugin) => {\n const nativeDistinctId = String(this.getDistinctId() || previousDistinctId)\n const anonymousId = String(this.getAnonymousId())\n const identified = plugin.identify(nativeDistinctId, anonymousId)\n this._logger.info(\n `Native PostHog identified with distinctId ${nativeDistinctId} and anonymousId ${anonymousId}.`\n )\n return identified\n })\n }\n\n // Account-switch safety — same as reset().\n void this._eventsStorage.waitForPersist()\n }\n\n /**\n * Capture a caught exception manually\n *\n * Exceptions also include capture-time `$app_state` (active, background, inactive or extension) on any\n * platform where React Native AppState provides a known value. On iOS and Android, optional\n * `expo-updates` (0.25.0 or newer) adds `$expo_update_id`, `$expo_runtime_version`, `$expo_channel`\n * and `$expo_is_embedded_launch` for enabled updates outside development mode. Unknown values\n * are omitted.\n * These exception-only fields are separate from the static app metadata controlled by\n * `customAppProperties`, including the existing `$app_version` and `$app_build`.\n * Override these fields with `additionalProperties`, or remove them using `before_send`.\n *\n * {@label Error tracking}\n *\n * @public\n *\n * @example\n * ```js\n * // Capture a caught exception\n * try {\n * // something that might throw\n * } catch (error) {\n * posthog.captureException(error)\n * }\n * ```\n *\n * @example\n * ```js\n * // With additional properties\n * posthog.captureException(error, {\n * customProperty: 'value',\n * anotherProperty: ['I', 'can be a list'],\n * ...\n * })\n * ```\n *\n * @param {Error} error The error to capture\n * @param {Object} [additionalProperties] Any additional properties to add to the error event\n * @returns {void}\n */\n captureException(\n error: Error | unknown,\n additionalProperties: PostHogEventProperties = {},\n hint?: CoreErrorTracking.EventHint\n ): void {\n try {\n const result = this.captureExceptionInternal(error, additionalProperties, hint)\n if (result?.additionalProperties?.$exception_level === 'fatal') {\n void this._eventsStorage.waitForPersist()\n void this._logsStorage.waitForPersist()\n }\n } catch (e) {\n this._logger.error('Error while capturing $exception:', e)\n }\n }\n\n private captureExceptionInternal(\n error: Error | unknown,\n additionalProperties: PostHogEventProperties = {},\n hint?: CoreErrorTracking.EventHint,\n options?: PostHogCaptureOptions\n ): {\n eventUuid: string\n timestamp: string\n additionalProperties: PostHogEventProperties\n } | null {\n const resolvedHint: CoreErrorTracking.EventHint = hint ?? {\n mechanism: { handled: true, type: 'generic' },\n syntheticException: new Error('Synthetic Error'),\n }\n\n const merged: PostHogEventProperties = { ...getExceptionContext(), ...additionalProperties }\n\n // Attach the rolling exception-steps buffer (no-op if the caller already provided their own).\n const finalAdditional = this._errorTracking.attachExceptionSteps(merged)\n\n const captureOptions: PostHogCaptureOptions = {\n ...(options || {}),\n _originatedFromCaptureException: true,\n }\n\n this.capture(\n '$exception',\n { ...this.buildExceptionProperties(error, resolvedHint), ...finalAdditional },\n captureOptions\n )\n\n const eventUuid = captureOptions.uuid ?? ''\n const timestamp = (captureOptions.timestamp ?? new Date()).toISOString()\n return {\n eventUuid,\n timestamp,\n additionalProperties: finalAdditional,\n }\n }\n\n private buildExceptionProperties(error: Error | unknown, hint: CoreErrorTracking.EventHint): PostHogEventProperties {\n try {\n const builder = this.getErrorPropertiesBuilder()\n const exceptionProperties = builder.buildFromUnknown(error, hint) as unknown as PostHogEventProperties\n return exceptionProperties\n } catch (e) {\n this._logger.error('Error while building exception properties:', e)\n return {}\n }\n }\n\n /**\n * Records a breadcrumb-style exception step. Steps accumulate in a rolling, byte-bounded buffer\n * and are attached to every captured `$exception` as `$exception_steps`, giving the error tracking\n * UI a timeline of recent activity before each error.\n *\n * The `$timestamp` is captured at call time. The reserved keys `$message` and `$timestamp` are\n * stripped from `properties` — the SDK sets the canonical values. This method never throws.\n *\n * @example\n * ```js\n * posthog.addExceptionStep('User tapped Checkout', { screen: 'cart' })\n * ```\n *\n * @param {string} message A non-empty description of the step\n * @param {Object} [properties] Optional additional context to attach to the step\n * @returns {void}\n */\n addExceptionStep(message: string, properties?: Properties): void {\n this._errorTracking.addExceptionStep(message, properties)\n }\n\n protected override createErrorPropertiesBuilder(): CoreErrorTracking.ErrorPropertiesBuilder {\n return new CoreErrorTracking.ErrorPropertiesBuilder(\n [\n new CoreErrorTracking.PromiseRejectionEventCoercer(),\n new CoreErrorTracking.ErrorCoercer(),\n new CoreErrorTracking.ErrorEventCoercer(),\n new CoreErrorTracking.ObjectCoercer(),\n new CoreErrorTracking.StringCoercer(),\n new CoreErrorTracking.PrimitiveCoercer(),\n ],\n CoreErrorTracking.createStackParser(\n isHermes() ? 'hermes' : 'web:javascript',\n CoreErrorTracking.chromeStackLineParser,\n CoreErrorTracking.geckoStackLineParser\n )\n )\n }\n\n initReactNativeNavigation(options: PostHogAutocaptureOptions): boolean {\n return withReactNativeNavigation(this, options)\n }\n\n /**\n * Creates a person profile for the current user, if they don't already have one.\n *\n * This is useful when using `personProfiles: 'identified_only'` mode and you want to\n * explicitly create a profile for an anonymous user before they identify.\n *\n * If `personProfiles` is 'identified_only' and no profile exists, this will create one.\n * If `personProfiles` is 'never', this will log an error and do nothing.\n * If `personProfiles` is 'always' or a profile already exists, this is a no-op.\n *\n * {@label Identification}\n *\n * @example\n * ```js\n * // Create a person profile for an anonymous user\n * posthog.createPersonProfile()\n * ```\n *\n * @public\n */\n createPersonProfile(): void {\n super.createPersonProfile()\n }\n\n /**\n * Sets properties on the person profile associated with the current `distinct_id`.\n * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @remarks\n * Updates user properties that are stored with the person profile in PostHog.\n * If `personProfiles` is set to `identified_only` and no profile exists, this will create one.\n *\n * @example\n * ```js\n * // set user properties\n * posthog.setPersonProperties({\n * email: 'user@example.com',\n * plan: 'premium'\n * })\n * ```\n *\n * @example\n * ```js\n * // set properties with $set_once\n * posthog.setPersonProperties(\n * { name: 'Max Hedgehog' }, // $set properties\n * { initial_url: '/blog' } // $set_once properties\n * )\n * ```\n *\n * @example\n * ```js\n * // set properties without reloading feature flags\n * posthog.setPersonProperties({ plan: 'premium' }, undefined, false)\n * ```\n *\n * @public\n *\n * @param userPropertiesToSet - Optional: An object of properties to store about the user.\n * These properties will overwrite any existing values for the same keys.\n * @param userPropertiesToSetOnce - Optional: An object of properties to store about the user.\n * If a property is previously set, this does not override that value.\n * @param reloadFeatureFlags - Whether to reload feature flags after setting the properties. Defaults to true.\n */\n setPersonProperties(\n userPropertiesToSet?: { [key: string]: JsonType },\n userPropertiesToSetOnce?: { [key: string]: JsonType },\n reloadFeatureFlags = true\n ): void {\n super.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce, reloadFeatureFlags)\n }\n\n /**\n * Removes properties from the person profile associated with the current `distinct_id`.\n * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)\n *\n * {@label Identification}\n *\n * @public\n *\n * @param propertyNames - The name (or names) of the person properties to remove.\n * @param reloadFeatureFlags - Whether to reload feature flags after removing the properties. Defaults to true.\n */\n unsetPersonProperties(propertyNames: string | string[], reloadFeatureFlags = true): void {\n super.unsetPersonProperties(propertyNames, reloadFeatureFlags)\n }\n\n public async getSurveys(): Promise<SurveyResponse['surveys']> {\n if (this._disableSurveys === true) {\n this._logger.info('Loading surveys is disabled.')\n this._cacheSurveys(null, 'disabled in config')\n return []\n }\n\n const surveys = this.getPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys)\n\n if (surveys && surveys.length > 0) {\n this._logger.info('Surveys fetched from storage: ', JSON.stringify(surveys))\n return surveys\n }\n\n this._logger.info('No surveys found in storage')\n return []\n }\n\n /**\n * Returns a promise that resolves when surveys are ready to be loaded.\n * If surveys are already loaded and ready to go, returns a resolved promise instead.\n * @internal\n */\n _onSurveysReady(): Promise<void> {\n if (this._surveysReady) {\n // If surveys are already ready, resolve immediately\n return Promise.resolve()\n }\n\n if (!this._surveysReadyPromise) {\n this._surveysReadyPromise = new Promise<void>((resolve) => {\n this._surveysReadyResolve = resolve\n })\n }\n\n return this._surveysReadyPromise\n }\n\n private _surveysReadyResolve: (() => void) | null = null\n\n /**\n * Helper function to cache surveys to storage with consistent logging\n */\n private _cacheSurveys(surveys: Survey[] | null, source: string): void {\n this.setPersistedProperty<SurveyResponse['surveys']>(PostHogPersistedProperty.Surveys, surveys)\n\n if (surveys && surveys.length > 0) {\n this._logger.info(`Surveys cached from ${source}:`, JSON.stringify(surveys))\n } else if (surveys === null) {\n this._logger.info(`Surveys cleared (${source})`)\n } else {\n this._logger.info(`No surveys to cache from ${source})`)\n }\n }\n\n /**\n * Internal method to notify that surveys are ready\n */\n private _notifySurveysReady(): void {\n this._surveysReady = true\n if (this._surveysReadyResolve) {\n this._surveysReadyResolve()\n this._surveysReadyResolve = null\n this._surveysReadyPromise = null\n }\n }\n\n /**\n * Handle surveys from remote config response\n */\n private _handleSurveysFromRemoteConfig(response: any): void {\n if (this._disableSurveys === true) {\n this._logger.info('Loading surveys skipped, disabled.')\n this._cacheSurveys(null, 'remote config (disabled)')\n return\n }\n\n const surveys = response.surveys\n\n // Keep an authoritative empty list distinct from an unavailable survey cache.\n if (Array.isArray(surveys)) {\n this._cacheSurveys(surveys as Survey[], 'remote config')\n } else {\n this._cacheSurveys(null, 'remote config')\n }\n }\n\n /**\n * Registers this device's push token so PostHog Workflows can target it.\n * Requires `@posthog/react-native-plugin`.\n *\n * Registration happens at startup on its own when\n * {@link PostHogOptions.capturePushNotificationSubscriptions} is on, so call this for\n * token refreshes, which that startup fetch cannot see — on Android only, since a\n * refresh listener yields an FCM token and iOS defaults to APNs. Safe to call before\n * the native SDK is ready; the call queues rather than being dropped.\n *\n * `appId` says which provider delivers: the Firebase `project_id` for an FCM token, the\n * APNs bundle id for an APNs token. Unset, iOS uses the bundle id and Android the\n * default `FirebaseApp`'s project id, so pass it if you don't use Firebase or use a\n * non-default project. Registration fails server-side if your PostHog project has no\n * matching integration for `appId`.\n *\n * To use FCM on iOS too, pass the Firebase `project_id` as `appId` and set\n * {@link PostHogOptions.capturePushNotificationSubscriptions} to `false` first —\n * otherwise the device registers twice (APNs under the bundle id, FCM under the project\n * id), a Workflow with both integrations delivers twice, and\n * {@link unregisterPushNotificationToken} clears only the most recent.\n *\n * Not supported on web or macOS.\n */\n async registerPushNotificationToken(deviceToken: string, options?: { appId?: string }): Promise<void> {\n return this._callPushPlugin(\n 'registerPushNotificationToken',\n // requireInit: a host driving registration itself may have both capture flags off, so\n // nothing else would ever bring the native SDK up and the token would be dropped.\n { allowMacOS: false, requireInit: true, noop: 'token not registered' },\n (plugin) => {\n // Native persists the subscription across launches; remember that so a later\n // launch's cleanup knows to boot native (see unregister/reset).\n this.setPersistedProperty(PostHogPersistedProperty.PushRegistered, true)\n return plugin.registerPushNotificationToken?.(deviceToken, options?.appId ?? null)\n }\n )\n }\n\n /**\n * Unregisters this device's push token so Workflows stop targeting it — for example\n * from your logout flow. Requires `@posthog/react-native-plugin`.\n *\n * Durable: a failed or offline request retries on the next flush or launch. `reset()`\n * already moves a registered token to the new identity, so this is only needed if you\n * manage subscriptions yourself.\n *\n * Not supported on web or macOS.\n */\n async unregisterPushNotificationToken(): Promise<void> {\n return this._callPushPlugin(\n 'unregisterPushNotificationToken',\n // requireInit only when a manual register persisted a subscription: native keeps it\n // across launches, so cleanup must boot native even in a process where nothing else\n // initialized it. Without one, native never came up with anything to remove, and\n // booting it to delete nothing would defeat the opt-out this usually follows.\n {\n allowMacOS: false,\n allowWhenOptedOut: true,\n requireInit: this.getPersistedProperty(PostHogPersistedProperty.PushRegistered) === true,\n noop: 'nothing to unregister',\n },\n (plugin) => {\n // Clear on dispatch: both native SDKs persist the delete intent before their\n // consent/network gates and retry it on later launches, so the retry is native's\n // from here on.\n this.setPersistedProperty(PostHogPersistedProperty.PushRegistered, null)\n return plugin.unregisterPushNotificationToken?.()\n }\n )\n }\n\n /**\n * Captures `$push_notification_opened` when a user opens a push notification.\n * Requires `@posthog/react-native-plugin`.\n *\n * Only for taps {@link PostHogOptions.capturePushNotificationOpened} cannot see itself —\n * local notifications, plus Android taps while the app is running if\n * `@posthog/react-native-plugin` is older than 2.6.0. A notification PostHog sent is still\n * counted once when both paths report it (same `posthog.invocation_id` and action within\n * five minutes); one from another provider is counted twice.\n *\n * Keys of `payload`'s `posthog` entry become `$notification_<key>` properties. Leave\n * `action` unset for a plain tap; `subtitle` is iOS only. The native SDK builds and\n * sends the event, so JS `before_send` never sees it — redact anything sensitive first.\n *\n * Not supported on web.\n */\n async capturePushNotificationOpened(options: {\n title?: string\n subtitle?: string\n body?: string\n payload?: { [key: string]: JsonType }\n action?: string\n }): Promise<void> {\n const properties: { [key: string]: JsonType } = {}\n for (const key of ['title', 'subtitle', 'body', 'payload', 'action'] as const) {\n if (options[key] !== undefined) {\n properties[key] = options[key]\n }\n }\n return this._callPushPlugin(\n 'capturePushNotificationOpened',\n { allowMacOS: true, requireInit: true, noop: 'event not captured' },\n (plugin) => plugin.capturePushNotificationOpened?.(properties)\n )\n }\n\n // Shared guard skeleton for the push methods: disabled → unsupported platform →\n // plugin missing or outdated → queued behind native init → swallow-and-warn on rejection.\n private async _callPushPlugin(\n method: 'registerPushNotificationToken' | 'unregisterPushNotificationToken' | 'capturePushNotificationOpened',\n behavior: { allowMacOS: boolean; allowWhenOptedOut?: boolean; requireInit: boolean; noop: string },\n invoke: (plugin: NonNullable<typeof OptionalReactNativePlugin>) => Promise<void> | undefined\n ): Promise<void> {\n if (this.isDisabled) {\n return\n }\n // Unregistering removes a subscription, so it stays available after opt-out; the two that\n // send data do not.\n if (this.optedOut && !behavior.allowWhenOptedOut) {\n this._logger.warn(`${method} skipped: the user is opted out; ${behavior.noop}.`)\n return\n }\n if (isWeb() || (!behavior.allowMacOS && isMacOS())) {\n this._logger.warn(`${method} is not supported on ${isWeb() ? 'web' : 'macOS'}; ${behavior.noop}.`)\n return\n }\n if (!OptionalReactNativePlugin?.[method]) {\n this._logger.warn(`${method} requires @posthog/react-native-plugin; install or update it.`)\n return\n }\n return this._enqueueNative(\n method,\n (plugin) => {\n // Re-check consent: it may have been withdrawn while this waited its turn.\n if (this.optedOut && !behavior.allowWhenOptedOut) {\n this._logger.warn(`${method} skipped: the user is opted out; ${behavior.noop}.`)\n return\n }\n return invoke(plugin)\n },\n behavior.requireInit\n )\n }\n\n /**\n * The one channel for JS->native commands (identity, consent, push):\n *\n * - ordered: commands reach native in call order, so a reset() can't be overtaken by an\n * identify() issued after it.\n * - late-bound: `run` reads live state at dispatch, so the newest identity/consent wins.\n * - init-gated: nothing runs before native setup(). `requireInit` brings a native SDK that\n * was never set up all the way up rather than dropping the command.\n *\n * Never rejects — failures are logged.\n */\n private _enqueueNative(\n label: string,\n run: (plugin: NonNullable<typeof OptionalReactNativePlugin>) => Promise<void> | void,\n requireInit: boolean = false\n ): Promise<void> {\n const next = this._nativeChain\n .catch(() => {})\n .then(async () => {\n if (this.isDisabled || isWeb() || !OptionalReactNativePlugin) {\n return\n }\n // ready() doesn't cover native setup — it's kicked off fire-and-forget, and the native\n // SDK resolves a call it dropped for not being initialized, so the caller sees a\n // success that registered nothing. _initPromise first: it is what assigns the eval\n // chain, so until it settles the chain is still its initial resolved value.\n await this._initPromise.catch(() => {})\n await this._sessionReplayEvalChain.catch(() => {})\n if (!this._isNativePluginInitialized()) {\n if (!requireInit) {\n return\n }\n await this._ensureNativeInitialized()\n if (!this._isNativePluginInitialized()) {\n this._logger.warn(`${label} skipped: the native plugin is not initialized.`)\n return\n }\n }\n // A call that never settles (bridge torn down mid-call, or a native hang) would own\n // _nativeChain for the rest of the process, silently blocking every later\n // identify/reset/consent/push. Timing out doesn't cancel the native work, just stops\n // it blocking the queue.\n await raceWithTimeout(Promise.resolve(run(OptionalReactNativePlugin)), NATIVE_CALL_TIMEOUT_MS, () =>\n this._logger.warn(`Native PostHog ${label} timed out after ${NATIVE_CALL_TIMEOUT_MS}ms; continuing.`)\n )\n })\n .catch((e) => this._logger.warn(`Native PostHog ${label} failed: ${e}.`))\n this._nativeChain = next\n return next\n }\n\n // Brings native up on demand (push call, or late consent). Runs on the replay eval chain\n // to avoid racing a flags-driven evaluation. Callers re-check _isNativePluginInitialized\n // since the return value is also true on the nothing-to-do path.\n private _ensureNativeInitialized(): Promise<void> {\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(async () => {\n if (!this._isNativePluginInitialized()) {\n // enableSessionReplay: false — only replay's own evaluation may start it; this just\n // brings the instance up. forcePush: true — needed even with both auto-capture flags\n // off, the one config nothing else would create an instance for.\n await this.initializeNativePlugin(this._sessionReplayOptions, undefined, false, true)\n }\n })\n return this._sessionReplayEvalChain\n }\n\n private _pluginVersionAtLeast(major: number, minor: number): boolean {\n const version = OptionalReactNativePluginVersion?.match(/^(\\d+)\\.(\\d+)\\.\\d+(?:\\+[\\w.-]+)?$/)\n if (!version) {\n return false\n }\n const [installedMajor, installedMinor] = [Number(version[1]), Number(version[2])]\n return installedMajor > major || (installedMajor === major && installedMinor >= minor)\n }\n\n // Two native opt-ins: nativeCrashes covers the platform's own crash handler, while Android\n // NDK crashes are a separate posthog-android toggle (its tombstone scanner).\n private _nativeErrorAutocapture(options?: PostHogOptions): { nativeCrashes: boolean; androidNdkCrashes: boolean } {\n const autocapture = options?.errorTracking?.autocapture\n if (this.isDisabled || typeof autocapture !== 'object') {\n return { nativeCrashes: false, androidNdkCrashes: false }\n }\n // Android-only, so it must not bring up the native SDK on other platforms.\n let androidNdkCrashes = Platform.OS === 'android' && autocapture.androidNdkCrashes === true\n // Older plugins ignore the key, so it would start the native SDK with nothing to capture.\n if (androidNdkCrashes && !this._pluginVersionAtLeast(2, 12)) {\n if (!this._androidNdkCrashesUnsupportedWarned) {\n this._androidNdkCrashesUnsupportedWarned = true\n this._logger.warn(\n `errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later ` +\n `(installed: ${OptionalReactNativePluginVersion ?? 'unknown'}); ignoring.`\n )\n }\n androidNdkCrashes = false\n }\n return { nativeCrashes: autocapture.nativeCrashes === true, androidNdkCrashes }\n }\n\n private _isAutocaptureNativeErrors(options?: PostHogOptions): boolean {\n const { nativeCrashes, androidNdkCrashes } = this._nativeErrorAutocapture(options)\n return nativeCrashes || androidNdkCrashes\n }\n\n /**\n * Fatal JavaScript exceptions are handed to the native SDK, which persists them to its own\n * disk queue synchronously before the process dies. That only works if the native SDK is\n * set up, so JS uncaught-exception autocapture now warrants native init on its own — an app\n * that enabled neither replay, native crashes nor push would otherwise have no durable\n * fatal path at all.\n */\n private _isFatalJsCaptureNativeEnabled(): boolean {\n if (this.isDisabled || this.optedOut || isWeb() || this._persistence === 'memory') {\n return false\n }\n return this._errorTracking.isUncaughtExceptionAutocaptureEnabled()\n }\n\n private _isNativePluginInitialized(): boolean {\n return (\n this._sessionReplayNativeInitialized ||\n this._nativeErrorTrackingInitialized ||\n this._pushNativeInitialized ||\n this._fatalJsCaptureNativeInitialized\n )\n }\n\n // Push is enabled unless everything push-related is switched off: both auto-capture\n // flags default to true, matching the native SDKs.\n //\n // `force` covers a host that disabled both auto-capture flags to drive registration itself —\n // the native SDK still must exist. It bypasses only the auto-capture test; consent/platform/\n // plugin-support still gate, and the config built from `options` means forcing never\n // re-enables auto-capture.\n private _isPushNativeEnabled(options?: PostHogOptions, force: boolean = false): boolean {\n // optedOut is the persisted consent state; isDisabled is the static `disabled` option.\n // Push registers a durable device token, so it must respect consent, not just `disabled`.\n if (this.isDisabled || this.optedOut || isWeb() || this._pushNativeUnsupported) {\n return false\n }\n return (\n force ||\n options?.capturePushNotificationSubscriptions !== false ||\n options?.capturePushNotificationOpened !== false ||\n !!options?.pushIdentityProvider\n )\n }\n\n /**\n * Initializes the native session replay SDK if not already initialized.\n * This is called automatically by startSessionReplay() or lazily by startSessionRecording().\n *\n * @returns true if the native SDK is ready (initialized or already was), false otherwise\n */\n private async initializeSessionReplayNative(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<boolean> {\n return this.initializeNativePlugin(options, cachedRemoteConfig, true)\n }\n\n private async initializeNativePlugin(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>,\n enableSessionReplay: boolean = this._isEnableSessionReplay(),\n forcePush: boolean = false\n ): Promise<boolean> {\n const nativeErrorAutocapture = this._nativeErrorAutocapture(options)\n let enableNativeErrorTracking = nativeErrorAutocapture.nativeCrashes || nativeErrorAutocapture.androidNdkCrashes\n let enablePush = this._isPushNativeEnabled(options, forcePush)\n const enableFatalJsCapture = this._isFatalJsCaptureNativeEnabled()\n\n // Session replay has no macOS backend — the native plugin no-ops its recording controls there.\n // Skip it in JS so we don't mark replay initialized or log a false \"started\" while nothing records.\n if (enableSessionReplay && isMacOS()) {\n if (!this._sessionReplayMacOSWarned) {\n this._sessionReplayMacOSWarned = true\n this._logger.warn('Session replay is not supported on macOS; ignoring.')\n }\n enableSessionReplay = false\n }\n\n if (!enableSessionReplay && !enableNativeErrorTracking && !enablePush && !enableFatalJsCapture) {\n return true\n }\n\n if (!OptionalReactNativePlugin) {\n // Only replay and error tracking warrant a warning: they are explicit opt-ins,\n // while push is on by default and shouldn't nag every plugin-less app.\n if (enableSessionReplay || enableNativeErrorTracking) {\n this._logger.warn(\n enableSessionReplay\n ? 'Session replay enabled but not installed.'\n : 'Native error tracking enabled but not installed.'\n )\n }\n // Push is on by default, so latch it unsupported or every flags reload re-enters this\n // method just to return here.\n this._pushNativeUnsupported = true\n return false\n }\n\n if (\n (!enableSessionReplay || this._sessionReplayNativeInitialized) &&\n (!enableNativeErrorTracking || this._nativeErrorTrackingInitialized) &&\n (!enablePush || this._pushNativeInitialized) &&\n (!enableFatalJsCapture || this._fatalJsCaptureNativeInitialized)\n ) {\n return true\n }\n\n // Both native SDKs ignore a second setup() once running (PostHogSDK.swift:139,\n // PostHog.kt:150), so whatever brought the instance up first — replay, error tracking, or\n // push — replay must resume on it instead of calling setup() again. Reaching here with\n // enableSessionReplay true already means sampling/event-trigger evaluation decided\n // recording may start.\n if (this._isNativePluginInitialized() && enableSessionReplay && !this._sessionReplayNativeInitialized) {\n this._sessionReplayNativeInitialized = true\n await OptionalReactNativePlugin.startRecording?.(true)\n return true\n }\n\n const sessionId = this.getSessionId()\n if (sessionId.length === 0) {\n this._logger.warn(`Native PostHog plugin enabled but no sessionId found.`)\n return false\n }\n\n const defaultThrottleDelayMs = 1000\n\n const {\n maskAllTextInputs = true,\n maskAllImages = true,\n maskAllSandboxedViews = true,\n captureTouches = true,\n captureLog: localCaptureLog = true,\n captureNetworkTelemetry: localCaptureNetworkTelemetry = true,\n verifyScreenshotMaskAlignment = false,\n screenshotScale,\n screenshotCompressionQuality,\n screenshotColorMode,\n screenshotModeBackgroundCapture = false,\n sampleRate: localSampleRate,\n iOSdebouncerDelayMs = defaultThrottleDelayMs,\n androidDebouncerDelayMs = defaultThrottleDelayMs,\n } = options?.sessionReplayConfig ?? {}\n\n if (captureTouches === false && !isMacOS()) {\n if (!this._pluginVersionAtLeast(2, 9)) {\n this._logger.warn(\n `sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. ` +\n `The installed plugin (version ${OptionalReactNativePluginVersion ?? 'unknown'}) may still record touch coordinates. ` +\n `Upgrade the plugin and rebuild your app before relying on this setting.`\n )\n }\n }\n\n let throttleDelayMs = options?.sessionReplayConfig?.throttleDelayMs ?? defaultThrottleDelayMs\n\n // if deprecated values are set, we use the higher one for back compatibility\n if (\n throttleDelayMs === defaultThrottleDelayMs &&\n (iOSdebouncerDelayMs !== defaultThrottleDelayMs || androidDebouncerDelayMs !== defaultThrottleDelayMs)\n ) {\n throttleDelayMs = Math.max(iOSdebouncerDelayMs, androidDebouncerDelayMs)\n }\n\n // Gate captureLog and captureNetworkTelemetry using cached remote config.\n // The effective state is: localEnabled AND remoteEnabled.\n // If remote config hasn't loaded yet (no cached value), defaults to true (don't block locally enabled capture).\n const remoteConsoleLogEnabled = getRemoteConfigBool(\n cachedRemoteConfig?.sessionRecording,\n 'consoleLogRecordingEnabled',\n true\n )\n const remoteNetworkTimingEnabled = getRemoteConfigBool(\n cachedRemoteConfig?.capturePerformance,\n 'network_timing',\n true\n )\n const remoteSampleRateRaw = getRemoteConfigNumber(cachedRemoteConfig?.sessionRecording, 'sampleRate')\n\n const captureLog = localCaptureLog && remoteConsoleLogEnabled\n const captureNetworkTelemetry = localCaptureNetworkTelemetry && remoteNetworkTimingEnabled\n\n const localSampleRateValid =\n localSampleRate === undefined ? undefined : isValidSampleRate(localSampleRate) ? localSampleRate : undefined\n const remoteSampleRateValid =\n remoteSampleRateRaw === undefined\n ? undefined\n : isValidSampleRate(remoteSampleRateRaw)\n ? remoteSampleRateRaw\n : undefined\n\n const sampleRate = localSampleRateValid ?? remoteSampleRateValid\n\n if (localCaptureLog && !remoteConsoleLogEnabled) {\n this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).')\n }\n if (localCaptureNetworkTelemetry && !remoteNetworkTimingEnabled) {\n this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).')\n }\n if (localSampleRate !== undefined && localSampleRateValid === undefined) {\n this._logger.warn(\n `Ignoring invalid sessionReplayConfig.sampleRate '${localSampleRate}'. Expected a number between 0 and 1.`\n )\n }\n if (remoteSampleRateRaw !== undefined && remoteSampleRateValid === undefined) {\n this._logger.warn(\n `Ignoring invalid remote config sessionRecording.sampleRate '${remoteSampleRateRaw}'. Expected a number between 0 and 1.`\n )\n }\n if (localSampleRateValid !== undefined && remoteSampleRateValid !== undefined) {\n this._logger.warn(\n `Local sessionReplayConfig.sampleRate (${localSampleRateValid}) overrides the remote sampleRate ` +\n `(${remoteSampleRateValid}). The project setting is ignored while the local option is set. ` +\n `Remove sessionReplayConfig.sampleRate to follow the project setting.`\n )\n } else if (typeof sampleRate === 'number') {\n const source = localSampleRateValid !== undefined ? 'local config' : 'remote config'\n this._logger.info(`sampleRate set from ${source} (${sampleRate}).`)\n } else if (cachedRemoteConfig === undefined) {\n this._logger.warn(\n 'Session replay starts with no sampleRate because no remote config is cached yet. ' +\n 'Any project sample rate applies from the next launch.'\n )\n }\n\n const sdkReplayConfig = {\n maskAllTextInputs,\n maskAllImages,\n maskAllSandboxedViews,\n captureTouches,\n captureLog,\n captureNetworkTelemetry,\n verifyScreenshotMaskAlignment,\n ...(Number.isFinite(screenshotScale) ? { screenshotScale } : {}),\n ...(Number.isFinite(screenshotCompressionQuality) ? { screenshotCompressionQuality } : {}),\n ...(screenshotColorMode !== undefined ? { screenshotColorMode } : {}),\n screenshotModeBackgroundCapture,\n sampleRate,\n iOSdebouncerDelayMs,\n androidDebouncerDelayMs,\n throttleDelayMs,\n }\n\n this._logger.info(\n `Native PostHog plugin (version ${OptionalReactNativePluginVersion ?? 'unknown'}) replay config: ${JSON.stringify(\n sdkReplayConfig\n )}`\n )\n\n // if Flags API has not returned yet, we will start session replay with default config.\n const sessionReplay = this.getPersistedProperty(PostHogPersistedProperty.SessionReplay) ?? {}\n const cachedSessionReplayConfig = (sessionReplay as { [key: string]: JsonType }) ?? {}\n\n this._logger.info(\n `Session replay session recording from flags cached config: ${JSON.stringify(cachedSessionReplayConfig)}`\n )\n\n // Neither push nor fatal-JS capture needs native's own feature-flag preload — JS already\n // owns flags, and the fatal path only uses native as a durable queue. Native error\n // tracking's autocapture kill-switch does need it, as does replay, so only skip when\n // those two are not why we are here. Remote config isn't skippable: both native SDKs\n // deprecated that option to a no-op.\n const pushOnlyInit = (enablePush || enableFatalJsCapture) && !enableSessionReplay && !enableNativeErrorTracking\n\n const sdkOptions = {\n apiKey: this.apiKey,\n host: this.host,\n debug: this.isDebug,\n distinctId: this.getDistinctId(),\n anonymousId: this.getAnonymousId(),\n sdkVersion: this.getLibraryVersion(),\n flushAt: this.flushAt,\n // Consent is persisted JS-side; without this the native SDK defaults to opted-in and\n // would keep registering a device token after optOut().\n optOut: this.optedOut,\n preloadFeatureFlags: !pushOnlyInit,\n // Native-sent requests (session replay, crash uploads) bypass the JS request path,\n // so the configured headers are passed through to the native plugin as well.\n requestHeaders: this._requestHeaders,\n }\n\n // Log header names only: requestHeaders values can carry secrets (e.g. an Authorization token).\n const loggableSdkOptions = { ...sdkOptions, requestHeaders: Object.keys(this._requestHeaders) }\n this._logger.info(`Native PostHog plugin sdk options: ${JSON.stringify(loggableSdkOptions)}`)\n\n try {\n const wasSessionReplayEnabled = enableSessionReplay\n ? await OptionalReactNativePlugin.isEnabled().catch(() => false)\n : false\n\n if (OptionalReactNativePlugin.setup) {\n // The provider can't cross the bridge, so only an enabled marker goes into the\n // setup map; the JS listener itself must be installed here, before setup() captures it.\n // Installed regardless of enablePush: an opted-out app's only setup() call comes from\n // replay/error-tracking, and native ignores a second — skip here and subscriptions stay\n // unauthenticated for the process. Inert while opted out, since native only mints on a\n // subscription request, which its own opt-out flag blocks.\n let pushIdentityProviderEnabled = false\n if (options?.pushIdentityProvider) {\n if (OptionalReactNativePlugin.setPushIdentityProvider) {\n OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider)\n pushIdentityProviderEnabled = true\n } else {\n this._logger.warn(\n 'pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.'\n )\n }\n }\n\n const pluginConfig = {\n sessionReplay: {\n enabled: enableSessionReplay,\n sdkReplayConfig,\n decideReplayConfig: cachedSessionReplayConfig,\n },\n errorTracking: {\n nativeAutocapture: nativeErrorAutocapture.nativeCrashes,\n androidNdkCrashes: nativeErrorAutocapture.androidNdkCrashes,\n exceptionSteps: this._errorTracking.getNativePluginExceptionStepsConfig(),\n },\n // Always sent, even when push init isn't the reason we're here: the native\n // defaults are true, so an explicit opt-out must reach the native config.\n push: {\n capturePushNotificationSubscriptions: options?.capturePushNotificationSubscriptions ?? true,\n capturePushNotificationOpened: options?.capturePushNotificationOpened ?? true,\n pushIdentityProviderEnabled,\n },\n ...(options?.rageClickConfig && { rageClick: options.rageClickConfig }),\n }\n await OptionalReactNativePlugin.setup(String(sessionId), sdkOptions, pluginConfig)\n // Native resolves its own persisted opt-out over the config value passed above, so an\n // earlier optIn() keeps winning and sdkOptions.optOut alone can't opt a user back out.\n // Only an explicit optOut()/optIn() overwrites it, so re-assert JS consent every setup.\n await OptionalReactNativePlugin.setOptOut?.(this.optedOut)\n if (wasSessionReplayEnabled) {\n // if somehow the SDK is already enabled with a different sessionId, we reset it\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n }\n } else {\n if (enableNativeErrorTracking) {\n this._logger.warn(\n 'Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.'\n )\n // The legacy plugin can't do native crash capture, so don't mark it initialized below.\n enableNativeErrorTracking = false\n }\n // start() carries no push config, so the legacy plugin can never do push. Unsupported,\n // not initialized: the latch stops enablePush recomputing true on every flags reload,\n // while claiming initialized would assert a native instance setup() never created.\n if (enablePush) {\n this._logger.warn(\n 'Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.'\n )\n }\n enablePush = false\n this._pushNativeUnsupported = true\n if (!enableSessionReplay) {\n return false\n }\n if (!(await OptionalReactNativePlugin.isEnabled())) {\n await OptionalReactNativePlugin.start(\n String(sessionId),\n sdkOptions,\n sdkReplayConfig,\n cachedSessionReplayConfig\n )\n } else {\n // if somehow the SDK is already enabled with a different sessionId, we reset it\n this._resetSessionId(OptionalReactNativePlugin, String(sessionId))\n }\n }\n this._currentSessionId = sessionId\n if (enableSessionReplay) {\n this._sessionReplayNativeInitialized = true\n this._logger.info(`Session replay started with sessionId ${sessionId}.`)\n }\n if (enableNativeErrorTracking) {\n this._nativeErrorTrackingInitialized = true\n this._errorTracking.onNativeErrorTrackingReady()\n this._logger.info('Native error tracking started.')\n }\n if (enablePush) {\n this._pushNativeInitialized = true\n this._logger.info('Push notification native support started.')\n }\n if (enableFatalJsCapture) {\n this._fatalJsCaptureNativeInitialized = true\n this._logger.info('Native durable capture for fatal JavaScript exceptions started.')\n }\n return true\n } catch (e) {\n this._logger.error(`Native PostHog plugin failed to start: ${e}.`)\n return false\n }\n }\n\n private async startSessionReplay(\n options?: PostHogOptions,\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<void> {\n this._enableSessionReplay = options?.enableSessionReplay\n this._sessionReplayOptions = options\n\n await this._evaluateAndStartSessionReplay(cachedRemoteConfig)\n }\n\n /**\n * Decides whether session replay should be recording (replay enabled AND the linked\n * flag, if any, on for the current user) and arms or pauses the native recorder to match.\n *\n * Runs at startup and on every feature flags load/reload (identify(), reset(),\n * reloadFeatureFlags()), so recording starts, resumes, or pauses on identity changes\n * without an app restart. `_sessionReplayRecordingActive` dedups repeated answers, and\n * the init guards prevent double-starts. When replay is off, the native plugin is still\n * initialized for native error tracking (both share one native instance).\n *\n * Pausing requires a real \"flag off\": core keeps the previous flag values across\n * quota-limited/failed reloads, so a transient error never pauses a recording. Right\n * after reset() the flags are genuinely unknown and pausing is the intended outcome.\n *\n * Evaluations are serialized so concurrent flags reloads run one at a time.\n */\n private _evaluateAndStartSessionReplay(cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>): Promise<void> {\n this._sessionReplayEvalChain = this._sessionReplayEvalChain\n .catch(() => {})\n .then(() => this._evaluateAndStartSessionReplayInternal(cachedRemoteConfig))\n return this._sessionReplayEvalChain\n }\n\n private async _evaluateAndStartSessionReplayInternal(\n cachedRemoteConfig?: Omit<PostHogRemoteConfig, 'surveys'>\n ): Promise<void> {\n const options = this._sessionReplayOptions\n const enableNativeErrorTracking = this._isAutocaptureNativeErrors(options)\n const enablePush = this._isPushNativeEnabled(options)\n const enableFatalJsCapture = this._isFatalJsCaptureNativeEnabled()\n // On the re-arm path (flags reloaded after identify/reset) cachedRemoteConfig\n // isn't passed in, so fall back to the persisted remote config for capture gating.\n const remoteConfig =\n cachedRemoteConfig ??\n this.getPersistedProperty<Omit<PostHogRemoteConfig, 'surveys'>>(PostHogPersistedProperty.RemoteConfig)\n\n if (!this._isEnableSessionReplay()) {\n this._logger.info('Session replay is not enabled.')\n // Replay off — disarm event triggers so the capture hook stays inert.\n this._sessionReplayEventTriggers = []\n if (enableNativeErrorTracking || enablePush || enableFatalJsCapture) {\n await this.initializeNativePlugin(options, remoteConfig, false)\n }\n const request = this._manualRecordingStartRequest\n if (request?.pending) {\n await this._attemptManualRecordingStart(request, true)\n }\n return\n }\n\n // if Flags API has not returned yet, we will start session replay with default config.\n const sessionReplay = this.getPersistedProperty(PostHogPersistedProperty.SessionReplay) ?? {}\n const featureFlags = this.getKnownFeatureFlags() ?? {}\n const cachedFeatureFlags = (featureFlags as { [key: string]: FeatureFlagValue }) ?? {}\n const cachedSessionReplayConfig = (sessionReplay as { [key: string]: JsonType }) ?? {}\n\n this._logger.info('Session replay feature flags from flags cached config:', JSON.stringify(cachedFeatureFlags))\n\n let recordingActive = true\n const linkedFlag = cachedSessionReplayConfig['linkedFlag'] as\n | string\n | { [key: string]: JsonType }\n | null\n | undefined\n\n if (typeof linkedFlag === 'string') {\n const value = cachedFeatureFlags[linkedFlag]\n if (typeof value === 'boolean') {\n recordingActive = value\n } else if (typeof value === 'string') {\n // if its a multi-variant flag linked to \"any\"\n recordingActive = true\n } else {\n // disable recording if the flag does not exist/quota limited\n recordingActive = false\n }\n\n this._logger.info(`Session replay '${linkedFlag}' linked flag value: '${value}'`)\n } else if (linkedFlag && typeof linkedFlag === 'object') {\n const flag = linkedFlag['flag'] as string | undefined\n const variant = linkedFlag['variant'] as string | undefined\n if (flag && variant) {\n const value = cachedFeatureFlags[flag]\n recordingActive = value === variant\n this._logger.info(`Session replay '${flag}' linked flag variant '${variant}' and value '${value}'`)\n } else {\n // disable recording if the flag does not exist/quota limited\n this._logger.info(`Session replay '${flag}' linked flag variant: '${variant}' does not exist/quota limited.`)\n recordingActive = false\n }\n } else {\n this._logger.info(`Session replay has no cached linkedFlag.`)\n }\n\n // Event triggers: replay records only once the client captures an event whose name matches a\n // configured trigger, and stays active for the rest of that session. Cache the armed triggers in\n // memory for the capture hot path (processBeforeEnqueue), then AND the activation into the gate —\n // an unfired trigger blocks recording exactly like an unsatisfied linked flag (restrictive AND).\n const eventTriggers = this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers'])\n this._sessionReplayEventTriggers = eventTriggers\n\n if (eventTriggers.length > 0) {\n const activated = this._isEventTriggerActivatedForSession(super.getSessionId())\n if (!activated) {\n recordingActive = false\n }\n this._logger.info(`Session replay event triggers configured (${eventTriggers.length}); activated: ${activated}.`)\n }\n\n if (recordingActive) {\n if (this._sessionReplayRecordingActive === true) {\n // Already recording — nothing to do.\n return\n }\n // Record the actual outcome; on failure it stays false so the next reload retries.\n // (Already initialized means replay was paused by an earlier flag-off, so resume it.)\n this._sessionReplayRecordingActive = this._sessionReplayNativeInitialized\n ? await this._startSessionRecording(true)\n : await this.initializeNativePlugin(options, remoteConfig, true)\n } else {\n this._logger.info('Session replay disabled.')\n\n if (this._sessionReplayRecordingActive === true) {\n // Linked flag turned off — pause so a gated-off user isn't recorded. Keep the flag\n // set if the native stop fails, so the next reload retries instead of giving up.\n this._sessionReplayRecordingActive = !(await this._stopSessionRecording())\n } else {\n this._sessionReplayRecordingActive = false\n }\n\n if (enableNativeErrorTracking || enablePush) {\n await this.initializeNativePlugin(options, remoteConfig, false)\n }\n }\n }\n\n /**\n * Capture chokepoint for session-replay event triggers. Every captured event (capture, $screen,\n * autocapture, lifecycle) passes through here. Chains to super first so `before_send` still runs;\n * when a surviving event's name matches an armed trigger and the session hasn't activated yet, it\n * activates replay for the session and kicks a re-evaluation that starts native recording. The\n * trigger check never drops an event or throws into the capture path.\n */\n protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null {\n const observation = this._fatalCaptureObservation\n const isObservedFatal =\n observation !== undefined && message.uuid === observation.eventUuid && message.event === '$exception'\n const processed = super.processBeforeEnqueue(message)\n let suppress = false\n if (isObservedFatal && processed && observation) {\n // The final, before_send-accepted payload. Offer it to the native SDK here rather than\n // after enqueueing: if native takes ownership the JS copy must never reach the queue,\n // and if the payload cannot be built we must still fall through to the JS queue. Both\n // outcomes have to be decided in this one step or the exception can end up in neither\n // queue, or in both.\n try {\n observation.nativeCapture = observation.prepareNativeCapture(processed)\n } catch (e) {\n this._logger.warn(`Fatal exception payload could not be prepared for native capture: ${e}`)\n observation.nativeCapture = undefined\n }\n suppress = observation.nativeCapture !== undefined\n observation.queued = !suppress\n }\n try {\n this._maybeActivateEventTrigger(processed?.['event'])\n } catch (e) {\n this._logger.error(`Session replay event trigger check failed: ${e}.`)\n }\n return suppress ? null : processed\n }\n\n /**\n * Capture a fatal exception and decide which queue owns it. The native SDK persists a\n * fatal `$exception` synchronously, so when it is available it takes the event and the JS\n * queue copy is dropped; otherwise the event stays in the JS queue as usual.\n */\n private _captureFatalAndChooseOwner(\n eventUuid: string,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined,\n capture: () => unknown\n ): { queued: boolean; nativeCapture?: () => Promise<void> } {\n const observation: NonNullable<PostHog['_fatalCaptureObservation']> = {\n eventUuid,\n prepareNativeCapture,\n queued: false,\n }\n const previousObservation = this._fatalCaptureObservation\n this._fatalCaptureObservation = observation\n try {\n capture()\n } finally {\n this._fatalCaptureObservation = previousObservation\n }\n return { queued: observation.queued, nativeCapture: observation.nativeCapture }\n }\n\n private _maybeActivateEventTrigger(eventName: unknown): void {\n if (this._sessionReplayEventTriggers.length === 0 || typeof eventName !== 'string') {\n return\n }\n if (!this._sessionReplayEventTriggers.includes(eventName)) {\n return\n }\n // Use super.getSessionId() (not this.getSessionId()) deliberately: the capture path already ran the\n // overriding getSessionId() during enrichProperties, so rotation handling has fired and the id is\n // synced. Calling the override again here would re-enter rotation logic from inside capture.\n const sessionId = super.getSessionId()\n if (!sessionId) {\n return\n }\n // Already activated AND the native recorder is confirmed running — nothing to do. If activation\n // was persisted but a prior start failed (recording still inactive), fall through to re-kick the\n // evaluation so a later matching event retries the native start instead of staying stuck.\n if (this._isEventTriggerActivatedForSession(sessionId) && this._sessionReplayRecordingActive === true) {\n return\n }\n if (!this._isEventTriggerActivatedForSession(sessionId)) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession, sessionId)\n this._logger.info(`Session replay event trigger '${eventName}' activated for session ${sessionId}.`)\n }\n // Re-evaluate so the native recorder starts; fire-and-forget keeps the capture path synchronous.\n // Serialized through _sessionReplayEvalChain, so this never races a concurrent evaluation.\n void this._evaluateAndStartSessionReplay()\n }\n\n private _parseEventTriggers(value: JsonType | undefined): string[] {\n if (!Array.isArray(value)) {\n return []\n }\n return value.filter((entry): entry is string => typeof entry === 'string')\n }\n\n private _isEventTriggerActivatedForSession(sessionId: string): boolean {\n return this.getPersistedProperty(PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession) === sessionId\n }\n\n private async captureAppLifecycleEvents(): Promise<void> {\n const appBuild = this._appProperties.$app_build\n const appVersion = this._appProperties.$app_version\n\n const isMemoryPersistence = this._persistence === 'memory'\n\n const properties: PostHogEventProperties = {}\n\n if (!isMemoryPersistence) {\n const prevAppBuild = this.getPersistedProperty(PostHogPersistedProperty.InstalledAppBuild) as string | undefined\n const prevAppVersion = this.getPersistedProperty(PostHogPersistedProperty.InstalledAppVersion) as\n | string\n | undefined\n\n if (!appBuild || !appVersion) {\n this._logger.warn(\n 'PostHog could not track installation/update/open, as the build and version were not set. ' +\n 'This can happen if some dependencies are not installed correctly, or if you have provided' +\n 'customAppProperties but not included $app_build or $app_version.'\n )\n }\n if (appBuild) {\n if (!prevAppBuild) {\n // new app install\n this.capture('Application Installed', properties)\n } else if (prevAppBuild !== appBuild) {\n // $app_version and $app_build are already added in the common event properties\n // app updated\n this.capture('Application Updated', {\n ...maybeAdd('previous_version', prevAppVersion),\n ...maybeAdd('previous_build', prevAppBuild),\n ...properties,\n })\n }\n }\n } else {\n this._logger.warn(\n 'PostHog was initialised with persistence set to \"memory\", capturing native app events (Application Installed and Application Updated) is not supported.'\n )\n }\n\n const initialUrl = (await Linking.getInitialURL()) ?? undefined\n\n this.capture('Application Opened', {\n ...properties,\n ...maybeAdd('url', initialUrl),\n })\n\n AppState.addEventListener('change', (state) => {\n if (state === 'active') {\n this.capture('Application Became Active')\n } else if (state === 'background') {\n this.capture('Application Backgrounded')\n }\n })\n }\n\n private async persistAppVersion(): Promise<void> {\n const appBuild = this._appProperties.$app_build\n const appVersion = this._appProperties.$app_version\n this.setPersistedProperty(PostHogPersistedProperty.InstalledAppBuild, appBuild)\n this.setPersistedProperty(PostHogPersistedProperty.InstalledAppVersion, appVersion)\n }\n}\n"],"mappings":"s3CAAA,IAAAA,YAAA,CAAAC,OAAA,iBAEA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