@bugsee/react-native 0.0.0-stage → 7.0.0-beta1

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 (250) hide show
  1. package/BugseeReactNative.podspec +95 -0
  2. package/LICENSE +21 -0
  3. package/README.md +552 -2
  4. package/android/build.gradle +162 -0
  5. package/android/consumer-rules.pro +2 -0
  6. package/android/src/main/AndroidManifest.xml +33 -0
  7. package/android/src/main/java/com/bugsee/reactnative/AppearanceBridge.java +82 -0
  8. package/android/src/main/java/com/bugsee/reactnative/AttributeBridge.java +209 -0
  9. package/android/src/main/java/com/bugsee/reactnative/BreadcrumbFilterBridge.java +443 -0
  10. package/android/src/main/java/com/bugsee/reactnative/BridgeJson.java +168 -0
  11. package/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +1869 -0
  12. package/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java +136 -0
  13. package/android/src/main/java/com/bugsee/reactnative/BugseePackage.java +42 -0
  14. package/android/src/main/java/com/bugsee/reactnative/BugseeReactNativeWrapper.java +200 -0
  15. package/android/src/main/java/com/bugsee/reactnative/BugseeStatusMapper.java +66 -0
  16. package/android/src/main/java/com/bugsee/reactnative/BugseeTokens.java +22 -0
  17. package/android/src/main/java/com/bugsee/reactnative/ConsoleEchoDedup.java +202 -0
  18. package/android/src/main/java/com/bugsee/reactnative/CreatedReports.java +127 -0
  19. package/android/src/main/java/com/bugsee/reactnative/DataRequestBridge.java +375 -0
  20. package/android/src/main/java/com/bugsee/reactnative/ExceptionBridge.java +88 -0
  21. package/android/src/main/java/com/bugsee/reactnative/ExceptionExecutors.java +33 -0
  22. package/android/src/main/java/com/bugsee/reactnative/LogFilterBridge.java +375 -0
  23. package/android/src/main/java/com/bugsee/reactnative/NetworkEvents.java +227 -0
  24. package/android/src/main/java/com/bugsee/reactnative/NetworkFilterBridge.java +498 -0
  25. package/android/src/main/java/com/bugsee/reactnative/PluginEndpoint.java +48 -0
  26. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWebException.java +19 -0
  27. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWrapperInitProvider.java +61 -0
  28. package/android/src/main/java/com/bugsee/reactnative/ReactRootOriginTracker.java +867 -0
  29. package/android/src/main/java/com/bugsee/reactnative/ReportArgs.java +58 -0
  30. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerBridge.java +336 -0
  31. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerDeadlines.java +57 -0
  32. package/android/src/main/java/com/bugsee/reactnative/ReportOps.java +287 -0
  33. package/android/src/main/java/com/bugsee/reactnative/SecureRectanglePulls.java +113 -0
  34. package/android/src/main/java/com/bugsee/reactnative/SecureRectangleStore.java +692 -0
  35. package/android/src/main/java/com/bugsee/reactnative/SpanHandles.java +143 -0
  36. package/android/src/main/java/com/bugsee/reactnative/WrapperChannelHolder.java +137 -0
  37. package/android/src/main/java/com/bugsee/reactnative/WrapperEventBus.java +110 -0
  38. package/android/src/main/java/com/bugsee/reactnative/WrapperRegistrar.java +54 -0
  39. package/app.plugin.js +4 -0
  40. package/ios/BGSRNConsoleCapture.h +52 -0
  41. package/ios/BGSRNConsoleCapture.mm +344 -0
  42. package/ios/BugseeModule.h +25 -0
  43. package/ios/BugseeModule.mm +2728 -0
  44. package/ios/Package.swift +71 -0
  45. package/ios/Support/Package.resolved +14 -0
  46. package/ios/Support/Package.swift +44 -0
  47. package/ios/Support/Sources/BugseeRNSupport/BGSRNAttributes.m +52 -0
  48. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReportOps.m +236 -0
  49. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReports.m +184 -0
  50. package/ios/Support/Sources/BugseeRNSupport/BGSRNDataRequestBridge.m +431 -0
  51. package/ios/Support/Sources/BugseeRNSupport/BGSRNErrorMessage.m +40 -0
  52. package/ios/Support/Sources/BugseeRNSupport/BGSRNEventBus.m +70 -0
  53. package/ios/Support/Sources/BugseeRNSupport/BGSRNExceptions.m +63 -0
  54. package/ios/Support/Sources/BugseeRNSupport/BGSRNGuardedEmit.mm +32 -0
  55. package/ios/Support/Sources/BugseeRNSupport/BGSRNJSON.m +40 -0
  56. package/ios/Support/Sources/BugseeRNSupport/BGSRNLaunchHold.m +147 -0
  57. package/ios/Support/Sources/BugseeRNSupport/BGSRNMainThread.m +23 -0
  58. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkEvents.m +159 -0
  59. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkFilter.m +155 -0
  60. package/ios/Support/Sources/BugseeRNSupport/BGSRNPluginEndpoint.m +21 -0
  61. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactRootOriginTracker.m +63 -0
  62. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactWindow.m +251 -0
  63. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportArgs.m +47 -0
  64. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportDeadlines.m +8 -0
  65. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportHandlerBridge.m +308 -0
  66. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportOps.m +345 -0
  67. package/ios/Support/Sources/BugseeRNSupport/BGSRNSecureRectangles.m +508 -0
  68. package/ios/Support/Sources/BugseeRNSupport/BGSRNSettleOnce.m +62 -0
  69. package/ios/Support/Sources/BugseeRNSupport/BGSRNSpanHandles.m +136 -0
  70. package/ios/Support/Sources/BugseeRNSupport/BGSRNStatusMapper.m +18 -0
  71. package/ios/Support/Sources/BugseeRNSupport/BGSRNTokens.m +9 -0
  72. package/ios/Support/Sources/BugseeRNSupport/BGSRNValues.m +5 -0
  73. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapper.m +54 -0
  74. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapperChannelHolder.m +59 -0
  75. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNAttributes.h +63 -0
  76. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReportOps.h +51 -0
  77. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReports.h +81 -0
  78. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNDataRequestBridge.h +118 -0
  79. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNErrorMessage.h +30 -0
  80. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNEventBus.h +45 -0
  81. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNExceptions.h +31 -0
  82. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNGuardedEmit.h +31 -0
  83. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNJSON.h +25 -0
  84. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNLaunchHold.h +86 -0
  85. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNMainThread.h +32 -0
  86. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkEvents.h +28 -0
  87. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkFilter.h +28 -0
  88. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNPluginEndpoint.h +17 -0
  89. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactRootOriginTracker.h +48 -0
  90. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactWindow.h +135 -0
  91. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportArgs.h +17 -0
  92. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportDeadlines.h +37 -0
  93. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportHandlerBridge.h +94 -0
  94. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportOps.h +86 -0
  95. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSecureRectangles.h +198 -0
  96. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSettleOnce.h +25 -0
  97. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSpanHandles.h +49 -0
  98. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNStatusMapper.h +26 -0
  99. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNTokens.h +14 -0
  100. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNValues.h +18 -0
  101. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapper.h +40 -0
  102. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapperChannelHolder.h +74 -0
  103. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNAttributesTests.m +194 -0
  104. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportOpsTests.m +274 -0
  105. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportsTests.m +240 -0
  106. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNDataRequestBridgeTests.m +685 -0
  107. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNErrorMessageTests.m +102 -0
  108. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNEventBusTests.m +136 -0
  109. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNExceptionsTests.m +68 -0
  110. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.h +41 -0
  111. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.m +166 -0
  112. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNGuardedEmitTests.mm +85 -0
  113. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNJSONTests.m +281 -0
  114. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNLaunchHoldTests.m +230 -0
  115. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNMainThreadTests.m +97 -0
  116. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkEventsTests.m +99 -0
  117. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkFilterTests.m +134 -0
  118. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNPluginEndpointTests.m +38 -0
  119. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactRootOriginTrackerTests.m +210 -0
  120. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactWindowTests.m +548 -0
  121. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportArgsTests.m +51 -0
  122. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportDeadlinesTests.m +22 -0
  123. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportHandlerBridgeTests.m +382 -0
  124. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportOpsTests.m +295 -0
  125. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSecureRectanglesTests.m +568 -0
  126. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSettleOnceTests.m +134 -0
  127. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSpanHandlesTests.m +153 -0
  128. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNStatusMapperTests.m +81 -0
  129. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNValuesTests.m +32 -0
  130. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperChannelHolderTests.m +205 -0
  131. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperTests.m +66 -0
  132. package/ios/react-native-spm-prefix.h +10 -0
  133. package/native-versions.json +10 -0
  134. package/package.json +62 -3
  135. package/plugin/build/bundle-phase.d.ts +41 -0
  136. package/plugin/build/bundle-phase.js +116 -0
  137. package/plugin/build/bundle-phase.js.map +1 -0
  138. package/plugin/build/dsym-script.d.ts +32 -0
  139. package/plugin/build/dsym-script.js +159 -0
  140. package/plugin/build/dsym-script.js.map +1 -0
  141. package/plugin/build/endpoint.d.ts +30 -0
  142. package/plugin/build/endpoint.js +69 -0
  143. package/plugin/build/endpoint.js.map +1 -0
  144. package/plugin/build/gradle.d.ts +65 -0
  145. package/plugin/build/gradle.js +1066 -0
  146. package/plugin/build/gradle.js.map +1 -0
  147. package/plugin/build/index.d.ts +85 -0
  148. package/plugin/build/index.js +217 -0
  149. package/plugin/build/index.js.map +1 -0
  150. package/plugin/build/manifest.d.ts +48 -0
  151. package/plugin/build/manifest.js +69 -0
  152. package/plugin/build/manifest.js.map +1 -0
  153. package/plugin/build/native-versions.baked.json +4 -0
  154. package/plugin/build/native-versions.d.ts +10 -0
  155. package/plugin/build/native-versions.js +27 -0
  156. package/plugin/build/native-versions.js.map +1 -0
  157. package/plugin/build/pbx-string.d.ts +8 -0
  158. package/plugin/build/pbx-string.js +31 -0
  159. package/plugin/build/pbx-string.js.map +1 -0
  160. package/plugin/build/podfile.d.ts +3 -0
  161. package/plugin/build/podfile.js +28 -0
  162. package/plugin/build/podfile.js.map +1 -0
  163. package/plugin/build/properties.d.ts +19 -0
  164. package/plugin/build/properties.js +41 -0
  165. package/plugin/build/properties.js.map +1 -0
  166. package/plugin/build/scheme.d.ts +20 -0
  167. package/plugin/build/scheme.js +107 -0
  168. package/plugin/build/scheme.js.map +1 -0
  169. package/react-native.config.js +26 -0
  170. package/scripts/bugsee-sourcemaps.gradle +201 -0
  171. package/scripts/bugsee-xcode.sh +83 -0
  172. package/scripts/compose-then-inject.js +113 -0
  173. package/scripts/hermes-sourcemaps.js +634 -0
  174. package/scripts/hermesc-preserve-js.cmd +6 -0
  175. package/scripts/hermesc-preserve-js.js +200 -0
  176. package/scripts/hermesc-preserve-js.sh +7 -0
  177. package/src/NativeBugsee.ts +622 -0
  178. package/src/apm/notify.ts +58 -0
  179. package/src/apm/span.ts +403 -0
  180. package/src/apm/types.ts +57 -0
  181. package/src/appearance/report.ts +171 -0
  182. package/src/architecture.ts +48 -0
  183. package/src/attributes/errors.ts +39 -0
  184. package/src/attributes/validate.ts +150 -0
  185. package/src/breadcrumbs/add.ts +58 -0
  186. package/src/breadcrumbs/data.ts +33 -0
  187. package/src/breadcrumbs/filter.ts +215 -0
  188. package/src/breadcrumbs/types.ts +64 -0
  189. package/src/bridge/json.ts +110 -0
  190. package/src/console/capture.ts +180 -0
  191. package/src/console/dedup.ts +175 -0
  192. package/src/data/validate.ts +259 -0
  193. package/src/errorName.ts +32 -0
  194. package/src/exceptions/ErrorBoundary.tsx +92 -0
  195. package/src/exceptions/RootErrorReporter.tsx +61 -0
  196. package/src/exceptions/debugIds.ts +118 -0
  197. package/src/exceptions/handlers.ts +236 -0
  198. package/src/exceptions/options.ts +85 -0
  199. package/src/exceptions/payload.ts +456 -0
  200. package/src/exceptions/report.ts +170 -0
  201. package/src/exceptions/sha1.ts +148 -0
  202. package/src/exceptions/stack.ts +355 -0
  203. package/src/index.ts +944 -0
  204. package/src/logs/filter.ts +90 -0
  205. package/src/logs/log.ts +36 -0
  206. package/src/network/add.ts +165 -0
  207. package/src/network/filter.ts +198 -0
  208. package/src/options/AndroidLaunchOptions.ts +78 -0
  209. package/src/options/BugseeLaunchOptions.ts +190 -0
  210. package/src/options/IOSLaunchOptions.ts +57 -0
  211. package/src/options/android-options-manifest.json +646 -0
  212. package/src/options/createDefaultLaunchOptions.ts +29 -0
  213. package/src/options/endpoint.ts +58 -0
  214. package/src/options/enums.ts +104 -0
  215. package/src/options/ios-enums.json +19 -0
  216. package/src/options/keys.ts +39 -0
  217. package/src/options/option-enums.json +34 -0
  218. package/src/options/option-keys.json +107 -0
  219. package/src/report/BugseeReport.ts +264 -0
  220. package/src/report/CreatedReport.ts +127 -0
  221. package/src/report/dispatcher.ts +95 -0
  222. package/src/report/errors.ts +48 -0
  223. package/src/report/fields.ts +40 -0
  224. package/src/report/types.ts +157 -0
  225. package/src/report/validate.ts +197 -0
  226. package/src/secure/BugseeSecure.tsx +202 -0
  227. package/src/secure/ancestry.ts +622 -0
  228. package/src/secure/drivers.ts +342 -0
  229. package/src/secure/followEvents.ts +57 -0
  230. package/src/secure/hold.ts +99 -0
  231. package/src/secure/measureLoop.ts +323 -0
  232. package/src/secure/nativeAnimation.ts +1005 -0
  233. package/src/secure/rectangles.ts +93 -0
  234. package/src/secure/registry.ts +237 -0
  235. package/src/secure/surface.ts +83 -0
  236. package/src/secure/tracker.ts +723 -0
  237. package/src/secure/transition.ts +488 -0
  238. package/src/secure/unit.ts +22 -0
  239. package/src/status.ts +16 -0
  240. package/src/version.ts +9 -0
  241. package/src/viewtree/anchor.tsx +105 -0
  242. package/src/viewtree/constants.ts +20 -0
  243. package/src/viewtree/fiber.ts +251 -0
  244. package/src/viewtree/requests.ts +347 -0
  245. package/src/viewtree/walk.ts +902 -0
  246. package/src/wrapper/channel.ts +33 -0
  247. package/src/wrapper/collect.ts +52 -0
  248. package/src/wrapper/events.ts +45 -0
  249. package/src/wrapper/identity.ts +54 -0
  250. package/src/wrapper/lifecycle-events.ts +89 -0
