@tugboat-ai/react-native 0.0.0-stage → 0.0.8

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/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # React Native adapter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@tugboat-ai/react-native` 0.0.8: Android and iOS. A thin TurboModule over
4
+ `tugboat-android` and the Swift host (`platforms/apple`). React Native draws real
5
+ native views, so the host's adapter records frames, masks, taps and scrolls as in
6
+ a native app. JavaScript starts the SDK and marks sensitive regions; events are
7
+ built by the shared C++ engine, never in JavaScript. Raw pixels never enter
8
+ JavaScript.
9
+
10
+ ```sh
11
+ npm install @tugboat-ai/react-native
12
+ ```
13
+
14
+ React Native 0.88 or later, New Architecture. The package needs the native
15
+ Tugboat SDKs (`com.gettugboat.sdk:tugboat-android` and the `Tugboat` pod); until
16
+ they are published, build against the in-repo SDKs as described below.
17
+
18
+ ```ts
19
+ Tugboat.start({
20
+ collector: { baseUrl, apiKey },
21
+ app: { name },
22
+ enabled: true, // default false: dormant until Tugboat.activate(id)
23
+ });
24
+ <Tugboat.Sensitive>{/* card fields, ... */}</Tugboat.Sensitive>
25
+ ```
26
+
27
+ Also `activate`, `deactivate`, `stop`, `setUserId`, `setTraits`. `fetch` and
28
+ `XMLHttpRequest` are recorded through an OkHttp interceptor (path only), which
29
+ replaces an app's own `NetworkingModule.setCustomClientBuilder`.
30
+
31
+ ## iOS: the Swift host as local pods
32
+
33
+ The module (`ios/`) calls the Swift host through `TugboatRN.swift`. The host is
34
+ unpublished, so the app's Podfile lists it as local pods from the repository root
35
+ (`example/ios/Podfile` does this; the three have no other source yet):
36
+
37
+ ```ruby
38
+ pod 'TugboatSessionEngine', :path => '<repo>' # core/session-engine (C++)
39
+ pod 'TugboatCaptureRuntime', :path => '<repo>' # masked screenshots
40
+ pod 'Tugboat', :path => '<repo>' # platforms/apple/Sources/Tugboat
41
+ ```
42
+
43
+ Local pods rather than SwiftPM: React Native's CocoaPods integration can only add
44
+ a SwiftPM package by URL and version (`spm_dependency`), and a local path cannot
45
+ be a dependency of an autolinked pod. `Tugboat.podspec` and
46
+ `TugboatSessionEngine.podspec` list the same sources as the targets in
47
+ `Package.swift`. The engine is built as C++17 (`-std=c++17`): React Native sets
48
+ C++20 on every pod, which its JSON types do not compile under.
49
+
50
+ Then `cd example/ios && pod install`, and build `RnExample.xcworkspace`.
51
+
52
+ How iOS differs from Android:
53
+ - JavaScript names every screen (`setScreen`, `trackNavigation`); no view
54
+ controller is a route (`trackHostingControllers: false`). The first screen named
55
+ is the session's initial route (`session_start`, with a frame of its own, as on
56
+ Android), and an app that never names one reports no routes.
57
+ - A `testID` is the view's `accessibilityIdentifier`. The host treats a view with
58
+ one as a tap target and a `Named#<ordinal>` path segment (the name never enters
59
+ the path), and the name is the anchor's `tag`, so `tagFingerprint` is the alias.
60
+ Android puts the `testID` in the path as `ViewGroup#<testID>`, so fingerprints
61
+ differ between platforms.
62
+ - React Native's paragraph and image views draw their own pixels and are masked
63
+ whole (the host's `setViewRoleClassifier`); `UITextField`/`UITextView` inside
64
+ text inputs are masked as in any app. `<Tugboat.Sensitive>` masks its view and
65
+ everything under it.
66
+ - Network: `TugboatHTTPRequestHandler` replaces React Native's HTTP handler while
67
+ `captureNetwork` is on (after `Tugboat.start`), with the same session setup (no
68
+ custom session configuration or interceptor, which RN lets an app set through
69
+ `RCTSetCustomNSURLSessionConfigurationProvider`). `captureNetwork: false` leaves
70
+ the default handler alone. Route is the URL path, percent-encoded, never the
71
+ query.
72
+ - Tap targets: only a view with a `testID` is a target (Android targets any
73
+ clickable view), so a `Pressable` without one resolves to its nearest named
74
+ ancestor. A named target's anchor carries `actions: ["tap"]` and `enabled` (the
75
+ view takes touches and is not marked not-enabled); iOS cannot tell a `Pressable` from a plain view, so every named view
76
+ reports `tap`. `<Text
77
+ testID>` and a `testID` on a `TextInput` or scroll view are not used as the tag.
78
+ `captureSystemInput` is ignored on iOS. `accessibilityIdentifier` values are sent
79
+ as the tag (as Android sends `testID`): data-derived ids are sent too.
80
+ - Network: remote `<Image>` downloads also go through React Native's networking
81
+ but are not recorded (as on Android and in Flutter): the handler skips requests
82
+ React Native's image loader tags (`trackingName` `RCTImageLoader`). A `fetch` or
83
+ `XMLHttpRequest` of an image URL is still recorded. The handler also bypasses anything that wraps
84
+ `RCTHTTPRequestHandler` (certificate pinning by category or swizzle), and copies
85
+ RN 0.88's handler, so check it on an RN upgrade. It handles requests from `start`
86
+ on, also while Tugboat is dormant.
87
+ - There is no early install as on Android: the host adopts the key window that
88
+ already exists when `Tugboat.start` runs, so frames begin at `start`.
89
+
90
+ ## Android: build against the in-repo SDK
91
+
92
+ The Android library depends on `tugboat-android` and `tugboat-okhttp` from the
93
+ git-ignored `.local-maven`. Publish them first (needs the NDK in `AGENTS.md`):
94
+
95
+ ```sh
96
+ cd platforms/android && ./gradlew :capture-runtime:publishAllPublicationsToLocalCaptureRepository \
97
+ :tugboat-android:publishAllPublicationsToLocalCaptureRepository \
98
+ :tugboat-okhttp:publishAllPublicationsToLocalCaptureRepository
99
+ ```
100
+
101
+ Then build `example/` (see its README). Known gaps in 0.0.8 (Android unless noted):
102
+ - Screens: `Tugboat.trackNavigation(navigationRef)` (React Navigation) or
103
+ `Tugboat.setScreen(name, instanceId?)`. A `testID` is the view's tag and
104
+ fingerprint name. A content provider installs the observation before the first
105
+ activity, so `Tugboat.start` may run late.
106
+ - Not yet handled: the screen name is lost when the activity is recreated; a
107
+ `setScreen` while the activity is paused is dropped; a reused instance id with
108
+ a new name keeps the old name; a late `start` skips launch correlation until the next
109
+ resume.
110
+ - Network: a call whose URL path has percent-encoded characters (spaces,
111
+ non-ASCII) is not recorded. `captureNetwork: false` leaves an app's own
112
+ `setCustomClientBuilder` alone; the default replaces it.
113
+ - `<Tugboat.Sensitive>` is a real view on Android and iOS; on other platforms it
114
+ renders its children only (no wrapper view, `style` ignored).
115
+ - If the native module is not linked, calls warn once ("the native module is not
116
+ linked") and `<Tugboat.Sensitive>` fails to render.
@@ -0,0 +1,23 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ # Autolinked into the app by React Native's CLI. The Swift host is the Tugboat
6
+ # pod from CocoaPods trunk; example/ios/Podfile uses local paths instead.
7
+ Pod::Spec.new do |s|
8
+ s.name = "TugboatReactNative"
9
+ s.version = package["version"]
10
+ s.summary = package["description"]
11
+ s.homepage = "https://github.com/blendto/tugboat-mobile-sdk"
12
+ s.license = { :type => "AGPL-3.0-only" }
13
+ s.author = { "Tugboat" => "dev@bijatech.com" }
14
+ s.platforms = { :ios => "15.1" }
15
+ s.source = { :git => "https://github.com/blendto/tugboat-mobile-sdk.git", :tag => "react-native-v#{s.version}" }
16
+ s.swift_version = "5.9"
17
+ s.source_files = "ios/**/*.{h,m,mm,cpp,swift}"
18
+ s.private_header_files = "ios/**/*.h"
19
+ s.dependency "Tugboat", "0.1.0"
20
+ s.pod_target_xcconfig = { "DEFINES_MODULE" => "YES" }
21
+
22
+ install_modules_dependencies(s)
23
+ end
@@ -0,0 +1,40 @@
1
+ // Autolinked into the app by the React Native Gradle plugin. The Android Gradle
2
+ // plugin, Kotlin and React Native Gradle plugins come from the app's root build.
3
+ // The Tugboat Android SDK comes from Maven Central. Inside this repository it
4
+ // can come from the git-ignored `.local-maven` instead: publish it there with
5
+ // the three Gradle tasks in sdks/react-native/README.md.
6
+ apply plugin: "com.android.library"
7
+ apply plugin: "org.jetbrains.kotlin.android"
8
+ apply plugin: "com.facebook.react"
9
+
10
+ def tugboatAndroidVersion = "0.1.0"
11
+
12
+ android {
13
+ namespace "com.tugboat.reactnative"
14
+ compileSdk rootProject.ext.compileSdkVersion
15
+
16
+ defaultConfig {
17
+ minSdk 24
18
+ }
19
+
20
+ compileOptions {
21
+ sourceCompatibility JavaVersion.VERSION_17
22
+ targetCompatibility JavaVersion.VERSION_17
23
+ }
24
+
25
+ kotlinOptions {
26
+ jvmTarget = "17"
27
+ }
28
+ }
29
+
30
+ repositories {
31
+ google()
32
+ mavenCentral()
33
+ maven { url = uri("${rootDir}/../../../../.local-maven") }
34
+ }
35
+
36
+ dependencies {
37
+ implementation "com.facebook.react:react-android"
38
+ implementation "com.gettugboat.sdk:tugboat-android:${tugboatAndroidVersion}"
39
+ implementation "com.gettugboat.sdk:tugboat-okhttp:${tugboatAndroidVersion}"
40
+ }
@@ -0,0 +1,8 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <application>
3
+ <provider
4
+ android:name="com.tugboat.reactnative.TugboatInitProvider"
5
+ android:authorities="${applicationId}.tugboat-init"
6
+ android:exported="false" />
7
+ </application>
8
+ </manifest>
@@ -0,0 +1,44 @@
1
+ package com.tugboat.reactnative
2
+
3
+ import android.app.Application
4
+ import android.content.ContentProvider
5
+ import android.content.ContentValues
6
+ import android.database.Cursor
7
+ import android.net.Uri
8
+ import android.util.Log
9
+ import android.view.View
10
+ import com.tugboat.android.adapter.TugboatAdapterApi
11
+ import com.tugboat.android.adapter.TugboatAdapters
12
+
13
+ /**
14
+ * Runs before any activity exists: the SDK then knows the first activity when
15
+ * JavaScript calls `Tugboat.start` later. Does nothing else, and nothing here
16
+ * throws. If `Tugboat.start` never runs, it only observes activities and fragments.
17
+ */
18
+ @OptIn(TugboatAdapterApi::class)
19
+ class TugboatInitProvider : ContentProvider() {
20
+ override fun onCreate(): Boolean {
21
+ try {
22
+ val application = context?.applicationContext as? Application ?: return true
23
+ TugboatAdapters.install(application)
24
+ // testID is the view's name: path token, alias, `tag`.
25
+ TugboatAdapters.setViewNameProvider(::testId)
26
+ // react-native-screens hosts each screen in a fragment; JavaScript names the screen.
27
+ TugboatAdapters.setFragmentFilter { it.startsWith("com.swmansion.rnscreens.") }
28
+ // JavaScript names every screen with setScreen; the activity is not a route.
29
+ TugboatAdapters.setHostNamesScreens(true)
30
+ } catch (t: Throwable) {
31
+ Log.w("TugboatRN", "early install failed", t)
32
+ }
33
+ return true
34
+ }
35
+
36
+ private fun testId(view: View): String? =
37
+ (view.getTag(com.facebook.react.R.id.react_test_id) as? String)?.takeIf { it.isNotEmpty() }
38
+
39
+ override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
40
+ override fun getType(uri: Uri): String? = null
41
+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null
42
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0
43
+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?) = 0
44
+ }
@@ -0,0 +1,99 @@
1
+ package com.tugboat.reactnative
2
+
3
+ import android.app.Application
4
+ import android.content.pm.PackageManager
5
+ import android.util.Log
6
+ import com.facebook.react.bridge.ReactApplicationContext
7
+ import com.facebook.react.bridge.ReadableMap
8
+ import com.facebook.react.module.annotations.ReactModule
9
+ import com.tugboat.android.AppInfo
10
+ import com.tugboat.android.CollectorConfig
11
+ import com.tugboat.android.Tugboat
12
+ import com.tugboat.android.TugboatConfig
13
+
14
+ /** Each method is one call to the same-named `Tugboat` function. Nothing throws into the app. */
15
+ @ReactModule(name = TugboatModule.NAME)
16
+ class TugboatModule(reactContext: ReactApplicationContext) : NativeTugboatSpec(reactContext) {
17
+ override fun getName(): String = NAME
18
+
19
+ override fun start(config: ReadableMap) = guarded("start") {
20
+ val application = reactApplicationContext.applicationContext as Application
21
+ val collector = config.getMap("collector") ?: error("collector is missing")
22
+ val app = config.getMap("app") ?: error("app is missing")
23
+ val info = packageInfo(application)
24
+ val appInfo = AppInfo(
25
+ name = app.string("name") ?: application.applicationInfo.loadLabel(application.packageManager).toString(),
26
+ version = app.string("version") ?: info?.versionName.orEmpty(),
27
+ buildNumber = app.string("buildNumber") ?: info?.let { longVersionCode(it).toString() }.orEmpty(),
28
+ appId = app.string("appId") ?: application.packageName,
29
+ installationId = app.string("installationId").orEmpty(),
30
+ )
31
+ Tugboat.start(
32
+ application,
33
+ TugboatConfig(
34
+ collector = CollectorConfig(
35
+ baseUrl = collector.string("baseUrl").orEmpty(),
36
+ apiKey = collector.string("apiKey").orEmpty(),
37
+ ),
38
+ app = appInfo,
39
+ enabled = config.bool("enabled", false),
40
+ // maskLevel is not read: only allTextAndMedia exists, and it is the default.
41
+ captureFocusChanges = config.bool("captureFocusChanges", false),
42
+ captureSystemInput = config.bool("captureSystemInput", false),
43
+ captureDiagnostics = config.bool("captureDiagnostics", false),
44
+ durableOutbox = config.bool("durableOutbox", false),
45
+ sdkVersion = config.string("sdkVersion"),
46
+ ),
47
+ )
48
+ if (config.bool("captureNetwork", true)) {
49
+ val hosts = config.getArray("networkAllowHosts")?.toArrayList()?.mapNotNull { it as? String }.orEmpty()
50
+ TugboatNetwork.install(hosts.toSet())
51
+ } else {
52
+ TugboatNetwork.uninstall()
53
+ }
54
+ }
55
+
56
+ override fun activate(activationRequestId: String) = guarded("activate") { Tugboat.activate(activationRequestId) }
57
+
58
+ override fun deactivate() = guarded("deactivate") { Tugboat.deactivate() }
59
+
60
+ override fun stop() = guarded("stop") { Tugboat.stop() }
61
+
62
+ override fun setScreen(name: String, instanceId: String?) = guarded("setScreen") {
63
+ Tugboat.setScreen(name, instanceId?.takeIf { it.isNotBlank() } ?: name)
64
+ }
65
+
66
+ override fun setUserId(id: String?) = guarded("setUserId") { Tugboat.setUserId(id) }
67
+
68
+ override fun setTraits(traits: ReadableMap) = guarded("setTraits") { Tugboat.setTraits(traits.toHashMap()) }
69
+
70
+ private fun guarded(what: String, block: () -> Unit) {
71
+ try {
72
+ block()
73
+ } catch (t: Throwable) {
74
+ Log.w(TAG, "$what failed", t)
75
+ }
76
+ }
77
+
78
+ @Suppress("DEPRECATION")
79
+ private fun packageInfo(application: Application) = try {
80
+ application.packageManager.getPackageInfo(application.packageName, 0)
81
+ } catch (_: PackageManager.NameNotFoundException) {
82
+ null
83
+ }
84
+
85
+ @Suppress("DEPRECATION")
86
+ private fun longVersionCode(info: android.content.pm.PackageInfo): Long =
87
+ if (android.os.Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
88
+
89
+ private fun ReadableMap.string(key: String): String? =
90
+ if (hasKey(key) && !isNull(key)) getString(key)?.takeIf { it.isNotBlank() } else null
91
+
92
+ private fun ReadableMap.bool(key: String, default: Boolean): Boolean =
93
+ if (hasKey(key) && !isNull(key)) getBoolean(key) else default
94
+
95
+ companion object {
96
+ const val NAME = "Tugboat"
97
+ private const val TAG = "TugboatRN"
98
+ }
99
+ }
@@ -0,0 +1,43 @@
1
+ package com.tugboat.reactnative
2
+
3
+ import com.facebook.react.modules.network.NetworkingModule
4
+ import com.tugboat.android.okhttp.TugboatOkHttpInterceptor
5
+ import okhttp3.OkHttpClient
6
+ import okhttp3.Request
7
+
8
+ /**
9
+ * Records `fetch` and `XMLHttpRequest` calls: both go through React Native's OkHttp
10
+ * client. The route is the URL path, never the URL or query. There is one slot for a
11
+ * custom client builder, so this replaces an app's own.
12
+ */
13
+ internal object TugboatNetwork {
14
+ // Only what this object installed is ever removed: an app's own builder stays.
15
+ private var installed = false
16
+
17
+ /** Removes the interceptor, if this object installed it (`captureNetwork: false`). */
18
+ @Synchronized
19
+ fun uninstall() {
20
+ if (!installed) return
21
+ installed = false
22
+ NetworkingModule.setCustomClientBuilder(null)
23
+ }
24
+
25
+ @Synchronized
26
+ fun install(hosts: Set<String>) {
27
+ // OkHttp lower-cases hosts.
28
+ val allowHosts = hosts.map { it.lowercase() }.toSet()
29
+ NetworkingModule.setCustomClientBuilder(
30
+ object : NetworkingModule.CustomClientBuilder {
31
+ override fun apply(builder: OkHttpClient.Builder) {
32
+ builder.addInterceptor(TugboatOkHttpInterceptor { request -> route(request, allowHosts) })
33
+ }
34
+ },
35
+ )
36
+ installed = true
37
+ }
38
+
39
+ private fun route(request: Request, allowHosts: Set<String>): String? {
40
+ if (allowHosts.isNotEmpty() && request.url.host !in allowHosts) return null
41
+ return request.url.encodedPath
42
+ }
43
+ }
@@ -0,0 +1,28 @@
1
+ package com.tugboat.reactnative
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import com.facebook.react.uimanager.ViewManager
9
+
10
+ class TugboatPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
12
+ if (name == TugboatModule.NAME) TugboatModule(reactContext) else null
13
+
14
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
15
+ mapOf(
16
+ TugboatModule.NAME to ReactModuleInfo(
17
+ TugboatModule.NAME, TugboatModule.NAME,
18
+ false, // canOverrideExistingModule
19
+ false, // needsEagerInit
20
+ false, // isCxxModule
21
+ true, // isTurboModule
22
+ ),
23
+ )
24
+ }
25
+
26
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
27
+ listOf(TugboatSensitiveViewManager())
28
+ }
@@ -0,0 +1,33 @@
1
+ package com.tugboat.reactnative
2
+
3
+ import com.facebook.react.uimanager.ThemedReactContext
4
+ import com.facebook.react.uimanager.ViewGroupManager
5
+ import com.facebook.react.uimanager.ViewManagerDelegate
6
+ import com.facebook.react.viewmanagers.TugboatSensitiveViewManagerDelegate
7
+ import com.facebook.react.viewmanagers.TugboatSensitiveViewManagerInterface
8
+ import com.facebook.react.views.view.ReactViewGroup
9
+ import com.tugboat.android.tugboatSensitive
10
+
11
+ /** `<Tugboat.Sensitive>`: a plain view the Views adapter masks with its whole subtree. */
12
+ class TugboatSensitiveViewManager :
13
+ ViewGroupManager<ReactViewGroup>(),
14
+ TugboatSensitiveViewManagerInterface<ReactViewGroup> {
15
+ private val delegate = TugboatSensitiveViewManagerDelegate(this)
16
+
17
+ override fun getDelegate(): ViewManagerDelegate<ReactViewGroup> = delegate
18
+
19
+ override fun getName(): String = NAME
20
+
21
+ override fun createViewInstance(context: ThemedReactContext): ReactViewGroup =
22
+ ReactViewGroup(context).also { view ->
23
+ try {
24
+ view.tugboatSensitive()
25
+ } catch (_: Throwable) {
26
+ // Never throw into the app.
27
+ }
28
+ }
29
+
30
+ companion object {
31
+ const val NAME = "TugboatSensitiveView"
32
+ }
33
+ }
@@ -0,0 +1,169 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTURLRequestDelegate.h>
3
+ #import <React/RCTURLRequestHandler.h>
4
+ #import <ReactCommon/RCTTurboModule.h>
5
+
6
+ #import <mutex>
7
+
8
+ #if __has_include(<TugboatReactNative/TugboatReactNative-Swift.h>)
9
+ #import <TugboatReactNative/TugboatReactNative-Swift.h>
10
+ #else
11
+ #import "TugboatReactNative-Swift.h"
12
+ #endif
13
+
14
+ // React Native's HTTP handler (RCTHTTPRequestHandler) makes its NSURLSession
15
+ // with itself as delegate, so the Swift host's instrumented session cannot wrap
16
+ // it. This handler does the same work with `Tugboat.instrumentedSession`: it
17
+ // outranks the default handler, and handles a request only while
18
+ // `captureNetwork` is on (after `Tugboat.start`), so each request is recorded
19
+ // once, and an app's own session configuration provider or request interceptor
20
+ // (RCTSetCustomNSURLSessionConfigurationProvider, RCTSetCustomHTTPRequestInterceptor)
21
+ // is bypassed only then.
22
+ @interface TugboatHTTPRequestHandler : NSObject <RCTURLRequestHandler, RCTInvalidating, NSURLSessionDataDelegate, RCTTurboModule>
23
+ @end
24
+
25
+ @implementation TugboatHTTPRequestHandler {
26
+ NSMapTable *_delegates;
27
+ NSURLSession *_session;
28
+ std::mutex _mutex;
29
+ }
30
+
31
+ @synthesize moduleRegistry = _moduleRegistry;
32
+
33
+ RCT_EXPORT_MODULE()
34
+
35
+ - (float)handlerPriority
36
+ {
37
+ return 1;
38
+ }
39
+
40
+ - (void)invalidate
41
+ {
42
+ std::lock_guard<std::mutex> lock(_mutex);
43
+ [_session invalidateAndCancel];
44
+ _session = nil;
45
+ }
46
+
47
+ // Needs the lock. A nil session with delegates means invalidated.
48
+ - (BOOL)isValid
49
+ {
50
+ return (_session != nil) || (_delegates == nil);
51
+ }
52
+
53
+ // React Native's image loader (RCTImageLoader) sends its downloads through the
54
+ // same handlers as fetch, and tags each request with the NSURLProtocol property
55
+ // "trackingName" = "RCTImageLoader" (React Native sets that value nowhere else;
56
+ // fetch never sets a tracking name and React Native's own Image code never
57
+ // calls XMLHttpRequest.setTrackingName, so only an app that passes that exact
58
+ // name from JS opts a request out). Flutter's Image.network and
59
+ // Android record nothing for image loads, so these are left to React Native's
60
+ // default handler, unrecorded. A JS fetch or XHR of an image URL carries no
61
+ // such tag and is still recorded.
62
+ + (BOOL)isImageLoaderRequest:(NSURLRequest *)request
63
+ {
64
+ return [[NSURLProtocol propertyForKey:@"trackingName" inRequest:request] isEqual:@"RCTImageLoader"];
65
+ }
66
+
67
+ - (BOOL)canHandleRequest:(NSURLRequest *)request
68
+ {
69
+ NSString *scheme = request.URL.scheme.lowercaseString;
70
+ return TugboatRN.capturesNetwork && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]) &&
71
+ ![TugboatHTTPRequestHandler isImageLoaderRequest:request];
72
+ }
73
+
74
+ - (NSURLSessionDataTask *)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
75
+ {
76
+ std::lock_guard<std::mutex> lock(_mutex);
77
+ if (_session == nil && [self isValid]) {
78
+ NSOperationQueue *callbackQueue = [NSOperationQueue new];
79
+ callbackQueue.maxConcurrentOperationCount = 1;
80
+ callbackQueue.underlyingQueue = [[_moduleRegistry moduleForName:"Networking"] methodQueue];
81
+ // The configuration of RCTHTTPRequestHandler without a custom provider.
82
+ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
83
+ NSNumber *useWifiOnly = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"ReactNetworkForceWifiOnly"];
84
+ if (useWifiOnly != nil) {
85
+ configuration.allowsCellularAccess = ![useWifiOnly boolValue];
86
+ }
87
+ [configuration setHTTPShouldSetCookies:YES];
88
+ [configuration setHTTPCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
89
+ [configuration setHTTPCookieStorage:[NSHTTPCookieStorage sharedHTTPCookieStorage]];
90
+ _session = [TugboatRN instrumentedSessionWithConfiguration:configuration delegate:self queue:callbackQueue];
91
+ _delegates = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory
92
+ valueOptions:NSPointerFunctionsStrongMemory
93
+ capacity:0];
94
+ }
95
+ NSURLSessionDataTask *task = [_session dataTaskWithRequest:request];
96
+ [_delegates setObject:delegate forKey:task];
97
+ [task resume];
98
+ return task;
99
+ }
100
+
101
+ - (void)cancelRequest:(NSURLSessionDataTask *)task
102
+ {
103
+ {
104
+ std::lock_guard<std::mutex> lock(_mutex);
105
+ [_delegates removeObjectForKey:task];
106
+ }
107
+ [task cancel];
108
+ }
109
+
110
+ #pragma mark - NSURLSession delegate (as RCTHTTPRequestHandler)
111
+
112
+ - (id<RCTURLRequestDelegate>)delegateForTask:(NSURLSessionTask *)task remove:(BOOL)remove
113
+ {
114
+ std::lock_guard<std::mutex> lock(_mutex);
115
+ id<RCTURLRequestDelegate> delegate = [_delegates objectForKey:task];
116
+ if (remove) {
117
+ [_delegates removeObjectForKey:task];
118
+ }
119
+ return delegate;
120
+ }
121
+
122
+ - (void)URLSession:(NSURLSession *)session
123
+ task:(NSURLSessionTask *)task
124
+ didSendBodyData:(int64_t)bytesSent
125
+ totalBytesSent:(int64_t)totalBytesSent
126
+ totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
127
+ {
128
+ [[self delegateForTask:task remove:NO] URLRequest:task didSendDataWithProgress:totalBytesSent];
129
+ }
130
+
131
+ - (void)URLSession:(NSURLSession *)session
132
+ task:(NSURLSessionTask *)task
133
+ willPerformHTTPRedirection:(NSHTTPURLResponse *)response
134
+ newRequest:(NSURLRequest *)request
135
+ completionHandler:(void (^)(NSURLRequest *))completionHandler
136
+ {
137
+ // Cookies are reset on redirect: React Native does not let iOS handle them itself.
138
+ NSMutableURLRequest *nextRequest = [request mutableCopy];
139
+ NSArray<NSHTTPCookie *> *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
140
+ nextRequest.allHTTPHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
141
+ completionHandler(nextRequest);
142
+ }
143
+
144
+ - (void)URLSession:(NSURLSession *)session
145
+ dataTask:(NSURLSessionDataTask *)task
146
+ didReceiveResponse:(NSURLResponse *)response
147
+ completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
148
+ {
149
+ [[self delegateForTask:task remove:NO] URLRequest:task didReceiveResponse:response];
150
+ completionHandler(NSURLSessionResponseAllow);
151
+ }
152
+
153
+ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data
154
+ {
155
+ [[self delegateForTask:task remove:NO] URLRequest:task didReceiveData:data];
156
+ }
157
+
158
+ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
159
+ {
160
+ [[self delegateForTask:task remove:YES] URLRequest:task didCompleteWithError:error];
161
+ }
162
+
163
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
164
+ (const facebook::react::ObjCTurboModule::InitParams &)params
165
+ {
166
+ return nullptr;
167
+ }
168
+
169
+ @end
@@ -0,0 +1,60 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <TugboatSpec/TugboatSpec.h>
3
+
4
+ #if __has_include(<TugboatReactNative/TugboatReactNative-Swift.h>)
5
+ #import <TugboatReactNative/TugboatReactNative-Swift.h>
6
+ #else
7
+ #import "TugboatReactNative-Swift.h"
8
+ #endif
9
+
10
+ // Each method is one call to the same-named `Tugboat` function in the Swift
11
+ // host, through `TugboatRN`. Nothing here throws into the app.
12
+ @interface TugboatModule : NSObject <NativeTugboatSpec>
13
+ @end
14
+
15
+ @implementation TugboatModule
16
+
17
+ RCT_EXPORT_MODULE(Tugboat)
18
+
19
+ - (void)start:(NSDictionary *)config
20
+ {
21
+ [TugboatRN start:config ?: @{}];
22
+ }
23
+
24
+ - (void)activate:(NSString *)activationRequestId
25
+ {
26
+ [TugboatRN activate:activationRequestId];
27
+ }
28
+
29
+ - (void)deactivate
30
+ {
31
+ [TugboatRN deactivate];
32
+ }
33
+
34
+ - (void)stop
35
+ {
36
+ [TugboatRN stop];
37
+ }
38
+
39
+ - (void)setScreen:(NSString *)name instanceId:(NSString *)instanceId
40
+ {
41
+ [TugboatRN setScreen:name instanceId:instanceId];
42
+ }
43
+
44
+ - (void)setUserId:(NSString *)userId
45
+ {
46
+ [TugboatRN setUserId:userId];
47
+ }
48
+
49
+ - (void)setTraits:(NSDictionary *)traits
50
+ {
51
+ [TugboatRN setTraits:traits ?: @{}];
52
+ }
53
+
54
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
55
+ (const facebook::react::ObjCTurboModule::InitParams &)params
56
+ {
57
+ return std::make_shared<facebook::react::NativeTugboatSpecJSI>(params);
58
+ }
59
+
60
+ @end