@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.
@@ -0,0 +1,144 @@
1
+ import Foundation
2
+ import UIKit
3
+
4
+ @_spi(TugboatAdapters) import Tugboat
5
+
6
+ /// The Swift side of the React Native module: each method is one call to the
7
+ /// same-named `Tugboat` function (as `TugboatModule.kt` on Android). Events
8
+ /// are built by the shared engine, never here. Nothing throws or traps into
9
+ /// the app; a failure is logged and ignored.
10
+ @objc(TugboatRN)
11
+ public final class TugboatRN: NSObject {
12
+ // Read on React Native's network queue, written by `start`.
13
+ private static let lock = NSLock()
14
+ private static var capture = false
15
+ private static var allowHosts: Set<String> = []
16
+
17
+ /// `config` is what JavaScript passed to `Tugboat.start`.
18
+ @objc public static func start(_ config: NSDictionary) {
19
+ installSeams()
20
+ TugboatAdapters.setHostNamesScreens(true)
21
+ guard let collector = config["collector"] as? [String: Any],
22
+ let baseUrl = (collector["baseUrl"] as? String).flatMap(URL.init(string:)),
23
+ let apiKey = collector["apiKey"] as? String,
24
+ let app = config["app"] as? [String: Any]
25
+ else {
26
+ NSLog("[TugboatRN] start ignored: collector and app are required")
27
+ return
28
+ }
29
+ let info = Bundle.main.infoDictionary ?? [:]
30
+ func text(_ value: Any?) -> String? {
31
+ (value as? String).flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }
32
+ }
33
+ let appInfo = TugboatConfig.App(
34
+ name: text(app["name"]) ?? text(info["CFBundleDisplayName"]) ?? text(info["CFBundleName"]) ?? "",
35
+ version: text(app["version"]) ?? text(info["CFBundleShortVersionString"]) ?? "",
36
+ buildNumber: text(app["buildNumber"]) ?? text(info["CFBundleVersion"]) ?? "",
37
+ appId: text(app["appId"]) ?? Bundle.main.bundleIdentifier ?? "",
38
+ installationId: text(app["installationId"]) ?? "")
39
+ let hosts = (config["networkAllowHosts"] as? [Any])?.compactMap { $0 as? String } ?? []
40
+ lock.lock()
41
+ capture = (config["captureNetwork"] as? Bool) ?? true
42
+ allowHosts = Set(hosts.map { $0.lowercased() })
43
+ lock.unlock()
44
+ Tugboat.start(
45
+ TugboatConfig(
46
+ collector: .init(baseURL: baseUrl, apiKey: apiKey),
47
+ app: appInfo,
48
+ enabled: (config["enabled"] as? Bool) ?? false,
49
+ captureFocusChanges: (config["captureFocusChanges"] as? Bool) ?? false,
50
+ captureDiagnostics: (config["captureDiagnostics"] as? Bool) ?? false,
51
+ // JavaScript names every screen with setScreen; no view controller is a route.
52
+ trackHostingControllers: false,
53
+ durableOutbox: (config["durableOutbox"] as? Bool) ?? false,
54
+ sdkVersion: text(config["sdkVersion"])))
55
+ }
56
+
57
+ @objc public static func activate(_ activationRequestId: String) {
58
+ Tugboat.activate(activationRequestId: activationRequestId)
59
+ }
60
+
61
+ @objc public static func deactivate() {
62
+ Tugboat.deactivate()
63
+ }
64
+
65
+ @objc public static func stop() {
66
+ Tugboat.stop()
67
+ }
68
+
69
+ @objc public static func setScreen(_ name: String, instanceId: String?) {
70
+ let id = instanceId.flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 } ?? name
71
+ TugboatAdapters.setScreen(name: name, instanceId: id)
72
+ }
73
+
74
+ @objc public static func setUserId(_ id: String?) {
75
+ Tugboat.setUserId(id)
76
+ }
77
+
78
+ @objc public static func setTraits(_ traits: NSDictionary) {
79
+ var bag: [String: Any] = [:]
80
+ for (key, value) in traits {
81
+ if let key = key as? String { bag[key] = value }
82
+ }
83
+ Tugboat.setTraits(bag)
84
+ }
85
+
86
+ /// `<Tugboat.Sensitive>`: the Fabric view calls this on creation (main thread).
87
+ @objc public static func markSensitive(_ view: UIView) {
88
+ TugboatAdapters.markSensitive(view)
89
+ }
90
+
91
+ // MARK: Network
92
+
93
+ /// True after `start` with `captureNetwork` not false: React Native's HTTP
94
+ /// requests then go through `TugboatHTTPRequestHandler`.
95
+ @objc public static var capturesNetwork: Bool {
96
+ lock.lock()
97
+ defer { lock.unlock() }
98
+ return capture
99
+ }
100
+
101
+ /// A session that records each task as `network_call`, with React Native's
102
+ /// own handler as delegate. The route is the URL path (percent-encoded),
103
+ /// never the URL or query; empty `networkAllowHosts` records every host.
104
+ @objc public static func instrumentedSession(
105
+ configuration: URLSessionConfiguration, delegate: URLSessionDelegate, queue: OperationQueue
106
+ ) -> URLSession {
107
+ Tugboat.instrumentedSession(configuration: configuration, delegate: delegate, delegateQueue: queue) { request in
108
+ route(of: request)
109
+ }
110
+ }
111
+
112
+ private static func route(of request: URLRequest) -> String? {
113
+ guard let url = request.url else { return nil }
114
+ lock.lock()
115
+ let hosts = allowHosts
116
+ lock.unlock()
117
+ if !hosts.isEmpty, !hosts.contains((url.host ?? "").lowercased()) { return nil }
118
+ let path = URLComponents(url: url, resolvingAgainstBaseURL: false)?.percentEncodedPath ?? ""
119
+ return path.isEmpty ? "/" : path
120
+ }
121
+
122
+ // MARK: React Native views
123
+
124
+ private static var installed = false
125
+
126
+ /// What the Swift host cannot know about React Native's views: `testID` is
127
+ /// the view's `accessibilityIdentifier`, and its paragraph and image views
128
+ /// draw their own text and pixels, which the screenshot masks.
129
+ private static func installSeams() {
130
+ lock.lock()
131
+ let first = !installed
132
+ installed = true
133
+ lock.unlock()
134
+ guard first else { return }
135
+ TugboatAdapters.setViewNameProvider { $0.accessibilityIdentifier }
136
+ let paragraph = NSClassFromString("RCTParagraphComponentView")
137
+ let image = NSClassFromString("RCTImageComponentView")
138
+ TugboatAdapters.setViewRoleClassifier { cls in
139
+ if let paragraph = paragraph, cls.isSubclass(of: paragraph) { return .text }
140
+ if let image = image, cls.isSubclass(of: image) { return .image }
141
+ return nil
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,41 @@
1
+ #import <React/RCTViewComponentView.h>
2
+
3
+ #import <react/renderer/components/TugboatSpec/ComponentDescriptors.h>
4
+ #import <react/renderer/components/TugboatSpec/Props.h>
5
+
6
+ #if __has_include(<TugboatReactNative/TugboatReactNative-Swift.h>)
7
+ #import <TugboatReactNative/TugboatReactNative-Swift.h>
8
+ #else
9
+ #import "TugboatReactNative-Swift.h"
10
+ #endif
11
+
12
+ using namespace facebook::react;
13
+
14
+ // `<Tugboat.Sensitive>`: a plain view the Swift host masks with its whole
15
+ // subtree in every screenshot (`TugboatAdapters.markSensitive`).
16
+ @interface TugboatSensitiveViewComponentView : RCTViewComponentView
17
+ @end
18
+
19
+ @implementation TugboatSensitiveViewComponentView
20
+
21
+ + (ComponentDescriptorProvider)componentDescriptorProvider
22
+ {
23
+ return concreteComponentDescriptorProvider<TugboatSensitiveViewComponentDescriptor>();
24
+ }
25
+
26
+ - (instancetype)initWithFrame:(CGRect)frame
27
+ {
28
+ if (self = [super initWithFrame:frame]) {
29
+ static const auto defaultProps = std::make_shared<const TugboatSensitiveViewProps>();
30
+ _props = defaultProps;
31
+ [TugboatRN markSensitive:self];
32
+ }
33
+ return self;
34
+ }
35
+
36
+ @end
37
+
38
+ Class<RCTComponentViewProtocol> TugboatSensitiveViewCls(void)
39
+ {
40
+ return TugboatSensitiveViewComponentView.class;
41
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@tugboat-ai/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.8",
4
+ "description": "Tugboat session capture for React Native (Android and iOS).",
5
+ "license": "AGPL-3.0-only",
6
+ "homepage": "https://github.com/blendto/tugboat-mobile-sdk/tree/main/sdks/react-native#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/blendto/tugboat-mobile-sdk.git",
10
+ "directory": "sdks/react-native"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/blendto/tugboat-mobile-sdk/issues"
14
+ },
15
+ "main": "src/index.ts",
16
+ "types": "src/index.ts",
17
+ "files": [
18
+ "src",
19
+ "android",
20
+ "ios",
21
+ "TugboatReactNative.podspec",
22
+ "LICENSE",
23
+ "CHANGELOG.md",
24
+ "!android/build",
25
+ "!android/.gradle",
26
+ "!android/.cxx"
27
+ ],
28
+ "peerDependencies": {
29
+ "@react-navigation/native": "*",
30
+ "react": "*",
31
+ "react-native": ">=0.88.0"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "@react-navigation/native": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "codegenConfig": {
39
+ "name": "TugboatSpec",
40
+ "type": "all",
41
+ "jsSrcsDir": "src",
42
+ "android": {
43
+ "javaPackageName": "com.tugboat.reactnative"
44
+ },
45
+ "ios": {
46
+ "modulesConformingToProtocol": {
47
+ "RCTURLRequestHandler": [
48
+ "TugboatHTTPRequestHandler"
49
+ ]
50
+ },
51
+ "components": {
52
+ "TugboatSensitiveView": {
53
+ "className": "TugboatSensitiveViewComponentView"
54
+ }
55
+ }
56
+ }
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }
@@ -0,0 +1,18 @@
1
+ import type { TurboModule } from 'react-native';
2
+ import { TurboModuleRegistry } from 'react-native';
3
+
4
+ // Codegen spec. Every method is one call to the same-named `Tugboat` function
5
+ // in tugboat-android or the Swift host. Events are built by the shared engine,
6
+ // never in JavaScript.
7
+ export interface Spec extends TurboModule {
8
+ start(config: Object): void;
9
+ activate(activationRequestId: string): void;
10
+ deactivate(): void;
11
+ stop(): void;
12
+ setScreen(name: string, instanceId: string | null): void;
13
+ setUserId(id: string | null): void;
14
+ setTraits(traits: Object): void;
15
+ }
16
+
17
+ // `get`, not `getEnforcing`: the module does not exist on other platforms.
18
+ export default TurboModuleRegistry.get<Spec>('Tugboat');
@@ -0,0 +1,9 @@
1
+ import type { ViewProps } from 'react-native';
2
+ import { codegenNativeComponent } from 'react-native';
3
+
4
+ export interface NativeProps extends ViewProps {}
5
+
6
+ // A plain view that marks itself sensitive (`tugboatSensitive()` on Android,
7
+ // `TugboatAdapters.markSensitive` on iOS): screenshots mask it and everything
8
+ // below it.
9
+ export default codegenNativeComponent<NativeProps>('TugboatSensitiveView');
package/src/index.ts ADDED
@@ -0,0 +1,139 @@
1
+ import React from 'react';
2
+ import { Platform } from 'react-native';
3
+ import type { ViewProps } from 'react-native';
4
+ import NativeTugboat from './NativeTugboat';
5
+ import { SDK_VERSION } from './sdkVersion';
6
+
7
+ export interface TugboatConfig {
8
+ collector: { baseUrl: string; apiKey: string };
9
+ app: {
10
+ name: string;
11
+ /** Default: the app's package info. */
12
+ version?: string;
13
+ buildNumber?: string;
14
+ appId?: string;
15
+ installationId?: string;
16
+ };
17
+ /** Default false: dormant until `activate()`. */
18
+ enabled?: boolean;
19
+ /** Only `'allTextAndMedia'` exists; any other string becomes it. */
20
+ maskLevel?: 'allTextAndMedia';
21
+ captureFocusChanges?: boolean;
22
+ captureSystemInput?: boolean;
23
+ captureDiagnostics?: boolean;
24
+ durableOutbox?: boolean;
25
+ /** Default true. */
26
+ captureNetwork?: boolean;
27
+ /** Record only calls to these hosts. Empty (default): every host. */
28
+ networkAllowHosts?: string[];
29
+ }
30
+
31
+ let warned = false;
32
+
33
+ const supported = Platform.OS === 'android' || Platform.OS === 'ios';
34
+
35
+ // Nothing here throws into the app. Where the native module is missing (an
36
+ // unsupported platform, or one that is not linked) every call is a no-op with
37
+ // one warning.
38
+ function call(name: string, run: () => void): void {
39
+ try {
40
+ if (!supported || NativeTugboat == null) {
41
+ if (!warned) {
42
+ warned = true;
43
+ console.warn(
44
+ supported
45
+ ? `[Tugboat] ${name}: the native module is not linked; ignored.`
46
+ : `[Tugboat] ${name}: only Android and iOS are supported; ignored.`,
47
+ );
48
+ }
49
+ return;
50
+ }
51
+ run();
52
+ } catch (e) {
53
+ console.warn(`[Tugboat] ${name} failed`, e);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Wrap anything that must never be recorded (card fields, OTP codes, ...). The
59
+ * native capture masks this view and everything below it.
60
+ */
61
+ function Sensitive(props: ViewProps) {
62
+ if (!supported) {
63
+ return React.createElement(React.Fragment, null, props.children);
64
+ }
65
+ const Native = require('./TugboatSensitiveViewNativeComponent').default;
66
+ return React.createElement(Native, { ...props, collapsable: false });
67
+ }
68
+
69
+ /** The focused route path (`Main/Feed`) and its leaf route key, from a React Navigation state. */
70
+ function focusedRoute(state: any): { name: string; key: string } | null {
71
+ const names: string[] = [];
72
+ let key = '';
73
+ while (state && Array.isArray(state.routes) && state.routes.length > 0) {
74
+ const route = state.routes[Math.min(state.index ?? 0, state.routes.length - 1)];
75
+ names.push(String(route.name));
76
+ key = String(route.key ?? route.name);
77
+ state = route.state;
78
+ }
79
+ return names.length > 0 ? { name: names.join('/'), key } : null;
80
+ }
81
+
82
+ export const Tugboat = {
83
+ start(config: TugboatConfig): void {
84
+ call('start', () => NativeTugboat!.start({ ...config, sdkVersion: SDK_VERSION }));
85
+ },
86
+ activate(activationRequestId: string): void {
87
+ call('activate', () => NativeTugboat!.activate(activationRequestId));
88
+ },
89
+ deactivate(): void {
90
+ call('deactivate', () => NativeTugboat!.deactivate());
91
+ },
92
+ stop(): void {
93
+ call('stop', () => NativeTugboat!.stop());
94
+ },
95
+ /**
96
+ * Names the current screen (a custom navigator). A new `instanceId` is a push, one
97
+ * already seen is a pop back to it. `instanceId` defaults to `name`.
98
+ */
99
+ setScreen(name: string, instanceId?: string): void {
100
+ call('setScreen', () => NativeTugboat!.setScreen(name, instanceId ?? null));
101
+ },
102
+ /**
103
+ * React Navigation: one `route_change` per navigation, named by the focused route
104
+ * path. Pass the ref given to `NavigationContainer`. Returns a function that stops
105
+ * tracking. Never throws.
106
+ */
107
+ trackNavigation(navigationRef: any): () => void {
108
+ let last = '';
109
+ const report = () => {
110
+ try {
111
+ const focused = focusedRoute(navigationRef?.getRootState?.());
112
+ if (focused == null) return;
113
+ const id = `${focused.name}\u0000${focused.key}`;
114
+ if (id === last) return;
115
+ Tugboat.setScreen(focused.name, focused.key);
116
+ last = id;
117
+ } catch (e) {
118
+ console.warn('[Tugboat] trackNavigation failed', e);
119
+ }
120
+ };
121
+ try {
122
+ const subs = [navigationRef.addListener('state', report), navigationRef.addListener('ready', report)];
123
+ if (navigationRef.isReady?.()) report(); // called after the container is ready
124
+ return () => subs.forEach((unsubscribe: () => void) => unsubscribe());
125
+ } catch (e) {
126
+ console.warn('[Tugboat] trackNavigation failed', e);
127
+ return () => {};
128
+ }
129
+ },
130
+ setUserId(id: string | null): void {
131
+ call('setUserId', () => NativeTugboat!.setUserId(id));
132
+ },
133
+ setTraits(traits: Record<string, unknown>): void {
134
+ call('setTraits', () => NativeTugboat!.setTraits({ ...traits }));
135
+ },
136
+ Sensitive,
137
+ };
138
+
139
+ export default Tugboat;
@@ -0,0 +1,2 @@
1
+ /** `package.json` version; sent as `X-Sdk-Version`, as Flutter sends its package version. Bump with it. */
2
+ export const SDK_VERSION = '0.0.8';