package com.klaviyoreactnativesdk import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Callback import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.ReadableType import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule import com.klaviyo.analytics.AuthTokenProvider import com.klaviyo.analytics.Klaviyo import com.klaviyo.analytics.model.Event import com.klaviyo.analytics.model.EventKey import com.klaviyo.analytics.model.EventMetric import com.klaviyo.analytics.model.Profile import com.klaviyo.analytics.model.ProfileKey import com.klaviyo.analytics.model.Subscription import com.klaviyo.core.MissingKlaviyoModule import com.klaviyo.core.Registry import com.klaviyo.core.config.Config import com.klaviyo.core.config.Log import com.klaviyo.core.utils.AdvancedAPI import com.klaviyo.forms.FormLifecycleEvent import com.klaviyo.forms.FormsProvider import com.klaviyo.forms.InAppFormsConfig import com.klaviyo.forms.registerForInAppForms import com.klaviyo.forms.registerFormLifecycleHandler import com.klaviyo.forms.unregisterFormLifecycleHandler import com.klaviyo.forms.unregisterFromInAppForms import com.klaviyo.location.GeofencingProvider import com.klaviyo.location.LocationManager import com.klaviyo.location.registerGeofencing import com.klaviyo.location.unregisterGeofencing import java.io.Serializable import java.net.SocketException import java.util.Locale import java.util.UUID import java.util.concurrent.ConcurrentHashMap import kotlin.time.Duration.Companion.seconds class KlaviyoReactNativeSdkModule( private val reactContext: ReactApplicationContext, ) : ReactContextBaseJavaModule(reactContext) { companion object { const val NAME = "KlaviyoReactNativeSdk" private const val LOCATION = "location" private const val PROPERTIES = "properties" private const val LIST_ID = "listId" private const val CUSTOM_SOURCE = "customSource" private const val CHANNELS = "channels" private const val EMAIL = "email" private const val SMS = "sms" private const val WHATSAPP = "whatsapp" } private fun sendEvent( eventName: String, params: WritableMap?, ): Boolean { // Form lifecycle callbacks fire from the native SDK and can race the // host Activity/Process being torn down (background → low-memory kill, // config change, deep-link launch from CTA, dev-mode HMR/fast-refresh). // `getJSModule` throws `RuntimeException: Catalyst Instance has already // disappeared` in that window, so guard the call. Pattern mirrors RN's // own AppStateModule.sendEvent fix. // Using `hasActiveCatalystInstance` (deprecated alias of // `hasActiveReactInstance`) for broader peer-dep range — the SDK's // peerDependencies allow any react-native version. // Returns whether the event was actually emitted, so callers that must // guarantee delivery (e.g. auth-token requests awaiting a JS response) can // fail fast when the bridge is unavailable rather than hang. if (!reactContext.hasActiveCatalystInstance()) return false return try { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) .emit(eventName, params) true } catch (e: Exception) { // TOCTOU race: catalyst instance was alive at the check above but is // being torn down by the time we call. Drop the event quietly. Registry.log.error("Failed to emit $eventName: catalyst instance unavailable", e) false } } override fun getName(): String = NAME // Mirrors every public singleton of the Android SDK's ProfileKey, in its declaration order. // Values are read from the SDK rather than retyped, so a rename or removal upstream fails // this module's build instead of silently shipping a stale string. An upstream ADDITION is // not caught -- a new public key must be added here by hand. That was already true in // practice: ProfileProperty in src/Profile.ts is a hand-written enum, so a new key never // reached JS without a TypeScript edit either way. // // The SDK's identity and push keys (EXTERNAL_ID, EMAIL, PHONE_NUMBER, ANONYMOUS_ID, // PUSH_TOKEN) are `internal`, not visible here, and were never exported -- JS supplies its // own literals for the three it needs, in Profile.setExternalId, setEmail and setPhoneNumber. // LOCATION and PROPERTIES are wrapper-owned with no SDK equivalent; their keys are // intentionally lowercase to match today's output byte for byte. private val profileKeys: Map = mapOf( "FIRST_NAME" to ProfileKey.FIRST_NAME.name, "LAST_NAME" to ProfileKey.LAST_NAME.name, "ORGANIZATION" to ProfileKey.ORGANIZATION.name, "TITLE" to ProfileKey.TITLE.name, "IMAGE" to ProfileKey.IMAGE.name, "ADDRESS1" to ProfileKey.ADDRESS1.name, "ADDRESS2" to ProfileKey.ADDRESS2.name, "CITY" to ProfileKey.CITY.name, "COUNTRY" to ProfileKey.COUNTRY.name, "LATITUDE" to ProfileKey.LATITUDE.name, "LONGITUDE" to ProfileKey.LONGITUDE.name, "REGION" to ProfileKey.REGION.name, "ZIP" to ProfileKey.ZIP.name, "TIMEZONE" to ProfileKey.TIMEZONE.name, LOCATION to LOCATION, PROPERTIES to PROPERTIES, ) // Public EventMetric singletons, in the SDK's declaration order. The `internal` OPENED_PUSH // metric is not visible here and was never exported. private val eventNames: Map = mapOf( "OPENED_APP" to EventMetric.OPENED_APP.name, "VIEWED_PRODUCT" to EventMetric.VIEWED_PRODUCT.name, "ADDED_TO_CART" to EventMetric.ADDED_TO_CART.name, "STARTED_CHECKOUT" to EventMetric.STARTED_CHECKOUT.name, ) override fun getConstants(): MutableMap = hashMapOf( "PROFILE_KEYS" to profileKeys, "EVENT_NAMES" to eventNames, "FORMS_AVAILABLE" to Registry.isRegistered(), "LOCATION_AVAILABLE" to Registry.isRegistered(), ) @ReactMethod @OptIn(AdvancedAPI::class) fun initialize(apiKey: String) { // Since initialize is being called after Application.onCreate, // we must hand over a reference to the current activity. // The native SDK will track Activity changes internally from here on. reactApplicationContext.currentActivity?.let(Registry.lifecycleMonitor::assignCurrentActivity) Klaviyo.initialize(apiKey, reactContext) } // The Android SDK has no dedicated logging on/off API (log verbosity is set via // manifest metadata), so the toggle is implemented on top of the SDK's mutable // log level: `None` silences all logging, and the prior level is captured here // so re-enabling restores the configured verbosity. private var logLevelToRestore: Log.Level? = null @ReactMethod fun setLoggingEnabled(enabled: Boolean) { if (enabled) { if (Registry.log.logLevel == Log.Level.None) { // Fall back to the SDK's default level if logging was already disabled // before this module captured a level (e.g. via manifest metadata). Registry.log.logLevel = logLevelToRestore ?: Log.Level.Error } } else { if (Registry.log.logLevel != Log.Level.None) { logLevelToRestore = Registry.log.logLevel } Registry.log.logLevel = Log.Level.None } } @ReactMethod fun isLoggingEnabled(callback: Callback) { callback.invoke(Registry.log.logLevel != Log.Level.None) } @ReactMethod fun registerForInAppForms(configuration: ReadableMap?) { UiThreadUtil.runOnUiThread { try { val timeout = configuration?.getDouble("sessionTimeoutDuration")?.seconds Klaviyo.registerForInAppForms( InAppFormsConfig( sessionTimeoutDuration = timeout ?: InAppFormsConfig.DEFAULT_SESSION_TIMEOUT, ), ) } catch (e: MissingKlaviyoModule) { Registry.log.error("Forms module is not available", e) } catch (e: Exception) { Registry.log.error("Android unable to register for in app forms on main thread", e) } } } @ReactMethod fun unregisterFromInAppForms() { UiThreadUtil.runOnUiThread { try { Klaviyo.unregisterFromInAppForms() } catch (e: MissingKlaviyoModule) { Registry.log.error("Forms module is not available", e) } } } @ReactMethod fun registerGeofencing() { try { Klaviyo.registerGeofencing() } catch (e: MissingKlaviyoModule) { Registry.log.error("Location module is not available", e) } } @ReactMethod fun unregisterGeofencing() { try { Klaviyo.unregisterGeofencing() } catch (e: MissingKlaviyoModule) { Registry.log.error("Location module is not available", e) } } @ReactMethod fun getCurrentGeofences(callback: Callback) { // Note: in the future, we may be storing more fences than we are observing, so we'd have to update this val geofencesArray = Arguments.createArray() Registry.getOrNull()?.getStoredGeofences()?.forEach { geofence -> geofencesArray.pushMap( Arguments.createMap().apply { putString("identifier", geofence.id) putDouble("latitude", geofence.latitude) putDouble("longitude", geofence.longitude) putDouble("radius", geofence.radius.toDouble()) }, ) } ?: run { Registry.log.wtf("Geofencing is not yet registered") } val resultMap = Arguments.createMap().apply { putArray("geofences", geofencesArray) } callback.invoke(resultMap) } @ReactMethod fun setProfile(profile: ReadableMap) { val parsedProfile = Profile() profile.toHashMap().iterator().forEach { (key, value) -> when (key) { LOCATION, PROPERTIES -> { (value as? HashMap<*, *>)?.forEach { (key, value) -> if (key is String && value is Serializable) { parsedProfile[key] = value } } } else -> { if (value is Serializable) { parsedProfile[key] = value } } } } Klaviyo.setProfile(parsedProfile) } @ReactMethod fun setExternalId(externalId: String) { Klaviyo.setExternalId(externalId) } @ReactMethod fun getExternalId(callback: Callback) { callback.invoke(Klaviyo.getExternalId()) } @ReactMethod fun setEmail(email: String) { Klaviyo.setEmail(email) } @ReactMethod fun getEmail(callback: Callback) { callback.invoke(Klaviyo.getEmail()) } @ReactMethod fun setPhoneNumber(phoneNumber: String) { Klaviyo.setPhoneNumber(phoneNumber) } @ReactMethod fun getPhoneNumber(callback: Callback) { callback.invoke(Klaviyo.getPhoneNumber()) } @ReactMethod fun setProfileAttribute( propertyKey: String, value: String, ) { Klaviyo.setProfileAttribute(ProfileKey.CUSTOM(propertyKey), value) } @ReactMethod fun resetProfile() { Klaviyo.resetProfile() } @ReactMethod fun setPushToken(token: String) { Klaviyo.setPushToken(token) } @ReactMethod fun getPushToken(callback: Callback) { callback.invoke(Klaviyo.getPushToken()) } @ReactMethod fun handleUniversalTrackingLink(urlStr: String) { Registry.log.debug("[Klaviyo React Native SDK] handleUniversalTrackingLink called with url string: $urlStr") if (urlStr.isEmpty()) { Registry.log.warning("[Klaviyo React Native SDK] Empty tracking link provided") return } if (!Registry.isRegistered()) { // If the SDK has not been initialized yet, we cannot handle the link without providing Context to Klaviyo SDK reactApplicationContext.currentActivity?.let { Klaviyo.registerForLifecycleCallbacks(it) } } Klaviyo.handleUniversalTrackingLink(urlStr) } @ReactMethod fun createEvent(event: ReadableMap) { val metric = event .takeIf { it.hasKey("name") && it.getType("name") == ReadableType.String }?.getString("name") ?: run { Registry.log.error("Klaviyo React Native SDK: Event name is required") return } val klaviyoEvent = Event( metric = metric.let { EventMetric.CUSTOM(it) }, properties = event .getMap("properties") ?.toHashMap() ?.filter { entry -> (entry.value as? Serializable) != null } ?.map { entry -> EventKey.CUSTOM(entry.key) to entry.value as Serializable } ?.toMap(), ) event .takeIf { it.hasKey("uniqueId") && it.getType("uniqueId") == ReadableType.String }?.getString("uniqueId") ?.let { uniqueId -> klaviyoEvent.uniqueId = uniqueId } // Explicitly cast value to double if it exists try { event .takeIf { it.hasKey("value") && it.getType("value") == ReadableType.Number } ?.getDouble("value") .let { value -> klaviyoEvent.setValue(value) } } catch (e: Exception) { Registry.log.error("Klaviyo React Native SDK: Error setting event value", e) return } Klaviyo.createEvent(event = klaviyoEvent) } @ReactMethod fun createSubscription(subscription: ReadableMap) { val listId = subscription .takeIf { it.hasKey(LIST_ID) && it.getType(LIST_ID) == ReadableType.String }?.getString(LIST_ID) ?.takeIf { it.isNotBlank() } ?: run { Registry.log.error("Klaviyo React Native SDK: Subscription listId is required") return } val customSource = subscription .takeIf { it.hasKey(CUSTOM_SOURCE) && it.getType(CUSTOM_SOURCE) == ReadableType.String }?.getString(CUSTOM_SOURCE) // Only a *missing* channels key means "all available marketing" — the broad grant is reachable // solely through the named factory on this SDK and the JS layer. A key that is present but not // an object is malformed, and is rejected rather than quietly widening consent. val channelsMap = if (subscription.hasKey(CHANNELS)) { subscription.takeIf { it.getType(CHANNELS) == ReadableType.Map }?.getMap(CHANNELS) ?: run { Registry.log.error( "Klaviyo React Native SDK: Subscription channels must be an object when present", ) return } } else { null } val parsed = channelsMap?.let { parseSubscriptionChannels(it) } Klaviyo.createSubscription( if (parsed == null) { Subscription.allAvailableMarketing(listId, customSource) } else { Subscription(listId, parsed, customSource) }, ) } /** * Maps the JS channels payload onto [Subscription.Channels]. An absent channel stays null (leave * it untouched); an empty array stays empty, so the native SDK's own validation reports it rather * than this bridge silently dropping the channel. */ private fun parseSubscriptionChannels(channels: ReadableMap): Subscription.Channels = Subscription.Channels( email = channels.parseConsentSet(EMAIL) { Subscription.Channels.Email.valueOf(it) }, sms = channels.parseConsentSet(SMS) { Subscription.Channels.Messaging.valueOf(it) }, whatsapp = channels.parseConsentSet(WHATSAPP) { Subscription.Channels.Messaging.valueOf(it) }, ) /** * Reads one channel's consent array off the JS payload, or null when the key is absent. * * The JS wire values are the lowercased enum names, so [valueOf] covers the mapping. An * unrecognized value is warned about and skipped rather than failing the whole request: skipping * only ever narrows the consent granted, and it keeps a newer JS layer from breaking against an * older native SDK. A non-string entry is skipped the same way. iOS drops both the same way. * * A present-but-wrong-type value (e.g. a string instead of an array) is also treated as an * omitted channel, but unlike a genuinely absent key, it's warned about first: silently applying * the same behavior as "not specified" could otherwise mask a caller mistake. */ private fun > ReadableMap.parseConsentSet( key: String, valueOf: (String) -> T, ): Set? { if (!hasKey(key)) return null if (getType(key) != ReadableType.Array) { Registry.log.warning( "Klaviyo React Native SDK: Ignoring non-array $key consent value", ) return null } return getArray(key) ?.toArrayList() ?.mapNotNull { entry -> entry as? String ?: run { Registry.log.warning( "Klaviyo React Native SDK: Ignoring non-string $key consent entry", ) null } }?.mapNotNull { rawValue -> runCatching { valueOf(rawValue.uppercase(Locale.ROOT)) }.getOrElse { Registry.log.warning( "Klaviyo React Native SDK: Ignoring unrecognized $key consent type '$rawValue'", ) null } }?.toSet() } @ReactMethod fun registerFormLifecycleHandler() { UiThreadUtil.runOnUiThread { try { Klaviyo.registerFormLifecycleHandler { event -> val params = Arguments.createMap().apply { putString("formId", event.formId) putString("formName", event.formName) when (event) { is FormLifecycleEvent.FormShown -> { putString("type", "formShown") } is FormLifecycleEvent.FormDismissed -> { putString("type", "formDismissed") } is FormLifecycleEvent.FormCtaClicked -> { putString("type", "formCtaClicked") putString("buttonLabel", event.buttonLabel) putString("deepLinkUrl", event.deepLinkUrl.toString()) } } } sendEvent("FormLifecycleEvent", params) } } catch (e: MissingKlaviyoModule) { Registry.log.error("Forms module is not available", e) } } } @ReactMethod fun unregisterFormLifecycleHandler() { UiThreadUtil.runOnUiThread { try { Klaviyo.unregisterFormLifecycleHandler() } catch (e: MissingKlaviyoModule) { Registry.log.error("Forms module is not available", e) } } } /** * Pending auth token requests keyed by correlation ID. The native SDK invokes * the provider on a background dispatcher and hands us a [AuthTokenProvider.Callback] * to complete once the JS side responds via [respondToAuthTokenRequest]. Each * entry is tagged with the registration [PendingAuthRequest.generation] it * belongs to. The token itself is never logged; all token logging happens in * the native SDK. */ private val pendingAuthCallbacks = ConcurrentHashMap() /** * Monotonic registration generation, bumped on every register and unregister * (both on the main/bridge thread). A pending request carries the generation * captured when its provider was registered; if that no longer matches * [authTokenGeneration] at response time, the provider was torn down or * replaced while the request was in flight, and the request is failed rather * than answered with a different registration's token. */ private var authTokenGeneration = 0 private data class PendingAuthRequest( val callback: AuthTokenProvider.Callback, val generation: Int, ) @ReactMethod fun registerAuthTokenProvider() { try { // Capture this registration's generation now; the lambda closes over it // by value, so it never races on shared state from the SDK's dispatcher. val generation = ++authTokenGeneration Klaviyo.registerAuthTokenProvider { callback -> // The native SDK keeps at most one token fetch in flight, so any entries // still pending when a NEW request arrives belong to a previous fetch the // SDK has already abandoned (e.g. it timed out). Android's callback API // gives no per-request timeout hook (unlike iOS withTaskCancellationHandler // onCancel), so this is where stale ids are reclaimed — failing them here // bounds the map and honors the "timed-out ids don't resolve" contract. failAndDrainPendingAuthCallbacks("Superseded by a newer auth token request") val id = UUID.randomUUID().toString() pendingAuthCallbacks[id] = PendingAuthRequest(callback, generation) val emitted = sendEvent( "klaviyo:authTokenRequested", Arguments.createMap().apply { putString("id", id) }, ) if (!emitted) { // The JS bridge is unavailable (catalyst torn down), so no response // will ever arrive. Fail fast instead of leaving the callback pending // until the native SDK's timeout, and don't leak the map entry. pendingAuthCallbacks.remove(id)?.callback?.onFailure( IllegalStateException("Unable to reach the JS auth token provider (bridge unavailable)"), ) } } } catch (e: Exception) { Registry.log.error("Failed to register auth token provider", e) } } @ReactMethod fun unregisterAuthTokenProvider() { try { Klaviyo.unregisterAuthTokenProvider() } catch (e: Exception) { Registry.log.error("Failed to unregister auth token provider", e) } finally { // Bump the generation so any request stored by an in-flight provider // callback that races this teardown is treated as stale at response time, // then fail and drop any requests still awaiting a JS response. ++authTokenGeneration failAndDrainPendingAuthCallbacks("Auth token provider was unregistered") } } /** * Fails and evicts every pending auth token callback with [reason]. Uses * remove-then-fail per key so a concurrent [respondToAuthTokenRequest] can't * also resolve the same callback (preserves the callback's "invoke exactly * once" contract). */ private fun failAndDrainPendingAuthCallbacks(reason: String) { pendingAuthCallbacks.keys.toList().forEach { id -> pendingAuthCallbacks.remove(id)?.callback?.onFailure(IllegalStateException(reason)) } } @ReactMethod fun respondToAuthTokenRequest( id: String, response: ReadableMap, ) { val pending = pendingAuthCallbacks.remove(id) if (pending == null) { // Unknown, already-resolved, or timed-out request. Nothing to do. Registry.log.verbose("No pending auth token request for id $id") return } if (pending.generation != authTokenGeneration) { // The provider was unregistered/replaced while this request was in flight, // so it belongs to a superseded registration. Fail it rather than answer // it with a different registration's token. pending.callback.onFailure( IllegalStateException("Auth token request superseded by re-registration"), ) return } val callback = pending.callback val jwt = response .takeIf { it.hasKey("jwt") && it.getType("jwt") == ReadableType.String } ?.getString("jwt") if (jwt != null) { callback.onSuccess(jwt) } else { val error = response .takeIf { it.hasKey("error") && it.getType("error") == ReadableType.String } ?.getString("error") ?: "Auth token provider returned no token" val isConnectivityError = response.hasKey("isConnectivityError") && response.getType("isConnectivityError") == ReadableType.Boolean && response.getBoolean("isConnectivityError") // Surface connectivity failures as an IOException so the SDK's // connectivity-driven retry classifier recognizes them; other failures // use a generic Throwable, which the SDK treats as non-retryable. if (isConnectivityError) { callback.onFailure(SocketException(error)) } else { callback.onFailure(Throwable(error)) } } } // Required by NativeEventEmitter on the JS side @ReactMethod fun addListener(eventName: String) {} @ReactMethod fun removeListeners(count: Int) {} }