package com.contentsquare.rn import android.util.Log import com.facebook.react.bridge.Dynamic import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.Promise import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule import com.contentsquare.rn.csq.HeapAutocaptureWrapperImpl import com.contentsquare.rn.csq.InvocationEventEmitter class HeapReactNativeBridgeModule(reactContext: ReactApplicationContext) : NativeHeapReactNativeBridgeModuleSpec(reactContext), InvocationEventEmitter { private val heapWrapper = HeapAutocaptureWrapperImpl(reactContext, this) private var listenerCount = 0 override fun getName(): String { return NAME } companion object { const val NAME = "HeapReactNativeBridgeModule" } @ReactMethod override fun handleInvocation(method: String, args: ReadableMap, promise: Promise) { heapWrapper.handleInvocation(method, args, promise) } @ReactMethod override fun handleResult( callbackId: String?, data: ReadableMap?, error: String? ) { callbackId?.let { heapWrapper.handleResult(it, data, error) } } @ReactMethod fun handleResult(callbackId: String, data: Dynamic?, error: String?) { heapWrapper.handleResult(callbackId, data, error) } @ReactMethod @Suppress("UNUSED_PARAMETER") override fun addListener(eventName: String) { listenerCount += 1 heapWrapper.onListenerAdded() } override fun removeListeners(count: Double) { listenerCount -= count.toInt() heapWrapper.onListenersRemoved(count.toInt()) } /** * Implementation of InvocationEventEmitter. * Emits invocation events to JavaScript using the legacy event emitter system. */ override fun sendInvocationEvent(payload: WritableMap) { if (listenerCount == 0) { // Throw exception so CSQAutocapture can handle the error throw IllegalStateException("Bridge has no listeners.") } try { reactApplicationContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) ?.emit("Invocation", payload) } catch (t: Throwable) { // Event emission failed, rethrow so CSQAutocapture can handle it throw t } } }