@@ -0,0 +1,2728 @@
1
+ #import "BugseeModule.h"
2
+ #import "BGSRNConsoleCapture.h"
3
+
4
+ // Header imports, not `@import`. This file is ObjC++, and neither delivery path
5
+ // turns on C++ modules — CocoaPods sets CLANG_ENABLE_MODULES for ObjC only, and
6
+ // the SPM target does not pass -fcxx-modules either. A module import here fails
7
+ // with "use of '@import' when C++ modules are disabled", and then with a
8
+ // cascade of undeclared identifiers that hides the real cause.
9
+ #import <Bugsee/Bugsee.h>
10
+ #import <UIKit/UIKit.h>
11
+ #import <os/lock.h>
12
+
13
+ // CocoaPods compiles BugseeRNSupport's sources straight into this pod, so its
14
+ // headers arrive flat; under SPM it is a separate target and they arrive under
15
+ // the module's own directory.
16
+ #if __has_include(<BugseeRNSupport/BGSRNTokens.h>)
17
+ #import <BugseeRNSupport/BGSRNMainThread.h>
18
+ #import <BugseeRNSupport/BGSRNWrapper.h>
19
+ #import <BugseeRNSupport/BGSRNWrapperChannelHolder.h>
20
+ #include <atomic>
21
+ #include <memory>
22
+
23
+ #import <BugseeRNSupport/BGSRNStatusMapper.h>
24
+ #import <BugseeRNSupport/BGSRNSecureRectangles.h>
25
+ #import <BugseeRNSupport/BGSRNReactRootOriginTracker.h>
26
+ #import <BugseeRNSupport/BGSRNEventBus.h>
27
+ #import <BugseeRNSupport/BGSRNTokens.h>
28
+ #import <BugseeRNSupport/BGSRNReportHandlerBridge.h>
29
+ #import <BugseeRNSupport/BGSRNReportOps.h>
30
+ #import <BugseeRNSupport/BGSRNGuardedEmit.h>
31
+ #import <BugseeRNSupport/BGSRNValues.h>
32
+ #import <BugseeRNSupport/BGSRNJSON.h>
33
+ #import <BugseeRNSupport/BGSRNNetworkFilter.h>
34
+ #import <BugseeRNSupport/BGSRNNetworkEvents.h>
35
+ #import <BugseeRNSupport/BGSRNAttributes.h>
36
+ #import <BugseeRNSupport/BGSRNDataRequestBridge.h>
37
+ #import <BugseeRNSupport/BGSRNReactWindow.h>
38
+ #import <BugseeRNSupport/BGSRNExceptions.h>
39
+ #import <BugseeRNSupport/BGSRNSettleOnce.h>
40
+ #import <BugseeRNSupport/BGSRNReportArgs.h>
41
+ #import <BugseeRNSupport/BGSRNCreatedReports.h>
42
+ #import <BugseeRNSupport/BGSRNCreatedReportOps.h>
43
+ #import <BugseeRNSupport/BGSRNSpanHandles.h>
44
+ #import <BugseeRNSupport/BGSRNErrorMessage.h>
45
+ #import <BugseeRNSupport/BGSRNPluginEndpoint.h>
46
+ #import <BugseeRNSupport/BGSRNLaunchHold.h>
47
+ #else
48
+ #import "BGSRNMainThread.h"
49
+ #import "BGSRNWrapper.h"
50
+ #import "BGSRNWrapperChannelHolder.h"
51
+ #import "BGSRNStatusMapper.h"
52
+ #import "BGSRNSecureRectangles.h"
53
+ #import "BGSRNReactRootOriginTracker.h"
54
+ #import "BGSRNEventBus.h"
55
+ #import "BGSRNTokens.h"
56
+ #import "BGSRNReportHandlerBridge.h"
57
+ #import "BGSRNReportOps.h"
58
+ #import "BGSRNGuardedEmit.h"
59
+ #import "BGSRNValues.h"
60
+ #import "BGSRNJSON.h"
61
+ #import "BGSRNNetworkFilter.h"
62
+ #import "BGSRNNetworkEvents.h"
63
+ #import "BGSRNAttributes.h"
64
+ #import "BGSRNDataRequestBridge.h"
65
+ #import "BGSRNReactWindow.h"
66
+ #import "BGSRNExceptions.h"
67
+ #import "BGSRNSettleOnce.h"
68
+ #import "BGSRNReportArgs.h"
69
+ #import "BGSRNCreatedReports.h"
70
+ #import "BGSRNCreatedReportOps.h"
71
+ #import "BGSRNSpanHandles.h"
72
+ #import "BGSRNErrorMessage.h"
73
+ #import "BGSRNPluginEndpoint.h"
74
+ #import "BGSRNLaunchHold.h"
75
+ #endif
76
+
77
+ /// Forward-declared: the wrapper's pull path refreshes the origins before the
78
+ /// functions' definitions later in this file.
79
+ static NSValue *_Nullable BGSRNReactOrigin(void);
80
+ static NSValue *_Nullable BGSRNModalSurfaceOrigin(NSInteger surface);
81
+ static Class _Nullable BGSRNModalHostClass(void);
82
+ static BGSRNReactRootOriginTracker *BGSRNSecureOriginTracker(void);
83
+
84
+ /// The conformance lives here rather than in the Support package so that the
85
+ /// package stays buildable and testable without the SDK's headers. BGSRNWrapper
86
+ /// already declares every property the protocol requires; this states that it
87
+ /// satisfies the contract.
88
+ @interface BGSRNWrapper (BugseeConformance) <BugseeWrapper>
89
+ @end
90
+
91
+ @implementation BGSRNWrapper (BugseeConformance)
92
+
93
+ /// Store the channel and return -- the SDK's contract for this callback,
94
+ /// verbatim. Nothing else belongs here: flushing anything buffered, taking a
95
+ /// lock, or calling back into the SDK from inside this callback are all ways
96
+ /// to discover one of the hazards `BGSWrapperChannel` documents.
97
+ - (void)onWrapperChannelAvailable:(id<BGSWrapperChannel>)channel {
98
+ BGSRNWrapperChannelHolder.shared.channel = channel;
99
+ }
100
+
101
+ /// Through the bus rather than straight to the module: this wrapper is
102
+ /// registered before React Native has a JS runtime and is replaced once it
103
+ /// does, while the bridge appears late and can be torn down by a reload. The
104
+ /// two lifetimes do not line up, so neither side holds the other.
105
+ ///
106
+ /// `data` is typed `id` because most events carry nothing; the ones that carry
107
+ /// something carry the report id as a string. Anything else is ignored rather
108
+ /// than stringified — a JS caller reading `reportId` should get the id or
109
+ /// nothing, never a description of some future payload shape.
110
+ - (void)onLifecycleEvent:(NSString *)eventType data:(id)data {
111
+ // WORKAROUND for bugsee-cocoa#227 (BGSRNLaunchHold): Launched releases the
112
+ // report calls held while the SDK was Launching; Stopping/Stopped drop them.
113
+ // Before the bus, and independent of it: the bus drops events while no JS
114
+ // is attached, and the hold must not.
115
+ [BGSRNLaunchHold.shared lifecycleEvent:eventType];
116
+ NSString *reportId = [data isKindOfClass:NSString.class] ? (NSString *)data : nil;
117
+ [BGSRNEventBus.shared emitLifecycle:eventType reportId:reportId];
118
+ }
119
+
120
+ /// The packed buffer the SDK expects: `[version, count, l,t,r,b, ...]` as
121
+ /// little-endian int32, every rectangle moved from the React root's window to
122
+ /// the screen.
123
+ ///
124
+ /// Read from the process-wide store rather than from this instance. The SDK
125
+ /// pulls on the MAIN thread once per captured frame, and the wrapper it pulls
126
+ /// through is replaced when `setWrapperInfo` runs — regions the app marked
127
+ /// secret must survive that swap. See `BGSRNSecureRectangles` for the version
128
+ /// contract, which is what makes the SDK notice a change at all.
129
+ - (NSData *)secureRectanglesForDisplay:(NSInteger)display {
130
+ // Every surface's origin is re-read on the pull, so a window move or a
131
+ // sheet settling still updates without waiting for the next JS publish,
132
+ // the same reason Android refreshes at pull time. The main surface is the
133
+ // React root's window; each <Modal> is its presented view controller's
134
+ // view. A Modal whose host is gone takes its empty lane with it; one that
135
+ // is not found yet keeps failing closed.
136
+ if (NSThread.isMainThread) {
137
+ BGSRNSecureRectangles *store = BGSRNSecureRectangles.shared;
138
+ // What a surface whose origin is unknown serves: the screen, not more.
139
+ [store setDisplaySize:UIScreen.mainScreen.bounds.size forDisplay:display];
140
+ NSValue *origin = BGSRNReactOrigin();
141
+ if (origin != nil) {
142
+ [store setOrigin:origin.CGPointValue forDisplay:display];
143
+ }
144
+ for (NSNumber *surface in [store surfacesForDisplay:display]) {
145
+ NSValue *modalOrigin = BGSRNModalSurfaceOrigin(surface.integerValue);
146
+ if (modalOrigin != nil) {
147
+ [store setOrigin:modalOrigin.CGPointValue forDisplay:display surface:surface.integerValue];
148
+ } else {
149
+ [store dropSurfaceIfEmpty:surface.integerValue];
150
+ }
151
+ }
152
+ }
153
+ return [BGSRNSecureRectangles.shared snapshotForDisplay:display];
154
+ }
155
+
156
+ /// Through the data request bridge, for the same reason lifecycle events go
157
+ /// through the bus: this wrapper outlives every JS runtime.
158
+ ///
159
+ /// The SDK asks on MAIN and does not wait there (SDK 0d9c9d0a3,
160
+ /// `BGSCaptureDataProviderViewHierarchy.m`): the callback is asynchronous and
161
+ /// accepted on any thread. The bridge answers exactly once -- synchronously
162
+ /// with nil when JS cannot answer, otherwise with JS's reply (on the module's
163
+ /// method queue) or nil at its deadline (on its own queue). Nothing here may
164
+ /// hop to or wait on main.
165
+ - (void)requestDataWithType:(NSString *)dataType
166
+ callback:(id<BGSDataRequestResultCallback>)callback {
167
+ [BGSRNDataRequestBridge.shared requestType:dataType
168
+ reply:^(NSString *d) {
169
+ if ([callback respondsToSelector:@selector(onResult:)]) {
170
+ [callback onResult:d];
171
+ }
172
+ }];
173
+ }
174
+
175
+ /// Through the report handler bridge, for the same reason lifecycle events go
176
+ /// through the bus: this wrapper outlives every JS runtime.
177
+ ///
178
+ /// The thread is the only thing that tells the two paths apart. Live reports
179
+ /// arrive on MAIN, dispatched there with `dispatch_async`; recovered ones
180
+ /// arrive off main (see BGSRNReportDeadlines.h). Both reach JS, with different
181
+ /// deadlines. Nothing on this path may hop to main -- not because the SDK is
182
+ /// blocked on main waiting for us (it isn't: the completion is a
183
+ /// thread-agnostic run-once that hops to the SDK's own private queue, and main
184
+ /// is never held for it), but because there is no need to, and an op that did
185
+ /// would queue behind whatever UI work is already on main, eating into the
186
+ /// handle's deadline for nothing.
187
+ - (void)onBeforeReportCreated:(id<BGSReportContract>)report
188
+ isTerminating:(BOOL)isTerminating
189
+ completion:(BGSCallback)completion {
190
+ [BGSRNReportHandlerBridge.shared dispatchPhase:BGSRNReportPhaseBefore
191
+ report:report
192
+ isTerminating:isTerminating
193
+ onMainThread:NSThread.isMainThread
194
+ completion:completion];
195
+ }
196
+
197
+ - (void)onAfterReportCreated:(id<BGSReportContract>)report
198
+ isTerminating:(BOOL)isTerminating
199
+ completion:(BGSCallback)completion {
200
+ [BGSRNReportHandlerBridge.shared dispatchPhase:BGSRNReportPhaseAfter
201
+ report:report
202
+ isTerminating:isTerminating
203
+ onMainThread:NSThread.isMainThread
204
+ completion:completion];
205
+ }
206
+
207
+ @end
208
+
209
+ /// The one route to `+[Bugsee setWrapper:]` in this module, so a future call
210
+ /// site cannot bypass either half of this: the main-thread hop
211
+ /// `setWrapperInfo` already needed, and clearing the held wrapper channel
212
+ /// after a `nil` registration. `onWrapperChannelAvailable:` delivers a fresh
213
+ /// channel for a non-nil registration, so clearing only happens for `nil` --
214
+ /// clearing on every call would wipe a channel the instant it arrived.
215
+ ///
216
+ /// Registrations must never overlap (the wrapper-channel contract). Main is
217
+ /// the lock: every call goes through a main-thread hop, so another call site
218
+ /// needs no lock of its own as long as it comes through here.
219
+ ///
220
+ /// `onlyIfAbsent` is the module-init registration. A reload constructs a new
221
+ /// module while the previous runtime's full identity is still what the SDK
222
+ /// should report, and replacing it with the thin pre-JS wrapper would drop
223
+ /// that identity until JS called `setWrapperInfo` again. The flag is read
224
+ /// and written on main, beside `setWrapper:`.
225
+ ///
226
+ /// Init uses `BGSRNRunOnMainSync`: `BGSRNRunOnMain` is async off main, so
227
+ /// `-init` could return with `+[Bugsee setWrapper:]` only queued. A later
228
+ /// `startBlackout` delivered on main would then run inline before that
229
+ /// registration and the SDK would drop `BlackoutStarted`. Ordinary
230
+ /// `setWrapperInfo` stays on the async hop.
231
+ static BOOL BGSRNWrapperIsRegistered = NO;
232
+
233
+ static void BGSRNSetWrapper(id<BugseeWrapper> _Nullable wrapper, BOOL onlyIfAbsent) {
234
+ void (^body)(void) = ^{
235
+ if (onlyIfAbsent && BGSRNWrapperIsRegistered) {
236
+ return;
237
+ }
238
+ [Bugsee setWrapper:wrapper];
239
+ if (wrapper == nil) {
240
+ BGSRNWrapperChannelHolder.shared.channel = nil;
241
+ BGSRNWrapperIsRegistered = NO;
242
+ } else {
243
+ BGSRNWrapperIsRegistered = YES;
244
+ }
245
+ };
246
+ if (onlyIfAbsent) {
247
+ BGSRNRunOnMainSync(body);
248
+ } else {
249
+ BGSRNRunOnMain(body);
250
+ }
251
+ }
252
+
253
+ /// The `vh` origin: where the window hosting the React root starts in the
254
+ /// frame the SDK records (points), among the windows the SDK's own
255
+ /// view-hierarchy walk visits -- the space the SDK places every native node
256
+ /// in, so the two trees share one space by construction (see
257
+ /// `BGSRNReactWindow.h`). nil without one, or off main: the SDK asks on main,
258
+ /// and UIKit must not be read anywhere else.
259
+ ///
260
+ /// The root is recognised by class name, not by import: `RCTSurfaceHostingView`
261
+ /// is the new architecture's root (the template's `RCTRootView` is its
262
+ /// `RCTSurfaceHostingProxyRootView` subclass); the legacy `RCTRootView` class
263
+ /// is matched too for interop hosts.
264
+ static BOOL BGSRNIsReactRoot(UIView *view) {
265
+ static Class surfaceHostingView;
266
+ static Class legacyRootView;
267
+ static dispatch_once_t once;
268
+ dispatch_once(&once, ^{
269
+ surfaceHostingView = NSClassFromString(@"RCTSurfaceHostingView");
270
+ legacyRootView = NSClassFromString(@"RCTRootView");
271
+ });
272
+ return (surfaceHostingView != Nil && [view isKindOfClass:surfaceHostingView]) ||
273
+ (legacyRootView != Nil && [view isKindOfClass:legacyRootView]);
274
+ }
275
+
276
+ static NSValue *_Nullable BGSRNReactOrigin(void) {
277
+ if (!NSThread.isMainThread) {
278
+ return nil;
279
+ }
280
+ return [BGSRNSecureOriginTracker() origin];
281
+ }
282
+
283
+ /// `BGSRNReactOrigin`, searching for the root at once when the one found last
284
+ /// is in no window: for a `vh` request, which comes once per walk.
285
+ static NSValue *_Nullable BGSRNReactOriginFindingTheRoot(void) {
286
+ if (!NSThread.isMainThread) {
287
+ return nil;
288
+ }
289
+ return [BGSRNSecureOriginTracker() originFindingTheRoot];
290
+ }
291
+
292
+ /// `RCTModalHostViewComponentView`, resolved by name rather than imported;
293
+ /// Nil when this React Native has no such class.
294
+ static Class _Nullable BGSRNModalHostClass(void) {
295
+ static Class modalHostClass;
296
+ static dispatch_once_t once;
297
+ dispatch_once(&once, ^{
298
+ modalHostClass = NSClassFromString(@"RCTModalHostViewComponentView");
299
+ });
300
+ return modalHostClass;
301
+ }
302
+
303
+ /// Where `measureInWindow`'s (0, 0) sits on the screen, in points, for the
304
+ /// `<Modal>` whose host has React tag `surface` (`BGSRNModalHostOrigin`).
305
+ /// Read from the current runtime's host, which its module names at publish
306
+ /// time (`nameModalHostForSurface:`), the same shape as Android's
307
+ /// `watchSurface`: a window can hold another runtime's host with the same
308
+ /// tag during a reload, and only the module's own view registry tells them
309
+ /// apart. While that host has not mounted, unknown. Only without a
310
+ /// registry, the one class+tag match in the windows the SDK walks. nil (none or several, or off main) leaves the lane's
311
+ /// origin as it was: unknown for a new lane, which is served as the whole
312
+ /// display.
313
+ static NSValue *_Nullable BGSRNModalSurfaceOrigin(NSInteger surface) {
314
+ if (!NSThread.isMainThread) {
315
+ return nil;
316
+ }
317
+ Class modalHostClass = BGSRNModalHostClass();
318
+ if (modalHostClass == Nil || surface <= 0) {
319
+ return nil;
320
+ }
321
+ return BGSRNSecureSurfaceOrigin(
322
+ BGSRNSecureRectangles.shared, surface, BGSRNSdkWalkedWindows(BGSRNSdkKeyWindow()),
323
+ ^BOOL(UIView *view) {
324
+ return [view isKindOfClass:modalHostClass];
325
+ },
326
+ ^NSValue *_Nullable(UIWindow *window) {
327
+ return BGSRNWindowRecordedOrigin(window);
328
+ });
329
+ }
330
+
331
+ /// Keeps the main surface's origin on the window JS measures in: the iOS
332
+ /// peer of Android's `ReactRootOriginTracker` (see
333
+ /// `BGSRNReactRootOriginTracker`). Process-wide, like the store it feeds: the
334
+ /// window lookup reads only UIKit, nothing of one module.
335
+ static BGSRNReactRootOriginTracker *BGSRNSecureOriginTracker(void) {
336
+ static BGSRNReactRootOriginTracker *tracker = nil;
337
+ static dispatch_once_t once;
338
+ dispatch_once(&once, ^{
339
+ tracker = [[BGSRNReactRootOriginTracker alloc]
340
+ initWithFindRoot:^UIView *_Nullable {
341
+ UIWindow *keyWindow = BGSRNSdkKeyWindow();
342
+ return BGSRNReactRootView(keyWindow,
343
+ BGSRNSdkWalkedWindows(keyWindow),
344
+ ^BOOL(UIView *view) {
345
+ return BGSRNIsReactRoot(view);
346
+ },
347
+ BGSRNReactRootSearchBudget);
348
+ }
349
+ readOrigin:^NSValue *_Nullable(UIWindow *window) {
350
+ return BGSRNWindowRecordedOrigin(window);
351
+ }
352
+ clock:^NSTimeInterval {
353
+ return NSProcessInfo.processInfo.systemUptime;
354
+ }];
355
+ });
356
+ return tracker;
357
+ }
358
+
359
+ static NSString *const kHandleDeadCode = @"E_REPORT_HANDLE_DEAD";
360
+ static NSString *const kCreateBusyCode = @"E_REPORT_CREATE_BUSY";
361
+
362
+ static void BGSRNRejectHandleDead(RCTPromiseRejectBlock reject) {
363
+ reject(kHandleDeadCode,
364
+ @"This BugseeReport handle is no longer valid: its handler has "
365
+ @"already settled, or its deadline has passed.",
366
+ nil);
367
+ }
368
+
369
+ static void BGSRNRejectCreatedHandleDead(RCTPromiseRejectBlock reject) {
370
+ reject(kHandleDeadCode, @"This created report handle is no longer valid.", nil);
371
+ }
372
+
373
+ /// No code of our own (React Native fills in `EUNSPECIFIED`, as Android's
374
+ /// `rejectReportFailure` does): an unexpected fault is not one of the codes the
375
+ /// JS contract names, and inventing another would make it matchable.
376
+ ///
377
+ /// The message names `operation` only (`failureMessageForOperation:`), never
378
+ /// `exception.reason`, which can echo report content (a summary, an attribute
379
+ /// value, a file path, an attachment name). Only the exception's class is
380
+ /// logged.
381
+ static void BGSRNRejectException(RCTPromiseRejectBlock reject, NSString *operation, NSException *exception) {
382
+ NSLog(@"BugseeRN %@ failed: %@", operation, NSStringFromClass(exception.class));
383
+ reject(nil, [BGSRNReportOps failureMessageForOperation:operation], nil);
384
+ }
385
+
386
+ /// The SDK returns nil both for a declined attachment and for a report that
387
+ /// is no longer live. The handle tells the two apart: if it died while the
388
+ /// call ran, that is the truer answer.
389
+ static void BGSRNSettleAttachment(NSString *handleId,
390
+ BOOL added,
391
+ NSError *error,
392
+ RCTPromiseResolveBlock resolve,
393
+ RCTPromiseRejectBlock reject) {
394
+ if (added) {
395
+ resolve(nil);
396
+ return;
397
+ }
398
+ NSString *code = BGSRNReportErrorWireCode(error);
399
+ if ([code isEqualToString:@"E_REPORT_ATTACHMENT_REJECTED"] &&
400
+ [BGSRNReportHandlerBridge.shared reportFor:handleId] == nil) {
401
+ BGSRNRejectHandleDead(reject);
402
+ return;
403
+ }
404
+ reject(code, BGSRNErrorMessage(error), nil);
405
+ }
406
+
407
+ static NSString *const kAttributeRejectedCode = @"E_ATTRIBUTE_REJECTED";
408
+
409
+ /// Sets `value` for `name` through `BGSRNAttributes`, which verifies with a
410
+ /// read-back rather than trusting the SDK's own return: `+setAttribute:
411
+ /// withValue:` returns `YES` even when it silently drops a value over its
412
+ /// archived-size limit (design doc, Phase 5 verified facts). The one path
413
+ /// `setAttributeString/-Number/-Boolean` share; on main, like every other SDK
414
+ /// entry point.
415
+ ///
416
+ /// The rejection message names the attribute only -- never `value`, which may
417
+ /// be sensitive.
418
+ static void BGSRNSetAttribute(NSString *name,
419
+ id value,
420
+ RCTPromiseResolveBlock resolve,
421
+ RCTPromiseRejectBlock reject) {
422
+ BGSRNRunOnMain(^{
423
+ const BOOL kept = [BGSRNAttributes setValue:value
424
+ forKey:name
425
+ setter:^BOOL(NSString *key, id v) {
426
+ return [Bugsee setAttribute:key withValue:v];
427
+ }
428
+ getter:^id(NSString *key) {
429
+ return [Bugsee getAttribute:key];
430
+ }];
431
+ if (kept) {
432
+ resolve(nil);
433
+ } else {
434
+ reject(kAttributeRejectedCode,
435
+ [NSString stringWithFormat:@"attribute \"%@\" was not kept by the SDK", name],
436
+ nil);
437
+ }
438
+ });
439
+ }
440
+
441
+
442
+ /// One in-flight network-filter request. The decision block is copied: the
443
+ /// SDK's block argument is not guaranteed to outlive the filter call, and the
444
+ /// reply comes back later, from JS. iOS's decision block is once-only and the
445
+ /// provider does not recycle the event, so a late reply still records. There
446
+ /// is no timer here: one that called `decision(nil)` would drop an event the
447
+ /// SDK is still willing to keep.
448
+ @interface BGSRNNetworkFilterPending : NSObject
449
+ @property (nonatomic, strong) BugseeNetworkEvent *event;
450
+ @property (nonatomic, copy) BugseeNetworkFilterDecisionBlock decision;
451
+ @property (nonatomic, weak) BugseeModule *owner;
452
+ @end
453
+ @implementation BGSRNNetworkFilterPending
454
+ @end
455
+
456
+ static __weak BugseeModule *BGSRNNetworkFilterModule = nil;
457
+ static BOOL BGSRNNetworkFilterInstalled = NO;
458
+ static NSMutableDictionary<NSString *, BGSRNNetworkFilterPending *> *BGSRNNetworkFilterPendingTable;
459
+ static int64_t BGSRNNetworkFilterNextId = 0;
460
+
461
+ static id BGSRNNetworkFilterLock(void) {
462
+ static id lock;
463
+ static dispatch_once_t once;
464
+ dispatch_once(&once, ^{
465
+ lock = [NSObject new];
466
+ BGSRNNetworkFilterPendingTable = [NSMutableDictionary dictionary];
467
+ });
468
+ return lock;
469
+ }
470
+
471
+ /// Answers nil for every request `module` still holds, which drops the event.
472
+ /// Called outside the lock: the SDK's decision block must not re-enter it.
473
+ static void BGSRNDropNetworkFiltersOwnedBy(BugseeModule *module) {
474
+ NSMutableArray<BugseeNetworkFilterDecisionBlock> *decisions = [NSMutableArray array];
475
+ @synchronized (BGSRNNetworkFilterLock()) {
476
+ for (NSString *key in BGSRNNetworkFilterPendingTable.allKeys) {
477
+ BGSRNNetworkFilterPending *item = BGSRNNetworkFilterPendingTable[key];
478
+ if (item.owner == module) {
479
+ [BGSRNNetworkFilterPendingTable removeObjectForKey:key];
480
+ if (item.decision != nil) {
481
+ [decisions addObject:item.decision];
482
+ }
483
+ }
484
+ }
485
+ }
486
+ for (BugseeNetworkFilterDecisionBlock decision in decisions) {
487
+ decision(nil);
488
+ }
489
+ }
490
+
491
+
492
+ @interface BGSRNLogFilterPending : NSObject
493
+ @property (nonatomic, strong) BugseeLogEvent *event;
494
+ @property (nonatomic, copy) BugseeLogFilterDecisionBlock decision;
495
+ @property (nonatomic, weak) BugseeModule *owner;
496
+ @end
497
+ @implementation BGSRNLogFilterPending
498
+ @end
499
+
500
+ static __weak BugseeModule *BGSRNLogFilterModule = nil;
501
+ static BOOL BGSRNLogFilterInstalled = NO;
502
+ /** The JS round trip. Off is the native pass-through, which stays installed. */
503
+ static BOOL BGSRNLogFilterUserEnabled = NO;
504
+ static NSMutableDictionary<NSString *, BGSRNLogFilterPending *> *BGSRNLogFilterPendingTable;
505
+ static int64_t BGSRNLogFilterNextId = 0;
506
+
507
+ static id BGSRNLogFilterLock(void) {
508
+ static id lock;
509
+ static dispatch_once_t once;
510
+ dispatch_once(&once, ^{
511
+ lock = [NSObject new];
512
+ BGSRNLogFilterPendingTable = [NSMutableDictionary dictionary];
513
+ });
514
+ return lock;
515
+ }
516
+
517
+ /// Answers `nil` for every request `module` still holds, which drops the line.
518
+ /// Called outside the lock: the SDK's decision block must not re-enter it.
519
+ static void BGSRNDropLogFiltersOwnedBy(BugseeModule *module) {
520
+ NSMutableArray<BugseeLogFilterDecisionBlock> *decisions = [NSMutableArray array];
521
+ @synchronized (BGSRNLogFilterLock()) {
522
+ for (NSString *key in BGSRNLogFilterPendingTable.allKeys) {
523
+ BGSRNLogFilterPending *item = BGSRNLogFilterPendingTable[key];
524
+ if (item.owner == module) {
525
+ [BGSRNLogFilterPendingTable removeObjectForKey:key];
526
+ if (item.decision != nil) {
527
+ [decisions addObject:item.decision];
528
+ }
529
+ }
530
+ }
531
+ }
532
+ for (BugseeLogFilterDecisionBlock decision in decisions) {
533
+ decision(nil);
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Declared up here so the filter installer, which sits above the method
539
+ * body, can call it. The implementation is on BugseeModule.
540
+ */
541
+ @interface BugseeModule (BGSRNLogFilterEmit)
542
+ - (BOOL)emitLogFilterRequest:(NSString *)requestId line:(NSString *)line;
543
+ @end
544
+
545
+ /**
546
+ * Installs the native log filter once. It stays installed when the app has
547
+ * no log callback: an echo is dropped, and every other line is returned
548
+ * immediately. A user callback asks JS. Clearing that callback restores the
549
+ * pass-through. The filter is not set back to nil.
550
+ */
551
+ static void BGSRNInstallLogEventFilter(void) {
552
+ @synchronized (BGSRNLogFilterLock()) {
553
+ BGSRNLogFilterInstalled = YES;
554
+ }
555
+ [Bugsee setLogEventFilter:^(BugseeLogEvent *event, BugseeLogFilterDecisionBlock decision) {
556
+ NSString *line = event.text;
557
+ if (decision == nil) {
558
+ return;
559
+ }
560
+ if (line == nil) {
561
+ decision(nil);
562
+ return;
563
+ }
564
+ // The console echo. A stderr stamp, and one raw stdout or stderr line
565
+ // of the noted text, are dropped here, before anything else is asked.
566
+ // Not a timeout: the line is not passed through. A Custom line is not
567
+ // that echo. `dictionary` is how the SDK stores the source on the
568
+ // event. When it is absent, the source is unknown and a non-stamp line
569
+ // is not dropped.
570
+ NSInteger source = -1;
571
+ SEL dictionarySelector = NSSelectorFromString(@"dictionary");
572
+ if ([event respondsToSelector:dictionarySelector]) {
573
+ id value = [event valueForKey:@"dictionary"];
574
+ if ([value isKindOfClass:[NSDictionary class]]) {
575
+ id raw = [(NSDictionary *)value objectForKey:@"source"];
576
+ if ([raw respondsToSelector:@selector(integerValue)]) {
577
+ source = [raw integerValue];
578
+ }
579
+ }
580
+ }
581
+ if (BGSRNDropConsoleEcho(line, source)) {
582
+ decision(nil);
583
+ return;
584
+ }
585
+ BOOL askJs = NO;
586
+ @synchronized (BGSRNLogFilterLock()) {
587
+ askJs = BGSRNLogFilterUserEnabled;
588
+ }
589
+ if (!askJs) {
590
+ decision(event);
591
+ return;
592
+ }
593
+ BugseeModule *module = BGSRNLogFilterModule;
594
+ if (module == nil) {
595
+ decision(nil);
596
+ return;
597
+ }
598
+ BGSRNLogFilterPending *item = [BGSRNLogFilterPending new];
599
+ item.event = event;
600
+ item.decision = decision;
601
+ item.owner = module;
602
+ NSString *requestId = nil;
603
+ @synchronized (BGSRNLogFilterLock()) {
604
+ BGSRNLogFilterNextId += 1;
605
+ requestId = [NSString stringWithFormat:@"%lld", BGSRNLogFilterNextId];
606
+ BGSRNLogFilterPendingTable[requestId] = item;
607
+ }
608
+ const BOOL delivered = [module emitLogFilterRequest:requestId line:line];
609
+ if (!delivered) {
610
+ BugseeLogFilterDecisionBlock drop = nil;
611
+ @synchronized (BGSRNLogFilterLock()) {
612
+ BGSRNLogFilterPending *removed = BGSRNLogFilterPendingTable[requestId];
613
+ [BGSRNLogFilterPendingTable removeObjectForKey:requestId];
614
+ drop = removed.decision;
615
+ }
616
+ if (drop != nil) {
617
+ drop(nil);
618
+ }
619
+ }
620
+ }];
621
+ }
622
+
623
+ /// One in-flight breadcrumb-filter request. The decision block is copied: the
624
+ /// SDK's block argument is not guaranteed to outlive the filter call, and the
625
+ /// reply comes back later, from JS. There is no timer. The SDK does not time
626
+ /// the filter out, and a late decision still records.
627
+ @interface BGSRNBreadcrumbFilterPending : NSObject
628
+ @property (nonatomic, strong) id<BGSBreadcrumb> breadcrumb;
629
+ @property (nonatomic, copy) BugseeBreadcrumbFilterDecisionBlock decision;
630
+ @property (nonatomic, weak) BugseeModule *owner;
631
+ @end
632
+ @implementation BGSRNBreadcrumbFilterPending
633
+ @end
634
+
635
+ static __weak BugseeModule *BGSRNBreadcrumbFilterModule = nil;
636
+ static BOOL BGSRNBreadcrumbFilterInstalled = NO;
637
+ /// Bumped on every enable and every disable. A disable queued on main nils
638
+ /// the filter only when this is still the generation it captured, so a later
639
+ /// enable is not wiped by a nil that was already queued.
640
+ static int64_t BGSRNBreadcrumbFilterGeneration = 0;
641
+ static NSMutableDictionary<NSString *, BGSRNBreadcrumbFilterPending *> *BGSRNBreadcrumbFilterPendingTable;
642
+ static int64_t BGSRNBreadcrumbFilterNextId = 0;
643
+ /// The `addId` of the manual add currently inside `[Bugsee addBreadcrumb:]`.
644
+ /// The filter block copies it onto that one request. SDK crumbs are filtered
645
+ /// outside this window, so their requests omit it.
646
+ static NSString *BGSRNBreadcrumbManualAddId = nil;
647
+
648
+ static id BGSRNBreadcrumbFilterLock(void) {
649
+ static id lock;
650
+ static dispatch_once_t once;
651
+ dispatch_once(&once, ^{
652
+ lock = [NSObject new];
653
+ BGSRNBreadcrumbFilterPendingTable = [NSMutableDictionary dictionary];
654
+ });
655
+ return lock;
656
+ }
657
+
658
+ /// Answers `nil` for every request `module` still holds, which drops the crumb.
659
+ /// Called outside the lock: the SDK's decision block must not re-enter it.
660
+ /// This is teardown, not a timeout.
661
+ static void BGSRNDropBreadcrumbFiltersOwnedBy(BugseeModule *module) {
662
+ NSMutableArray<BugseeBreadcrumbFilterDecisionBlock> *decisions = [NSMutableArray array];
663
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
664
+ for (NSString *key in BGSRNBreadcrumbFilterPendingTable.allKeys) {
665
+ BGSRNBreadcrumbFilterPending *item = BGSRNBreadcrumbFilterPendingTable[key];
666
+ if (item.owner == module) {
667
+ [BGSRNBreadcrumbFilterPendingTable removeObjectForKey:key];
668
+ if (item.decision != nil) {
669
+ [decisions addObject:item.decision];
670
+ }
671
+ }
672
+ }
673
+ }
674
+ for (BugseeBreadcrumbFilterDecisionBlock decision in decisions) {
675
+ decision(nil);
676
+ }
677
+ }
678
+
679
+ /// `BugseeLogLevel`, not Android `Breadcrumb.Level.getValue()`.
680
+ /// error 1, warning 2, info 3, debug 4. `fatal` has no rung and is stored
681
+ /// as error (1). Verbose (5) is not a JS name; a stored verbose reads back
682
+ /// as `debug`, which is how the bundle folds it. 0 and anything else have
683
+ /// no name.
684
+ static NSString *BGSRNBreadcrumbLevelName(NSInteger level) {
685
+ switch (level) {
686
+ case 1: return @"error";
687
+ case 2: return @"warning";
688
+ case 3: return @"info";
689
+ case 4: return @"debug";
690
+ case 5: return @"debug";
691
+ default: return nil;
692
+ }
693
+ }
694
+
695
+ /// The integer to store for a JS level name. `fatal` is 1. NO when `name`
696
+ /// is not one of the names.
697
+ static BOOL BGSRNBreadcrumbLevelFromName(NSString *name, NSInteger *out) {
698
+ if ([name isEqualToString:@"error"] || [name isEqualToString:@"fatal"]) {
699
+ *out = 1;
700
+ return YES;
701
+ }
702
+ if ([name isEqualToString:@"warning"]) {
703
+ *out = 2;
704
+ return YES;
705
+ }
706
+ if ([name isEqualToString:@"info"]) {
707
+ *out = 3;
708
+ return YES;
709
+ }
710
+ if ([name isEqualToString:@"debug"]) {
711
+ *out = 4;
712
+ return YES;
713
+ }
714
+ return NO;
715
+ }
716
+
717
+ /// The crumb as JSON, with only the keys the SDK actually set. `level` is
718
+ /// the JS name (0 means unset and is omitted). An integer that has no name
719
+ /// drops the snapshot, rather than sending that integer. A zero timestamp
720
+ /// is omitted. Nil when the crumb cannot be serialised: the caller drops it
721
+ /// rather than sending a partial snapshot.
722
+ static NSString *BGSRNBreadcrumbSnapshotJson(id<BGSBreadcrumb> crumb) {
723
+ if (crumb == nil) {
724
+ return nil;
725
+ }
726
+ NSMutableDictionary *object = [NSMutableDictionary dictionary];
727
+ if (crumb.category != nil) {
728
+ object[@"category"] = crumb.category;
729
+ }
730
+ if (crumb.level != 0) {
731
+ NSString *name = BGSRNBreadcrumbLevelName(crumb.level);
732
+ if (name == nil) {
733
+ return nil;
734
+ }
735
+ object[@"level"] = name;
736
+ }
737
+ if (crumb.message != nil) {
738
+ object[@"message"] = crumb.message;
739
+ }
740
+ if (crumb.type != nil) {
741
+ object[@"type"] = crumb.type;
742
+ }
743
+ if (crumb.data != nil) {
744
+ object[@"data"] = crumb.data;
745
+ }
746
+ if (crumb.timestamp != 0) {
747
+ object[@"timestamp"] = @(crumb.timestamp);
748
+ }
749
+ if (![NSJSONSerialization isValidJSONObject:object]) {
750
+ return nil;
751
+ }
752
+ NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:nil];
753
+ if (data == nil) {
754
+ return nil;
755
+ }
756
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
757
+ }
758
+
759
+ /// Writes the keys `kept` names onto `breadcrumb`. A key it omits stays.
760
+ /// `timestamp` is read-only and is not written. Returns NO when a write is
761
+ /// the wrong type or does not stick, so the caller can drop the crumb.
762
+ static BOOL BGSRNApplyBreadcrumbKeep(id<BGSBreadcrumb> breadcrumb, NSDictionary *kept) {
763
+ id category = kept[@"category"];
764
+ if (category != nil) {
765
+ if (![category isKindOfClass:NSString.class]) {
766
+ return NO;
767
+ }
768
+ breadcrumb.category = (NSString *)category;
769
+ if (![breadcrumb.category isEqualToString:category]) {
770
+ return NO;
771
+ }
772
+ }
773
+ id message = kept[@"message"];
774
+ if (message != nil) {
775
+ if (![message isKindOfClass:NSString.class]) {
776
+ return NO;
777
+ }
778
+ breadcrumb.message = (NSString *)message;
779
+ if (![breadcrumb.message isEqualToString:message]) {
780
+ return NO;
781
+ }
782
+ }
783
+ id type = kept[@"type"];
784
+ if (type != nil) {
785
+ if (![type isKindOfClass:NSString.class]) {
786
+ return NO;
787
+ }
788
+ breadcrumb.type = (NSString *)type;
789
+ if (![breadcrumb.type isEqualToString:type]) {
790
+ return NO;
791
+ }
792
+ }
793
+ id level = kept[@"level"];
794
+ if (level != nil) {
795
+ // The keep echoes the name. An Android integer is not a level here.
796
+ if (![level isKindOfClass:NSString.class]) {
797
+ return NO;
798
+ }
799
+ NSInteger value = 0;
800
+ if (!BGSRNBreadcrumbLevelFromName((NSString *)level, &value)) {
801
+ return NO;
802
+ }
803
+ breadcrumb.level = value;
804
+ if (breadcrumb.level != value) {
805
+ return NO;
806
+ }
807
+ }
808
+ if ([kept objectForKey:@"data"] != nil) {
809
+ id data = kept[@"data"];
810
+ if (data == [NSNull null]) {
811
+ breadcrumb.data = nil;
812
+ if (breadcrumb.data != nil) {
813
+ return NO;
814
+ }
815
+ } else if ([data isKindOfClass:NSDictionary.class]) {
816
+ breadcrumb.data = (NSDictionary *)data;
817
+ if (breadcrumb.data == nil) {
818
+ return NO;
819
+ }
820
+ } else {
821
+ return NO;
822
+ }
823
+ }
824
+ return YES;
825
+ }
826
+
827
+ @interface BGSRNLiveSpan : NSObject <BGSRNRetainedSpan>
828
+ @property (nonatomic, readonly) id<BGSSpan> span;
829
+ - (instancetype)initWithSpan:(id<BGSSpan>)span;
830
+ @end
831
+
832
+ @implementation BGSRNLiveSpan {
833
+ id<BGSSpan> _span;
834
+ }
835
+
836
+ - (instancetype)initWithSpan:(id<BGSSpan>)span {
837
+ self = [super init];
838
+ if (self != nil) {
839
+ _span = span;
840
+ }
841
+ return self;
842
+ }
843
+
844
+ - (id<BGSSpan>)span {
845
+ return _span;
846
+ }
847
+
848
+ - (void)bgsrnFinishWithStatus:(NSNumber *)status {
849
+ if (status == nil) {
850
+ [_span finish];
851
+ return;
852
+ }
853
+ [_span finishWithStatus:(BGSSpanStatus)status.integerValue];
854
+ }
855
+
856
+ - (BOOL)bgsrnIsFinished {
857
+ return _span.isFinished;
858
+ }
859
+
860
+ @end
861
+
862
+ /// One JSON value, or nil when it is missing, null, an object or an array.
863
+ static id BGSRNJSONScalar(NSString *json) {
864
+ if (json == nil) {
865
+ return nil;
866
+ }
867
+ NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
868
+ if (data == nil) {
869
+ return nil;
870
+ }
871
+ NSError *error = nil;
872
+ id value = [NSJSONSerialization JSONObjectWithData:data
873
+ options:NSJSONReadingFragmentsAllowed
874
+ error:&error];
875
+ if (error != nil || value == nil || value == [NSNull null]) {
876
+ return nil;
877
+ }
878
+ if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
879
+ return nil;
880
+ }
881
+ return value;
882
+ }
883
+
884
+ static NSString *BGSRNAttributesJSON(NSDictionary *attributes) {
885
+ if (attributes == nil || attributes.count == 0) {
886
+ return @"{}";
887
+ }
888
+ if (![NSJSONSerialization isValidJSONObject:attributes]) {
889
+ return @"{}";
890
+ }
891
+ NSData *data = [NSJSONSerialization dataWithJSONObject:attributes options:0 error:nil];
892
+ if (data == nil) {
893
+ return @"{}";
894
+ }
895
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"{}";
896
+ }
897
+
898
+ static NSDictionary *BGSRNSpanSnapshot(NSString *handle, id<BGSSpan> span) {
899
+ NSMutableDictionary *map = [NSMutableDictionary dictionary];
900
+ map[@"handle"] = handle ?: @"";
901
+ map[@"spanId"] = span.spanId ?: @"";
902
+ map[@"traceId"] = span.traceId ?: @"";
903
+ map[@"operation"] = span.operation ?: @"";
904
+ map[@"description"] = span.spanDescription ?: [NSNull null];
905
+ map[@"status"] = @((NSInteger)span.status);
906
+ map[@"finished"] = @(span.isFinished);
907
+ map[@"attributesJson"] = BGSRNAttributesJSON(span.attributes);
908
+ if ([span conformsToProtocol:@protocol(BGSTransaction)]) {
909
+ id<BGSTransaction> transaction = (id<BGSTransaction>)span;
910
+ map[@"name"] = transaction.name ?: @"";
911
+ map[@"sampled"] = @(transaction.isSampled);
912
+ }
913
+ return map;
914
+ }
915
+
916
+ static NSDictionary *BGSRNNoSpan(void) {
917
+ return @{@"handle": @""};
918
+ }
919
+
920
+ @interface BugseeModule ()
921
+ @property (nonatomic, strong) BGSRNSpanHandles *spanHandles;
922
+ @end
923
+
924
+ @implementation BugseeModule {
925
+ os_unfair_lock _spanRegistryLock;
926
+ /// This module's claim on the secure store (`claimRuntime`).
927
+ NSInteger _secureRuntime;
928
+ BOOL _spansRetired;
929
+ }
930
+
931
+ @synthesize spanHandles = _spanHandles;
932
+ /// This runtime's view registry (set by React Native through
933
+ /// `RCTBridgeModuleDecorator`): how a `<Modal>` host is found by its React
934
+ /// tag without searching windows another runtime shares.
935
+ @synthesize viewRegistry_DEPRECATED = _viewRegistry_DEPRECATED;
936
+
937
+ RCT_EXPORT_MODULE(Bugsee)
938
+
939
+ /// Design §6.1: this wrapper registers at module init, the iOS counterpart of
940
+ /// Android's ContentProvider. Early enough that a `startBlackout()` made
941
+ /// before `launch()` has a wrapper to deliver `BlackoutStarted` to. Not
942
+ /// `attachToBridges` — that waits until `getTurboModule:` because the codegen
943
+ /// emitter is unset before then, and this call does not emit.
944
+ - (instancetype)init {
945
+ if ((self = [super init])) {
946
+ _spanRegistryLock = OS_UNFAIR_LOCK_INIT;
947
+ // A new JS runtime: Modal surfaces the previous one left behind (a reload
948
+ // with a secure Modal open) are dropped before this one's JS can publish.
949
+ _secureRuntime = [BGSRNSecureRectangles.shared claimRuntime];
950
+ BGSRNSetWrapper((id<BugseeWrapper>)[BGSRNWrapper wrapperWithoutJsRuntime], YES);
951
+ BGSRNInstallConsoleCapture();
952
+ BGSRNInstallLogEventFilter();
953
+ }
954
+ return self;
955
+ }
956
+
957
+ /// Attaches this module to the lifecycle bus and the report handler bridge.
958
+ ///
959
+ /// Called from `getTurboModule:`, right after the JSI object is built -- not
960
+ /// from `init`, and not on first subscribe. Not on first subscribe: the SDK
961
+ /// may emit before JS has subscribed, and a listener that only existed once JS
962
+ /// asked for it would miss the launch transitions a caller most wants. Not
963
+ /// from `init`: the codegen `emitOn*` methods call a `std::function` that the
964
+ /// generated `NativeBugseeSpecJSI` constructor sets, so attaching earlier let
965
+ /// the SDK's threads call it unset, and read it while the JS thread was still
966
+ /// assigning it. Attaching after it is set, under the bus's and bridge's own
967
+ /// locks, orders that write before any read.
968
+ - (void)attachToBridges {
969
+ __weak __typeof(self) weakSelf = self;
970
+ [BGSRNEventBus.shared attach:self block:^BOOL(NSString *name, NSString *reportId) {
971
+ __strong __typeof(weakSelf) strongSelf = weakSelf;
972
+ if (strongSelf == nil) {
973
+ return NO;
974
+ }
975
+ // `reportId` omitted rather than NSNull when absent: the JS type marks it
976
+ // optional, and a null would force every caller to distinguish "absent"
977
+ // from "explicitly nothing".
978
+ NSMutableDictionary *payload = [NSMutableDictionary dictionaryWithObject:name forKey:@"name"];
979
+ if (reportId != nil) {
980
+ payload[@"reportId"] = reportId;
981
+ }
982
+ // Guarded like the report path below: a lifecycle event can arrive
983
+ // after this module is gone (mid-reload), and an unset std::function
984
+ // throws a C++ exception. BGSRNGuardedEmit catches it here, in
985
+ // Objective-C++, and returns NO; the bus logs and drops the event --
986
+ // there is no subscriber to queue it for.
987
+ return BGSRNGuardedEmit(^{
988
+ [strongSelf emitOnLifecycleEvent:payload];
989
+ }, @"onLifecycleEvent");
990
+ }];
991
+ // The same lifetime rule for report handlers. The request is emitted
992
+ // as-is: the bridge already built the wire payload.
993
+ [BGSRNReportHandlerBridge.shared attach:self block:^BOOL(NSDictionary *request) {
994
+ __strong __typeof(weakSelf) strongSelf = weakSelf;
995
+ if (strongSelf == nil) {
996
+ // NO makes the bridge complete the handle now, rather than leave the
997
+ // report waiting out a deadline no JS will ever meet.
998
+ return NO;
999
+ }
1000
+ // The codegen emitter is a std::function, and an unset one throws a C++
1001
+ // exception. BGSRNGuardedEmit catches it here, in Objective-C++, and
1002
+ // returns NO, so the bridge completes the handle -- nothing unwinds
1003
+ // through the bridge's non-exception-safe ARC frames.
1004
+ return BGSRNGuardedEmit(^{
1005
+ [strongSelf emitOnReportHandlerRequest:request];
1006
+ }, @"onReportHandlerRequest");
1007
+ }];
1008
+ // And for the SDK's `vh` data request: the same guarded emit, so NO makes
1009
+ // the bridge answer the SDK nil at once (`by=sink-threw`).
1010
+ [BGSRNDataRequestBridge.shared attach:self
1011
+ block:^BOOL(NSDictionary *request) {
1012
+ __strong __typeof(weakSelf) strongSelf = weakSelf;
1013
+ if (strongSelf == nil) {
1014
+ return NO;
1015
+ }
1016
+ return BGSRNGuardedEmit(^{
1017
+ [strongSelf emitOnDataRequest:request];
1018
+ }, @"onDataRequest");
1019
+ }
1020
+ origin:^NSValue *_Nullable {
1021
+ return BGSRNReactOriginFindingTheRoot();
1022
+ }];
1023
+ // After the emitter exists. A network filter installed earlier reads this
1024
+ // pointer when an event arrives; it is nil until then, and a nil module
1025
+ // drops the event.
1026
+ BGSRNNetworkFilterModule = self;
1027
+ // After the emitter exists. The native log filter is already installed.
1028
+ // While a user callback is on, a nil module drops the line. With no user
1029
+ // callback the same filter returns the line.
1030
+ BGSRNLogFilterModule = self;
1031
+ // Same lifetime as the log filter: nil until the emitter exists, and a nil
1032
+ // module drops the crumb.
1033
+ BGSRNBreadcrumbFilterModule = self;
1034
+ }
1035
+
1036
+ /// Identity-checked inside the bus: a reload can construct and attach the NEW
1037
+ /// module before this one is invalidated, and an unconditional clear would then
1038
+ /// silence the live bridge.
1039
+ - (void)invalidate {
1040
+ // No super call: `invalidate` comes from RCTInvalidating, and
1041
+ // NativeBugseeSpecBase inherits NSObject, which does not declare it.
1042
+ [BGSRNEventBus.shared detach:self];
1043
+ // This runtime's Modal surfaces cannot be cleared by its JS any more. A
1044
+ // no-op when the next module has already claimed the store.
1045
+ [BGSRNSecureRectangles.shared releaseRuntime:_secureRuntime];
1046
+ // Also completes every report handle this module's JS was given: the next
1047
+ // runtime cannot know them, so the reports must not wait out their
1048
+ // deadlines.
1049
+ [BGSRNReportHandlerBridge.shared detach:self];
1050
+ // And answers nil to every data request this module's JS was given, and
1051
+ // disables the view tree until the next runtime mounts its anchor.
1052
+ [BGSRNDataRequestBridge.shared detach:self];
1053
+ // The next runtime cannot know a created-report handle, and a slot left
1054
+ // reserved would make every later createReport reject busy.
1055
+ [BGSRNCreatedReports.shared clear];
1056
+ // Drop this module's unanswered network events. A reload may already have
1057
+ // attached the new module; only clear the pointer when it is still us.
1058
+ BGSRNDropNetworkFiltersOwnedBy(self);
1059
+ if (BGSRNNetworkFilterModule == self) {
1060
+ BGSRNNetworkFilterModule = nil;
1061
+ }
1062
+ // Drop this module's unanswered log lines. A reload may already have
1063
+ // attached the new module; only clear the pointer when it is still us.
1064
+ BGSRNDropLogFiltersOwnedBy(self);
1065
+ if (BGSRNLogFilterModule == self) {
1066
+ BGSRNLogFilterModule = nil;
1067
+ }
1068
+ // Drop this module's unanswered crumbs. A reload may already have attached
1069
+ // the new module; only clear the pointer when it is still us.
1070
+ BGSRNDropBreadcrumbFiltersOwnedBy(self);
1071
+ if (BGSRNBreadcrumbFilterModule == self) {
1072
+ BGSRNBreadcrumbFilterModule = nil;
1073
+ }
1074
+ // The next runtime cannot know these handles. Drop them without finishing:
1075
+ // a reload must not close a transaction the SDK still has. The getter
1076
+ // must not allocate a fresh registry after this: a span call still in
1077
+ // flight would adopt into an object invalidate already abandoned.
1078
+ os_unfair_lock_lock(&_spanRegistryLock);
1079
+ _spansRetired = YES;
1080
+ BGSRNSpanHandles *previous = _spanHandles;
1081
+ _spanHandles = [BGSRNSpanHandles closedRegistry];
1082
+ os_unfair_lock_unlock(&_spanRegistryLock);
1083
+ [previous releaseAll];
1084
+ }
1085
+
1086
+ /// The SDK touches UIKit during start-up, so it must not be constructed on a
1087
+ /// background queue. React Native honours this for module setup; the main-queue
1088
+ /// hops below cover the method calls, which it does not.
1089
+ + (BOOL)requiresMainQueueSetup {
1090
+ return YES;
1091
+ }
1092
+
1093
+ - (void)setSecureRectangles:(double)display
1094
+ coordinates:(NSArray *)coordinates {
1095
+ [self setSecureRectanglesOnSurface:display
1096
+ surface:BGSRNSecureMainSurface
1097
+ coordinates:coordinates];
1098
+ }
1099
+
1100
+ - (void)setSecureRectanglesOnSurface:(double)display
1101
+ surface:(double)surface
1102
+ coordinates:(NSArray *)coordinates {
1103
+ const NSUInteger count = coordinates.count;
1104
+ // Codegen hands numbers across as double, because that is what a JS number
1105
+ // is. Rounding rather than truncating: the JS side has already rounded each
1106
+ // edge outwards, and truncating would pull an edge back inside the region it
1107
+ // was widened to cover.
1108
+ int32_t *flat = count > 0 ? (int32_t *)malloc(count * sizeof(int32_t)) : NULL;
1109
+ if (count > 0 && flat == NULL) {
1110
+ return;
1111
+ }
1112
+ for (NSUInteger i = 0; i < count; i++) {
1113
+ flat[i] = (int32_t)llround([coordinates[i] doubleValue]);
1114
+ }
1115
+
1116
+ // Ignored once a newer runtime has claimed the store: this module's late
1117
+ // writes (a reload's teardown) must not touch the next runtime's lanes,
1118
+ // whose keys may be the same React tags.
1119
+ const NSInteger key = (NSInteger)llround(surface);
1120
+ const BOOL published = [BGSRNSecureRectangles.shared setCoordinates:flat
1121
+ count:count
1122
+ forDisplay:(NSInteger)display
1123
+ surface:key
1124
+ runtime:_secureRuntime];
1125
+ free(flat);
1126
+ // The main surface's rectangles: find the React root now, on main, and
1127
+ // record its window's place, rather than leave the lane failing closed
1128
+ // until a pull's search (`BGSRNReactRootOriginTracker`) gets to it.
1129
+ if (published && count > 0 && key == BGSRNSecureMainSurface) {
1130
+ const NSInteger target = (NSInteger)display;
1131
+ BGSRNRunOnMain(^{
1132
+ NSValue *origin = [BGSRNSecureOriginTracker() originFindingTheRoot];
1133
+ if (origin != nil) {
1134
+ [BGSRNSecureRectangles.shared setOrigin:origin.CGPointValue forDisplay:target];
1135
+ }
1136
+ });
1137
+ }
1138
+ // A <Modal>'s rectangles: name this runtime's lookup of its host, so the
1139
+ // pull places them by this runtime's Modal. An empty publish (the Modal
1140
+ // clearing on unmount) names nothing.
1141
+ if (published && count > 0 && key != BGSRNSecureMainSurface) {
1142
+ [self nameModalHostForSurface:key];
1143
+ }
1144
+ }
1145
+
1146
+ /// Names, under this module's claim, how the store finds the `<Modal>` host
1147
+ /// with React tag `surface`: this runtime's view registry, which another
1148
+ /// runtime's same-tag host is not in. Not looked up here: Fabric mounts the
1149
+ /// host after JS has measured and published inside it, so the pull asks (on
1150
+ /// main) until the host is there, then holds it weakly; until then the lane
1151
+ /// fails closed. No registry: nothing is named, and the pull falls back to a
1152
+ /// unique class+tag match.
1153
+ - (void)nameModalHostForSurface:(NSInteger)surface {
1154
+ __weak RCTViewRegistry *registry = self.viewRegistry_DEPRECATED;
1155
+ if (registry == nil) {
1156
+ return;
1157
+ }
1158
+ [BGSRNSecureRectangles.shared setHostResolver:^id _Nullable(NSInteger tag) {
1159
+ return [registry viewForReactTag:@(tag)];
1160
+ }
1161
+ forSurface:surface
1162
+ runtime:_secureRuntime];
1163
+ }
1164
+
1165
+ /// The screen origin `[x, y]` (points) of the `<Modal>` whose host has React
1166
+ /// tag `surface`, for the `vh` walk, which asks once per Modal per walk.
1167
+ /// Empty when the Modal is not presented.
1168
+ - (NSArray<NSNumber *> *)secureSurfaceOrigin:(double)surface {
1169
+ __block NSArray<NSNumber *> *origin = @[];
1170
+ const NSInteger key = (NSInteger)llround(surface);
1171
+ BGSRNRunOnMainSync(^{
1172
+ NSValue *value = BGSRNModalSurfaceOrigin(key);
1173
+ if (value != nil) {
1174
+ CGPoint p = value.CGPointValue;
1175
+ origin = @[ @(p.x), @(p.y) ];
1176
+ }
1177
+ });
1178
+ return origin;
1179
+ }
1180
+
1181
+ #pragma mark - Blackout and view-hierarchy capture (design doc §4.1)
1182
+
1183
+ // iOS honours startBlackout/endBlackout regardless of launch state; Android
1184
+ // does too since 7.4.0 (bugsee-android#248).
1185
+
1186
+ - (void)startBlackout {
1187
+ BGSRNRunOnMain(^{
1188
+ [Bugsee startBlackout];
1189
+ });
1190
+ }
1191
+
1192
+ - (void)endBlackout {
1193
+ BGSRNRunOnMain(^{
1194
+ [Bugsee endBlackout];
1195
+ });
1196
+ }
1197
+
1198
+ - (void)isBlackout:(RCTPromiseResolveBlock)resolve
1199
+ reject:(RCTPromiseRejectBlock)reject {
1200
+ BGSRNRunOnMain(^{
1201
+ resolve(@([Bugsee isBlackout]));
1202
+ });
1203
+ }
1204
+
1205
+ - (void)captureViewHierarchy {
1206
+ BGSRNRunOnMain(^{
1207
+ [Bugsee captureViewHierarchy];
1208
+ });
1209
+ }
1210
+
1211
+ #pragma mark - View-hierarchy data request (design doc Phase 6, Task 6.6)
1212
+
1213
+ /// JS mounted its first `Bugsee.wrap` anchor (YES) or unmounted its last (NO).
1214
+ /// Until YES, the bridge answers the SDK nil without asking JS.
1215
+ - (void)setViewTreeEnabled:(BOOL)enabled {
1216
+ [BGSRNDataRequestBridge.shared setViewTreeEnabled:enabled forSink:self];
1217
+ }
1218
+
1219
+ /// JS's one synchronous answer to `onDataRequest`: the view tree as JSON
1220
+ /// text, or `nil`. A late, repeated or unknown id is dropped by the bridge.
1221
+ /// Runs on the module's method queue and never hops to main: the SDK is not
1222
+ /// waiting on main, and a hop would only spend the deadline queueing behind
1223
+ /// UI work.
1224
+ - (void)replyDataRequest:(NSString *)requestId
1225
+ payload:(NSString * _Nullable)payload {
1226
+ [BGSRNDataRequestBridge.shared complete:requestId payload:payload];
1227
+ }
1228
+
1229
+ - (void)setWrapperInfo:(NSDictionary *)identity {
1230
+ // The SDK holds the wrapper for the process's lifetime and reads it while
1231
+ // composing a report's environment, so this must be registered before
1232
+ // launch rather than alongside it. Through BGSRNSetWrapper, the one route
1233
+ // to `+setWrapper:` in this module. Not onlyIfAbsent: this is the
1234
+ // replacement of the thin identity `init` registered.
1235
+ BGSRNSetWrapper((id<BugseeWrapper>)[BGSRNWrapper wrapperWithIdentity:identity], NO);
1236
+ }
1237
+
1238
+ /// The SDK's status now, Stopped when it was never launched.
1239
+ static BugseeStatus BGSRNCurrentStatus(void) {
1240
+ Bugsee *instance = [Bugsee sharedInstance];
1241
+ return instance != nil ? instance.status : BugseeStatusStopped;
1242
+ }
1243
+
1244
+ /// The launch options with the Expo plugin's `endpoint` option, from this
1245
+ /// app's Info.plist, when JS passed no endpoint (BGSRNPluginEndpoint).
1246
+ static NSDictionary *BGSRNResolvedLaunchOptions(NSDictionary *options) {
1247
+ return BGSRNOptionsWithPluginEndpoint(
1248
+ options, [NSBundle.mainBundle objectForInfoDictionaryKey:BGSRNPluginEndpointInfoKey]);
1249
+ }
1250
+
1251
+ - (void)launch:(NSString *)token
1252
+ options:(NSDictionary *)options
1253
+ resolve:(RCTPromiseResolveBlock)resolve
1254
+ reject:(RCTPromiseRejectBlock)reject {
1255
+ if (!BGSRNTokenIsUsable(token)) {
1256
+ reject(@"E_TOKEN", @"Bugsee.launch requires a non-empty app token", nil);
1257
+ return;
1258
+ }
1259
+ BGSRNRunOnMain(^{
1260
+ // launchWithToken: returns the instance, or nil when the SDK declines —
1261
+ // already running, or the token was rejected. Declining is a normal
1262
+ // outcome, so it resolves false rather than rejecting.
1263
+ Bugsee *instance = [Bugsee launchWithToken:token andOptions:BGSRNResolvedLaunchOptions(options)];
1264
+ // launch can replace the log filter. Put the pass-through, or the user
1265
+ // filter if one is already on, back. This does not set the filter to nil.
1266
+ BGSRNInstallLogEventFilter();
1267
+ resolve(@(instance != nil));
1268
+ });
1269
+ }
1270
+
1271
+ - (void)relaunch:(NSDictionary *)options
1272
+ resolve:(RCTPromiseResolveBlock)resolve
1273
+ reject:(RCTPromiseRejectBlock)reject {
1274
+ BGSRNRunOnMain(^{
1275
+ // NOT relaunchWithDictionaryOptions:, which is void — the bridge would
1276
+ // have to resolve an unconditional YES, so `relaunch` would mean "the
1277
+ // call was made" on iOS and "the SDK restarted" on Android, for one JS
1278
+ // signature. optionsFrom: converts the same dictionary, and the started:
1279
+ // overload reports what actually happened.
1280
+ [Bugsee relaunchWithOptions:[BugseeOptions optionsFrom:BGSRNResolvedLaunchOptions(options)]
1281
+ started:^(BOOL success) {
1282
+ // Onto the main queue: the SDK invokes started: on
1283
+ // whatever thread its stop completion happens to
1284
+ // use, and resolve/reject must be called from the
1285
+ // same queue this method hopped onto. Reinstall
1286
+ // here: relaunch can replace the log filter.
1287
+ dispatch_async(dispatch_get_main_queue(), ^{
1288
+ BGSRNInstallLogEventFilter();
1289
+ resolve(@(success));
1290
+ });
1291
+ }];
1292
+ });
1293
+ }
1294
+
1295
+ - (void)stop:(RCTPromiseResolveBlock)resolve
1296
+ reject:(RCTPromiseRejectBlock)reject {
1297
+ BGSRNRunOnMain(^{
1298
+ [Bugsee stop:^{
1299
+ resolve(@YES);
1300
+ }];
1301
+ });
1302
+ }
1303
+
1304
+ - (void)getStatus:(RCTPromiseResolveBlock)resolve
1305
+ reject:(RCTPromiseRejectBlock)reject {
1306
+ BGSRNRunOnMain(^{
1307
+ Bugsee *instance = [Bugsee sharedInstance];
1308
+ // No instance means the SDK was never launched, which is Stopped.
1309
+ BugseeStatus status = instance ? instance.status : BugseeStatusStopped;
1310
+ resolve(@(BGSRNStatusToWire(status)));
1311
+ });
1312
+ }
1313
+
1314
+ - (void)getLaunchOptions:(RCTPromiseResolveBlock)resolve
1315
+ reject:(RCTPromiseRejectBlock)reject {
1316
+ BGSRNRunOnMain(^{
1317
+ NSDictionary *options = [Bugsee getLaunchOptions] ?: @{};
1318
+ #if DEBUG
1319
+ // The example's e2e reads these off the simulator console. Logging them
1320
+ // from the JS continuation of this call does not arrive there: the lines
1321
+ // on either side do, and these two do not. NSLog is what `simctl` streams.
1322
+ id duration = options[@"com.bugsee.option.config.duration"];
1323
+ id wifi = options[@"com.bugsee.option.config.wifi-only-upload"];
1324
+ NSString *wifiText = @"undefined";
1325
+ if ([wifi isKindOfClass:[NSNumber class]]) {
1326
+ wifiText = [(NSNumber *)wifi boolValue] ? @"true" : @"false";
1327
+ } else if ([wifi isKindOfClass:[NSString class]]) {
1328
+ wifiText = wifi;
1329
+ }
1330
+ NSLog(@"BUGSEE_E2E effective duration=%@ keys=%lu",
1331
+ duration ?: @"undefined", (unsigned long)options.count);
1332
+ NSLog(@"BUGSEE_E2E effective wifi-only-upload=%@", wifiText);
1333
+ #endif
1334
+ resolve(options);
1335
+ });
1336
+ }
1337
+
1338
+ - (void)testCrash {
1339
+ BGSRNRunOnMain(^{
1340
+ [Bugsee testCrash];
1341
+ });
1342
+ }
1343
+
1344
+ /// A handled JS exception. `payloadJson` is the Task 7.1a payload, forwarded
1345
+ /// verbatim as the reason; `optionsJson` is `{domain?}` or null. Unparseable
1346
+ /// options are logged and the exception is still sent, without a domain — a
1347
+ /// void method has no promise to reject.
1348
+ - (void)logException:(NSString *)payloadJson
1349
+ optionsJson:(NSString * _Nullable)optionsJson {
1350
+ BGSRNRunOnMain(^{
1351
+ NSError *error = nil;
1352
+ BGSRNExceptionOptions *opts =
1353
+ [BGSRNExceptions loggingOptionsFromJSON:optionsJson error:&error];
1354
+ if (optionsJson != nil && opts == nil) {
1355
+ NSLog(@"BugseeRN exception options unparseable: %@", BGSRNErrorMessage(error));
1356
+ }
1357
+ const NSUInteger bytes = [payloadJson lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1358
+ // WORKAROUND for bugsee-cocoa#227: held while the SDK is Launching, which
1359
+ // would drop it silently (BGSRNLaunchHold).
1360
+ NSString *label = [NSString stringWithFormat:@"exception handled bytes=%lu", (unsigned long)bytes];
1361
+ [BGSRNLaunchHold.shared submit:label call:^(BGSRNGatedRun run) {
1362
+ if (run == BGSRNGatedRunDrop) {
1363
+ NSLog(@"BugseeRN exception handled dropped bytes=%lu: the SDK did not launch", (unsigned long)bytes);
1364
+ return;
1365
+ }
1366
+ const BugseeStatus status = BGSRNCurrentStatus();
1367
+ // 7.0.0-beta7 has no options object: the domain is an argument.
1368
+ [Bugsee logException:BGSRNReactNativeExceptionName
1369
+ reason:payloadJson
1370
+ domain:opts.domain
1371
+ skipFrames:0
1372
+ completion:nil];
1373
+ // "sent" only for a call the SDK accepts: it drops one made when it is
1374
+ // not Launched (before launch(), or after stop()).
1375
+ if (status == BugseeStatusLaunched) {
1376
+ NSLog(@"BugseeRN exception handled sent bytes=%lu", (unsigned long)bytes);
1377
+ } else {
1378
+ NSLog(@"BugseeRN exception handled dropped bytes=%lu status=%ld: the SDK is not launched",
1379
+ (unsigned long)bytes, (long)BGSRNStatusToWire(status));
1380
+ }
1381
+ }];
1382
+ });
1383
+ }
1384
+
1385
+ /// An unhandled JS exception. The call stores `override_report.plcrash`,
1386
+ /// for the next launch to recover. 7.0.0-beta4 claims it ahead of
1387
+ /// `live_report.plcrash` (bugsee-cocoa #177; beta3 claimed only the live
1388
+ /// file and dropped this report); beta4 still missed some relaunches on an
1389
+ /// iPhone XS, which 7.0.0-beta5 fixes (bugsee-cocoa #191: the report is
1390
+ /// claimed by the build that armed the reporter). Do not copy one file onto the other. The completion is wrapped in `BGSRNSettleOnce`: on the
1391
+ /// simulator the SDK compiles `logUnhandledException` out and never calls
1392
+ /// this completion (verified facts), and a promise must still settle.
1393
+ - (void)logUnhandledException:(NSString *)payloadJson
1394
+ resolve:(RCTPromiseResolveBlock)resolve
1395
+ reject:(RCTPromiseRejectBlock)reject {
1396
+ BGSRNRunOnMain(^{
1397
+ NSUInteger bytes = [payloadJson lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1398
+ NSLog(@"BugseeRN exception unhandled sent bytes=%lu", (unsigned long)bytes);
1399
+ // `by=sdk` when the SDK's completion settled this, `by=deadline` when the
1400
+ // wrapper's own deadline did. Observability only: it changes no timing.
1401
+ auto sdkCompleted = std::make_shared<std::atomic<bool>>(false);
1402
+ dispatch_block_t done =
1403
+ BGSRNSettleOnce(BGSRNUnhandledCompletionDeadlineMs, dispatch_get_main_queue(), ^{
1404
+ NSLog(@"BugseeRN exception unhandled completed by=%s", sdkCompleted->load() ? "sdk" : "deadline");
1405
+ resolve(nil);
1406
+ });
1407
+ [Bugsee logUnhandledException:BGSRNReactNativeExceptionName
1408
+ reason:payloadJson
1409
+ completion:^{
1410
+ sdkCompleted->store(true);
1411
+ done();
1412
+ }];
1413
+ });
1414
+ }
1415
+
1416
+ /// JS has already checked both strings, the severity range and the labels.
1417
+ /// Severity 0 is resolved here: the requested value, else the launch option
1418
+ /// `BugseeOptionReportingDefaultBugPriority`, else High. On main, like every
1419
+ /// other SDK entry point. Does nothing before launch() -- the SDK returns;
1420
+ /// held while the SDK is Launching (bugsee-cocoa#227, BGSRNLaunchHold).
1421
+ /// The report it creates is a LIVE one, so its handlers run on main too,
1422
+ /// after this returns.
1423
+ - (void)upload:(NSString *)summary
1424
+ description:(NSString *)description
1425
+ severity:(double)severity
1426
+ labels:(NSArray *)labels {
1427
+ BGSRNRunOnMain(^{
1428
+ // WORKAROUND for bugsee-cocoa#227: held while the SDK is Launching
1429
+ // (BGSRNLaunchHold). Severity is resolved at replay, against the options
1430
+ // the launch actually applied.
1431
+ [BGSRNLaunchHold.shared submit:@"upload" call:^(BGSRNGatedRun run) {
1432
+ if (run == BGSRNGatedRunDrop) {
1433
+ NSLog(@"BugseeRN upload dropped: the SDK did not launch");
1434
+ return;
1435
+ }
1436
+ [Bugsee uploadWithSummary:summary
1437
+ description:description
1438
+ severity:(BugseeSeverityLevel)BGSRNUploadSeverity((NSInteger)severity,
1439
+ [Bugsee getLaunchOptions])
1440
+ labels:BGSRNStringArray(labels)];
1441
+ if (run == BGSRNGatedRunReplay) {
1442
+ NSLog(@"BugseeRN upload sent");
1443
+ }
1444
+ }];
1445
+ });
1446
+ }
1447
+
1448
+ /// Every argument absent (`nil`, `nil`, `0`, `nil`) calls the no-argument
1449
+ /// dialog. Otherwise an omitted summary or description stays `nil`: beta3
1450
+ /// writes the field only when the pointer is non-nil, and `@""` would
1451
+ /// pre-fill an empty string. A 0 severity is left for the SDK to skip.
1452
+ /// On main. Does nothing before launch(); held while Launching
1453
+ /// (bugsee-cocoa#227, BGSRNLaunchHold). The dialog runs
1454
+ /// `onBeforeReportCreated` before it opens.
1455
+ - (void)showReportDialog:(NSString *)summary
1456
+ description:(NSString *)description
1457
+ severity:(double)severity
1458
+ labels:(NSArray *)labels {
1459
+ BGSRNRunOnMain(^{
1460
+ // WORKAROUND for bugsee-cocoa#227: held while the SDK is Launching
1461
+ // (BGSRNLaunchHold).
1462
+ [BGSRNLaunchHold.shared submit:@"report dialog" call:^(BGSRNGatedRun run) {
1463
+ if (run == BGSRNGatedRunDrop) {
1464
+ NSLog(@"BugseeRN report dialog dropped: the SDK did not launch");
1465
+ return;
1466
+ }
1467
+ if (run == BGSRNGatedRunReplay) {
1468
+ NSLog(@"BugseeRN report dialog sent");
1469
+ }
1470
+ if (summary == nil && description == nil && severity == 0.0 && labels == nil) {
1471
+ [Bugsee showReportDialog];
1472
+ return;
1473
+ }
1474
+ [Bugsee showReportDialogWithSummary:summary
1475
+ description:description
1476
+ severity:(BugseeSeverityLevel)severity
1477
+ labels:BGSRNStringArray(labels)];
1478
+ }];
1479
+ });
1480
+ }
1481
+
1482
+ /// Records a named event, with optional params.
1483
+ ///
1484
+ /// `paramsJson` is the params as JSON text (`src/bridge/json.ts`), parsed by
1485
+ /// `BGSRNJSONObject`. Not an `NSDictionary` argument: React Native's
1486
+ /// conversion of one drops every member whose JS value is `null`, so
1487
+ /// `{ nil: null }` reached the SDK as `{}` here while Android kept it. Parsed
1488
+ /// text keeps it as `NSNull`. Text that does not parse drops the event,
1489
+ /// logged: a void method has no promise to reject.
1490
+ ///
1491
+ /// `paramsJson` is `nil` exactly when JS sent `null` (no params given) rather
1492
+ /// than `'{}'` -- the bundle's event entry has no `params` key at all when
1493
+ /// none were given (design doc, Phase 4 bundle facts). JS has already
1494
+ /// validated params against the accepted value domain and copied it
1495
+ /// (`src/data/validate.ts`), so nothing here is re-checked. On main, like
1496
+ /// every other SDK entry point.
1497
+ - (void)event:(NSString *)name
1498
+ paramsJson:(NSString * _Nullable)paramsJson {
1499
+ NSDictionary *params = nil;
1500
+ if (paramsJson != nil) {
1501
+ NSError *error = nil;
1502
+ params = BGSRNJSONObject(paramsJson, &error);
1503
+ if (params == nil) {
1504
+ NSLog(@"BugseeRN event \"%@\" dropped: its params are not a JSON object: %@", name,
1505
+ BGSRNErrorMessage(error));
1506
+ return;
1507
+ }
1508
+ }
1509
+ BGSRNRunOnMain(^{
1510
+ [Bugsee event:name params:params];
1511
+ });
1512
+ }
1513
+
1514
+ /// A numeric trace value, boxed the ordinary way -- `@(value)` for a
1515
+ /// `double` always produces a plain `NSNumber`, not a `CFBoolean`, so there is
1516
+ /// no identity hazard here the way there is for `traceBoolean:value:` below.
1517
+ - (void)traceNumber:(NSString *)name
1518
+ value:(double)value {
1519
+ BGSRNRunOnMain(^{
1520
+ [Bugsee trace:name value:@(value)];
1521
+ });
1522
+ }
1523
+
1524
+ /// A string trace value.
1525
+ - (void)traceString:(NSString *)name
1526
+ value:(NSString *)value {
1527
+ BGSRNRunOnMain(^{
1528
+ [Bugsee trace:name value:value];
1529
+ });
1530
+ }
1531
+
1532
+ /// A boolean trace value, through `BGSRNBoolNumber` -- kept apart from
1533
+ /// `traceNumber:value:` so it cannot silently arrive as `0`/`1`, and boxed
1534
+ /// through the CFBoolean singleton rather than `@(value)` so the SDK's JSON
1535
+ /// writer, which special-cases `CFBoolean` by object identity, actually
1536
+ /// serialises it as `true`/`false`.
1537
+ - (void)traceBoolean:(NSString *)name
1538
+ value:(BOOL)value {
1539
+ BGSRNRunOnMain(^{
1540
+ [Bugsee trace:name value:BGSRNBoolNumber(value)];
1541
+ });
1542
+ }
1543
+
1544
+ /// The app's own `Bugsee.log()` line, through the SDK's public `+[Bugsee
1545
+ /// log:level:requiresFiltering:]` -- not the wrapper channel, which records
1546
+ /// nothing with `capture.logs` off. `requiresFiltering` is the app's choice,
1547
+ /// passed through: the app's log filter runs on the line only when it is YES.
1548
+ ///
1549
+ /// Not a channel line, so no `BGSRNBeginChannelLine`: the echo drop in the log
1550
+ /// filter never takes a line that is neither stdout/stderr nor a console stamp.
1551
+ /// Level by value, rounded as in `wrapperLog:` below.
1552
+ ///
1553
+ /// Not hopped to main. Android's `log` calls `Bugsee.log` on the native-modules
1554
+ /// thread too, and `wrapperLog:` reached the same SDK log core from this queue.
1555
+ /// Staying here keeps these lines in JS order with the console lines.
1556
+ - (void)log:(NSString *)message
1557
+ level:(double)level
1558
+ requiresFiltering:(BOOL)requiresFiltering {
1559
+ [Bugsee log:message
1560
+ level:BGSRNLogLevelForWireValue((NSInteger)llround(level))
1561
+ requiresFiltering:requiresFiltering];
1562
+ }
1563
+
1564
+ /// Forwards a JS log line through the wrapper channel (tag nil,
1565
+ /// `BGSLogEventSourceCustom`, level by value -- see `BGSRNWrapperChannelHolder`).
1566
+ ///
1567
+ /// `level` arrives as `double` because that is what a JS number is; JS
1568
+ /// already restricts it to the 1-5 wire values (`forwardLog` in
1569
+ /// `wrapper/channel.ts`), but rounding rather than truncating matches the
1570
+ /// caution taken with secure-rectangle coordinates above -- a stray fraction
1571
+ /// should land on the nearest level, not be chopped toward one.
1572
+ - (void)wrapperLog:(NSString *)message
1573
+ level:(double)level {
1574
+ // Keeping this channel line ends the equal-text claim. A later Custom line
1575
+ // of the same text is not dropped. One raw stdout or stderr line of this
1576
+ // text may still be, and so may a stderr stamp.
1577
+ BGSRNBeginChannelLine(message);
1578
+ @try {
1579
+ [BGSRNWrapperChannelHolder.shared logMessage:message level:(NSInteger)llround(level)];
1580
+ } @finally {
1581
+ BGSRNEndChannelLine(message);
1582
+ }
1583
+ }
1584
+
1585
+ /// `NSNumber`, not void: codegen queues a void method on the method queue,
1586
+ /// and the SDK could capture the console echo before the note existed. The
1587
+ /// console hook calls this on the JS thread before it writes the line.
1588
+ - (NSNumber *)noteConsoleEcho:(NSString *)message {
1589
+ BGSRNNoteConsoleEcho(message);
1590
+ return @YES;
1591
+ }
1592
+
1593
+
1594
+ /// `setNetworkEventFilter:`, the method the iOS SDK installs a network filter
1595
+ /// with. `enabled` registers the bridge; `NO` passes nil, which removes it.
1596
+ /// The write is synchronized and does not need the main queue, so it happens
1597
+ /// before this method returns: a later Bugsee call on the same turn already
1598
+ /// sees the filter. The block returns without waiting on JS. There is no
1599
+ /// deadline here.
1600
+ ///
1601
+ /// Returns `@YES`. The return is what keeps the call on the JS thread:
1602
+ /// codegen queues a `void` TurboModule method onto the module queue, so a
1603
+ /// request started on the next line could be recorded before a queued
1604
+ /// install landed, with its url, headers and body unfiltered. The SDK setter
1605
+ /// only takes a lock, so it is safe on the JS thread.
1606
+ - (NSNumber *)setNetworkFilterEnabled:(BOOL)enabled {
1607
+ if (enabled) {
1608
+ @synchronized (BGSRNNetworkFilterLock()) {
1609
+ if (BGSRNNetworkFilterInstalled) {
1610
+ return @YES;
1611
+ }
1612
+ BGSRNNetworkFilterInstalled = YES;
1613
+ }
1614
+ [Bugsee setNetworkEventFilter:^(BugseeNetworkEvent *event, BugseeNetworkFilterDecisionBlock decision) {
1615
+ if (decision == nil) {
1616
+ return;
1617
+ }
1618
+ if (event == nil) {
1619
+ decision(nil);
1620
+ return;
1621
+ }
1622
+ BugseeModule *module = BGSRNNetworkFilterModule;
1623
+ if (module == nil) {
1624
+ decision(nil);
1625
+ return;
1626
+ }
1627
+ NSString *eventJson = BGSRNNetworkEventJSON(event);
1628
+ if (eventJson == nil) {
1629
+ decision(nil);
1630
+ return;
1631
+ }
1632
+ BGSRNNetworkFilterPending *item = [BGSRNNetworkFilterPending new];
1633
+ item.event = event;
1634
+ item.decision = decision;
1635
+ item.owner = module;
1636
+ NSString *requestId = nil;
1637
+ @synchronized (BGSRNNetworkFilterLock()) {
1638
+ BGSRNNetworkFilterNextId += 1;
1639
+ requestId = [NSString stringWithFormat:@"%lld", BGSRNNetworkFilterNextId];
1640
+ BGSRNNetworkFilterPendingTable[requestId] = item;
1641
+ }
1642
+ const BOOL delivered = [module emitNetworkFilterRequest:requestId eventJson:eventJson];
1643
+ if (!delivered) {
1644
+ BugseeNetworkFilterDecisionBlock drop = nil;
1645
+ @synchronized (BGSRNNetworkFilterLock()) {
1646
+ BGSRNNetworkFilterPending *removed = BGSRNNetworkFilterPendingTable[requestId];
1647
+ [BGSRNNetworkFilterPendingTable removeObjectForKey:requestId];
1648
+ drop = removed.decision;
1649
+ }
1650
+ if (drop != nil) {
1651
+ drop(nil);
1652
+ }
1653
+ }
1654
+ }];
1655
+ return @YES;
1656
+ }
1657
+ @synchronized (BGSRNNetworkFilterLock()) {
1658
+ BGSRNNetworkFilterInstalled = NO;
1659
+ }
1660
+ [Bugsee setNetworkEventFilter:nil];
1661
+ return @YES;
1662
+ }
1663
+
1664
+ - (BOOL)emitNetworkFilterRequest:(NSString *)requestId eventJson:(NSString *)eventJson {
1665
+ NSDictionary *payload = @{ @"requestId" : requestId, @"eventJson" : eventJson };
1666
+ return BGSRNGuardedEmit(^{
1667
+ [self emitOnNetworkFilterRequest:payload];
1668
+ }, @"onNetworkFilterRequest");
1669
+ }
1670
+
1671
+ /// `eventJson` nil drops. A JSON object is written onto the same event, so
1672
+ /// the timestamp stays. A second reply is a no-op. A late reply still
1673
+ /// records: this method does not expire the decision.
1674
+ - (void)replyNetworkFilter:(NSString *)requestId eventJson:(NSString * _Nullable)eventJson {
1675
+ if (requestId == nil) {
1676
+ return;
1677
+ }
1678
+ BGSRNNetworkFilterPending *item = nil;
1679
+ @synchronized (BGSRNNetworkFilterLock()) {
1680
+ item = BGSRNNetworkFilterPendingTable[requestId];
1681
+ if (item != nil) {
1682
+ [BGSRNNetworkFilterPendingTable removeObjectForKey:requestId];
1683
+ }
1684
+ }
1685
+ if (item.decision == nil) {
1686
+ return;
1687
+ }
1688
+ if (eventJson == nil) {
1689
+ item.decision(nil);
1690
+ return;
1691
+ }
1692
+ if (!BGSRNApplyNetworkReplacement(item.event, eventJson)) {
1693
+ item.decision(nil);
1694
+ return;
1695
+ }
1696
+ item.decision(item.event);
1697
+ }
1698
+
1699
+ /// A network event the app recorded itself. The bridge stamps the time in
1700
+ /// epoch milliseconds and builds a `BugseeNetworkEvent`. Beta3's exchange
1701
+ /// factory `createNetworkEvent` always returns nil, so this does not call it.
1702
+ /// The event is submitted with filtering required. The one-argument
1703
+ /// `addNetworkEvent:` passes NO and is not used. There is no timer that
1704
+ /// would pass the original through.
1705
+ - (void)addNetworkEvent:(NSString *)eventJson {
1706
+ NSError *error = nil;
1707
+ NSDictionary *object = BGSRNJSONObject(eventJson, &error);
1708
+ if (object == nil) {
1709
+ return;
1710
+ }
1711
+ BGSRNNetworkEventOutcome outcome = BGSRNRecordNetworkEvent(
1712
+ object,
1713
+ ^(BugseeNetworkEvent *event, BOOL requiresFiltering) {
1714
+ if (!requiresFiltering) {
1715
+ return;
1716
+ }
1717
+ [Bugsee addNetworkEvent:event requiresFiltering:YES];
1718
+ },
1719
+ [[NSDate date] timeIntervalSince1970] * 1000.0);
1720
+ if (outcome == BGSRNNetworkEventOutcomeNoEvent) {
1721
+ NSLog(@"BugseeRN addNetworkEvent dropped: the SDK made no event");
1722
+ }
1723
+ }
1724
+
1725
+ /// Returns `@YES`. The return is what keeps the call on the JS thread:
1726
+ /// codegen queues a `void` TurboModule method onto the module queue, so a
1727
+ /// console line written on the next line could be captured before a queued
1728
+ /// flag flip landed. The flag write and the SDK setter only take locks.
1729
+ - (NSNumber *)setLogFilterEnabled:(BOOL)enabled {
1730
+ @synchronized (BGSRNLogFilterLock()) {
1731
+ BGSRNLogFilterUserEnabled = enabled;
1732
+ }
1733
+ BGSRNInstallLogEventFilter();
1734
+ return @YES;
1735
+ }
1736
+
1737
+ - (BOOL)emitLogFilterRequest:(NSString *)requestId line:(NSString *)line {
1738
+ NSDictionary *payload = @{ @"requestId" : requestId, @"line" : line };
1739
+ return BGSRNGuardedEmit(^{
1740
+ [self emitOnLogFilterRequest:payload];
1741
+ }, @"onLogFilterRequest");
1742
+ }
1743
+
1744
+ /// `line` nil drops. A string is written onto the same event, so the level
1745
+ /// and the timestamp stay. If the write does not stick, the line is dropped
1746
+ /// rather than kept unredacted. A second reply is a no-op.
1747
+ - (void)replyLogFilter:(NSString *)requestId line:(NSString * _Nullable)line {
1748
+ if (requestId == nil) {
1749
+ return;
1750
+ }
1751
+ BGSRNLogFilterPending *item = nil;
1752
+ @synchronized (BGSRNLogFilterLock()) {
1753
+ item = BGSRNLogFilterPendingTable[requestId];
1754
+ if (item != nil) {
1755
+ [BGSRNLogFilterPendingTable removeObjectForKey:requestId];
1756
+ }
1757
+ }
1758
+ if (item.decision == nil) {
1759
+ return;
1760
+ }
1761
+ if (line == nil) {
1762
+ item.decision(nil);
1763
+ return;
1764
+ }
1765
+ item.event.text = line;
1766
+ if (![item.event.text isEqualToString:line]) {
1767
+ item.decision(nil);
1768
+ return;
1769
+ }
1770
+ item.decision(item.event);
1771
+ }
1772
+
1773
+ /// `setBreadcrumbFilter:`. `enabled` registers the bridge; `NO` passes nil,
1774
+ /// which removes it. The block returns without waiting on JS.
1775
+ ///
1776
+ /// Returns `@YES`. The return is what keeps the call on the JS thread:
1777
+ /// codegen queues a `void` TurboModule method onto the shared module queue,
1778
+ /// and `addBreadcrumb` (which returns a value) runs inline. A queued clear
1779
+ /// could then uninstall on main between a same-turn re-enable and the add
1780
+ /// after it, and that add recorded with no filter, its original value kept.
1781
+ ///
1782
+ /// Enable stays on the calling queue, before this method returns. Not wrapped
1783
+ /// in `BGSRNRunOnMain`: an async install would let a crumb recorded on the
1784
+ /// next line pass before the filter existed. Disable hops to the main queue,
1785
+ /// where `addBreadcrumb` already queued its record. That queue is FIFO, so
1786
+ /// the nil cannot overtake the crumb. The generation this disable captured
1787
+ /// has to still be current or the nil does not run: a clear and then a new
1788
+ /// callback, before main runs, must not have the queued nil remove the newer
1789
+ /// filter. There is no timer that calls `decision(nil)`. A late decision
1790
+ /// still records.
1791
+ - (NSNumber *)setBreadcrumbFilterEnabled:(BOOL)enabled {
1792
+ if (enabled) {
1793
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1794
+ BGSRNBreadcrumbFilterGeneration += 1;
1795
+ if (BGSRNBreadcrumbFilterInstalled) {
1796
+ return @YES;
1797
+ }
1798
+ BGSRNBreadcrumbFilterInstalled = YES;
1799
+ }
1800
+ [Bugsee setBreadcrumbFilter:^(id<BGSBreadcrumb> breadcrumb, BugseeBreadcrumbFilterDecisionBlock decision) {
1801
+ if (decision == nil) {
1802
+ return;
1803
+ }
1804
+ if (breadcrumb == nil) {
1805
+ decision(nil);
1806
+ return;
1807
+ }
1808
+ BugseeModule *module = BGSRNBreadcrumbFilterModule;
1809
+ if (module == nil) {
1810
+ decision(nil);
1811
+ return;
1812
+ }
1813
+ NSString *crumbJson = BGSRNBreadcrumbSnapshotJson(breadcrumb);
1814
+ if (crumbJson == nil) {
1815
+ decision(nil);
1816
+ return;
1817
+ }
1818
+ BGSRNBreadcrumbFilterPending *item = [BGSRNBreadcrumbFilterPending new];
1819
+ item.breadcrumb = breadcrumb;
1820
+ item.decision = decision;
1821
+ item.owner = module;
1822
+ NSString *requestId = nil;
1823
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1824
+ BGSRNBreadcrumbFilterNextId += 1;
1825
+ requestId = [NSString stringWithFormat:@"%lld", BGSRNBreadcrumbFilterNextId];
1826
+ BGSRNBreadcrumbFilterPendingTable[requestId] = item;
1827
+ }
1828
+ NSString *manualAddId = nil;
1829
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1830
+ manualAddId = BGSRNBreadcrumbManualAddId;
1831
+ }
1832
+ const BOOL delivered = [module emitBreadcrumbFilterRequest:requestId
1833
+ crumbJson:crumbJson
1834
+ addId:manualAddId];
1835
+ if (delivered && manualAddId != nil) {
1836
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1837
+ if ([BGSRNBreadcrumbManualAddId isEqualToString:manualAddId]) {
1838
+ BGSRNBreadcrumbManualAddId = nil;
1839
+ }
1840
+ }
1841
+ }
1842
+ if (!delivered) {
1843
+ BugseeBreadcrumbFilterDecisionBlock drop = nil;
1844
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1845
+ BGSRNBreadcrumbFilterPending *removed = BGSRNBreadcrumbFilterPendingTable[requestId];
1846
+ [BGSRNBreadcrumbFilterPendingTable removeObjectForKey:requestId];
1847
+ drop = removed.decision;
1848
+ }
1849
+ if (drop != nil) {
1850
+ drop(nil);
1851
+ }
1852
+ }
1853
+ }];
1854
+ return @YES;
1855
+ }
1856
+ int64_t generation = 0;
1857
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1858
+ BGSRNBreadcrumbFilterGeneration += 1;
1859
+ generation = BGSRNBreadcrumbFilterGeneration;
1860
+ }
1861
+ BGSRNRunOnMain(^{
1862
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1863
+ if (BGSRNBreadcrumbFilterGeneration != generation) {
1864
+ return;
1865
+ }
1866
+ BGSRNBreadcrumbFilterInstalled = NO;
1867
+ [Bugsee setBreadcrumbFilter:nil];
1868
+ }
1869
+ });
1870
+ return @YES;
1871
+ }
1872
+
1873
+ - (BOOL)emitBreadcrumbFilterRequest:(NSString *)requestId
1874
+ crumbJson:(NSString *)crumbJson
1875
+ addId:(NSString * _Nullable)addId {
1876
+ NSDictionary *payload = addId != nil
1877
+ ? @{ @"requestId" : requestId, @"crumbJson" : crumbJson, @"addId" : addId }
1878
+ : @{ @"requestId" : requestId, @"crumbJson" : crumbJson };
1879
+ return BGSRNGuardedEmit(^{
1880
+ [self emitOnBreadcrumbFilterRequest:payload];
1881
+ }, @"onBreadcrumbFilterRequest");
1882
+ }
1883
+
1884
+ /// The main-queue record dropped this id (no factory, no crumb, or the filter
1885
+ /// never asked). JS drops the owed callback. `crumbJson` is empty, so the
1886
+ /// callback does not run. The request id is not in the pending table, so the
1887
+ /// reply is a no-op. There is no timer.
1888
+ - (void)releaseBreadcrumbManualAdd:(NSString *)addId {
1889
+ if (addId.length == 0) {
1890
+ return;
1891
+ }
1892
+ [self emitBreadcrumbFilterRequest:@"release" crumbJson:@"" addId:addId];
1893
+ }
1894
+
1895
+ /// `crumbJson` nil drops. An object is written onto the same breadcrumb.
1896
+ /// `timestamp` is not written: `BGSEvent.timestamp` is read-only, and the SDK
1897
+ /// pins the time it observed before the filter ran. If a write does not
1898
+ /// stick, the crumb is dropped rather than kept unredacted. A second reply
1899
+ /// is a no-op. There is no timer.
1900
+ - (void)replyBreadcrumbFilter:(NSString *)requestId crumbJson:(NSString * _Nullable)crumbJson {
1901
+ if (requestId == nil) {
1902
+ return;
1903
+ }
1904
+ BGSRNBreadcrumbFilterPending *item = nil;
1905
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1906
+ item = BGSRNBreadcrumbFilterPendingTable[requestId];
1907
+ if (item != nil) {
1908
+ [BGSRNBreadcrumbFilterPendingTable removeObjectForKey:requestId];
1909
+ }
1910
+ }
1911
+ if (item.decision == nil) {
1912
+ return;
1913
+ }
1914
+ if (crumbJson == nil) {
1915
+ item.decision(nil);
1916
+ return;
1917
+ }
1918
+ NSError *error = nil;
1919
+ NSDictionary *kept = BGSRNJSONObject(crumbJson, &error);
1920
+ if (kept == nil || !BGSRNApplyBreadcrumbKeep(item.breadcrumb, kept)) {
1921
+ item.decision(nil);
1922
+ return;
1923
+ }
1924
+ item.decision(item.breadcrumb);
1925
+ }
1926
+
1927
+ /// The no-argument `createBreadcrumb` leaves the timestamp unset so the
1928
+ /// provider stamps it. `level` is the JS name, mapped to `BugseeLogLevel`.
1929
+ /// `dataJson` nil leaves data unset. The record itself is on main, like
1930
+ /// every other SDK entry point. Capture being off is decided here, on the
1931
+ /// calling queue, so this can return false without queueing. The filter
1932
+ /// install above is also on the calling queue. A filter clear is on the
1933
+ /// main queue, behind the block queued here.
1934
+ ///
1935
+ /// Returns true only when a filter request for `addId` was emitted or will
1936
+ /// be emitted. A drop on main (no factory, no crumb, or the filter never
1937
+ /// asked) releases that id so JS does not leave it owed. `addId` is echoed
1938
+ /// only for the duration of `[Bugsee addBreadcrumb:]`.
1939
+ - (NSNumber *)addBreadcrumb:(NSString *)category
1940
+ level:(NSString *)level
1941
+ message:(NSString *)message
1942
+ type:(NSString *)type
1943
+ dataJson:(NSString * _Nullable)dataJson
1944
+ addId:(NSString * _Nullable)addId {
1945
+ NSDictionary *data = nil;
1946
+ const BOOL hasData = dataJson != nil;
1947
+ if (hasData) {
1948
+ NSError *error = nil;
1949
+ data = BGSRNJSONObject(dataJson, &error);
1950
+ if (data == nil) {
1951
+ NSLog(@"BugseeRN addBreadcrumb dropped: its data is not a JSON object: %@",
1952
+ BGSRNErrorMessage(error));
1953
+ return @NO;
1954
+ }
1955
+ }
1956
+ NSInteger levelValue = 0;
1957
+ if (![level isKindOfClass:NSString.class]
1958
+ || !BGSRNBreadcrumbLevelFromName(level, &levelValue)) {
1959
+ NSLog(@"BugseeRN addBreadcrumb dropped: level is not a breadcrumb level name");
1960
+ return @NO;
1961
+ }
1962
+ // createBreadcrumb still returns a crumb when capture is left off, and
1963
+ // addBreadcrumb: then records nothing. The option is the signal, and it
1964
+ // is read here so a false return does not queue a record.
1965
+ id capture = [Bugsee getLaunchOptions][BugseeOptionCaptureBreadcrumbs];
1966
+ if (![capture isKindOfClass:NSNumber.class] || ![(NSNumber *)capture boolValue]) {
1967
+ NSLog(@"BugseeRN addBreadcrumb dropped: capture is off or the SDK made no crumb");
1968
+ return @NO;
1969
+ }
1970
+ __weak BugseeModule *module = self;
1971
+ BGSRNRunOnMain(^{
1972
+ BugseeModule *strong = module;
1973
+ id<BGSBugseeExchangeFactory> factory = [Bugsee getExchangeFactory];
1974
+ id<BGSBreadcrumb> crumb = factory != nil ? [factory createBreadcrumb] : nil;
1975
+ if (crumb == nil) {
1976
+ NSLog(@"BugseeRN addBreadcrumb dropped: capture is off or the SDK made no crumb");
1977
+ [strong releaseBreadcrumbManualAdd:addId];
1978
+ return;
1979
+ }
1980
+ crumb.category = category;
1981
+ crumb.level = levelValue;
1982
+ crumb.message = message;
1983
+ crumb.type = type;
1984
+ if (hasData) {
1985
+ crumb.data = data;
1986
+ }
1987
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1988
+ BGSRNBreadcrumbManualAddId = addId;
1989
+ }
1990
+ @try {
1991
+ [Bugsee addBreadcrumb:crumb];
1992
+ } @finally {
1993
+ NSString *leftover = nil;
1994
+ @synchronized (BGSRNBreadcrumbFilterLock()) {
1995
+ leftover = BGSRNBreadcrumbManualAddId;
1996
+ BGSRNBreadcrumbManualAddId = nil;
1997
+ }
1998
+ if (leftover != nil) {
1999
+ [strong releaseBreadcrumbManualAdd:leftover];
2000
+ }
2001
+ }
2002
+ });
2003
+ return addId != nil ? @YES : @NO;
2004
+ }
2005
+
2006
+ #pragma mark - Attributes and identity
2007
+
2008
+ - (void)setAttributeString:(NSString *)name
2009
+ value:(NSString *)value
2010
+ resolve:(RCTPromiseResolveBlock)resolve
2011
+ reject:(RCTPromiseRejectBlock)reject {
2012
+ BGSRNSetAttribute(name, value, resolve, reject);
2013
+ }
2014
+
2015
+ /// `@(value)`: iOS stores a double exactly, so unlike Android's `AttributeBridge
2016
+ /// .numberValue`, no integral conversion is needed to avoid a rounding trip.
2017
+ - (void)setAttributeNumber:(NSString *)name
2018
+ value:(double)value
2019
+ resolve:(RCTPromiseResolveBlock)resolve
2020
+ reject:(RCTPromiseRejectBlock)reject {
2021
+ BGSRNSetAttribute(name, @(value), resolve, reject);
2022
+ }
2023
+
2024
+ /// Through `BGSRNBoolNumber`, the CFBoolean singleton -- see `traceBoolean:
2025
+ /// value:` above for why a plain `@(value)` boxing is not good enough here
2026
+ /// either.
2027
+ - (void)setAttributeBoolean:(NSString *)name
2028
+ value:(BOOL)value
2029
+ resolve:(RCTPromiseResolveBlock)resolve
2030
+ reject:(RCTPromiseRejectBlock)reject {
2031
+ BGSRNSetAttribute(name, BGSRNBoolNumber(value), resolve, reject);
2032
+ }
2033
+
2034
+ /// Reads through `+getAllAttributes`, filtered by `BGSRNAttributes readable:`,
2035
+ /// rather than `+getAttribute:` -- the one persisted source `getAllAttributes`
2036
+ /// below also reads, so a single attribute and the whole set never disagree
2037
+ /// about what survived filtering (mirrors Android's `AttributeBridge.readOne`,
2038
+ /// which reads the persisted copy for the same reason).
2039
+ - (void)getAttribute:(NSString *)name
2040
+ resolve:(RCTPromiseResolveBlock)resolve
2041
+ reject:(RCTPromiseRejectBlock)reject {
2042
+ BGSRNRunOnMain(^{
2043
+ id value = [BGSRNAttributes readable:[Bugsee getAllAttributes]][name];
2044
+ resolve(value != nil ? @{ @"value" : value } : @{});
2045
+ });
2046
+ }
2047
+
2048
+ - (void)getAllAttributes:(RCTPromiseResolveBlock)resolve
2049
+ reject:(RCTPromiseRejectBlock)reject {
2050
+ BGSRNRunOnMain(^{
2051
+ resolve([BGSRNAttributes readable:[Bugsee getAllAttributes]]);
2052
+ });
2053
+ }
2054
+
2055
+ - (void)clearAttribute:(NSString *)name
2056
+ resolve:(RCTPromiseResolveBlock)resolve
2057
+ reject:(RCTPromiseRejectBlock)reject {
2058
+ BGSRNRunOnMain(^{
2059
+ [Bugsee clearAttribute:name];
2060
+ resolve(nil);
2061
+ });
2062
+ }
2063
+
2064
+ - (void)clearAllAttributes:(RCTPromiseResolveBlock)resolve
2065
+ reject:(RCTPromiseRejectBlock)reject {
2066
+ BGSRNRunOnMain(^{
2067
+ [Bugsee clearAllAttributes];
2068
+ resolve(nil);
2069
+ });
2070
+ }
2071
+
2072
+ - (void)setUserIdentifier:(NSString *)identifier {
2073
+ BGSRNRunOnMain(^{
2074
+ [Bugsee setUserIdentifier:identifier];
2075
+ });
2076
+ }
2077
+
2078
+ /// `nil`/`@""` both read as absent (`BGSRNAttributes identifier:`) -- iOS's
2079
+ /// own getter already never returns `@""`, but this keeps the rule explicit
2080
+ /// and in parity with Android.
2081
+ - (void)getUserIdentifier:(RCTPromiseResolveBlock)resolve
2082
+ reject:(RCTPromiseRejectBlock)reject {
2083
+ BGSRNRunOnMain(^{
2084
+ NSString *identifier = [BGSRNAttributes identifier:[Bugsee getUserIdentifier]];
2085
+ resolve(identifier != nil ? @{ @"value" : identifier } : @{});
2086
+ });
2087
+ }
2088
+
2089
+ - (void)clearUserIdentifier {
2090
+ BGSRNRunOnMain(^{
2091
+ [Bugsee clearUserIdentifier];
2092
+ });
2093
+ }
2094
+
2095
+ /// Which phases JS wants delivered; the other completes natively at once.
2096
+ - (void)setReportHandlerPhases:(BOOL)before
2097
+ after:(BOOL)after {
2098
+ [BGSRNReportHandlerBridge.shared setPhasesBefore:before after:after];
2099
+ }
2100
+
2101
+ /// A second call for the same handle is a no-op in the bridge.
2102
+ ///
2103
+ /// Never hops to main -- not because the SDK is blocked on main waiting for
2104
+ /// this (it isn't: the live handler runs on main via `dispatch_async`, but
2105
+ /// its completion is a thread-agnostic run-once that hops to a private queue,
2106
+ /// so main is never held for it), but because there is no need to, and an op
2107
+ /// that did would queue behind whatever UI work is already on main, eating
2108
+ /// into the handle's deadline for nothing. Neither do the report ops below:
2109
+ /// they run on this module's method queue, which is safe because the report
2110
+ /// contract's methods are lock-synchronized (BGSContracts.h). Each catches
2111
+ /// everything: an exception escaping a TurboModule method is a crash in a
2112
+ /// release build, and the SDK's fault is not worth the app.
2113
+ - (void)completeReportHandler:(NSString *)handleId {
2114
+ [BGSRNReportHandlerBridge.shared complete:handleId];
2115
+ }
2116
+
2117
+ - (void)reportRead:(NSString *)handleId
2118
+ resolve:(RCTPromiseResolveBlock)resolve
2119
+ reject:(RCTPromiseRejectBlock)reject {
2120
+ id<BGSReportContract> report = [BGSRNReportHandlerBridge.shared reportFor:handleId];
2121
+ if (report == nil) {
2122
+ BGSRNRejectHandleDead(reject);
2123
+ return;
2124
+ }
2125
+ @try {
2126
+ resolve([BGSRNReportOps readReport:report]);
2127
+ } @catch (NSException *exception) {
2128
+ BGSRNRejectException(reject, @"reportRead", exception);
2129
+ }
2130
+ }
2131
+
2132
+ /// `patchJson` is JSON text (`src/bridge/json.ts`), not an `NSDictionary`:
2133
+ /// React Native's object-argument conversion drops a `null` member, which
2134
+ /// here means "clear the summary" or "remove this attribute" -- so those
2135
+ /// edits silently did nothing. Text that is not a JSON object rejects
2136
+ /// `E_REPORT_BAD_ARGUMENT`, like any malformed field.
2137
+ - (void)reportUpdate:(NSString *)handleId
2138
+ patchJson:(NSString *)patchJson
2139
+ resolve:(RCTPromiseResolveBlock)resolve
2140
+ reject:(RCTPromiseRejectBlock)reject {
2141
+ id<BGSReportContract> report = [BGSRNReportHandlerBridge.shared reportFor:handleId];
2142
+ if (report == nil) {
2143
+ BGSRNRejectHandleDead(reject);
2144
+ return;
2145
+ }
2146
+ @try {
2147
+ NSError *error = nil;
2148
+ if ([BGSRNReportOps applyPatchJSON:patchJson toReport:report error:&error]) {
2149
+ resolve(nil);
2150
+ } else {
2151
+ reject(BGSRNReportErrorWireCode(error), BGSRNErrorMessage(error), nil);
2152
+ }
2153
+ } @catch (NSException *exception) {
2154
+ BGSRNRejectException(reject, @"reportUpdate", exception);
2155
+ }
2156
+ }
2157
+
2158
+ - (void)reportAddFileAttachment:(NSString *)handleId
2159
+ path:(NSString *)path
2160
+ name:(NSString *)name
2161
+ mimeType:(NSString * _Nullable)mimeType
2162
+ move:(BOOL)move
2163
+ resolve:(RCTPromiseResolveBlock)resolve
2164
+ reject:(RCTPromiseRejectBlock)reject {
2165
+ id<BGSReportContract> report = [BGSRNReportHandlerBridge.shared reportFor:handleId];
2166
+ if (report == nil) {
2167
+ BGSRNRejectHandleDead(reject);
2168
+ return;
2169
+ }
2170
+ @try {
2171
+ NSError *error = nil;
2172
+ const BOOL added = [BGSRNReportOps addFileAtPath:path
2173
+ name:name
2174
+ mimeType:mimeType
2175
+ move:move
2176
+ toReport:report
2177
+ error:&error];
2178
+ BGSRNSettleAttachment(handleId, added, error, resolve, reject);
2179
+ } @catch (NSException *exception) {
2180
+ BGSRNRejectException(reject, @"reportAddFileAttachment", exception);
2181
+ }
2182
+ }
2183
+
2184
+ - (void)reportAddDataAttachment:(NSString *)handleId
2185
+ base64:(NSString *)base64
2186
+ name:(NSString *)name
2187
+ mimeType:(NSString * _Nullable)mimeType
2188
+ resolve:(RCTPromiseResolveBlock)resolve
2189
+ reject:(RCTPromiseRejectBlock)reject {
2190
+ id<BGSReportContract> report = [BGSRNReportHandlerBridge.shared reportFor:handleId];
2191
+ if (report == nil) {
2192
+ BGSRNRejectHandleDead(reject);
2193
+ return;
2194
+ }
2195
+ @try {
2196
+ NSError *error = nil;
2197
+ const BOOL added = [BGSRNReportOps addData:base64
2198
+ name:name
2199
+ mimeType:mimeType
2200
+ toReport:report
2201
+ error:&error];
2202
+ BGSRNSettleAttachment(handleId, added, error, resolve, reject);
2203
+ } @catch (NSException *exception) {
2204
+ BGSRNRejectException(reject, @"reportAddDataAttachment", exception);
2205
+ }
2206
+ }
2207
+
2208
+ /// On main, unlike the handler's report ops. `BugseeExtendedReport` is
2209
+ /// unsynchronised, and the SDK hands it out and takes it back on main.
2210
+ ///
2211
+ /// `reserve` runs before that hop. `invalidate` calls `clear` on another
2212
+ /// queue and cannot cancel a block already queued. Reserving inside the
2213
+ /// block would run after that clear and hold the slot for a handle the
2214
+ /// torn-down JS will never upload.
2215
+ - (void)createReport:(RCTPromiseResolveBlock)resolve
2216
+ reject:(RCTPromiseRejectBlock)reject {
2217
+ BGSRNCreatedReports *registry = BGSRNCreatedReports.shared;
2218
+ const NSUInteger reservation = [registry reserve];
2219
+ if (reservation == 0) {
2220
+ NSLog(@"BugseeRN created report - busy");
2221
+ reject(kCreateBusyCode, @"a created report is already outstanding", nil);
2222
+ return;
2223
+ }
2224
+ BGSRNRunOnMain(^{
2225
+ // WORKAROUND for bugsee-cocoa#227: held while the SDK is Launching
2226
+ // (BGSRNLaunchHold), which would complete it with nil. The promise
2227
+ // settles when the replayed call completes. `beginCreate:` stays right
2228
+ // before the SDK call, not before the hold: until it runs, `invalidate`'s
2229
+ // `clear` can still drop this reservation and free the slot for the next
2230
+ // runtime, and the replay then resolves nil without `-init`ing a report.
2231
+ [BGSRNLaunchHold.shared submit:@"created report" call:^(BGSRNGatedRun run) {
2232
+ if (run == BGSRNGatedRunDrop) {
2233
+ // As the SDK settles a dropped call: its completion with nil. Frees
2234
+ // the slot, or does nothing when `clear` already dropped the token.
2235
+ [registry fulfil:nil reservation:reservation];
2236
+ NSLog(@"BugseeRN created report dropped: the SDK did not launch");
2237
+ resolve(nil);
2238
+ return;
2239
+ }
2240
+ // One check with the mark. `clear` between an open test and the SDK call
2241
+ // would still `-init` a `BugseeExtendedReport`. NO means `clear` already
2242
+ // dropped this token and freed the slot. YES means `clear` from here on
2243
+ // keeps the slot until `fulfil`, and that fulfil does not publish.
2244
+ if (![registry beginCreate:reservation]) {
2245
+ NSLog(@"BugseeRN created report - reservation ended");
2246
+ resolve(nil);
2247
+ return;
2248
+ }
2249
+ @try {
2250
+ // Captured above, before the hop. `invalidate` clears the registry
2251
+ // without cancelling this completion. Once `beginCreate:` has run, that
2252
+ // clear keeps the slot and this fulfil must not mint a handle.
2253
+ // The completion runs on every path, with nil when the SDK is not launched.
2254
+ [Bugsee createReportWithCompletion:^(BugseeExtendedReport *report) {
2255
+ NSString *handle = [registry fulfil:report reservation:reservation];
2256
+ if (handle == nil) {
2257
+ NSLog(@"BugseeRN created report - none");
2258
+ resolve(nil);
2259
+ } else {
2260
+ NSLog(@"BugseeRN created report %@ created", handle);
2261
+ resolve(handle);
2262
+ }
2263
+ }];
2264
+ } @catch (NSException *exception) {
2265
+ [registry fulfil:nil reservation:reservation];
2266
+ BGSRNRejectException(reject, @"createReport", exception);
2267
+ }
2268
+ }];
2269
+ });
2270
+ }
2271
+
2272
+ - (void)createdReportRead:(NSString *)handleId
2273
+ resolve:(RCTPromiseResolveBlock)resolve
2274
+ reject:(RCTPromiseRejectBlock)reject {
2275
+ BGSRNRunOnMain(^{
2276
+ @try {
2277
+ BugseeExtendedReport *report = [BGSRNCreatedReports.shared reportFor:handleId];
2278
+ if (report == nil) {
2279
+ BGSRNRejectCreatedHandleDead(reject);
2280
+ return;
2281
+ }
2282
+ resolve([BGSRNCreatedReportOps readReport:report]);
2283
+ } @catch (NSException *exception) {
2284
+ BGSRNRejectException(reject, @"createdReportRead", exception);
2285
+ }
2286
+ });
2287
+ }
2288
+ - (void)createdReportUpdate:(NSString *)handleId
2289
+ patchJson:(NSString *)patchJson
2290
+ resolve:(RCTPromiseResolveBlock)resolve
2291
+ reject:(RCTPromiseRejectBlock)reject {
2292
+ BGSRNRunOnMain(^{
2293
+ @try {
2294
+ BugseeExtendedReport *report = [BGSRNCreatedReports.shared reportFor:handleId];
2295
+ if (report == nil) {
2296
+ BGSRNRejectCreatedHandleDead(reject);
2297
+ return;
2298
+ }
2299
+ NSError *error = nil;
2300
+ if ([BGSRNCreatedReportOps applyPatchJSON:patchJson toReport:report error:&error]) {
2301
+ resolve(nil);
2302
+ } else {
2303
+ reject(BGSRNReportErrorWireCode(error), BGSRNErrorMessage(error), nil);
2304
+ }
2305
+ } @catch (NSException *exception) {
2306
+ BGSRNRejectException(reject, @"createdReportUpdate", exception);
2307
+ }
2308
+ });
2309
+ }
2310
+
2311
+ /// `mimeType` is accepted because JS sends it. `BugseeAttachment` has no type,
2312
+ /// and iOS drops it (P7).
2313
+ - (void)createdReportAddDataAttachment:(NSString *)handleId
2314
+ base64:(NSString *)base64
2315
+ name:(NSString *)name
2316
+ mimeType:(NSString * _Nullable)mimeType
2317
+ resolve:(RCTPromiseResolveBlock)resolve
2318
+ reject:(RCTPromiseRejectBlock)reject {
2319
+ (void)mimeType;
2320
+ BGSRNRunOnMain(^{
2321
+ @try {
2322
+ BugseeExtendedReport *report = [BGSRNCreatedReports.shared reportFor:handleId];
2323
+ if (report == nil) {
2324
+ BGSRNRejectCreatedHandleDead(reject);
2325
+ return;
2326
+ }
2327
+ NSError *error = nil;
2328
+ if ([BGSRNCreatedReportOps addData:base64 name:name toReport:report error:&error]) {
2329
+ resolve(nil);
2330
+ } else {
2331
+ reject(BGSRNReportErrorWireCode(error), BGSRNErrorMessage(error), nil);
2332
+ }
2333
+ } @catch (NSException *exception) {
2334
+ BGSRNRejectException(reject, @"createdReportAddDataAttachment", exception);
2335
+ }
2336
+ });
2337
+ }
2338
+
2339
+ /// No `move`: the bytes are copied at add time. `mimeType` is ignored (P7).
2340
+ - (void)createdReportAddFileAttachment:(NSString *)handleId
2341
+ path:(NSString *)path
2342
+ name:(NSString *)name
2343
+ mimeType:(NSString * _Nullable)mimeType
2344
+ resolve:(RCTPromiseResolveBlock)resolve
2345
+ reject:(RCTPromiseRejectBlock)reject {
2346
+ (void)mimeType;
2347
+ BGSRNRunOnMain(^{
2348
+ @try {
2349
+ BugseeExtendedReport *report = [BGSRNCreatedReports.shared reportFor:handleId];
2350
+ if (report == nil) {
2351
+ BGSRNRejectCreatedHandleDead(reject);
2352
+ return;
2353
+ }
2354
+ NSError *error = nil;
2355
+ if ([BGSRNCreatedReportOps addFileAtPath:path name:name toReport:report error:&error]) {
2356
+ resolve(nil);
2357
+ } else {
2358
+ reject(BGSRNReportErrorWireCode(error), BGSRNErrorMessage(error), nil);
2359
+ }
2360
+ } @catch (NSException *exception) {
2361
+ BGSRNRejectException(reject, @"createdReportAddFileAttachment", exception);
2362
+ }
2363
+ });
2364
+ }
2365
+
2366
+ - (void)createdReportUpload:(NSString *)handleId
2367
+ resolve:(RCTPromiseResolveBlock)resolve
2368
+ reject:(RCTPromiseRejectBlock)reject {
2369
+ BGSRNRunOnMain(^{
2370
+ NSUInteger generation = 0;
2371
+ @try {
2372
+ BugseeExtendedReport *report =
2373
+ [BGSRNCreatedReports.shared detachForUpload:handleId generation:&generation];
2374
+ if (report == nil) {
2375
+ BGSRNRejectCreatedHandleDead(reject);
2376
+ return;
2377
+ }
2378
+ // The handle is already dead. The slot stays taken until this upload
2379
+ // ends: a second created report would reset beta3's file-scope attributes
2380
+ // before `uploadReport:` copies them. The completion carries no success
2381
+ // flag. It runs once the report is handed off, including when the SDK
2382
+ // was not launched (it calls back immediately). `ok` is YES on that path.
2383
+ [Bugsee uploadReport:report completion:^{
2384
+ [BGSRNCreatedReports.shared endUpload:generation];
2385
+ NSLog(@"BugseeRN created report %@ uploaded ok=%@", handleId, @YES);
2386
+ resolve(@YES);
2387
+ }];
2388
+ } @catch (NSException *exception) {
2389
+ [BGSRNCreatedReports.shared endUpload:generation];
2390
+ BGSRNRejectException(reject, @"createdReportUpload", exception);
2391
+ }
2392
+ });
2393
+ }
2394
+
2395
+ - (BGSRNSpanHandles *)spanHandles {
2396
+ os_unfair_lock_lock(&_spanRegistryLock);
2397
+ BGSRNSpanHandles *handles = _spansRetired ? [BGSRNSpanHandles closedRegistry] : _spanHandles;
2398
+ if (handles == nil) {
2399
+ handles = [BGSRNSpanHandles new];
2400
+ _spanHandles = handles;
2401
+ }
2402
+ os_unfair_lock_unlock(&_spanRegistryLock);
2403
+ return handles;
2404
+ }
2405
+
2406
+ - (BGSRNLiveSpan *)liveSpan:(NSString *)handle {
2407
+ id adapter = [self.spanHandles adapterForHandle:handle];
2408
+ return [adapter isKindOfClass:[BGSRNLiveSpan class]] ? adapter : nil;
2409
+ }
2410
+
2411
+ - (NSDictionary *)adoptSpan:(id<BGSSpan>)span {
2412
+ if (span == nil) {
2413
+ return BGSRNNoSpan();
2414
+ }
2415
+ BGSRNLiveSpan *adapter = [[BGSRNLiveSpan alloc] initWithSpan:span];
2416
+ NSString *handle = [self.spanHandles retainSpan:span adapter:adapter];
2417
+ return BGSRNSpanSnapshot(handle, span);
2418
+ }
2419
+
2420
+ /// On main, synchronously. The active span is pthread-local and does not
2421
+ /// cross dispatch_async, and every span call has to see the same thread.
2422
+ - (void)notify:(NSString *)title
2423
+ body:(NSString *)body
2424
+ severity:(double)severity
2425
+ fieldsJson:(NSString *)fieldsJson
2426
+ urgent:(BOOL)urgent {
2427
+ NSDictionary *parsed = nil;
2428
+ if (fieldsJson != nil) {
2429
+ NSError *error = nil;
2430
+ parsed = BGSRNJSONObject(fieldsJson, &error);
2431
+ if (parsed == nil) {
2432
+ NSLog(@"BugseeRN notify dropped: %@", BGSRNErrorMessage(error));
2433
+ return;
2434
+ }
2435
+ }
2436
+ NSMutableDictionary<NSString *, NSString *> *fields = nil;
2437
+ if (parsed != nil) {
2438
+ fields = [NSMutableDictionary dictionary];
2439
+ for (NSString *key in parsed) {
2440
+ id value = parsed[key];
2441
+ if ([value isKindOfClass:[NSString class]]) {
2442
+ fields[key] = value;
2443
+ }
2444
+ }
2445
+ }
2446
+ NSInteger wire = (NSInteger)llround(severity);
2447
+ BGSRNRunOnMain(^{
2448
+ [Bugsee notifyWithTitle:title
2449
+ body:body
2450
+ severity:(BugseeSeverityLevel)wire
2451
+ fields:fields
2452
+ urgent:urgent];
2453
+ });
2454
+ }
2455
+
2456
+ - (NSDictionary *)startTransaction:(NSString *)name
2457
+ operation:(NSString *)operation
2458
+ attributesJson:(NSString *)attributesJson {
2459
+ __block NSDictionary *snapshot = nil;
2460
+ BGSRNRunOnMainSync(^{
2461
+ NSDictionary *attributes = nil;
2462
+ if (attributesJson != nil) {
2463
+ NSError *error = nil;
2464
+ attributes = BGSRNJSONObject(attributesJson, &error);
2465
+ if (attributes == nil) {
2466
+ NSLog(@"BugseeRN startTransaction dropped attributes: %@", BGSRNErrorMessage(error));
2467
+ }
2468
+ }
2469
+ id<BGSTransaction> transaction = attributes == nil
2470
+ ? [Bugsee startTransactionWithName:name operation:operation]
2471
+ : [Bugsee startTransactionWithName:name operation:operation attributes:attributes];
2472
+ snapshot = [self adoptSpan:transaction];
2473
+ });
2474
+ return snapshot;
2475
+ }
2476
+
2477
+ - (NSDictionary *)startSpan:(NSString *)operation description:(NSString *)description {
2478
+ __block NSDictionary *snapshot = nil;
2479
+ BGSRNRunOnMainSync(^{
2480
+ snapshot = [self adoptSpan:[Bugsee startSpanWithOperation:operation description:description]];
2481
+ });
2482
+ return snapshot;
2483
+ }
2484
+
2485
+ - (NSDictionary *)getActiveSpan {
2486
+ __block NSDictionary *snapshot = nil;
2487
+ BGSRNRunOnMainSync(^{
2488
+ snapshot = [self adoptSpan:[Bugsee getActiveSpan]];
2489
+ });
2490
+ return snapshot;
2491
+ }
2492
+
2493
+ /// `NSNumber`, not void: codegen queues a void method, so a setter then
2494
+ /// `spanFinish` in one turn would release the handle before the setter ran.
2495
+ /// The hop stays synchronous so the active span's thread is still main.
2496
+ /// Codegen's boolean is `NSNumber *`, the same as `addBreadcrumb`.
2497
+ - (NSNumber *)spanSetName:(NSString *)handle name:(NSString *)name {
2498
+ __block BOOL applied = NO;
2499
+ BGSRNRunOnMainSync(^{
2500
+ BGSRNLiveSpan *live = [self liveSpan:handle];
2501
+ if (live == nil) {
2502
+ return;
2503
+ }
2504
+ [live.span setName:name];
2505
+ applied = YES;
2506
+ });
2507
+ return @(applied);
2508
+ }
2509
+
2510
+ - (NSNumber *)spanSetDescription:(NSString *)handle description:(NSString *)description {
2511
+ __block BOOL applied = NO;
2512
+ BGSRNRunOnMainSync(^{
2513
+ BGSRNLiveSpan *live = [self liveSpan:handle];
2514
+ if (live == nil) {
2515
+ return;
2516
+ }
2517
+ [live.span setSpanDescription:description];
2518
+ applied = YES;
2519
+ });
2520
+ return @(applied);
2521
+ }
2522
+
2523
+ - (NSNumber *)spanSetAttribute:(NSString *)handle key:(NSString *)key valueJson:(NSString *)valueJson {
2524
+ __block BOOL applied = NO;
2525
+ BGSRNRunOnMainSync(^{
2526
+ id value = BGSRNJSONScalar(valueJson);
2527
+ if (value == nil) {
2528
+ NSLog(@"BugseeRN span attribute dropped: value is not a string, number or boolean");
2529
+ return;
2530
+ }
2531
+ BGSRNLiveSpan *live = [self liveSpan:handle];
2532
+ if (live == nil) {
2533
+ return;
2534
+ }
2535
+ [live.span setAttribute:key value:value];
2536
+ applied = YES;
2537
+ });
2538
+ return @(applied);
2539
+ }
2540
+
2541
+ - (NSNumber *)spanSetStatus:(NSString *)handle status:(double)status {
2542
+ __block BOOL applied = NO;
2543
+ BGSRNRunOnMainSync(^{
2544
+ NSInteger wire = (NSInteger)llround(status);
2545
+ if (wire < BGSSpanStatusOK || wire > BGSSpanStatusUnknown) {
2546
+ NSLog(@"BugseeRN span status is outside 0..5");
2547
+ return;
2548
+ }
2549
+ BGSRNLiveSpan *live = [self liveSpan:handle];
2550
+ if (live == nil) {
2551
+ return;
2552
+ }
2553
+ [live.span setStatus:(BGSSpanStatus)wire];
2554
+ applied = YES;
2555
+ });
2556
+ return @(applied);
2557
+ }
2558
+
2559
+ - (NSDictionary *)spanStartChild:(NSString *)handle
2560
+ operation:(NSString *)operation
2561
+ description:(NSString *)description {
2562
+ __block NSDictionary *snapshot = nil;
2563
+ BGSRNRunOnMainSync(^{
2564
+ BGSRNLiveSpan *live = [self liveSpan:handle];
2565
+ if (live == nil) {
2566
+ snapshot = BGSRNNoSpan();
2567
+ return;
2568
+ }
2569
+ id<BGSSpan> child = description == nil
2570
+ ? [live.span startChildSpanWithOperation:operation]
2571
+ : [live.span startChildSpanWithOperation:operation description:description];
2572
+ snapshot = [self adoptSpan:child];
2573
+ });
2574
+ return snapshot;
2575
+ }
2576
+
2577
+ - (NSArray<NSString *> *)spanFinish:(NSString *)handle
2578
+ status:(double)status
2579
+ statusSet:(BOOL)statusSet {
2580
+ __block NSArray<NSString *> *released = @[];
2581
+ BGSRNRunOnMainSync(^{
2582
+ NSNumber *wire = nil;
2583
+ if (statusSet) {
2584
+ NSInteger value = (NSInteger)llround(status);
2585
+ if (value < BGSSpanStatusOK || value > BGSSpanStatusUnknown) {
2586
+ NSLog(@"BugseeRN span finish status is outside 0..5");
2587
+ return;
2588
+ }
2589
+ wire = @(value);
2590
+ }
2591
+ released = [self.spanHandles finishHandle:handle status:wire];
2592
+ });
2593
+ return released;
2594
+ }
2595
+
2596
+ /// Writable report colors on BugseeTheme (7.0.0-beta4; unchanged from beta3). Feedback properties
2597
+ /// and the readonly palette are not report appearance. KVC with any other
2598
+ /// name throws NSUnknownKeyException.
2599
+ static NSSet<NSString *> *BGSRNReportColorKeys(void) {
2600
+ static NSSet<NSString *> *keys;
2601
+ static dispatch_once_t once;
2602
+ dispatch_once(&once, ^{
2603
+ keys = [NSSet setWithArray:@[
2604
+ @"reportBackgroundColor",
2605
+ @"reportCellBackgroundColor",
2606
+ @"reportCloseButtonColor",
2607
+ @"reportNavigationBarColor",
2608
+ @"reportPlaceholderColor",
2609
+ @"reportSendButtonColor",
2610
+ @"reportTextColor",
2611
+ @"reportVersionColor",
2612
+ ]];
2613
+ });
2614
+ return keys;
2615
+ }
2616
+
2617
+ static BOOL BGSRNColorComponentOK(double value) {
2618
+ return value >= 0.0 && value <= 255.0 && value == floor(value);
2619
+ }
2620
+
2621
+ static NSString *BGSRNHexFromColor(UIColor *color) {
2622
+ if (![color isKindOfClass:[UIColor class]]) {
2623
+ return @"";
2624
+ }
2625
+ CGFloat r = 0, g = 0, b = 0, a = 0;
2626
+ if (![color getRed:&r green:&g blue:&b alpha:&a]) {
2627
+ return @"";
2628
+ }
2629
+ int ri = (int)llround(r * 255.0);
2630
+ int gi = (int)llround(g * 255.0);
2631
+ int bi = (int)llround(b * 255.0);
2632
+ int ai = (int)llround(a * 255.0);
2633
+ ri = MAX(0, MIN(255, ri));
2634
+ gi = MAX(0, MIN(255, gi));
2635
+ bi = MAX(0, MIN(255, bi));
2636
+ ai = MAX(0, MIN(255, ai));
2637
+ return [NSString stringWithFormat:@"#%02x%02x%02x%02x", ri, gi, bi, ai];
2638
+ }
2639
+
2640
+ - (NSNumber *)setAppearanceColor:(NSString *)name
2641
+ r:(double)r
2642
+ g:(double)g
2643
+ b:(double)b
2644
+ a:(double)a {
2645
+ if (![BGSRNReportColorKeys() containsObject:name]) {
2646
+ return @NO;
2647
+ }
2648
+ if (!BGSRNColorComponentOK(r) || !BGSRNColorComponentOK(g) ||
2649
+ !BGSRNColorComponentOK(b) || !BGSRNColorComponentOK(a)) {
2650
+ return @NO;
2651
+ }
2652
+ UIColor *color = [UIColor colorWithRed:(CGFloat)(r / 255.0)
2653
+ green:(CGFloat)(g / 255.0)
2654
+ blue:(CGFloat)(b / 255.0)
2655
+ alpha:(CGFloat)(a / 255.0)];
2656
+ __block BOOL applied = NO;
2657
+ BGSRNRunOnMainSync(^{
2658
+ [[Bugsee getAppearance] setValue:color forKey:name];
2659
+ applied = YES;
2660
+ });
2661
+ return @(applied);
2662
+ }
2663
+
2664
+ - (NSString *)getAppearanceColor:(NSString *)name {
2665
+ if (![BGSRNReportColorKeys() containsObject:name]) {
2666
+ return @"";
2667
+ }
2668
+ __block NSString *hex = @"";
2669
+ BGSRNRunOnMainSync(^{
2670
+ id value = [[Bugsee getAppearance] valueForKey:name];
2671
+ hex = BGSRNHexFromColor(value);
2672
+ });
2673
+ return hex;
2674
+ }
2675
+
2676
+ /// iOS 7.0.0-beta3 and beta4 return without invoking `completion` when the SDK is
2677
+ /// not stopped, so a launched call resolves `false` immediately. That is the
2678
+ /// missing completion, not a wait. Stopped, including a nil instance, still
2679
+ /// calls the SDK method and settles through `BGSRNSettleOnce`: the
2680
+ /// completion's success, or `false` if the deadline fires first. Status and
2681
+ /// both SDK calls run on the main queue. A completion that arrives off main
2682
+ /// hops back before it writes the result the settler resolves.
2683
+ - (void)deleteCollectedDataOnDevice:(BOOL)includingIntermediate
2684
+ resolve:(RCTPromiseResolveBlock)resolve
2685
+ reject:(RCTPromiseRejectBlock)reject {
2686
+ BGSRNRunOnMain(^{
2687
+ Bugsee *instance = [Bugsee sharedInstance];
2688
+ BugseeStatus status = instance != nil ? instance.status : BugseeStatusStopped;
2689
+ if (status != BugseeStatusStopped) {
2690
+ __block BOOL settled = NO;
2691
+ [Bugsee deleteCollectedDataOnDevice:includingIntermediate completion:^(BOOL success) {
2692
+ BGSRNRunOnMain(^{
2693
+ if (settled) {
2694
+ return;
2695
+ }
2696
+ settled = YES;
2697
+ resolve(@(success));
2698
+ });
2699
+ }];
2700
+ if (!settled) {
2701
+ settled = YES;
2702
+ resolve(@NO);
2703
+ }
2704
+ return;
2705
+ }
2706
+ __block NSNumber *result = @NO;
2707
+ dispatch_block_t done =
2708
+ BGSRNSettleOnce(BGSRNUnhandledCompletionDeadlineMs, dispatch_get_main_queue(), ^{
2709
+ resolve(result);
2710
+ });
2711
+ [Bugsee deleteCollectedDataOnDevice:includingIntermediate completion:^(BOOL success) {
2712
+ BGSRNRunOnMain(^{
2713
+ result = @(success);
2714
+ done();
2715
+ });
2716
+ }];
2717
+ });
2718
+ }
2719
+
2720
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
2721
+ (const facebook::react::ObjCTurboModule::InitParams &)params {
2722
+ auto module = std::make_shared<facebook::react::NativeBugseeSpecJSI>(params);
2723
+ // Only now is the codegen event emitter set: see attachToBridges.
2724
+ [self attachToBridges];
2725
+ return module;
2726
+ }
2727
+
2728
+ @end