@mobileinspect/react-native 0.0.0-stage → 0.1.0

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.
Files changed (34) hide show
  1. package/LICENSE +21 -0
  2. package/MobileInspectReactNative.podspec +27 -0
  3. package/README.md +51 -2
  4. package/android/build.gradle +79 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectModule.kt +36 -0
  7. package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectPackage.kt +52 -0
  8. package/ios/MobileInspectCore/ConsoleCapture.swift +113 -0
  9. package/ios/MobileInspectCore/HARExporter.swift +72 -0
  10. package/ios/MobileInspectCore/InspectorCore.swift +173 -0
  11. package/ios/MobileInspectCore/InspectorDatabase.swift +337 -0
  12. package/ios/MobileInspectCore/InspectorPresenter.swift +74 -0
  13. package/ios/MobileInspectCore/InspectorRootView.swift +167 -0
  14. package/ios/MobileInspectCore/InspectorViewModel.swift +80 -0
  15. package/ios/MobileInspectCore/MobileInspect.swift +78 -0
  16. package/ios/MobileInspectCore/MobileInspectConfig.swift +63 -0
  17. package/ios/MobileInspectCore/MobileInspectURLProtocol.swift +225 -0
  18. package/ios/MobileInspectCore/Models.swift +96 -0
  19. package/ios/MobileInspectCore/NetworkDetailView.swift +204 -0
  20. package/ios/MobileInspectCore/Redactor.swift +87 -0
  21. package/ios/MobileInspectCore/SessionExporter.swift +70 -0
  22. package/ios/MobileInspectCore/UISupport.swift +86 -0
  23. package/ios/MobileInspectCore/URLSessionSwizzler.swift +55 -0
  24. package/ios/MobileInspectCore/ZipWriter.swift +75 -0
  25. package/ios/MobileInspectModule.mm +85 -0
  26. package/ios/PrivacyInfo.xcprivacy +23 -0
  27. package/lib/NativeMobileInspect.d.ts +10 -0
  28. package/lib/NativeMobileInspect.js +2 -0
  29. package/lib/index.d.ts +38 -0
  30. package/lib/index.js +102 -0
  31. package/package.json +71 -4
  32. package/scripts/sync-native.js +41 -0
  33. package/src/NativeMobileInspect.ts +12 -0
  34. package/src/index.ts +117 -0
