txlemetry-react-native-session-replay 1.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 PostHog
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # txlemetry-react-native-session-replay
2
+
3
+ Txlemetry session replay for React Native (Android and iOS)
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install txlemetry-react-native-session-replay
9
+ ```
10
+
11
+ ## iOS dependency resolution
12
+
13
+ By default, the native SDK is resolved through CocoaPods trunk via `pod install`.
14
+
15
+ To opt this package into the Swift Package Manager resolution path, add the following to your app's `ios/Podfile.properties.json`:
16
+
17
+ ```json
18
+ {
19
+ "txlemetry.useSpm": "true"
20
+ }
21
+ ```
22
+
23
+ When that property is set and React Native >= 0.75 is in use, `pod install` resolves the native SDK through the RN `spm_dependency` helper. The SPM path requires `use_frameworks! :linkage => :dynamic` in your `Podfile`.
@@ -0,0 +1,89 @@
1
+ def reactNativeArchitectures() {
2
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
3
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
4
+ }
5
+
6
+ def isNewArchitectureEnabled() {
7
+ return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
8
+ }
9
+
10
+ apply plugin: "com.android.library"
11
+ apply plugin: "kotlin-android"
12
+
13
+ if (isNewArchitectureEnabled()) {
14
+ apply plugin: "com.facebook.react"
15
+ }
16
+
17
+ def getExtOrDefault(name) {
18
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["PosthogReactNativeSessionReplay_" + name]
19
+ }
20
+
21
+ def getExtOrIntegerDefault(name) {
22
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["PosthogReactNativeSessionReplay_" + name]).toInteger()
23
+ }
24
+
25
+ def supportsNamespace() {
26
+ def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
27
+ def major = parsed[0].toInteger()
28
+ def minor = parsed[1].toInteger()
29
+
30
+ // Namespace support was added in 7.3.0
31
+ return (major == 7 && minor >= 3) || major >= 8
32
+ }
33
+
34
+ android {
35
+ if (supportsNamespace()) {
36
+ namespace "com.posthogreactnativesessionreplay"
37
+
38
+ sourceSets {
39
+ main {
40
+ manifest.srcFile "src/main/AndroidManifestNew.xml"
41
+ }
42
+ }
43
+ }
44
+
45
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
46
+
47
+ defaultConfig {
48
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
49
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
50
+
51
+ }
52
+
53
+ buildTypes {
54
+ release {
55
+ minifyEnabled false
56
+ }
57
+ }
58
+
59
+ lintOptions {
60
+ disable "GradleCompatible"
61
+ }
62
+
63
+ compileOptions {
64
+ sourceCompatibility JavaVersion.VERSION_1_8
65
+ targetCompatibility JavaVersion.VERSION_1_8
66
+ }
67
+ }
68
+
69
+ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
70
+ kotlinOptions {
71
+ jvmTarget = android.compileOptions.targetCompatibility.toString()
72
+ }
73
+ }
74
+
75
+ repositories {
76
+ mavenCentral()
77
+ google()
78
+ }
79
+
80
+ def kotlin_version = getExtOrDefault("kotlinVersion")
81
+
82
+ dependencies {
83
+ // For < 0.71, this will be from the local maven repo
84
+ // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
85
+ //noinspection GradleDynamicVersion
86
+ implementation "com.facebook.react:react-native:+"
87
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
88
+ implementation "com.posthog:posthog-android:3.40.2"
89
+ }
@@ -0,0 +1,5 @@
1
+ PosthogReactNativeSessionReplay_kotlinVersion=2.0.21
2
+ PosthogReactNativeSessionReplay_minSdkVersion=23
3
+ PosthogReactNativeSessionReplay_targetSdkVersion=36
4
+ PosthogReactNativeSessionReplay_compileSdkVersion=36
5
+ PosthogReactNativeSessionReplay_ndkversion=25.1.8937393
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.posthogreactnativesessionreplay">
3
+ </manifest>
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,232 @@
1
+ package com.posthogreactnativesessionreplay
2
+
3
+ import android.util.Log
4
+ import com.facebook.react.bridge.Promise
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
7
+ import com.facebook.react.bridge.ReactMethod
8
+ import com.facebook.react.bridge.ReadableMap
9
+ import com.facebook.react.bridge.UiThreadUtil
10
+ import com.posthog.PostHog
11
+ import com.posthog.PostHogConfig
12
+ import com.posthog.android.PostHogAndroid
13
+ import com.posthog.android.PostHogAndroidConfig
14
+ import com.posthog.internal.PostHogPreferences
15
+ import com.posthog.internal.PostHogPreferences.Companion.ANONYMOUS_ID
16
+ import com.posthog.internal.PostHogPreferences.Companion.DISTINCT_ID
17
+ import com.posthog.internal.PostHogSessionManager
18
+ import java.util.UUID
19
+
20
+ class PosthogReactNativeSessionReplayModule(
21
+ reactContext: ReactApplicationContext,
22
+ ) : ReactContextBaseJavaModule(reactContext) {
23
+ override fun getName(): String = NAME
24
+
25
+ @ReactMethod
26
+ fun start(
27
+ sessionId: String,
28
+ sdkOptions: ReadableMap,
29
+ sdkReplayConfig: ReadableMap,
30
+ decideReplayConfig: ReadableMap,
31
+ promise: Promise,
32
+ ) {
33
+ val initRunnable =
34
+ Runnable {
35
+ try {
36
+ val uuid = UUID.fromString(sessionId)
37
+ PostHogSessionManager.setSessionId(uuid)
38
+
39
+ val context = this.reactApplicationContext
40
+ val apiKey = runCatching { sdkOptions.getString("apiKey") }.getOrNull() ?: ""
41
+ val host = runCatching { sdkOptions.getString("host") }.getOrNull() ?: PostHogConfig.DEFAULT_HOST
42
+ val debugValue = runCatching { sdkOptions.getBoolean("debug") }.getOrNull() ?: false
43
+
44
+ val maskAllTextInputs = runCatching { sdkReplayConfig.getBoolean("maskAllTextInputs") }.getOrNull() ?: DEFAULT_MASK_ALL_TEXT_INPUTS
45
+ val maskAllImages = runCatching { sdkReplayConfig.getBoolean("maskAllImages") }.getOrNull() ?: DEFAULT_MASK_ALL_IMAGES
46
+ val captureLog = runCatching { sdkReplayConfig.getBoolean("captureLog") }.getOrNull() ?: DEFAULT_CAPTURE_LOG
47
+
48
+ // read throttleDelayMs and use androidDebouncerDelayMs as a fallback for back compatibility
49
+ val throttleDelayMs =
50
+ if (sdkReplayConfig.hasKey("throttleDelayMs")) {
51
+ sdkReplayConfig.getInt("throttleDelayMs")
52
+ } else if (sdkReplayConfig.hasKey("androidDebouncerDelayMs")) {
53
+ sdkReplayConfig.getInt("androidDebouncerDelayMs")
54
+ } else {
55
+ DEFAULT_THROTTLE_DELAY_MS
56
+ }
57
+
58
+ val sampleRate = runCatching { sdkReplayConfig.getDouble("sampleRate") }.getOrNull()
59
+
60
+ val endpoint = decideReplayConfig.getString("endpoint")
61
+
62
+ val distinctId =
63
+ try {
64
+ sdkOptions.getString("distinctId") ?: ""
65
+ } catch (e: Throwable) {
66
+ logError("parse distinctId", e)
67
+ ""
68
+ }
69
+ val anonymousId =
70
+ try {
71
+ sdkOptions.getString("anonymousId") ?: ""
72
+ } catch (e: Throwable) {
73
+ logError("parse anonymousId", e)
74
+ ""
75
+ }
76
+ val theSdkVersion = runCatching { sdkOptions.getString("sdkVersion") }.getOrNull()
77
+
78
+ val theFlushAt = runCatching { sdkOptions.getInt("flushAt") }.getOrNull() ?: DEFAULT_FLUSH_AT
79
+
80
+ val config =
81
+ PostHogAndroidConfig(apiKey, host).apply {
82
+ debug = debugValue
83
+ captureDeepLinks = false
84
+ captureApplicationLifecycleEvents = false
85
+ captureScreenViews = false
86
+ flushAt = theFlushAt
87
+ sessionReplay = true
88
+ sessionReplayConfig.screenshot = true
89
+ sessionReplayConfig.captureLogcat = captureLog
90
+ sessionReplayConfig.throttleDelayMs = throttleDelayMs.toLong()
91
+ sessionReplayConfig.maskAllImages = maskAllImages
92
+ sessionReplayConfig.maskAllTextInputs = maskAllTextInputs
93
+ sessionReplayConfig.sampleRate = sampleRate
94
+
95
+ if (!endpoint.isNullOrEmpty()) {
96
+ snapshotEndpoint = endpoint
97
+ }
98
+
99
+ if (!theSdkVersion.isNullOrEmpty()) {
100
+ sdkName = "posthog-react-native"
101
+ sdkVersion = theSdkVersion
102
+ }
103
+ }
104
+ PostHogAndroid.setup(context, config)
105
+
106
+ setIdentify(config.cachePreferences, distinctId, anonymousId)
107
+ } catch (e: Throwable) {
108
+ logError("start", e)
109
+ } finally {
110
+ promise.resolve(null)
111
+ }
112
+ }
113
+
114
+ // forces the SDK to be initialized on the main thread
115
+ if (UiThreadUtil.isOnUiThread()) {
116
+ initRunnable.run()
117
+ } else {
118
+ UiThreadUtil.runOnUiThread(initRunnable)
119
+ }
120
+ }
121
+
122
+ @ReactMethod
123
+ fun startSession(
124
+ sessionId: String,
125
+ promise: Promise,
126
+ ) {
127
+ try {
128
+ val uuid = UUID.fromString(sessionId)
129
+ PostHogSessionManager.setSessionId(uuid)
130
+ PostHog.startSession()
131
+ } catch (e: Throwable) {
132
+ logError("startSession", e)
133
+ } finally {
134
+ promise.resolve(null)
135
+ }
136
+ }
137
+
138
+ @ReactMethod
139
+ fun isEnabled(promise: Promise) {
140
+ try {
141
+ promise.resolve(PostHog.isSessionReplayActive())
142
+ } catch (e: Throwable) {
143
+ logError("isEnabled", e)
144
+ promise.resolve(false)
145
+ }
146
+ }
147
+
148
+ @ReactMethod
149
+ fun endSession(promise: Promise) {
150
+ try {
151
+ PostHog.endSession()
152
+ } catch (e: Throwable) {
153
+ logError("endSession", e)
154
+ } finally {
155
+ promise.resolve(null)
156
+ }
157
+ }
158
+
159
+ @ReactMethod
160
+ fun identify(
161
+ distinctId: String,
162
+ anonymousId: String,
163
+ promise: Promise,
164
+ ) {
165
+ try {
166
+ setIdentify(PostHog.getConfig<PostHogConfig>()?.cachePreferences, distinctId, anonymousId)
167
+ } catch (e: Throwable) {
168
+ logError("identify", e)
169
+ } finally {
170
+ promise.resolve(null)
171
+ }
172
+ }
173
+
174
+ private fun setIdentify(
175
+ cachePreferences: PostHogPreferences?,
176
+ distinctId: String,
177
+ anonymousId: String,
178
+ ) {
179
+ cachePreferences?.let { preferences ->
180
+ if (anonymousId.isNotEmpty()) {
181
+ preferences.setValue(ANONYMOUS_ID, anonymousId)
182
+ }
183
+ if (distinctId.isNotEmpty()) {
184
+ preferences.setValue(DISTINCT_ID, distinctId)
185
+ }
186
+ }
187
+ }
188
+
189
+ @ReactMethod
190
+ fun startRecording(
191
+ resumeCurrent: Boolean,
192
+ promise: Promise,
193
+ ) {
194
+ try {
195
+ PostHog.startSessionReplay(resumeCurrent)
196
+ } catch (e: Throwable) {
197
+ logError("startRecording", e)
198
+ } finally {
199
+ promise.resolve(null)
200
+ }
201
+ }
202
+
203
+ @ReactMethod
204
+ fun stopRecording(promise: Promise) {
205
+ try {
206
+ PostHog.stopSessionReplay()
207
+ } catch (e: Throwable) {
208
+ logError("stopRecording", e)
209
+ } finally {
210
+ promise.resolve(null)
211
+ }
212
+ }
213
+
214
+ private fun logError(
215
+ method: String,
216
+ error: Throwable,
217
+ ) {
218
+ Log.println(Log.ERROR, POSTHOG_TAG, "Method $method, error: $error")
219
+ }
220
+
221
+ companion object {
222
+ const val NAME = "PosthogReactNativeSessionReplay"
223
+ const val POSTHOG_TAG = "PostHog"
224
+
225
+ // Default session replay configuration values
226
+ const val DEFAULT_MASK_ALL_TEXT_INPUTS = true
227
+ const val DEFAULT_MASK_ALL_IMAGES = true
228
+ const val DEFAULT_CAPTURE_LOG = true
229
+ const val DEFAULT_FLUSH_AT = 20
230
+ const val DEFAULT_THROTTLE_DELAY_MS = 1000
231
+ }
232
+ }
@@ -0,0 +1,13 @@
1
+ package com.posthogreactnativesessionreplay
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class PosthogReactNativeSessionReplayPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
10
+ listOf(PosthogReactNativeSessionReplayModule(reactContext))
11
+
12
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
13
+ }
@@ -0,0 +1,2 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTViewManager.h>
@@ -0,0 +1,39 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ @interface RCT_EXTERN_MODULE(PosthogReactNativeSessionReplay, NSObject)
4
+
5
+ RCT_EXTERN_METHOD(start:(NSString)sessionId
6
+ withSdkOptions:(NSDictionary)sdkOptions
7
+ withSdkReplayConfig:(NSDictionary)sdkReplayConfig
8
+ withDecideReplayConfig:(NSDictionary)decideReplayConfig
9
+ withResolver:(RCTPromiseResolveBlock)resolve
10
+ withRejecter:(RCTPromiseRejectBlock)reject)
11
+
12
+ RCT_EXTERN_METHOD(startSession:(NSString)sessionId
13
+ withResolver:(RCTPromiseResolveBlock)resolve
14
+ withRejecter:(RCTPromiseRejectBlock)reject)
15
+
16
+ RCT_EXTERN_METHOD(isEnabled:(RCTPromiseResolveBlock)resolve
17
+ withRejecter:(RCTPromiseRejectBlock)reject)
18
+
19
+ RCT_EXTERN_METHOD(endSession:(RCTPromiseResolveBlock)resolve
20
+ withRejecter:(RCTPromiseRejectBlock)reject)
21
+
22
+ RCT_EXTERN_METHOD(identify:(NSString)distinctId
23
+ withAnonymousId:(NSString)anonymousId
24
+ withResolver:(RCTPromiseResolveBlock)resolve
25
+ withRejecter:(RCTPromiseRejectBlock)reject)
26
+
27
+ RCT_EXTERN_METHOD(startRecording:(BOOL)resumeCurrent
28
+ withResolver:(RCTPromiseResolveBlock)resolve
29
+ withRejecter:(RCTPromiseRejectBlock)reject)
30
+
31
+ RCT_EXTERN_METHOD(stopRecording:(RCTPromiseResolveBlock)resolve
32
+ withRejecter:(RCTPromiseRejectBlock)reject)
33
+
34
+ + (BOOL)requiresMainQueueSetup
35
+ {
36
+ return NO;
37
+ }
38
+
39
+ @end
@@ -0,0 +1,183 @@
1
+ import PostHog
2
+
3
+ /// Meant for internally logging PostHog related things
4
+ private func hedgeLog(_ message: String) {
5
+ print("[PostHog] \(message)")
6
+ }
7
+
8
+ @objc(PosthogReactNativeSessionReplay)
9
+ class PosthogReactNativeSessionReplay: NSObject {
10
+ private var config: PostHogConfig?
11
+
12
+ @objc(start:withSdkOptions:withSdkReplayConfig:withDecideReplayConfig:withResolver:withRejecter:)
13
+ func start(
14
+ sessionId: String, sdkOptions: [String: Any], sdkReplayConfig: [String: Any],
15
+ decideReplayConfig: [String: Any], resolve: RCTPromiseResolveBlock,
16
+ reject _: RCTPromiseRejectBlock
17
+ ) {
18
+ // we've seen cases where distinctId and anonymousId are not strings, so we need to check and convert them
19
+ guard let sessionIdStr = sessionId as? String else {
20
+ hedgeLog("Invalid sessionId provided: \(sessionId). Expected a string.")
21
+ resolve(nil)
22
+ return
23
+ }
24
+
25
+ let projectToken =
26
+ (sdkOptions["projectToken"] as? String)
27
+ ?? (sdkOptions["apiKey"] as? String)
28
+ ?? ""
29
+ let host = sdkOptions["host"] as? String ?? PostHogConfig.defaultHost
30
+ let debug = sdkOptions["debug"] as? Bool ?? false
31
+
32
+ PostHogSessionManager.shared.setSessionId(sessionIdStr)
33
+
34
+ let config = PostHogConfig(projectToken: projectToken, host: host)
35
+ config.sessionReplay = true
36
+ config.captureApplicationLifecycleEvents = false
37
+ config.captureScreenViews = false
38
+ config.debug = debug
39
+ config.sessionReplayConfig.screenshotMode = true
40
+
41
+ if #available(iOS 15.0, *) {
42
+ config.surveys = false
43
+ }
44
+
45
+ let maskAllTextInputs = sdkReplayConfig["maskAllTextInputs"] as? Bool ?? true
46
+ config.sessionReplayConfig.maskAllTextInputs = maskAllTextInputs
47
+
48
+ let maskAllImages = sdkReplayConfig["maskAllImages"] as? Bool ?? true
49
+ config.sessionReplayConfig.maskAllImages = maskAllImages
50
+
51
+ let maskAllSandboxedViews = sdkReplayConfig["maskAllSandboxedViews"] as? Bool ?? true
52
+ config.sessionReplayConfig.maskAllSandboxedViews = maskAllSandboxedViews
53
+
54
+ // read throttleDelayMs and use iOSdebouncerDelayMs as a fallback for back compatibility
55
+ let throttleDelayMs =
56
+ (sdkReplayConfig["throttleDelayMs"] as? Int)
57
+ ?? (sdkReplayConfig["iOSdebouncerDelayMs"] as? Int)
58
+ ?? 1000
59
+
60
+ let timeInterval: TimeInterval = Double(throttleDelayMs) / 1000.0
61
+ config.sessionReplayConfig.throttleDelay = timeInterval
62
+
63
+ let captureNetworkTelemetry = sdkReplayConfig["captureNetworkTelemetry"] as? Bool ?? true
64
+ config.sessionReplayConfig.captureNetworkTelemetry = captureNetworkTelemetry
65
+
66
+ let captureLog = sdkReplayConfig["captureLog"] as? Bool ?? true
67
+ config.sessionReplayConfig.captureLogs = captureLog
68
+
69
+ config.sessionReplayConfig.sampleRate = sdkReplayConfig["sampleRate"] as? NSNumber
70
+
71
+ let screenshotModeBackgroundCapture = sdkReplayConfig["screenshotModeBackgroundCapture"] as? Bool ?? false
72
+ config.sessionReplayConfig.screenshotModeBackgroundCapture = screenshotModeBackgroundCapture
73
+
74
+ let endpoint = decideReplayConfig["endpoint"] as? String ?? ""
75
+ if !endpoint.isEmpty {
76
+ config.snapshotEndpoint = endpoint
77
+ }
78
+
79
+ let distinctId = sdkOptions["distinctId"] as? String ?? ""
80
+ let anonymousId = sdkOptions["anonymousId"] as? String ?? ""
81
+
82
+ let sdkVersion = sdkOptions["sdkVersion"] as? String ?? ""
83
+
84
+ let flushAt = sdkOptions["flushAt"] as? Int ?? 20
85
+ config.flushAt = flushAt
86
+
87
+ if !sdkVersion.isEmpty {
88
+ postHogSdkName = "posthog-react-native"
89
+ postHogVersion = sdkVersion
90
+ }
91
+
92
+ PostHogSDK.shared.setup(config)
93
+
94
+ self.config = config
95
+
96
+ guard let storageManager = self.config?.storageManager else {
97
+ hedgeLog("Storage manager is not available in the config.")
98
+ resolve(nil)
99
+ return
100
+ }
101
+
102
+ setIdentify(storageManager, distinctId: distinctId, anonymousId: anonymousId)
103
+
104
+ resolve(nil)
105
+ }
106
+
107
+ @objc(startSession:withResolver:withRejecter:)
108
+ func startSession(
109
+ sessionId: String, resolve: RCTPromiseResolveBlock, reject _: RCTPromiseRejectBlock
110
+ ) {
111
+ // we've seen cases where distinctId and anonymousId are not strings, so we need to check and convert them
112
+ guard let sessionIdStr = sessionId as? String else {
113
+ hedgeLog("Invalid sessionId provided: \(sessionId). Expected a string.")
114
+ resolve(nil)
115
+ return
116
+ }
117
+ PostHogSessionManager.shared.setSessionId(sessionIdStr)
118
+ PostHogSDK.shared.startSession()
119
+ resolve(nil)
120
+ }
121
+
122
+ @objc(isEnabled:withRejecter:)
123
+ func isEnabled(resolve: RCTPromiseResolveBlock, reject _: RCTPromiseRejectBlock) {
124
+ let isEnabled = PostHogSDK.shared.isSessionReplayActive()
125
+ resolve(isEnabled)
126
+ }
127
+
128
+ @objc(endSession:withRejecter:)
129
+ func endSession(resolve: RCTPromiseResolveBlock, reject _: RCTPromiseRejectBlock) {
130
+ PostHogSDK.shared.endSession()
131
+ resolve(nil)
132
+ }
133
+
134
+ @objc(identify:withAnonymousId:withResolver:withRejecter:)
135
+ func identify(
136
+ distinctId: String, anonymousId: String, resolve: RCTPromiseResolveBlock,
137
+ reject _: RCTPromiseRejectBlock
138
+ ) {
139
+ // we've seen cases where distinctId and anonymousId are not strings, so we need to check and convert them
140
+ guard let distinctIdStr = distinctId as? String,
141
+ let anonymousIdStr = anonymousId as? String
142
+ else {
143
+ hedgeLog(
144
+ "Invalid distinctId: \(distinctId) or anonymousId: \(anonymousId) provided. Expected strings."
145
+ )
146
+ resolve(nil)
147
+ return
148
+ }
149
+ guard let storageManager = config?.storageManager else {
150
+ hedgeLog("Storage manager is not available in the config.")
151
+ resolve(nil)
152
+ return
153
+ }
154
+ setIdentify(storageManager, distinctId: distinctIdStr, anonymousId: anonymousIdStr)
155
+
156
+ resolve(nil)
157
+ }
158
+
159
+ private func setIdentify(
160
+ _ storageManager: PostHogStorageManager, distinctId: String, anonymousId: String
161
+ ) {
162
+ if !anonymousId.isEmpty {
163
+ storageManager.setAnonymousId(anonymousId)
164
+ }
165
+ if !distinctId.isEmpty {
166
+ storageManager.setDistinctId(distinctId)
167
+ }
168
+ }
169
+
170
+ @objc(startRecording:withResolver:withRejecter:)
171
+ func startRecording(
172
+ resumeCurrent: Bool, resolve: RCTPromiseResolveBlock, reject _: RCTPromiseRejectBlock
173
+ ) {
174
+ PostHogSDK.shared.startSessionRecording(resumeCurrent: resumeCurrent)
175
+ resolve(nil)
176
+ }
177
+
178
+ @objc(stopRecording:withRejecter:)
179
+ func stopRecording(resolve: RCTPromiseResolveBlock, reject _: RCTPromiseRejectBlock) {
180
+ PostHogSDK.shared.stopSessionRecording()
181
+ resolve(nil)
182
+ }
183
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ exports.endSession = endSession;
8
+ exports.identify = identify;
9
+ exports.isEnabled = isEnabled;
10
+ exports.start = start;
11
+ exports.startRecording = startRecording;
12
+ exports.startSession = startSession;
13
+ exports.stopRecording = stopRecording;
14
+ var _reactNative = require("react-native");
15
+ const LINKING_ERROR = `The package 'txlemetry-react-native-session-replay' doesn't seem to be linked. Make sure: \n\n` + _reactNative.Platform.select({
16
+ ios: "- You have run 'pod install'\n",
17
+ default: ''
18
+ }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
19
+ const nativeSessionReplay = _reactNative.NativeModules.TxlemetryReactNativeSessionReplay || _reactNative.NativeModules.PosthogReactNativeSessionReplay ? _reactNative.NativeModules.TxlemetryReactNativeSessionReplay || _reactNative.NativeModules.PosthogReactNativeSessionReplay : new Proxy({}, {
20
+ get() {
21
+ throw new Error(LINKING_ERROR);
22
+ }
23
+ });
24
+ function start(sessionId, sdkOptions, sdkReplayConfig, decideReplayConfig) {
25
+ return nativeSessionReplay.start(sessionId, sdkOptions, sdkReplayConfig, decideReplayConfig);
26
+ }
27
+ function startSession(sessionId) {
28
+ return nativeSessionReplay.startSession(sessionId);
29
+ }
30
+ function endSession() {
31
+ return nativeSessionReplay.endSession();
32
+ }
33
+ function isEnabled() {
34
+ return nativeSessionReplay.isEnabled();
35
+ }
36
+ function identify(distinctId, anonymousId) {
37
+ return nativeSessionReplay.identify(distinctId, anonymousId);
38
+ }
39
+ function startRecording(resumeCurrent) {
40
+ return nativeSessionReplay.startRecording(resumeCurrent);
41
+ }
42
+ function stopRecording() {
43
+ return nativeSessionReplay.stopRecording();
44
+ }
45
+ const TxlemetryReactNativeSessionReplay = {
46
+ start,
47
+ startSession,
48
+ endSession,
49
+ isEnabled,
50
+ identify,
51
+ startRecording,
52
+ stopRecording
53
+ };
54
+ var _default = exports.default = TxlemetryReactNativeSessionReplay;
55
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ import { NativeModules, Platform } from 'react-native';
4
+ const LINKING_ERROR = `The package 'txlemetry-react-native-session-replay' doesn't seem to be linked. Make sure: \n\n` + Platform.select({
5
+ ios: "- You have run 'pod install'\n",
6
+ default: ''
7
+ }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
8
+ const nativeSessionReplay = NativeModules.TxlemetryReactNativeSessionReplay || NativeModules.PosthogReactNativeSessionReplay ? NativeModules.TxlemetryReactNativeSessionReplay || NativeModules.PosthogReactNativeSessionReplay : new Proxy({}, {
9
+ get() {
10
+ throw new Error(LINKING_ERROR);
11
+ }
12
+ });
13
+ export function start(sessionId, sdkOptions, sdkReplayConfig, decideReplayConfig) {
14
+ return nativeSessionReplay.start(sessionId, sdkOptions, sdkReplayConfig, decideReplayConfig);
15
+ }
16
+ export function startSession(sessionId) {
17
+ return nativeSessionReplay.startSession(sessionId);
18
+ }
19
+ export function endSession() {
20
+ return nativeSessionReplay.endSession();
21
+ }
22
+ export function isEnabled() {
23
+ return nativeSessionReplay.isEnabled();
24
+ }
25
+ export function identify(distinctId, anonymousId) {
26
+ return nativeSessionReplay.identify(distinctId, anonymousId);
27
+ }
28
+ export function startRecording(resumeCurrent) {
29
+ return nativeSessionReplay.startRecording(resumeCurrent);
30
+ }
31
+ export function stopRecording() {
32
+ return nativeSessionReplay.stopRecording();
33
+ }
34
+ const TxlemetryReactNativeSessionReplay = {
35
+ start,
36
+ startSession,
37
+ endSession,
38
+ isEnabled,
39
+ identify,
40
+ startRecording,
41
+ stopRecording
42
+ };
43
+ export default TxlemetryReactNativeSessionReplay;
44
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,33 @@
1
+ export declare function start(sessionId: string, sdkOptions: {
2
+ [key: string]: any;
3
+ }, sdkReplayConfig: {
4
+ [key: string]: any;
5
+ }, decideReplayConfig: {
6
+ [key: string]: any;
7
+ }): Promise<void>;
8
+ export declare function startSession(sessionId: string): Promise<void>;
9
+ export declare function endSession(): Promise<void>;
10
+ export declare function isEnabled(): Promise<boolean>;
11
+ export declare function identify(distinctId: string, anonymousId: string): Promise<void>;
12
+ export declare function startRecording(resumeCurrent: boolean): Promise<void>;
13
+ export declare function stopRecording(): Promise<void>;
14
+ export interface TxlemetryReactNativeSessionReplayModule {
15
+ start: (sessionId: string, sdkOptions: {
16
+ [key: string]: any;
17
+ }, // options from SDK such as apiKey
18
+ sdkReplayConfig: {
19
+ [key: string]: any;
20
+ }, // config from SDK
21
+ decideReplayConfig: {
22
+ [key: string]: any;
23
+ }) => Promise<void>;
24
+ startSession: (sessionId: string) => Promise<void>;
25
+ endSession: () => Promise<void>;
26
+ isEnabled: () => Promise<boolean>;
27
+ identify: (distinctId: string, anonymousId: string) => Promise<void>;
28
+ startRecording: (resumeCurrent: boolean) => Promise<void>;
29
+ stopRecording: () => Promise<void>;
30
+ }
31
+ declare const TxlemetryReactNativeSessionReplay: TxlemetryReactNativeSessionReplayModule;
32
+ export default TxlemetryReactNativeSessionReplay;
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,33 @@
1
+ export declare function start(sessionId: string, sdkOptions: {
2
+ [key: string]: any;
3
+ }, sdkReplayConfig: {
4
+ [key: string]: any;
5
+ }, decideReplayConfig: {
6
+ [key: string]: any;
7
+ }): Promise<void>;
8
+ export declare function startSession(sessionId: string): Promise<void>;
9
+ export declare function endSession(): Promise<void>;
10
+ export declare function isEnabled(): Promise<boolean>;
11
+ export declare function identify(distinctId: string, anonymousId: string): Promise<void>;
12
+ export declare function startRecording(resumeCurrent: boolean): Promise<void>;
13
+ export declare function stopRecording(): Promise<void>;
14
+ export interface TxlemetryReactNativeSessionReplayModule {
15
+ start: (sessionId: string, sdkOptions: {
16
+ [key: string]: any;
17
+ }, // options from SDK such as apiKey
18
+ sdkReplayConfig: {
19
+ [key: string]: any;
20
+ }, // config from SDK
21
+ decideReplayConfig: {
22
+ [key: string]: any;
23
+ }) => Promise<void>;
24
+ startSession: (sessionId: string) => Promise<void>;
25
+ endSession: () => Promise<void>;
26
+ isEnabled: () => Promise<boolean>;
27
+ identify: (distinctId: string, anonymousId: string) => Promise<void>;
28
+ startRecording: (resumeCurrent: boolean) => Promise<void>;
29
+ stopRecording: () => Promise<void>;
30
+ }
31
+ declare const TxlemetryReactNativeSessionReplay: TxlemetryReactNativeSessionReplayModule;
32
+ export default TxlemetryReactNativeSessionReplay;
33
+ //# sourceMappingURL=index.d.ts.map
package/package.json ADDED
@@ -0,0 +1,159 @@
1
+ {
2
+ "name": "txlemetry-react-native-session-replay",
3
+ "version": "1.6.1",
4
+ "description": "Txlemetry session replay for React Native",
5
+ "keywords": [
6
+ "android",
7
+ "ios",
8
+ "react-native"
9
+ ],
10
+ "homepage": "https://txlemetry.com",
11
+ "bugs": {
12
+ "url": "https://github.com/hectorvss/Txlemetry/issues"
13
+ },
14
+ "license": "MIT",
15
+ "author": "Txlemetry",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/hectorvss/Txlemetry.git",
19
+ "directory": "txlemetry-sdk/react-native-session-replay"
20
+ },
21
+ "source": "./src/index.tsx",
22
+ "files": [
23
+ "src",
24
+ "lib",
25
+ "android",
26
+ "ios",
27
+ "cpp",
28
+ "txlemetry-react-native-session-replay.podspec",
29
+ "!ios/build",
30
+ "!android/build",
31
+ "!android/gradle",
32
+ "!android/gradlew",
33
+ "!android/gradlew.bat",
34
+ "!android/local.properties",
35
+ "!**/__tests__",
36
+ "!**/__fixtures__",
37
+ "!**/__mocks__",
38
+ "!**/.*",
39
+ "!**/*.map"
40
+ ],
41
+ "main": "./lib/commonjs/index.js",
42
+ "module": "./lib/module/index.js",
43
+ "types": "./lib/typescript/module/src/index.d.ts",
44
+ "exports": {
45
+ ".": {
46
+ "import": {
47
+ "types": "./lib/typescript/module/src/index.d.ts",
48
+ "default": "./lib/module/index.js"
49
+ },
50
+ "require": {
51
+ "types": "./lib/typescript/commonjs/src/index.d.ts",
52
+ "default": "./lib/commonjs/index.js"
53
+ }
54
+ }
55
+ },
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "registry": "https://registry.npmjs.org/"
59
+ },
60
+ "scripts": {
61
+ "example": "pnpm --filter txlemetry-react-native-session-replay-example",
62
+ "test": "jest",
63
+ "typecheck": "tsc",
64
+ "lint": "eslint \"**/*.{js,ts,tsx}\"",
65
+ "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
66
+ "changeset": "changeset"
67
+ },
68
+ "devDependencies": {
69
+ "@changesets/cli": "^2.27.0",
70
+ "@evilmartians/lefthook": "^1.5.0",
71
+ "@react-native-community/cli": "20.0.0",
72
+ "@react-native/eslint-config": "^0.73.1",
73
+ "@types/jest": "^29.5.5",
74
+ "@types/react": "^18.2.44",
75
+ "del-cli": "^5.1.0",
76
+ "eslint": "^8.51.0",
77
+ "eslint-config-prettier": "^9.0.0",
78
+ "eslint-plugin-prettier": "^5.0.1",
79
+ "jest": "^29.7.0",
80
+ "prettier": "^3.0.3",
81
+ "react": "18.3.1",
82
+ "react-native": "0.75.3",
83
+ "react-native-builder-bob": "^0.30.2",
84
+ "turbo": "^2.0.0",
85
+ "typescript": "^5.2.2"
86
+ },
87
+ "peerDependencies": {
88
+ "react": "*",
89
+ "react-native": "*"
90
+ },
91
+ "prettier": {
92
+ "quoteProps": "consistent",
93
+ "singleQuote": true,
94
+ "tabWidth": 2,
95
+ "trailingComma": "es5",
96
+ "useTabs": false
97
+ },
98
+ "eslintConfig": {
99
+ "extends": [
100
+ "@react-native",
101
+ "prettier"
102
+ ],
103
+ "root": true,
104
+ "rules": {
105
+ "prettier/prettier": [
106
+ "error",
107
+ {
108
+ "quoteProps": "consistent",
109
+ "singleQuote": true,
110
+ "tabWidth": 2,
111
+ "trailingComma": "es5",
112
+ "useTabs": false
113
+ }
114
+ ],
115
+ "react/react-in-jsx-scope": "off"
116
+ }
117
+ },
118
+ "eslintIgnore": [
119
+ "node_modules/",
120
+ "lib/"
121
+ ],
122
+ "jest": {
123
+ "modulePathIgnorePatterns": [
124
+ "<rootDir>/example/node_modules",
125
+ "<rootDir>/lib/"
126
+ ],
127
+ "preset": "react-native"
128
+ },
129
+ "create-react-native-library": {
130
+ "type": "module-legacy",
131
+ "languages": "kotlin-swift",
132
+ "version": "0.41.2"
133
+ },
134
+ "react-native-builder-bob": {
135
+ "source": "src",
136
+ "output": "lib",
137
+ "targets": [
138
+ [
139
+ "commonjs",
140
+ {
141
+ "esm": true
142
+ }
143
+ ],
144
+ [
145
+ "module",
146
+ {
147
+ "esm": true
148
+ }
149
+ ],
150
+ [
151
+ "typescript",
152
+ {
153
+ "project": "tsconfig.build.json",
154
+ "esm": true
155
+ }
156
+ ]
157
+ ]
158
+ }
159
+ }
package/src/index.tsx ADDED
@@ -0,0 +1,93 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+
3
+ const LINKING_ERROR =
4
+ `The package 'txlemetry-react-native-session-replay' doesn't seem to be linked. Make sure: \n\n` +
5
+ Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
6
+ '- You rebuilt the app after installing the package\n' +
7
+ '- You are not using Expo Go\n';
8
+
9
+ const nativeSessionReplay =
10
+ NativeModules.TxlemetryReactNativeSessionReplay || NativeModules.PosthogReactNativeSessionReplay
11
+ ? NativeModules.TxlemetryReactNativeSessionReplay || NativeModules.PosthogReactNativeSessionReplay
12
+ : new Proxy(
13
+ {},
14
+ {
15
+ get() {
16
+ throw new Error(LINKING_ERROR);
17
+ },
18
+ }
19
+ );
20
+
21
+ export function start(
22
+ sessionId: string,
23
+ sdkOptions: { [key: string]: any },
24
+ sdkReplayConfig: { [key: string]: any },
25
+ decideReplayConfig: { [key: string]: any }
26
+ ): Promise<void> {
27
+ return nativeSessionReplay.start(
28
+ sessionId,
29
+ sdkOptions,
30
+ sdkReplayConfig,
31
+ decideReplayConfig
32
+ );
33
+ }
34
+
35
+ export function startSession(sessionId: string): Promise<void> {
36
+ return nativeSessionReplay.startSession(sessionId);
37
+ }
38
+
39
+ export function endSession(): Promise<void> {
40
+ return nativeSessionReplay.endSession();
41
+ }
42
+
43
+ export function isEnabled(): Promise<boolean> {
44
+ return nativeSessionReplay.isEnabled();
45
+ }
46
+
47
+ export function identify(
48
+ distinctId: string,
49
+ anonymousId: string
50
+ ): Promise<void> {
51
+ return nativeSessionReplay.identify(distinctId, anonymousId);
52
+ }
53
+
54
+ export function startRecording(resumeCurrent: boolean): Promise<void> {
55
+ return nativeSessionReplay.startRecording(resumeCurrent);
56
+ }
57
+
58
+ export function stopRecording(): Promise<void> {
59
+ return nativeSessionReplay.stopRecording();
60
+ }
61
+
62
+ export interface TxlemetryReactNativeSessionReplayModule {
63
+ start: (
64
+ sessionId: string,
65
+ sdkOptions: { [key: string]: any }, // options from SDK such as apiKey
66
+ sdkReplayConfig: { [key: string]: any }, // config from SDK
67
+ decideReplayConfig: { [key: string]: any } // config from Decide API
68
+ ) => Promise<void>;
69
+
70
+ startSession: (sessionId: string) => Promise<void>;
71
+
72
+ endSession: () => Promise<void>;
73
+
74
+ isEnabled: () => Promise<boolean>;
75
+
76
+ identify: (distinctId: string, anonymousId: string) => Promise<void>;
77
+
78
+ startRecording: (resumeCurrent: boolean) => Promise<void>;
79
+
80
+ stopRecording: () => Promise<void>;
81
+ }
82
+
83
+ const TxlemetryReactNativeSessionReplay: TxlemetryReactNativeSessionReplayModule = {
84
+ start,
85
+ startSession,
86
+ endSession,
87
+ isEnabled,
88
+ identify,
89
+ startRecording,
90
+ stopRecording,
91
+ };
92
+
93
+ export default TxlemetryReactNativeSessionReplay;
@@ -0,0 +1,68 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+ folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5
+
6
+ # Single source of truth for the native dependency version.
7
+ # Used by both the SPM and CocoaPods resolution paths below; bump this
8
+ # line when picking up a new native SDK release.
9
+ posthog_ios_version = '3.58.1'
10
+
11
+ Pod::Spec.new do |s|
12
+ s.name = "txlemetry-react-native-session-replay"
13
+ s.version = package["version"]
14
+ s.summary = package["description"]
15
+ s.homepage = package["homepage"]
16
+ s.license = package["license"]
17
+ s.authors = package["author"]
18
+
19
+ s.platforms = { :ios => min_ios_version_supported }
20
+ s.source = { :git => "https://github.com/hectorvss/Txlemetry.git", :tag => "txlemetry-react-native-session-replay@#{s.version}" }
21
+
22
+ s.source_files = "ios/**/*.{swift,h,hpp,m,mm,c,cpp}"
23
+
24
+ # Default: resolve the native SDK via CocoaPods trunk.
25
+ # Opt-in: set `txlemetry.useSpm` to `"true"` in the consumer's
26
+ # `ios/Podfile.properties.json` to resolve the native SDK via Swift Package
27
+ # Manager using the React Native `spm_dependency` helper (RN >= 0.75).
28
+ # The SPM path requires `use_frameworks! :linkage => :dynamic` in the Podfile.
29
+ podfile_properties_path = File.join(Pod::Config.instance.installation_root.to_s, 'Podfile.properties.json')
30
+ podfile_properties = File.exist?(podfile_properties_path) ? (JSON.parse(File.read(podfile_properties_path)) rescue {}) : {}
31
+ txlemetry_use_spm = podfile_properties['txlemetry.useSpm'].to_s == 'true' || podfile_properties['posthog.useSpm'].to_s == 'true'
32
+
33
+ if txlemetry_use_spm && respond_to?(:spm_dependency, true)
34
+ spm_dependency(s,
35
+ url: 'https://github.com/PostHog/posthog-ios.git',
36
+ requirement: { kind: 'upToNextMinorVersion', minimumVersion: posthog_ios_version },
37
+ products: ['PostHog']
38
+ )
39
+ else
40
+ s.dependency 'PostHog', "~> #{posthog_ios_version}"
41
+ end
42
+ s.ios.deployment_target = '13.0'
43
+ s.swift_versions = "5.3"
44
+
45
+
46
+ # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
47
+ # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
48
+ if respond_to?(:install_modules_dependencies, true)
49
+ install_modules_dependencies(s)
50
+ else
51
+ s.dependency "React-Core"
52
+
53
+ # Don't install the dependencies when we run `pod install` in the old architecture.
54
+ if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
55
+ s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
56
+ s.pod_target_xcconfig = {
57
+ "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
58
+ "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
59
+ "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
60
+ }
61
+ s.dependency "React-Codegen"
62
+ s.dependency "RCT-Folly"
63
+ s.dependency "RCTRequired"
64
+ s.dependency "RCTTypeSafety"
65
+ s.dependency "ReactCommon/turbomodule/core"
66
+ end
67
+ end
68
+ end