@@ -0,0 +1,87 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// Masks sensitive headers and JSON/form body values (FR-5).
5
+ /// All work happens in memory before anything is written to SQLite.
6
+ final class Redactor: @unchecked Sendable {
7
+ static let placeholder = "***REDACTED***"
8
+
9
+ private let headerSet: Set<String>
10
+ private let keySet: Set<String>
11
+ private let keyRegex: NSRegularExpression?
12
+
13
+ init(headers: [String], bodyKeys: [String]) {
14
+ headerSet = Set(headers.map { $0.lowercased() })
15
+ keySet = Set(bodyKeys.map { $0.lowercased() })
16
+ if bodyKeys.isEmpty {
17
+ keyRegex = nil
18
+ } else {
19
+ let alternation = bodyKeys.map { NSRegularExpression.escapedPattern(for: $0) }.joined(separator: "|")
20
+ // "key" : "value" | "key" : bareword (fallback for non-parsable/truncated JSON)
21
+ keyRegex = try? NSRegularExpression(
22
+ pattern: "\"(\(alternation))\"\\s*:\\s*(\"(?:[^\"\\\\]|\\\\.)*\"?|[^,}\\]\\s]+)",
23
+ options: [.caseInsensitive]
24
+ )
25
+ }
26
+ }
27
+
28
+ func redactHeaders(_ headers: [String: String]) -> [String: String] {
29
+ var out = headers
30
+ for key in headers.keys where headerSet.contains(key.lowercased()) {
31
+ out[key] = Self.placeholder
32
+ }
33
+ return out
34
+ }
35
+
36
+ func redactBody(_ body: String?) -> String? {
37
+ guard let body, !body.isEmpty, !keySet.isEmpty else { return body }
38
+ let trimmed = body.trimmingCharacters(in: .whitespacesAndNewlines)
39
+
40
+ if trimmed.hasPrefix("{") || trimmed.hasPrefix("[") {
41
+ if let data = trimmed.data(using: .utf8),
42
+ let obj = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) {
43
+ let redacted = redactValue(obj)
44
+ if JSONSerialization.isValidJSONObject(redacted),
45
+ let out = try? JSONSerialization.data(withJSONObject: redacted, options: [.withoutEscapingSlashes]),
46
+ let s = String(data: out, encoding: .utf8) {
47
+ return s
48
+ }
49
+ }
50
+ return regexRedact(body)
51
+ }
52
+
53
+ // application/x-www-form-urlencoded style: a=1&password=x
54
+ if !trimmed.contains("\n"), trimmed.contains("=") {
55
+ return trimmed.split(separator: "&", omittingEmptySubsequences: false).map { pair -> String in
56
+ guard let eq = pair.firstIndex(of: "=") else { return String(pair) }
57
+ let key = String(pair[pair.startIndex..<eq])
58
+ let decoded = key.removingPercentEncoding ?? key
59
+ return keySet.contains(decoded.lowercased()) ? "\(key)=\(Self.placeholder)" : String(pair)
60
+ }.joined(separator: "&")
61
+ }
62
+ return body
63
+ }
64
+
65
+ private func redactValue(_ value: Any) -> Any {
66
+ if let dict = value as? [String: Any] {
67
+ var out: [String: Any] = [:]
68
+ for (k, v) in dict {
69
+ out[k] = keySet.contains(k.lowercased()) ? Self.placeholder : redactValue(v)
70
+ }
71
+ return out
72
+ }
73
+ if let arr = value as? [Any] { return arr.map(redactValue) }
74
+ return value
75
+ }
76
+
77
+ private func regexRedact(_ text: String) -> String {
78
+ guard let keyRegex else { return text }
79
+ let range = NSRange(text.startIndex..., in: text)
80
+ return keyRegex.stringByReplacingMatches(
81
+ in: text, options: [], range: range,
82
+ withTemplate: "\"$1\":\"\(Self.placeholder)\""
83
+ )
84
+ }
85
+ }
86
+
87
+ #endif
@@ -0,0 +1,70 @@
1
+ #if DEBUG
2
+ import Foundation
3
+ #if canImport(UIKit)
4
+ import UIKit
5
+ #endif
6
+ import os
7
+
8
+ /// One-tap session export: `network.har`, `console.log`, `device_info.json` zipped (FR-6).
9
+ enum SessionExporter {
10
+ static func consoleText(_ logs: [ConsoleLog]) -> String {
11
+ let f = DateFormatter()
12
+ f.locale = Locale(identifier: "en_US_POSIX")
13
+ f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
14
+ return logs.sorted { $0.timestamp < $1.timestamp }.map { l in
15
+ let t = f.string(from: Date(timeIntervalSince1970: Double(l.timestamp) / 1000))
16
+ return "\(t) [\(l.level.uppercased())] [\(l.sourceLayer)]\(l.tag.map { " \($0):" } ?? "") \(l.message)"
17
+ }.joined(separator: "\n")
18
+ }
19
+
20
+ static func deviceInfo() -> Data {
21
+ var info: [String: Any] = [
22
+ "osVersion": ProcessInfo.processInfo.operatingSystemVersionString,
23
+ "appVersion": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown",
24
+ "appBuild": Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "unknown",
25
+ "bundleId": Bundle.main.bundleIdentifier ?? "unknown",
26
+ "totalMemoryBytes": ProcessInfo.processInfo.physicalMemory,
27
+ "sdkVersion": MobileInspect.sdkVersion,
28
+ ]
29
+ #if os(iOS)
30
+ info["deviceModel"] = modelIdentifier()
31
+ info["systemName"] = "iOS"
32
+ info["availableMemoryBytes"] = os_proc_available_memory()
33
+ #endif
34
+ return (try? JSONSerialization.data(withJSONObject: info, options: [.prettyPrinted, .sortedKeys])) ?? Data("{}".utf8)
35
+ }
36
+
37
+ #if os(iOS)
38
+ private static func modelIdentifier() -> String {
39
+ var sys = utsname()
40
+ uname(&sys)
41
+ return withUnsafePointer(to: &sys.machine) {
42
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(_SYS_NAMELEN)) { String(cString: $0) }
43
+ }
44
+ }
45
+ #endif
46
+
47
+ /// Builds the zip in memory (bodies are capped per record) and writes it to a temp file.
48
+ static func makeZip(core: InspectorCore) async -> URL? {
49
+ let data: Data = await withCheckedContinuation { cont in
50
+ DispatchQueue.global(qos: .utility).async {
51
+ core.database.flush()
52
+ var zip = ZipWriter()
53
+ zip.add(name: "network.har", data: HARExporter.build(calls: core.database.allNetworkCalls()))
54
+ zip.add(name: "console.log", data: Data(consoleText(core.database.allLogs()).utf8))
55
+ zip.add(name: "device_info.json", data: deviceInfo())
56
+ cont.resume(returning: zip.finish())
57
+ }
58
+ }
59
+ let stamp = Int(Date().timeIntervalSince1970)
60
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("mobileinspect-session-\(stamp).zip")
61
+ do {
62
+ try data.write(to: url, options: .atomic)
63
+ return url
64
+ } catch {
65
+ return nil
66
+ }
67
+ }
68
+ }
69
+
70
+ #endif
@@ -0,0 +1,86 @@
1
+ #if DEBUG
2
+ #if canImport(UIKit)
3
+ import SwiftUI
4
+ import UIKit
5
+
6
+ struct ShareSheet: UIViewControllerRepresentable {
7
+ let items: [Any]
8
+ func makeUIViewController(context: Context) -> UIActivityViewController {
9
+ UIActivityViewController(activityItems: items, applicationActivities: nil)
10
+ }
11
+ func updateUIViewController(_ vc: UIActivityViewController, context: Context) {}
12
+ }
13
+
14
+ /// Wrapper so `.sheet(item:)` can present share content.
15
+ struct ShareItem: Identifiable {
16
+ let id = UUID()
17
+ let items: [Any]
18
+ }
19
+
20
+ enum Palette {
21
+ static func status(_ code: Int) -> Color {
22
+ switch code {
23
+ case 200..<300: return .green
24
+ case 300..<400: return .blue
25
+ case 400..<500: return .orange
26
+ default: return .red // 5xx and network failures (0)
27
+ }
28
+ }
29
+
30
+ static func phase(_ name: String) -> Color {
31
+ switch name {
32
+ case "DNS": return .teal
33
+ case "Connect": return .orange
34
+ case "TLS": return .purple
35
+ case "Send": return .blue
36
+ case "Wait": return .green
37
+ case "Receive": return .indigo
38
+ default: return .gray
39
+ }
40
+ }
41
+
42
+ static func level(_ level: String) -> Color {
43
+ switch level {
44
+ case "error": return .red
45
+ case "warn": return .orange
46
+ case "debug": return .gray
47
+ default: return .blue
48
+ }
49
+ }
50
+ }
51
+
52
+ struct Badge: View {
53
+ let text: String
54
+ let color: Color
55
+ var body: some View {
56
+ Text(text)
57
+ .font(.system(size: 11, weight: .bold, design: .monospaced))
58
+ .padding(.horizontal, 6).padding(.vertical, 2)
59
+ .foregroundColor(.white)
60
+ .background(color)
61
+ .clipShape(RoundedRectangle(cornerRadius: 4))
62
+ }
63
+ }
64
+
65
+ enum Format {
66
+ static func time(_ ms: Int64) -> String {
67
+ let f = DateFormatter()
68
+ f.dateFormat = "HH:mm:ss.SSS"
69
+ return f.string(from: Date(timeIntervalSince1970: Double(ms) / 1000))
70
+ }
71
+
72
+ static func bytes(_ n: Int64) -> String {
73
+ ByteCountFormatter.string(fromByteCount: n, countStyle: .file)
74
+ }
75
+
76
+ static func pretty(json: String?) -> String? {
77
+ guard let json, let data = json.data(using: .utf8),
78
+ let obj = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]),
79
+ let out = try? JSONSerialization.data(withJSONObject: obj, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes, .fragmentsAllowed]),
80
+ let s = String(data: out, encoding: .utf8) else { return nil }
81
+ return s
82
+ }
83
+ }
84
+ #endif
85
+
86
+ #endif
@@ -0,0 +1,55 @@
1
+ #if DEBUG
2
+ import Foundation
3
+ import ObjectiveC
4
+
5
+ /// Injects `MobileInspectURLProtocol` into every `.default` / `.ephemeral` session configuration so third-party
6
+ /// libraries (Alamofire, Kingfisher, React Native's RCTHTTPRequestHandler, ...) are captured with no code changes.
7
+ enum URLSessionSwizzler {
8
+ private static let installed = Locked(false)
9
+
10
+ static func install() {
11
+ let first = installed.withLock { done -> Bool in
12
+ if done { return false }
13
+ done = true
14
+ return true
15
+ }
16
+ guard first else { return }
17
+
18
+ // ObjC names of `URLSessionConfiguration.default` / `.ephemeral`.
19
+ swap(Selector(("defaultSessionConfiguration")), #selector(URLSessionConfiguration.mi_default))
20
+ swap(Selector(("ephemeralSessionConfiguration")), #selector(URLSessionConfiguration.mi_ephemeral))
21
+ // URLSession.shared is not built from a swizzled configuration, so register globally as well.
22
+ URLProtocol.registerClass(MobileInspectURLProtocol.self)
23
+ }
24
+
25
+ private static func swap(_ original: Selector, _ replacement: Selector) {
26
+ let cls: AnyClass = URLSessionConfiguration.self
27
+ guard let o = class_getClassMethod(cls, original), let r = class_getClassMethod(cls, replacement) else { return }
28
+ method_exchangeImplementations(o, r)
29
+ }
30
+ }
31
+
32
+ extension URLSessionConfiguration {
33
+ /// After the exchange, `mi_default` holds the original implementation.
34
+ @objc class func mi_default() -> URLSessionConfiguration {
35
+ let config = mi_default()
36
+ config.mi_injectProtocol()
37
+ return config
38
+ }
39
+
40
+ @objc class func mi_ephemeral() -> URLSessionConfiguration {
41
+ let config = mi_ephemeral()
42
+ config.mi_injectProtocol()
43
+ return config
44
+ }
45
+
46
+ fileprivate func mi_injectProtocol() {
47
+ var classes = protocolClasses ?? []
48
+ if !classes.contains(where: { $0 == MobileInspectURLProtocol.self }) {
49
+ classes.insert(MobileInspectURLProtocol.self, at: 0)
50
+ protocolClasses = classes
51
+ }
52
+ }
53
+ }
54
+
55
+ #endif
@@ -0,0 +1,75 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// Minimal ZIP writer (stored entries, no compression). Enough for three small text files and dependency-free.
5
+ struct ZipWriter {
6
+ private var body = Data()
7
+ private var central = Data()
8
+ private var count: UInt16 = 0
9
+
10
+ private static let crcTable: [UInt32] = (0..<256).map { i -> UInt32 in
11
+ var c = UInt32(i)
12
+ for _ in 0..<8 { c = (c & 1) != 0 ? 0xEDB8_8320 ^ (c >> 1) : c >> 1 }
13
+ return c
14
+ }
15
+
16
+ static func crc32(_ data: Data) -> UInt32 {
17
+ var c: UInt32 = 0xFFFF_FFFF
18
+ for b in data { c = crcTable[Int((c ^ UInt32(b)) & 0xFF)] ^ (c >> 8) }
19
+ return c ^ 0xFFFF_FFFF
20
+ }
21
+
22
+ mutating func add(name: String, data: Data, date: Date = Date()) {
23
+ let nameData = Data(name.utf8)
24
+ let crc = Self.crc32(data)
25
+ let (dosTime, dosDate) = Self.dos(date)
26
+ let offset = UInt32(body.count)
27
+
28
+ var local = Data()
29
+ local.le(UInt32(0x0403_4B50)); local.le(UInt16(20)); local.le(UInt16(0x0800)); local.le(UInt16(0))
30
+ local.le(dosTime); local.le(dosDate); local.le(crc)
31
+ local.le(UInt32(data.count)); local.le(UInt32(data.count))
32
+ local.le(UInt16(nameData.count)); local.le(UInt16(0))
33
+ local.append(nameData)
34
+ body.append(local); body.append(data)
35
+
36
+ var c = Data()
37
+ c.le(UInt32(0x0201_4B50)); c.le(UInt16(20)); c.le(UInt16(20)); c.le(UInt16(0x0800)); c.le(UInt16(0))
38
+ c.le(dosTime); c.le(dosDate); c.le(crc)
39
+ c.le(UInt32(data.count)); c.le(UInt32(data.count))
40
+ c.le(UInt16(nameData.count)); c.le(UInt16(0)); c.le(UInt16(0)); c.le(UInt16(0)); c.le(UInt16(0))
41
+ c.le(UInt32(0)); c.le(offset)
42
+ c.append(nameData)
43
+ central.append(c)
44
+ count += 1
45
+ }
46
+
47
+ func finish() -> Data {
48
+ var out = body
49
+ let centralOffset = UInt32(body.count)
50
+ out.append(central)
51
+ var end = Data()
52
+ end.le(UInt32(0x0605_4B50)); end.le(UInt16(0)); end.le(UInt16(0))
53
+ end.le(count); end.le(count)
54
+ end.le(UInt32(central.count)); end.le(centralOffset); end.le(UInt16(0))
55
+ out.append(end)
56
+ return out
57
+ }
58
+
59
+ private static func dos(_ date: Date) -> (UInt16, UInt16) {
60
+ let c = Calendar(identifier: .gregorian).dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
61
+ let time = UInt16((c.hour ?? 0) << 11 | (c.minute ?? 0) << 5 | ((c.second ?? 0) / 2))
62
+ let year = max(1980, c.year ?? 1980) - 1980
63
+ let day = UInt16(year << 9 | (c.month ?? 1) << 5 | (c.day ?? 1))
64
+ return (time, day)
65
+ }
66
+ }
67
+
68
+ private extension Data {
69
+ mutating func le<T: FixedWidthInteger>(_ value: T) {
70
+ var v = value.littleEndian
71
+ Swift.withUnsafeBytes(of: &v) { append(contentsOf: $0) }
72
+ }
73
+ }
74
+
75
+ #endif
@@ -0,0 +1,85 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #import <React/RCTHTTPRequestHandler.h>
3
+ #import <MobileInspectSpec/MobileInspectSpec.h>
4
+
5
+ // The Swift SDK sources are compiled into this pod inside `#if DEBUG`, so Release builds contain no inspector code.
6
+ #if DEBUG
7
+ #if __has_include("MobileInspectReactNative-Swift.h")
8
+ #import "MobileInspectReactNative-Swift.h"
9
+ #else
10
+ #import <MobileInspectReactNative/MobileInspectReactNative-Swift.h>
11
+ #endif
12
+ #endif
13
+
14
+ #if DEBUG
15
+ // Runs at image load, before React Native creates its URLSession, so JS fetch/XHR traffic is tagged
16
+ // "react-native". A constructor is used because RCT_EXPORT_MODULE already defines +load.
17
+ // The configuration mirrors React Native's own defaults (RCTHTTPRequestHandler).
18
+ // An app that sets its own provider later replaces this one; capture still works, tagged "native".
19
+ __attribute__((constructor)) static void MobileInspectInstallReactNativeSessionProvider(void)
20
+ {
21
+ RCTSetCustomNSURLSessionConfigurationProvider(^NSURLSessionConfiguration *{
22
+ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
23
+ NSNumber *useWifiOnly = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"ReactNetworkForceWifiOnly"];
24
+ if (useWifiOnly != nil) {
25
+ configuration.allowsCellularAccess = ![useWifiOnly boolValue];
26
+ }
27
+ [configuration setHTTPShouldSetCookies:YES];
28
+ [configuration setHTTPCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
29
+ [configuration setHTTPCookieStorage:[NSHTTPCookieStorage sharedHTTPCookieStorage]];
30
+ [MobileInspect injectReactNativeCaptureInto:configuration];
31
+ return configuration;
32
+ });
33
+ }
34
+ #endif
35
+
36
+ @interface MobileInspectModule : NSObject <NativeMobileInspectSpec>
37
+ @end
38
+
39
+ /// TurboModule bridging JS to the native MobileInspect Swift SDK. Holds no storage or UI of its own.
40
+ @implementation MobileInspectModule
41
+
42
+ RCT_EXPORT_MODULE(MobileInspectModule)
43
+
44
+
45
+ - (void)configure:(NSString *)configJson
46
+ {
47
+ #if DEBUG
48
+ [MobileInspect startWithJSON:configJson];
49
+ #endif
50
+ }
51
+
52
+ - (void)openInspector
53
+ {
54
+ #if DEBUG
55
+ [MobileInspect open];
56
+ #endif
57
+ }
58
+
59
+ - (void)closeInspector
60
+ {
61
+ #if DEBUG
62
+ [MobileInspect close];
63
+ #endif
64
+ }
65
+
66
+ - (void)clearAll
67
+ {
68
+ #if DEBUG
69
+ [MobileInspect clearAll];
70
+ #endif
71
+ }
72
+
73
+ - (void)logConsoleMessage:(NSString *)level tag:(NSString *)tag message:(NSString *)message
74
+ {
75
+ #if DEBUG
76
+ [MobileInspect logConsoleMessageWithLevel:level tag:tag message:message];
77
+ #endif
78
+ }
79
+
80
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params
81
+ {
82
+ return std::make_shared<facebook::react::NativeMobileInspectSpecJSI>(params);
83
+ }
84
+
85
+ @end
@@ -0,0 +1,23 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSPrivacyTracking</key>
6
+ <false/>
7
+ <key>NSPrivacyTrackingDomains</key>
8
+ <array/>
9
+ <key>NSPrivacyCollectedDataTypes</key>
10
+ <array/>
11
+ <key>NSPrivacyAccessedAPITypes</key>
12
+ <array>
13
+ <dict>
14
+ <key>NSPrivacyAccessedAPIType</key>
15
+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
16
+ <key>NSPrivacyAccessedAPITypeReasons</key>
17
+ <array>
18
+ <string>C617.1</string>
19
+ </array>
20
+ </dict>
21
+ </array>
22
+ </dict>
23
+ </plist>
@@ -0,0 +1,10 @@
1
+ import type { TurboModule } from 'react-native';
2
+ export interface Spec extends TurboModule {
3
+ configure(configJson: string): void;
4
+ openInspector(): void;
5
+ closeInspector(): void;
6
+ clearAll(): void;
7
+ logConsoleMessage(level: string, tag: string, message: string): void;
8
+ }
9
+ declare const _default: Spec;
10
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { TurboModuleRegistry } from 'react-native';
2
+ export default TurboModuleRegistry.getEnforcing('MobileInspectModule');
package/lib/index.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ export interface MobileInspectConfig {
2
+ /** Defaults to `__DEV__`. When false, nothing is captured and the console is left untouched. */
3
+ enabled?: boolean;
4
+ /** Open the inspector on device shake. Default true. */
5
+ shakeToOpen?: boolean;
6
+ /** Oldest HTTP rows are pruned beyond this. Default 500. */
7
+ maxNetworkRecords?: number;
8
+ /** Oldest console rows are pruned beyond this. Default 5000. */
9
+ maxLogRecords?: number;
10
+ /** Larger payloads are truncated with a `[TRUNCATED]` marker. Default 262144. */
11
+ maxBodySizeBytes?: number;
12
+ /** Case-insensitive. Default Authorization, Cookie, Set-Cookie, X-Api-Key. */
13
+ redactedHeaders?: string[];
14
+ /** Default password, token, secret, access_token, refresh_token. */
15
+ redactedBodyKeys?: string[];
16
+ /** Hostnames excluded from network capture, e.g. the local Metro bundler. */
17
+ ignoredHosts?: string[];
18
+ }
19
+ /** Formats console arguments the way a developer expects to read them. */
20
+ export declare function formatConsoleArgs(args: unknown[]): string;
21
+ /**
22
+ * Configures the native inspector and starts capturing `console.*`. Call once, as early as possible
23
+ * (top of index.js). Network capture is done natively (OkHttp on Android, URLSession on iOS).
24
+ */
25
+ export declare function configure(config?: MobileInspectConfig): void;
26
+ /** Opens the native inspector overlay. */
27
+ export declare function open(): void;
28
+ /** Closes the native inspector overlay. */
29
+ export declare function close(): void;
30
+ /** Deletes all captured network calls and console logs. */
31
+ export declare function clearAll(): void;
32
+ declare const MobileInspect: {
33
+ configure: typeof configure;
34
+ open: typeof open;
35
+ close: typeof close;
36
+ clearAll: typeof clearAll;
37
+ };
38
+ export default MobileInspect;
package/lib/index.js ADDED
@@ -0,0 +1,102 @@
1
+ import NativeMobileInspect from './NativeMobileInspect';
2
+ const LEVELS = ['log', 'info', 'warn', 'error', 'debug'];
3
+ const TAG = 'JS';
4
+ const originals = {};
5
+ let proxyInstalled = false;
6
+ // Set while forwarding so that anything the bridge logs cannot re-enter the proxy.
7
+ let forwarding = false;
8
+ function stringify(value) {
9
+ if (typeof value === 'string')
10
+ return value;
11
+ if (value instanceof Error)
12
+ return value.stack ?? `${value.name}: ${value.message}`;
13
+ if (value === undefined)
14
+ return 'undefined';
15
+ if (typeof value === 'function')
16
+ return `[Function ${value.name || 'anonymous'}]`;
17
+ if (typeof value === 'symbol' || typeof value === 'bigint')
18
+ return String(value);
19
+ try {
20
+ const seen = new WeakSet();
21
+ return JSON.stringify(value, (_key, v) => {
22
+ if (typeof v === 'bigint')
23
+ return String(v);
24
+ if (typeof v === 'object' && v !== null) {
25
+ if (seen.has(v))
26
+ return '[Circular]';
27
+ seen.add(v);
28
+ }
29
+ return v;
30
+ });
31
+ }
32
+ catch {
33
+ return String(value);
34
+ }
35
+ }
36
+ /** Formats console arguments the way a developer expects to read them. */
37
+ export function formatConsoleArgs(args) {
38
+ return args.map(stringify).join(' ');
39
+ }
40
+ function installConsoleProxy() {
41
+ if (proxyInstalled)
42
+ return;
43
+ proxyInstalled = true;
44
+ for (const level of LEVELS) {
45
+ const original = console[level];
46
+ if (typeof original !== 'function')
47
+ continue;
48
+ originals[level] = original;
49
+ console[level] = (...args) => {
50
+ // Always invoke the original handler first so Metro/Logcat/Xcode output is unchanged.
51
+ original.apply(console, args);
52
+ if (forwarding)
53
+ return;
54
+ forwarding = true;
55
+ try {
56
+ NativeMobileInspect.logConsoleMessage(level, TAG, formatConsoleArgs(args));
57
+ }
58
+ catch {
59
+ // Never let inspection break the app.
60
+ }
61
+ finally {
62
+ forwarding = false;
63
+ }
64
+ };
65
+ }
66
+ }
67
+ function restoreConsole() {
68
+ if (!proxyInstalled)
69
+ return;
70
+ for (const level of LEVELS) {
71
+ const original = originals[level];
72
+ if (original)
73
+ console[level] = original;
74
+ }
75
+ proxyInstalled = false;
76
+ }
77
+ /**
78
+ * Configures the native inspector and starts capturing `console.*`. Call once, as early as possible
79
+ * (top of index.js). Network capture is done natively (OkHttp on Android, URLSession on iOS).
80
+ */
81
+ export function configure(config = {}) {
82
+ const enabled = config.enabled ?? __DEV__;
83
+ NativeMobileInspect.configure(JSON.stringify({ ...config, enabled }));
84
+ if (enabled)
85
+ installConsoleProxy();
86
+ else
87
+ restoreConsole();
88
+ }
89
+ /** Opens the native inspector overlay. */
90
+ export function open() {
91
+ NativeMobileInspect.openInspector();
92
+ }
93
+ /** Closes the native inspector overlay. */
94
+ export function close() {
95
+ NativeMobileInspect.closeInspector();
96
+ }
97
+ /** Deletes all captured network calls and console logs. */
98
+ export function clearAll() {
99
+ NativeMobileInspect.clearAll();
100
+ }
101
+ const MobileInspect = { configure, open, close, clearAll };
102
+ export default MobileInspect;