From ac868c95e31cb9ff3c34a19311dd9e246a32182b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 10:34:03 +0500 Subject: [PATCH 01/16] Launch options: a typed accessor for every option either SDK registers Shake-to-report was reachable only through setCustomOption, and a customer on 7.0.0-beta3 could not turn it off. Only 21 of the 109 options the pinned SDKs register had an accessor, and a wrong key was dropped without a word. - 104 accessors, generated against Android 7.4.2 (golden manifest) and iOS 7.0.0 (origin/release): shared ones on the base class, platform-only ones on the subclasses, including reporting triggers (shake, screenshot, notification-bar, broadcast), the NDK and leak extension options, and the iOS-only capture options. Enum options are typed (LogLevel, VideoQuality, FrameRate, IssueSeverity, VideoMode, ReportingUIStyle, MemoryLeakMode). - launch/relaunch warn once per key the platform's SDK does not know, naming the 7.x key for a 6.x name. Android drops such keys silently; iOS maps its own 6.x names, so ShakeToReport worked on iOS and did nothing on Android. - The key list now includes the NDK and leak holders; the extractor reads them and says to point it at the pinned SDK versions. A coverage test fails when a known key has neither an accessor nor a NO_ACCESSOR entry, so this cannot drift again. - Android bridge: an enum with no number (MemoryLeakMode) read back as -1; it now reads back as its constant name, which is also what sets it. - docs/launch-options.md and a README section: the full option table, the unknown-key warning, launch() ignoring options when the SDK is already running, and relaunch() restarting with exactly the options passed. Human guided, AI implemented --- docs/launch-options.md | 171 +++++++ packages/react-native/README.md | 24 + .../com/bugsee/reactnative/BugseeModule.java | 10 +- .../bugsee/reactnative/BugseeOptionEnums.java | 15 + .../reactnative/BugseeOptionEnumsTest.java | 20 + .../__tests__/launch-unknown-options.test.ts | 53 ++ packages/react-native/src/index.ts | 21 +- .../src/options/AndroidLaunchOptions.ts | 330 ++++++++++++- .../src/options/BugseeLaunchOptions.ts | 452 +++++++++++++++++- .../src/options/IOSLaunchOptions.ts | 184 ++++++- .../src/options/__tests__/accessors.test.ts | 133 ++++-- .../src/options/__tests__/coverage.test.ts | 71 +++ .../src/options/__tests__/enums.test.ts | 22 + .../src/options/__tests__/unknownKeys.test.ts | 97 ++++ .../src/options/android-options-manifest.json | 52 +- packages/react-native/src/options/enums.ts | 28 ++ .../react-native/src/options/ios-enums.json | 6 + packages/react-native/src/options/keys.ts | 25 +- .../react-native/src/options/option-keys.json | 6 + .../react-native/src/options/unknownKeys.ts | 159 ++++++ .../__tests__/option-manifest-parity.test.ts | 16 +- scripts/cli-extract-option-keys.ts | 47 +- scripts/raw-messages.ts | 7 +- 23 files changed, 1854 insertions(+), 95 deletions(-) create mode 100644 docs/launch-options.md create mode 100644 packages/react-native/src/__tests__/launch-unknown-options.test.ts create mode 100644 packages/react-native/src/options/__tests__/coverage.test.ts create mode 100644 packages/react-native/src/options/__tests__/unknownKeys.test.ts create mode 100644 packages/react-native/src/options/unknownKeys.ts diff --git a/docs/launch-options.md b/docs/launch-options.md new file mode 100644 index 00000000..a4e5b82c --- /dev/null +++ b/docs/launch-options.md @@ -0,0 +1,171 @@ +# Launch options + +Every launch option either native SDK registers has a typed accessor on the options object +from `createDefaultLaunchOptions()`. The wrapper sets no defaults: an option you leave unset +takes the native SDK's own default, and `Bugsee.getLaunchOptions()` reports what is in effect. + +```ts +import Bugsee, { createDefaultLaunchOptions } from '@bugsee/react-native'; + +const options = createDefaultLaunchOptions(); +options.triggerByShake = false; // shake-to-report is ON by default in both SDKs +await Bugsee.launch('', options); +``` + +The tables are checked against the SDK versions pinned in `native-versions.json` (Android 7.4.2, iOS 7.0.0): +a test fails when either SDK registers an option this package has no accessor for. Options a +*newer* SDK adds are reachable with `options.setCustomOption(key, value)` until the package catches up. + +## Keys the SDK drops + +Both SDKs accept an unknown key without an error. The Android SDK **silently drops it**; the iOS SDK stores it and +ignores it (it still maps its own 6.x names, which Android does not). So a 6.x name such as `ShakeToReport` works on +iOS, does nothing on Android, and reports nothing on either. `launch()` and `relaunch()` therefore log one +`console.warn` per unknown key, naming the 7.x key to use. The launch itself is unchanged. + +## `launch()` and `relaunch()` + +- `launch(token, options)` starts the SDK with `options`. If the SDK is **already running** (iOS, or an Android process the + SDK relaunched itself after the OS killed it) the new options are **ignored**. Do not treat `true` as proof they were applied: + check `getStatus()` before the call if the difference matters. Android SDK 7.5.1 resolves `false` in this case, earlier SDKs `true`. +- `relaunch(options)` restarts with **exactly** the options you pass. Anything you leave out goes back to the SDK default; + it does **not** keep what the previous launch set. Pass the full set each time. + +## Reference + +`Enum` types are exported from `@bugsee/react-native` and cross the bridge as the SDK's internal value (never an ordinal). + +### Reporting triggers and dialog + +| Accessor | Option key | Type | Platforms | Notes | +|---|---|---|---|---| +| `reportingDefaultBugPriority` | `com.bugsee.option.reporting.defaults.bug-priority` | `IssueSeverity` | iOS, Android | Default priority of bug reports; see `IssueSeverity`. | +| `reportingDefaultCrashPriority` | `com.bugsee.option.reporting.defaults.crash-priority` | `IssueSeverity` | iOS, Android | Default priority of crash reports; see `IssueSeverity`. | +| `reportingDefaultErrorPriority` | `com.bugsee.option.reporting.defaults.error-priority` | `IssueSeverity` | iOS, Android | Default priority of error reports; see `IssueSeverity`. | +| `triggerByBroadcast` | `com.bugsee.option.reporting.triggers.broadcast` | `boolean` | Android | Let a broadcast open the report dialog. | +| `triggerByNotification` | `com.bugsee.option.reporting.triggers.notification-bar` | `boolean` | Android | Let the user open the report dialog from the notification bar. The SDK default is on. | +| `triggerByScreenshot` | `com.bugsee.option.reporting.triggers.screenshot` | `boolean` | iOS, Android | Let the user open the report dialog by taking a screenshot. | +| `triggerByShake` | `com.bugsee.option.reporting.triggers.shake` | `boolean` | iOS, Android | Let the user open the report dialog by shaking the device. **The SDK default is on:** set this to `false` to turn shake-to-report off. | +| `reportingUIDescriptionRequired` | `com.bugsee.option.reporting.ui.description-required` | `boolean` | iOS, Android | Make the Description field mandatory in the report dialog. | +| `reportingUIEmailRequired` | `com.bugsee.option.reporting.ui.email-required` | `boolean` | iOS, Android | Make the Email field mandatory in the report dialog. | +| `reportingUILabelsEnabled` | `com.bugsee.option.reporting.ui.labels-enabled` | `boolean` | iOS, Android | Show the Labels field in the report dialog. | +| `reportingUILabelsRequired` | `com.bugsee.option.reporting.ui.labels-required` | `boolean` | iOS, Android | Make the Labels field mandatory in the report dialog. | +| `reportingUIPrioritySelectorEnabled` | `com.bugsee.option.reporting.ui.priority-selector-enabled` | `boolean` | iOS, Android | Let the user change the priority in the report dialog. | +| `reportingUIStyle` | `com.bugsee.option.reporting.ui.style` | `ReportingUIStyle` | iOS | Appearance of the report dialog; see `ReportingUIStyle`. | +| `reportingUISummaryRequired` | `com.bugsee.option.reporting.ui.summary-required` | `boolean` | iOS, Android | Make the Summary field mandatory in the report dialog. | + +### Capture + +| Accessor | Option key | Type | Platforms | Notes | +|---|---|---|---|---| +| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | Capture `AVPlayer` content. | +| `captureBluetoothStatus` | `com.bugsee.option.capture.bluetooth-status` | `boolean` | iOS | Record the Bluetooth status. | +| `captureBreadcrumbs` | `com.bugsee.option.capture.breadcrumbs` | `boolean` | iOS, Android | Capture breadcrumbs (user and system events). | +| `captureBreadcrumbsExtras` | `com.bugsee.option.capture.breadcrumbs.extras` | `boolean` | iOS, Android | Attach the extra detail of automatically collected device-event breadcrumbs. | +| `captureCameraPreview` | `com.bugsee.option.capture.camera-preview` | `boolean` | iOS | Capture camera preview layers. Read the iOS SDK's privacy and overhead notes before enabling. | +| `crashHandlerType` | `com.bugsee.option.capture.crash-handler-type` | `CrashHandlerType` | iOS | How the crash reporter intercepts crashes; see `CrashHandlerType`. Unset leaves the SDK default, `CrashHandlerType.MachAndBSD`. | +| `crashSignals` | `com.bugsee.option.capture.crash-signals` | `number` | iOS | The fatal signals the crash reporter intercepts, as the iOS SDK's `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, TRAP 32. Unset leaves the SDK default (every signal). Added in 7.0.0-beta7. | +| `captureDeviceAndNetworkNames` | `com.bugsee.option.capture.device-network-names` | `boolean` | iOS | Record the device and network names. | +| `captureDiskSpace` | `com.bugsee.option.capture.disk-space` | `boolean` | iOS | Record free disk space. | +| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | Capture logs. Lines sent with `Bugsee.log()` are always recorded. | +| `logsUseAllSources` | `com.bugsee.option.capture.logs.allsources` | `boolean` | Android | Query every logging source (system, radio, ...) rather than only the default ones. | +| `captureLogsLevel` | `com.bugsee.option.capture.logs.level` | `LogLevel` | iOS, Android | Least severe level captured; see `LogLevel`. | +| `captureOSLogs` | `com.bugsee.option.capture.logs.oslog` | `boolean` | iOS | Has no effect: the iOS SDK accepts the key and ignores it. | +| `captureNetwork` | `com.bugsee.option.capture.network` | `boolean` | iOS, Android | Capture network events. | +| `captureNetworkBodySizeLimit` | `com.bugsee.option.capture.network.body-size-limit` | `number` | iOS, Android | Largest request or response body captured, in bytes. | +| `captureNetworkBodyWithoutType` | `com.bugsee.option.capture.network.body-without-type` | `boolean` | iOS, Android | Also capture bodies that declare no content type. Off keeps only textual bodies. | +| `captureNetworkUseDefaultSanitizer` | `com.bugsee.option.capture.network.default-sanitizer` | `boolean` | iOS, Android | Redact known-sensitive values (query parameters, headers, JSON bodies) when no network filter is set. | +| `captureNetworkOnLaunch` | `com.bugsee.option.capture.network.on-launch` | `boolean` | iOS, Android | Subscribe network capture synchronously during launch, so requests issued in the launch window are seen. | +| `captureOnDeviceSymbolication` | `com.bugsee.option.capture.on-device-symbolication` | `boolean` | iOS | Symbolicate stack traces on the device. | +| `captureRespectFlagSecure` | `com.bugsee.option.capture.respect-flag-secure` | `boolean` | Android | Honour `FLAG_SECURE`: blank secure windows in capture and treat such an activity as a full blackout. | +| `captureSampleBufferDisplayLayer` | `com.bugsee.option.capture.sample-buffer-display-layer` | `boolean` | iOS | Capture `AVSampleBufferDisplayLayer` content. | +| `captureScreenshot` | `com.bugsee.option.capture.screenshot` | `boolean` | iOS, Android | Capture screenshots for reports, independent of video. | +| `captureScreenshotScale` | `com.bugsee.option.capture.screenshot.scale` | `number` | iOS, Android | Privacy scaling applied to screenshots; below `1` removes fine detail such as text. | +| `captureStatusBarInfo` | `com.bugsee.option.capture.status-bar-info` | `boolean` | iOS | Show capture status in the status bar. Debug builds only; ignored in release. | +| `captureVideo` | `com.bugsee.option.capture.video` | `boolean` | iOS, Android | Record video for reports. | +| `captureVideoAdaptive` | `com.bugsee.option.capture.video.adaptive` | `boolean` | iOS, Android | Skip capture work while the screen is idle. The SDKs' own defaults differ. | +| `captureVideoUsingCustomMuxer` | `com.bugsee.option.capture.video.custom-muxer` | `boolean` | Android | Use a lightweight MP4 muxer instead of `MediaMuxer`. | +| `captureVideoFrameRate` | `com.bugsee.option.capture.video.frame-rate` | `FrameRate` | iOS, Android | How often frames are captured; see `FrameRate`. | +| `captureVideoFullscreenKeepRunning` | `com.bugsee.option.capture.video.fullscreen-keep-running` | `boolean` | Android | Keep fullscreen (MediaProjection) capture running while the app is in the background. | +| `captureVideoFullscreenRememberUserDecision` | `com.bugsee.option.capture.video.fullscreen-remember-decision` | `boolean` | Android | Remember the user's screen-capture consent decision across launches. | +| `captureVideoMaxFramerate` | `com.bugsee.option.capture.video.max-frame-rate` | `number` | iOS | Highest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | +| `captureVideoMinFramerate` | `com.bugsee.option.capture.video.min-frame-rate` | `number` | iOS | Lowest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | +| `videoMode` | `com.bugsee.option.capture.video.mode` | `VideoMode` | Android | Screen-capture mode; see `VideoMode`. | +| `captureVideoPrivacyBlur` | `com.bugsee.option.capture.video.privacy-blur` | `boolean` | iOS | Blur transition frames instead of skipping them. | +| `captureVideoQuality` | `com.bugsee.option.capture.video.quality` | `VideoQuality` | iOS, Android | Quality of the encoded video; see `VideoQuality`. | +| `captureVideoScale` | `com.bugsee.option.capture.video.scale` | `number` | iOS, Android | Extra down-scaling of recorded video; `0.5` halves width and height. | +| `captureVideoSecureScrolling` | `com.bugsee.option.capture.video.secure-scrolling` | `boolean` | Android | In `VideoMode.V1`, skip more frames while secure views are on screen. | +| `captureViewHierarchy` | `com.bugsee.option.capture.view-hierarchy` | `boolean` | iOS, Android | Capture the view hierarchy for reports. | +| `captureWebSocket` | `com.bugsee.option.capture.websocket` | `boolean` | iOS | Capture WebSocket traffic. | +| `captureWebViewAdvanced` | `com.bugsee.option.capture.webview.advanced` | `boolean` | iOS, Android | Inject the advanced WebView SDK into instrumented WebViews for full-fidelity in-page capture. | +| `captureWebViewDomainAllowlist` | `com.bugsee.option.capture.webview.domain-allowlist` | `string` | Android | Has no effect: the SDK no longer scopes WebView capture by domain. | +| `captureWebViewReportTrigger` | `com.bugsee.option.capture.webview.report-trigger` | `boolean` | iOS, Android | Let an incident raised inside an instrumented WebView open a native bug report. | + +### Detection + +| Accessor | Option key | Type | Platforms | Notes | +|---|---|---|---|---| +| `ndkIncludeTombstoneLogs` | `com.bugsee.option.crash-ndk.tombstone-logs` | `boolean` | Android | Attach the Android tombstone logs to NDK crash reports. | +| `detectAndReportAnomaly` | `com.bugsee.option.detect.anomaly` | `boolean` | iOS, Android | Detect and report performance anomalies. | +| `detectAndReportAnrSampling` | `com.bugsee.option.detect.anr.sampling` | `boolean` | Android | Sample the main thread during an ANR to attribute the report to culprit frames. | +| `detectAndReportCrash` | `com.bugsee.option.detect.crash` | `boolean` | iOS, Android | Detect and report crashes. | +| `detectAndReportNdkCrash` | `com.bugsee.option.detect.crash-ndk` | `boolean` | Android | Detect native (NDK) crashes. Needs `detectAndReportCrash`; this package bundles the NDK module. | +| `detectCrashFillEmptyExceptionStacks` | `com.bugsee.option.detect.crash.fill_empty_exception_stacks` | `boolean` | iOS | Fill the stack of an uncaught `NSException` that has none, which can change crash grouping. | +| `detectCrashSwiftAsyncStackTraces` | `com.bugsee.option.detect.crash.swift_async_stacktraces` | `boolean` | iOS | Stitch Swift async frames into C++ throw stacks (iOS 15+). | +| `detectAndReportEarlyCrash` | `com.bugsee.option.detect.early-crash` | `boolean` | iOS, Android | Recover crashes that happen during app start-up. | +| `detectAndReportExit` | `com.bugsee.option.detect.exit` | `boolean` | iOS, Android | Detect and report app exits. | +| `detectAndReportExitLowMemoryBackgroundAsError` | `com.bugsee.option.detect.exit.bg_low_memory_as_error` | `boolean` | Android | Report a low-memory kill of a process that was not in the foreground as a non-fatal error rather than a crash. Applies only while `detectAndReportExitLowMemory` is on. Android 7.3.0. | +| `detectAndReportExitDependencyDied` | `com.bugsee.option.detect.exit.dependency_died` | `boolean` | Android | Report exits caused by a dependency process dying. | +| `detectAndReportExitExcessiveResourceUsage` | `com.bugsee.option.detect.exit.excessive_resource_usage` | `boolean` | Android | Report exits caused by excessive resource usage. | +| `detectAndReportExitLowMemory` | `com.bugsee.option.detect.exit.low_memory` | `boolean` | Android | Report exits caused by low memory (the OOM killer). | +| `detectAndReportExitNotResponding` | `com.bugsee.option.detect.exit.not_responding` | `boolean` | Android | Report exits caused by the app not responding (ANR). | +| `detectAndReportExitNotRespondingAsCrash` | `com.bugsee.option.detect.exit.not_responding.as_crash` | `boolean` | Android | Report ANR exits as crashes instead of non-fatal errors. | +| `detectAndReportExitOther` | `com.bugsee.option.detect.exit.other` | `boolean` | Android | Report exits with an "other" reason. | +| `detectAndReportExitPackageStateChanged` | `com.bugsee.option.detect.exit.package_state_changed` | `boolean` | Android | Report exits caused by a package state change. | +| `detectAndReportExitPackageUpdated` | `com.bugsee.option.detect.exit.package_updated` | `boolean` | Android | Report exits caused by a package update. | +| `detectAndReportExitPermissionChanged` | `com.bugsee.option.detect.exit.permission_changed` | `boolean` | Android | Report exits caused by a runtime permission change. | +| `detectAndReportExitUnknown` | `com.bugsee.option.detect.exit.unknown` | `boolean` | Android | Report exits with an unknown reason. | +| `detectAndReportExitUserRequested` | `com.bugsee.option.detect.exit.user_requested` | `boolean` | Android | Report exits the user requested, such as a force stop. | +| `detectAndReportExitUserWasStopped` | `com.bugsee.option.detect.exit.user_was_stopped` | `boolean` | Android | Report exits caused by the system stopping the app. | +| `detectFrustration` | `com.bugsee.option.detect.frustration` | `boolean` | iOS, Android | Detect and report user-frustration patterns such as rage taps. | +| `detectAndReportHang` | `com.bugsee.option.detect.hang` | `boolean` | iOS, Android | Detect and report hangs. | +| `detectAndReportHangFairLevel` | `com.bugsee.option.detect.hang.level.fair` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "fair" hang. Less than the medium level. | +| `detectAndReportHangMediumLevel` | `com.bugsee.option.detect.hang.level.medium` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "medium" hang. | +| `detectAndReportHangSevereLevel` | `com.bugsee.option.detect.hang.level.severe` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "severe" hang. Greater than the medium level. | +| `detectAndReportHangSampling` | `com.bugsee.option.detect.hang.sampling` | `boolean` | Android | Sample the main thread during a hang to attribute the report to culprit frames. Needs `detectAndReportHang`. | +| `detectAndReportHttpErrors` | `com.bugsee.option.detect.http-errors` | `boolean` | iOS, Android | Turn HTTP 5xx responses into error reports. | +| `detectAndReportMainThreadMisuse` | `com.bugsee.option.detect.main_thread_misuse` | `boolean` | iOS, Android | Detect and report blocking work on the main thread. | +| `detectMemoryLeaks` | `com.bugsee.option.detect.memory_leaks` | `boolean` | Android | Detect memory leaks. Honoured only when the app also depends on `com.bugsee:bugsee-android-leak`, which this package does not add. | +| `detectMemoryLeaksDeepSampleRate` | `com.bugsee.option.detect.memory_leaks.deep_sample_rate` | `number` | Android | Fraction of sessions that run the deep leak modes. Needs `bugsee-android-leak`. | +| `detectMemoryLeaksMode` | `com.bugsee.option.detect.memory_leaks.mode` | `MemoryLeakMode` | Android | Leak detection depth; see `MemoryLeakMode`. Needs `bugsee-android-leak`. | +| `detectThreadLeaks` | `com.bugsee.option.detect.thread_leaks` | `boolean` | Android | Detect thread leaks. Needs `bugsee-android-leak`. | + +### Configuration + +| Accessor | Option key | Type | Platforms | Notes | +|---|---|---|---|---| +| `buildTarget` | `com.bugsee.option.config.build-target` | `string` | iOS | Build target name attached to reports. | +| `buildType` | `com.bugsee.option.config.build-type` | `string` | iOS | Build type attached to reports. | +| `duration` | `com.bugsee.option.config.duration` | `number` | iOS, Android | Seconds of history a report carries. | +| `maxDataSize` | `com.bugsee.option.config.max-data-size` | `number` | iOS, Android | Disk space, in megabytes, that reports waiting to be sent may occupy. Past it the oldest reports are deleted whole. The SDKs' defaults can differ; the wrapper sets neither. | +| `maxPendingReportAge` | `com.bugsee.option.config.max-pending-report-age` | `number` | iOS, Android | Oldest a report waiting to be sent may get, in days; `0` or less keeps reports until they are sent or evicted. Android 7.3.0, iOS 7.0.0. | +| `maxPendingReports` | `com.bugsee.option.config.max-pending-reports` | `number` | iOS, Android | Most reports kept waiting to be sent. Android 7.3.0, iOS 7.0.0. | +| `notifyFlushDelay` | `com.bugsee.option.config.notify-flush-delay` | `number` | iOS, Android | Coalesce window, in milliseconds, before `Bugsee.notify` uploads flush; `0` posts as soon as the item is on disk. | +| `reportHandlerCallbackTimeout` | `com.bugsee.option.config.report-handler-callback-timeout` | `number` | Android | Seconds before a report handler's completion callback is auto-fired; `0` disables the timeout. | +| `reportProcessingInProcess` | `com.bugsee.option.config.report-processing-in-process` | `boolean` | Android | Export and upload reports in-process on background threads instead of through JobScheduler. | +| `wifiOnlyUpload` | `com.bugsee.option.config.wifi-only-upload` | `boolean` | iOS, Android | Upload only over Wi-Fi. | + +### Performance + +| Accessor | Option key | Type | Platforms | Notes | +|---|---|---|---|---| +| `performanceAdaptiveSampling` | `com.bugsee.option.performance.adaptive-sampling` | `boolean` | iOS, Android | Promote "interesting" transactions that lost the random sampling draw. | +| `performanceMonitoring` | `com.bugsee.option.performance.enabled` | `boolean` | iOS, Android | Enable performance monitoring (APM). | +| `performanceSampleRate` | `com.bugsee.option.performance.sample-rate` | `number` | iOS, Android | Probability, `0` to `1`, that a transaction is sampled. | +| `performanceUploadMode` | `com.bugsee.option.performance.upload-mode` | `string` | Android | Upload mode for performance data: `'batched'` or `'realtime'`. | + +### Not exposed on purpose + +- `com.bugsee.option.config.data-encryption` (iOS): declared in the SDK's private header, not its public API. +- `com.bugsee.option.$$DEBUG`, `$$WRAPPER` (Android): internal; the package registers itself as the wrapper. +- `endpoint` / `$$ENDPOINT`: use the `endpoint` accessor, which writes the right key for the platform. diff --git a/packages/react-native/README.md b/packages/react-native/README.md index af2a4405..e7a292fe 100644 --- a/packages/react-native/README.md +++ b/packages/react-native/README.md @@ -95,6 +95,30 @@ running, or a token the backend rejects — without that being an error worth throwing on. Capture comes up asynchronously, so poll `getStatus()` rather than assuming a resolved `launch` means recording has begun. +### Launch options + +Every option either native SDK accepts has a typed accessor on the options object, shared ones on both +platforms and platform-only ones on the Android or iOS object. Nothing is defaulted by the wrapper: an +option you leave unset takes the SDK's own default. + +```ts +const options = createDefaultLaunchOptions(); +options.triggerByShake = false; // shake-to-report is ON by default in both SDKs +options.triggerByScreenshot = false; +options.reportingUIEmailRequired = true; +``` + +- **Wrong keys are not silent.** The Android SDK drops a key it does not know and the iOS SDK ignores it, so a + 6.x name such as `ShakeToReport` (which iOS still maps) would otherwise do nothing on Android. `launch` and + `relaunch` log one `console.warn` per unknown key and name the key to use. +- **`launch` while the SDK is already running ignores the options** you pass: an iOS session that is + already up, or an Android process the SDK relaunched itself after the OS killed it. Check `getStatus()` first. +- **`relaunch(options)` restarts with exactly the options you pass.** Options you omit return to the SDK + default; the previous launch's are not kept. + +The full list, with keys, types and platforms, is in +[`docs/launch-options.md`](https://github.com/bugsee/bugsee-react-native/blob/main/docs/launch-options.md). + ### Reporting render errors Wrap part of the tree (or the whole app) in `` to report an error thrown while rendering diff --git a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java index 713dcecd..c685f1e1 100644 --- a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +++ b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java @@ -1483,8 +1483,14 @@ private static WritableMap toWritableMap(@Nullable final Map) value); + if (wire instanceof Double) { + result.putDouble(entry.getKey(), (Double) wire); + } else { + result.putString(entry.getKey(), (String) wire); + } } // Anything else has no JS representation; omitted rather than // stringified, which would read as a value the app could set back. diff --git a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java index 4861437c..fe061e99 100644 --- a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java +++ b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java @@ -125,6 +125,21 @@ static double wireValue(@NonNull final Object constant) { return -1; } + /** + * What an enum constant travels back to JS as: its internal value for the + * five numeric option enums, and its constant NAME for any other. + * + *

The other enums (the leak module's {@code MemoryLeakMode}) have no + * number, and {@link #wireValue} answers -1 for them, which JS would read as + * a real setting. Their constant name is also what JS sends to set them, so + * the value round-trips. + */ + @NonNull + static Object wireFor(@NonNull final Enum constant) { + final double value = wireValue(constant); + return value >= 0 ? (Object) value : constant.name(); + } + /** DirectBuffers, at 21, is the largest value any option enum carries. */ private static final int MAX_ENUM_VALUE = 64; diff --git a/packages/react-native/android/src/test/java/com/bugsee/reactnative/BugseeOptionEnumsTest.java b/packages/react-native/android/src/test/java/com/bugsee/reactnative/BugseeOptionEnumsTest.java index 040cdb4e..8239e7c4 100644 --- a/packages/react-native/android/src/test/java/com/bugsee/reactnative/BugseeOptionEnumsTest.java +++ b/packages/react-native/android/src/test/java/com/bugsee/reactnative/BugseeOptionEnumsTest.java @@ -174,4 +174,24 @@ public void wireValueRefusesSomethingThatIsNotAnOptionEnum() { public void knowsExactlyTheEnumTypedKeys() { assertEquals(7, BugseeOptionEnums.enumKeys().size()); } + /** Stands in for an option enum with no number, like the leak module's MemoryLeakMode. */ + private enum Unnumbered { + DEEP_DEBUG_ONLY + } + + @Test + public void wireForAnswersTheInternalValueForANumericOptionEnum() { + assertEquals(20.0, (Double) BugseeOptionEnums.wireFor(VideoMode.Fullscreen), 0.0); + assertEquals(1.0, (Double) BugseeOptionEnums.wireFor(IssueSeverity.VeryLow), 0.0); + } + + /** + * wireValue answers -1 for an enum it does not know, which JS would read as + * a real setting. The constant name is also what JS sends to set such an + * option, so the value round-trips. + */ + @Test + public void wireForAnswersTheConstantNameForAnEnumWithNoNumber() { + assertEquals("DEEP_DEBUG_ONLY", BugseeOptionEnums.wireFor(Unnumbered.DEEP_DEBUG_ONLY)); + } } diff --git a/packages/react-native/src/__tests__/launch-unknown-options.test.ts b/packages/react-native/src/__tests__/launch-unknown-options.test.ts new file mode 100644 index 00000000..d57e7571 --- /dev/null +++ b/packages/react-native/src/__tests__/launch-unknown-options.test.ts @@ -0,0 +1,53 @@ +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('../exceptions/handlers', () => ({ + installExceptionHandlers: jest.fn(), + setExceptionCaptureEnabled: jest.fn(), + setCrashDetectionOptedOut: jest.fn(), +})); +jest.mock('../console/capture', () => ({ installConsoleCapture: jest.fn() })); +jest.mock('../NativeBugsee', () => require('../__mocks__/native').nativeMock); + +import Bugsee from '../index'; +import { native } from '../__mocks__/native'; +import { createDefaultLaunchOptions } from '../options/createDefaultLaunchOptions'; +import { resetUnknownOptionWarnings } from '../options/unknownKeys'; + +const TOKEN = '00000000-0000-4000-8000-000000000000'; + +describe('launch and relaunch name options the SDK would drop', () => { + let warn: jest.SpyInstance; + beforeEach(() => { + native.reset(); + resetUnknownOptionWarnings(); + warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + afterEach(() => warn.mockRestore()); + + it('warns about a 6.x key in a plain map, and still launches with it', async () => { + await Bugsee.launch(TOKEN, { ShakeToReport: false }); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain('ShakeToReport'); + // Warn, never refuse: a key this build does not know may belong to a newer SDK. + expect(native.launch).toHaveBeenCalledWith(TOKEN, { ShakeToReport: false }); + }); + + it('warns on relaunch too', async () => { + await Bugsee.relaunch({ typo: true }); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it('forwards triggerByShake = false untouched and says nothing', async () => { + const options = createDefaultLaunchOptions('android'); + options.triggerByShake = false; + await Bugsee.launch(TOKEN, options); + expect(native.launch).toHaveBeenCalledWith(TOKEN, { + 'com.bugsee.option.reporting.triggers.shake': false, + }); + expect(warn).not.toHaveBeenCalled(); + }); + + it('says nothing for an empty map', async () => { + await Bugsee.launch(TOKEN); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index bec2b4f5..c71ecfb3 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -1,4 +1,5 @@ import type { ComponentType } from 'react'; +import { Platform } from 'react-native'; import NativeBugsee from './NativeBugsee'; import { PACKAGE_VERSION } from './version'; import { wrap } from './viewtree/anchor'; @@ -32,6 +33,7 @@ import { addNetworkEvent as recordNetworkEvent } from './network/add'; import type { AddedNetworkEvent } from './network/add'; import { type IssueSeverity, LogLevel } from './options/enums'; import { BugseeLaunchOptions } from './options/BugseeLaunchOptions'; +import { warnUnknownOptions } from './options/unknownKeys'; import { labelsArgument, severityArgument } from './report/fields'; import { assertEventOrTraceName, @@ -118,11 +120,22 @@ export type LaunchOptions = Record; */ export type LaunchOptionsInput = BugseeLaunchOptions | LaunchOptions; -/** The native payload for either form. An options object is serialised here, once, so callers never have to. */ +/** + * The native payload for either form. An options object is serialised here, once, so callers never have to. + * + * Also warns about keys the running platform's SDK would silently drop. Both SDKs ignore an unknown key + * without any error, so a misspelt or 6.x-style name (`ShakeToReport`) otherwise leaves the setting + * unapplied with nothing to say so. The launch itself is unchanged. + */ function nativeOptionsOf(options: LaunchOptionsInput): LaunchOptions { - return options instanceof BugseeLaunchOptions - ? BugseeLaunchOptions.serialize(options) - : options; + const native = + options instanceof BugseeLaunchOptions + ? BugseeLaunchOptions.serialize(options) + : options; + if (Platform.OS === 'ios' || Platform.OS === 'android') { + warnUnknownOptions(Platform.OS, native); + } + return native; } class Bugsee { diff --git a/packages/react-native/src/options/AndroidLaunchOptions.ts b/packages/react-native/src/options/AndroidLaunchOptions.ts index 2947bc22..8708fc31 100644 --- a/packages/react-native/src/options/AndroidLaunchOptions.ts +++ b/packages/react-native/src/options/AndroidLaunchOptions.ts @@ -1,4 +1,5 @@ import { BugseeLaunchOptions } from './BugseeLaunchOptions'; +import type { MemoryLeakMode, VideoMode } from './enums'; import { ANDROID_ENDPOINT_KEY, endpointFor } from './endpoint'; /** Launch options for Android, adding the keys only that SDK accepts. */ @@ -17,31 +18,121 @@ export class AndroidLaunchOptions extends BugseeLaunchOptions { this.$set(ANDROID_ENDPOINT_KEY, payload[ANDROID_ENDPOINT_KEY]); } - get videoMode(): number | undefined { + /** + * Query every logging source (system, radio, ...) rather than only the default ones. + */ + get logsUseAllSources(): boolean | undefined { + return this.$get('com.bugsee.option.capture.logs.allsources'); + } + set logsUseAllSources(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.logs.allsources', value); + } + + /** + * Honour `FLAG_SECURE`: blank secure windows in capture and treat such an activity as a full blackout. + */ + get captureRespectFlagSecure(): boolean | undefined { + return this.$get('com.bugsee.option.capture.respect-flag-secure'); + } + set captureRespectFlagSecure(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.respect-flag-secure', value); + } + + /** + * Use a lightweight MP4 muxer instead of `MediaMuxer`. + */ + get captureVideoUsingCustomMuxer(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.custom-muxer'); + } + set captureVideoUsingCustomMuxer(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.custom-muxer', value); + } + + /** + * Keep fullscreen (MediaProjection) capture running while the app is in the background. + */ + get captureVideoFullscreenKeepRunning(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.fullscreen-keep-running'); + } + set captureVideoFullscreenKeepRunning(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.fullscreen-keep-running', value); + } + + /** + * Remember the user's screen-capture consent decision across launches. + */ + get captureVideoFullscreenRememberUserDecision(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.fullscreen-remember-decision'); + } + set captureVideoFullscreenRememberUserDecision(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.fullscreen-remember-decision', value); + } + + /** + * Screen-capture mode; see {@link VideoMode}. + */ + get videoMode(): VideoMode | undefined { return this.$get('com.bugsee.option.capture.video.mode'); } - set videoMode(value: number | undefined) { + set videoMode(value: VideoMode | undefined) { this.$set('com.bugsee.option.capture.video.mode', value); } - get logsUseAllSources(): boolean | undefined { - return this.$get('com.bugsee.option.capture.logs.allsources'); + /** + * In `VideoMode.V1`, skip more frames while secure views are on screen. + */ + get captureVideoSecureScrolling(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.secure-scrolling'); } - set logsUseAllSources(value: boolean | undefined) { - this.$set('com.bugsee.option.capture.logs.allsources', value); + set captureVideoSecureScrolling(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.secure-scrolling', value); } - get detectAndReportExitLowMemory(): boolean | undefined { - return this.$get('com.bugsee.option.detect.exit.low_memory'); + /** + * Has no effect: the SDK no longer scopes WebView capture by domain. + * + * @deprecated Android 7.1.2 deprecated this option and the SDK does not honour it. + */ + get captureWebViewDomainAllowlist(): string | undefined { + return this.$get('com.bugsee.option.capture.webview.domain-allowlist'); } - set detectAndReportExitLowMemory(value: boolean | undefined) { - this.$set('com.bugsee.option.detect.exit.low_memory', value); + set captureWebViewDomainAllowlist(value: string | undefined) { + this.$set('com.bugsee.option.capture.webview.domain-allowlist', value); + } + + /** + * Seconds before a report handler's completion callback is auto-fired; `0` disables the timeout. + */ + get reportHandlerCallbackTimeout(): number | undefined { + return this.$get('com.bugsee.option.config.report-handler-callback-timeout'); + } + set reportHandlerCallbackTimeout(value: number | undefined) { + this.$set('com.bugsee.option.config.report-handler-callback-timeout', value); + } + + /** + * Export and upload reports in-process on background threads instead of through JobScheduler. + */ + get reportProcessingInProcess(): boolean | undefined { + return this.$get('com.bugsee.option.config.report-processing-in-process'); + } + set reportProcessingInProcess(value: boolean | undefined) { + this.$set('com.bugsee.option.config.report-processing-in-process', value); } /** - * Report a low-memory kill of a process that was not in the foreground as - * a non-fatal error rather than a crash. Applies only while - * {@link detectAndReportExitLowMemory} is on. Android 7.3.0. + * Sample the main thread during an ANR to attribute the report to culprit frames. + */ + get detectAndReportAnrSampling(): boolean | undefined { + return this.$get('com.bugsee.option.detect.anr.sampling'); + } + set detectAndReportAnrSampling(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.anr.sampling', value); + } + + /** + * Report a low-memory kill of a process that was not in the foreground as a non-fatal error rather than a + * crash. Applies only while {@link detectAndReportExitLowMemory} is on. Android 7.3.0. */ get detectAndReportExitLowMemoryBackgroundAsError(): boolean | undefined { return this.$get('com.bugsee.option.detect.exit.bg_low_memory_as_error'); @@ -50,10 +141,223 @@ export class AndroidLaunchOptions extends BugseeLaunchOptions { this.$set('com.bugsee.option.detect.exit.bg_low_memory_as_error', value); } + /** + * Report exits caused by a dependency process dying. + */ + get detectAndReportExitDependencyDied(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.dependency_died'); + } + set detectAndReportExitDependencyDied(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.dependency_died', value); + } + + /** + * Report exits caused by excessive resource usage. + */ + get detectAndReportExitExcessiveResourceUsage(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.excessive_resource_usage'); + } + set detectAndReportExitExcessiveResourceUsage(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.excessive_resource_usage', value); + } + + /** + * Report exits caused by low memory (the OOM killer). + */ + get detectAndReportExitLowMemory(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.low_memory'); + } + set detectAndReportExitLowMemory(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.low_memory', value); + } + + /** + * Report exits caused by the app not responding (ANR). + */ + get detectAndReportExitNotResponding(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.not_responding'); + } + set detectAndReportExitNotResponding(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.not_responding', value); + } + + /** + * Report ANR exits as crashes instead of non-fatal errors. + */ + get detectAndReportExitNotRespondingAsCrash(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.not_responding.as_crash'); + } + set detectAndReportExitNotRespondingAsCrash(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.not_responding.as_crash', value); + } + + /** + * Report exits with an "other" reason. + */ + get detectAndReportExitOther(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.other'); + } + set detectAndReportExitOther(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.other', value); + } + + /** + * Report exits caused by a package state change. + */ + get detectAndReportExitPackageStateChanged(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.package_state_changed'); + } + set detectAndReportExitPackageStateChanged(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.package_state_changed', value); + } + + /** + * Report exits caused by a package update. + */ + get detectAndReportExitPackageUpdated(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.package_updated'); + } + set detectAndReportExitPackageUpdated(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.package_updated', value); + } + + /** + * Report exits caused by a runtime permission change. + */ + get detectAndReportExitPermissionChanged(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.permission_changed'); + } + set detectAndReportExitPermissionChanged(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.permission_changed', value); + } + + /** + * Report exits with an unknown reason. + */ + get detectAndReportExitUnknown(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.unknown'); + } + set detectAndReportExitUnknown(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.unknown', value); + } + + /** + * Report exits the user requested, such as a force stop. + */ + get detectAndReportExitUserRequested(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.user_requested'); + } + set detectAndReportExitUserRequested(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.user_requested', value); + } + + /** + * Report exits caused by the system stopping the app. + */ + get detectAndReportExitUserWasStopped(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit.user_was_stopped'); + } + set detectAndReportExitUserWasStopped(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit.user_was_stopped', value); + } + + /** + * Sample the main thread during a hang to attribute the report to culprit frames. Needs {@link detectAndReportHang}. + */ + get detectAndReportHangSampling(): boolean | undefined { + return this.$get('com.bugsee.option.detect.hang.sampling'); + } + set detectAndReportHangSampling(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.hang.sampling', value); + } + + /** + * Upload mode for performance data: `'batched'` or `'realtime'`. + */ + get performanceUploadMode(): string | undefined { + return this.$get('com.bugsee.option.performance.upload-mode'); + } + set performanceUploadMode(value: string | undefined) { + this.$set('com.bugsee.option.performance.upload-mode', value); + } + + /** + * Let a broadcast open the report dialog. + */ + get triggerByBroadcast(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.triggers.broadcast'); + } + set triggerByBroadcast(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.triggers.broadcast', value); + } + + /** + * Let the user open the report dialog from the notification bar. The SDK default is on. + */ get triggerByNotification(): boolean | undefined { return this.$get('com.bugsee.option.reporting.triggers.notification-bar'); } set triggerByNotification(value: boolean | undefined) { this.$set('com.bugsee.option.reporting.triggers.notification-bar', value); } + + /** + * Detect native (NDK) crashes. Needs {@link detectAndReportCrash}; this package bundles the NDK module. + */ + get detectAndReportNdkCrash(): boolean | undefined { + return this.$get('com.bugsee.option.detect.crash-ndk'); + } + set detectAndReportNdkCrash(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.crash-ndk', value); + } + + /** + * Attach the Android tombstone logs to NDK crash reports. + */ + get ndkIncludeTombstoneLogs(): boolean | undefined { + return this.$get('com.bugsee.option.crash-ndk.tombstone-logs'); + } + set ndkIncludeTombstoneLogs(value: boolean | undefined) { + this.$set('com.bugsee.option.crash-ndk.tombstone-logs', value); + } + + /** + * Detect memory leaks. Honoured only when the app also depends on `com.bugsee:bugsee-android-leak`, which this package does not add. + */ + get detectMemoryLeaks(): boolean | undefined { + return this.$get('com.bugsee.option.detect.memory_leaks'); + } + set detectMemoryLeaks(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.memory_leaks', value); + } + + /** + * Leak detection depth; see {@link MemoryLeakMode}. Needs `bugsee-android-leak`. + */ + get detectMemoryLeaksMode(): MemoryLeakMode | undefined { + return this.$get('com.bugsee.option.detect.memory_leaks.mode'); + } + set detectMemoryLeaksMode(value: MemoryLeakMode | undefined) { + this.$set('com.bugsee.option.detect.memory_leaks.mode', value); + } + + /** + * Fraction of sessions that run the deep leak modes. Needs `bugsee-android-leak`. + */ + get detectMemoryLeaksDeepSampleRate(): number | undefined { + return this.$get('com.bugsee.option.detect.memory_leaks.deep_sample_rate'); + } + set detectMemoryLeaksDeepSampleRate(value: number | undefined) { + this.$set('com.bugsee.option.detect.memory_leaks.deep_sample_rate', value); + } + + /** + * Detect thread leaks. Needs `bugsee-android-leak`. + */ + get detectThreadLeaks(): boolean | undefined { + return this.$get('com.bugsee.option.detect.thread_leaks'); + } + set detectThreadLeaks(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.thread_leaks', value); + } } diff --git a/packages/react-native/src/options/BugseeLaunchOptions.ts b/packages/react-native/src/options/BugseeLaunchOptions.ts index a511f897..b4ab216e 100644 --- a/packages/react-native/src/options/BugseeLaunchOptions.ts +++ b/packages/react-native/src/options/BugseeLaunchOptions.ts @@ -1,3 +1,5 @@ +import type { FrameRate, IssueSeverity, LogLevel, VideoQuality } from './enums'; + /** * Launch options, keyed by the SDKs' real 7.x option keys. * @@ -75,6 +77,9 @@ export abstract class BugseeLaunchOptions { // live on the subclasses, so an iOS-only key is not reachable from an // Android options object. + /** + * Capture logs. Lines sent with `Bugsee.log()` are always recorded. + */ get captureLogs(): boolean | undefined { return this.$get('com.bugsee.option.capture.logs'); } @@ -82,13 +87,19 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.capture.logs', value); } - get captureLogsLevel(): number | undefined { + /** + * Least severe level captured; see {@link LogLevel}. + */ + get captureLogsLevel(): LogLevel | undefined { return this.$get('com.bugsee.option.capture.logs.level'); } - set captureLogsLevel(value: number | undefined) { + set captureLogsLevel(value: LogLevel | undefined) { this.$set('com.bugsee.option.capture.logs.level', value); } + /** + * Capture network events. + */ get captureNetwork(): boolean | undefined { return this.$get('com.bugsee.option.capture.network'); } @@ -96,6 +107,49 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.capture.network', value); } + /** + * Largest request or response body captured, in bytes. + */ + get captureNetworkBodySizeLimit(): number | undefined { + return this.$get('com.bugsee.option.capture.network.body-size-limit'); + } + set captureNetworkBodySizeLimit(value: number | undefined) { + this.$set('com.bugsee.option.capture.network.body-size-limit', value); + } + + /** + * Also capture bodies that declare no content type. Off keeps only textual bodies. + */ + get captureNetworkBodyWithoutType(): boolean | undefined { + return this.$get('com.bugsee.option.capture.network.body-without-type'); + } + set captureNetworkBodyWithoutType(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.network.body-without-type', value); + } + + /** + * Redact known-sensitive values (query parameters, headers, JSON bodies) when no network filter is set. + */ + get captureNetworkUseDefaultSanitizer(): boolean | undefined { + return this.$get('com.bugsee.option.capture.network.default-sanitizer'); + } + set captureNetworkUseDefaultSanitizer(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.network.default-sanitizer', value); + } + + /** + * Subscribe network capture synchronously during launch, so requests issued in the launch window are seen. + */ + get captureNetworkOnLaunch(): boolean | undefined { + return this.$get('com.bugsee.option.capture.network.on-launch'); + } + set captureNetworkOnLaunch(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.network.on-launch', value); + } + + /** + * Capture breadcrumbs (user and system events). + */ get captureBreadcrumbs(): boolean | undefined { return this.$get('com.bugsee.option.capture.breadcrumbs'); } @@ -103,6 +157,39 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.capture.breadcrumbs', value); } + /** + * Attach the extra detail of automatically collected device-event breadcrumbs. + */ + get captureBreadcrumbsExtras(): boolean | undefined { + return this.$get('com.bugsee.option.capture.breadcrumbs.extras'); + } + set captureBreadcrumbsExtras(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.breadcrumbs.extras', value); + } + + /** + * Capture screenshots for reports, independent of video. + */ + get captureScreenshot(): boolean | undefined { + return this.$get('com.bugsee.option.capture.screenshot'); + } + set captureScreenshot(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.screenshot', value); + } + + /** + * Privacy scaling applied to screenshots; below `1` removes fine detail such as text. + */ + get captureScreenshotScale(): number | undefined { + return this.$get('com.bugsee.option.capture.screenshot.scale'); + } + set captureScreenshotScale(value: number | undefined) { + this.$set('com.bugsee.option.capture.screenshot.scale', value); + } + + /** + * Record video for reports. + */ get captureVideo(): boolean | undefined { return this.$get('com.bugsee.option.capture.video'); } @@ -110,27 +197,79 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.capture.video', value); } - get detectAndReportCrash(): boolean | undefined { - return this.$get('com.bugsee.option.detect.crash'); + /** + * Skip capture work while the screen is idle. The SDKs' own defaults differ. + */ + get captureVideoAdaptive(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.adaptive'); } - set detectAndReportCrash(value: boolean | undefined) { - this.$set('com.bugsee.option.detect.crash', value); + set captureVideoAdaptive(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.adaptive', value); } - get detectAndReportHang(): boolean | undefined { - return this.$get('com.bugsee.option.detect.hang'); + /** + * How often frames are captured; see {@link FrameRate}. + */ + get captureVideoFrameRate(): FrameRate | undefined { + return this.$get('com.bugsee.option.capture.video.frame-rate'); } - set detectAndReportHang(value: boolean | undefined) { - this.$set('com.bugsee.option.detect.hang', value); + set captureVideoFrameRate(value: FrameRate | undefined) { + this.$set('com.bugsee.option.capture.video.frame-rate', value); } - get wifiOnlyUpload(): boolean | undefined { - return this.$get('com.bugsee.option.config.wifi-only-upload'); + /** + * Quality of the encoded video; see {@link VideoQuality}. + */ + get captureVideoQuality(): VideoQuality | undefined { + return this.$get('com.bugsee.option.capture.video.quality'); } - set wifiOnlyUpload(value: boolean | undefined) { - this.$set('com.bugsee.option.config.wifi-only-upload', value); + set captureVideoQuality(value: VideoQuality | undefined) { + this.$set('com.bugsee.option.capture.video.quality', value); + } + + /** + * Extra down-scaling of recorded video; `0.5` halves width and height. + */ + get captureVideoScale(): number | undefined { + return this.$get('com.bugsee.option.capture.video.scale'); + } + set captureVideoScale(value: number | undefined) { + this.$set('com.bugsee.option.capture.video.scale', value); + } + + /** + * Capture the view hierarchy for reports. + */ + get captureViewHierarchy(): boolean | undefined { + return this.$get('com.bugsee.option.capture.view-hierarchy'); + } + set captureViewHierarchy(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.view-hierarchy', value); } + /** + * Inject the advanced WebView SDK into instrumented WebViews for full-fidelity in-page capture. + */ + get captureWebViewAdvanced(): boolean | undefined { + return this.$get('com.bugsee.option.capture.webview.advanced'); + } + set captureWebViewAdvanced(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.webview.advanced', value); + } + + /** + * Let an incident raised inside an instrumented WebView open a native bug report. + */ + get captureWebViewReportTrigger(): boolean | undefined { + return this.$get('com.bugsee.option.capture.webview.report-trigger'); + } + set captureWebViewReportTrigger(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.webview.report-trigger', value); + } + + /** + * Seconds of history a report carries. + */ get duration(): number | undefined { return this.$get('com.bugsee.option.config.duration'); } @@ -139,10 +278,8 @@ export abstract class BugseeLaunchOptions { } /** - * Disk space, in megabytes, that reports waiting to be sent may occupy. - * iOS-only until Android 7.3.0 registered the same key in the same unit; - * the SDKs' defaults differ (iOS 50, Android 150), and the wrapper sets - * neither. + * Disk space, in megabytes, that reports waiting to be sent may occupy. Past it the + * oldest reports are deleted whole. The SDKs' defaults can differ; the wrapper sets neither. */ get maxDataSize(): number | undefined { return this.$get('com.bugsee.option.config.max-data-size'); @@ -151,7 +288,9 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.config.max-data-size', value); } - /** Most reports kept waiting to be sent. Android 7.3.0, iOS 7.0.0. */ + /** + * Most reports kept waiting to be sent. Android 7.3.0, iOS 7.0.0. + */ get maxPendingReports(): number | undefined { return this.$get('com.bugsee.option.config.max-pending-reports'); } @@ -160,8 +299,8 @@ export abstract class BugseeLaunchOptions { } /** - * Oldest a report waiting to be sent may get, in days; `0` or less keeps - * reports until they are sent or evicted. Android 7.3.0, iOS 7.0.0. + * Oldest a report waiting to be sent may get, in days; `0` or less keeps reports until + * they are sent or evicted. Android 7.3.0, iOS 7.0.0. */ get maxPendingReportAge(): number | undefined { return this.$get('com.bugsee.option.config.max-pending-report-age'); @@ -170,6 +309,277 @@ export abstract class BugseeLaunchOptions { this.$set('com.bugsee.option.config.max-pending-report-age', value); } + /** + * Coalesce window, in milliseconds, before `Bugsee.notify` uploads flush; `0` posts as soon as the item is on disk. + */ + get notifyFlushDelay(): number | undefined { + return this.$get('com.bugsee.option.config.notify-flush-delay'); + } + set notifyFlushDelay(value: number | undefined) { + this.$set('com.bugsee.option.config.notify-flush-delay', value); + } + + /** + * Upload only over Wi-Fi. + */ + get wifiOnlyUpload(): boolean | undefined { + return this.$get('com.bugsee.option.config.wifi-only-upload'); + } + set wifiOnlyUpload(value: boolean | undefined) { + this.$set('com.bugsee.option.config.wifi-only-upload', value); + } + + /** + * Detect and report performance anomalies. + */ + get detectAndReportAnomaly(): boolean | undefined { + return this.$get('com.bugsee.option.detect.anomaly'); + } + set detectAndReportAnomaly(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.anomaly', value); + } + + /** + * Detect and report crashes. + */ + get detectAndReportCrash(): boolean | undefined { + return this.$get('com.bugsee.option.detect.crash'); + } + set detectAndReportCrash(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.crash', value); + } + + /** + * Recover crashes that happen during app start-up. + */ + get detectAndReportEarlyCrash(): boolean | undefined { + return this.$get('com.bugsee.option.detect.early-crash'); + } + set detectAndReportEarlyCrash(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.early-crash', value); + } + + /** + * Detect and report app exits. + */ + get detectAndReportExit(): boolean | undefined { + return this.$get('com.bugsee.option.detect.exit'); + } + set detectAndReportExit(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.exit', value); + } + + /** + * Detect and report user-frustration patterns such as rage taps. + */ + get detectFrustration(): boolean | undefined { + return this.$get('com.bugsee.option.detect.frustration'); + } + set detectFrustration(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.frustration', value); + } + + /** + * Detect and report hangs. + */ + get detectAndReportHang(): boolean | undefined { + return this.$get('com.bugsee.option.detect.hang'); + } + set detectAndReportHang(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.hang', value); + } + + /** + * Main-thread block, in milliseconds, that raises a "fair" hang. Less than the medium level. + */ + get detectAndReportHangFairLevel(): number | undefined { + return this.$get('com.bugsee.option.detect.hang.level.fair'); + } + set detectAndReportHangFairLevel(value: number | undefined) { + this.$set('com.bugsee.option.detect.hang.level.fair', value); + } + + /** + * Main-thread block, in milliseconds, that raises a "medium" hang. + */ + get detectAndReportHangMediumLevel(): number | undefined { + return this.$get('com.bugsee.option.detect.hang.level.medium'); + } + set detectAndReportHangMediumLevel(value: number | undefined) { + this.$set('com.bugsee.option.detect.hang.level.medium', value); + } + + /** + * Main-thread block, in milliseconds, that raises a "severe" hang. Greater than the medium level. + */ + get detectAndReportHangSevereLevel(): number | undefined { + return this.$get('com.bugsee.option.detect.hang.level.severe'); + } + set detectAndReportHangSevereLevel(value: number | undefined) { + this.$set('com.bugsee.option.detect.hang.level.severe', value); + } + + /** + * Turn HTTP 5xx responses into error reports. + */ + get detectAndReportHttpErrors(): boolean | undefined { + return this.$get('com.bugsee.option.detect.http-errors'); + } + set detectAndReportHttpErrors(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.http-errors', value); + } + + /** + * Detect and report blocking work on the main thread. + */ + get detectAndReportMainThreadMisuse(): boolean | undefined { + return this.$get('com.bugsee.option.detect.main_thread_misuse'); + } + set detectAndReportMainThreadMisuse(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.main_thread_misuse', value); + } + + /** + * Promote "interesting" transactions that lost the random sampling draw. + */ + get performanceAdaptiveSampling(): boolean | undefined { + return this.$get('com.bugsee.option.performance.adaptive-sampling'); + } + set performanceAdaptiveSampling(value: boolean | undefined) { + this.$set('com.bugsee.option.performance.adaptive-sampling', value); + } + + /** + * Enable performance monitoring (APM). + */ + get performanceMonitoring(): boolean | undefined { + return this.$get('com.bugsee.option.performance.enabled'); + } + set performanceMonitoring(value: boolean | undefined) { + this.$set('com.bugsee.option.performance.enabled', value); + } + + /** + * Probability, `0` to `1`, that a transaction is sampled. + */ + get performanceSampleRate(): number | undefined { + return this.$get('com.bugsee.option.performance.sample-rate'); + } + set performanceSampleRate(value: number | undefined) { + this.$set('com.bugsee.option.performance.sample-rate', value); + } + + /** + * Default priority of bug reports; see {@link IssueSeverity}. + */ + get reportingDefaultBugPriority(): IssueSeverity | undefined { + return this.$get('com.bugsee.option.reporting.defaults.bug-priority'); + } + set reportingDefaultBugPriority(value: IssueSeverity | undefined) { + this.$set('com.bugsee.option.reporting.defaults.bug-priority', value); + } + + /** + * Default priority of crash reports; see {@link IssueSeverity}. + */ + get reportingDefaultCrashPriority(): IssueSeverity | undefined { + return this.$get('com.bugsee.option.reporting.defaults.crash-priority'); + } + set reportingDefaultCrashPriority(value: IssueSeverity | undefined) { + this.$set('com.bugsee.option.reporting.defaults.crash-priority', value); + } + + /** + * Default priority of error reports; see {@link IssueSeverity}. + */ + get reportingDefaultErrorPriority(): IssueSeverity | undefined { + return this.$get('com.bugsee.option.reporting.defaults.error-priority'); + } + set reportingDefaultErrorPriority(value: IssueSeverity | undefined) { + this.$set('com.bugsee.option.reporting.defaults.error-priority', value); + } + + /** + * Let the user open the report dialog by shaking the device. **The SDK default is on:** + * set this to `false` to turn shake-to-report off. + */ + get triggerByShake(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.triggers.shake'); + } + set triggerByShake(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.triggers.shake', value); + } + + /** + * Let the user open the report dialog by taking a screenshot. + */ + get triggerByScreenshot(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.triggers.screenshot'); + } + set triggerByScreenshot(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.triggers.screenshot', value); + } + + /** + * Make the Description field mandatory in the report dialog. + */ + get reportingUIDescriptionRequired(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.description-required'); + } + set reportingUIDescriptionRequired(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.description-required', value); + } + + /** + * Make the Email field mandatory in the report dialog. + */ + get reportingUIEmailRequired(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.email-required'); + } + set reportingUIEmailRequired(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.email-required', value); + } + + /** + * Show the Labels field in the report dialog. + */ + get reportingUILabelsEnabled(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.labels-enabled'); + } + set reportingUILabelsEnabled(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.labels-enabled', value); + } + + /** + * Make the Labels field mandatory in the report dialog. + */ + get reportingUILabelsRequired(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.labels-required'); + } + set reportingUILabelsRequired(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.labels-required', value); + } + + /** + * Let the user change the priority in the report dialog. + */ + get reportingUIPrioritySelectorEnabled(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.priority-selector-enabled'); + } + set reportingUIPrioritySelectorEnabled(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.priority-selector-enabled', value); + } + + /** + * Make the Summary field mandatory in the report dialog. + */ + get reportingUISummaryRequired(): boolean | undefined { + return this.$get('com.bugsee.option.reporting.ui.summary-required'); + } + set reportingUISummaryRequired(value: boolean | undefined) { + this.$set('com.bugsee.option.reporting.ui.summary-required', value); + } + /** * Sets any option by its real `com.bugsee.option.*` key, surfaced or not. * `undefined` deletes, exactly as a first-class accessor does. diff --git a/packages/react-native/src/options/IOSLaunchOptions.ts b/packages/react-native/src/options/IOSLaunchOptions.ts index 6217dc88..30396fb9 100644 --- a/packages/react-native/src/options/IOSLaunchOptions.ts +++ b/packages/react-native/src/options/IOSLaunchOptions.ts @@ -1,5 +1,5 @@ import { BugseeLaunchOptions } from './BugseeLaunchOptions'; -import type { CrashHandlerType } from './enums'; +import type { CrashHandlerType, ReportingUIStyle } from './enums'; import { IOS_ENDPOINT_KEY, endpointFor } from './endpoint'; /** Launch options for iOS, adding the keys only that SDK accepts. */ @@ -18,6 +18,9 @@ export class IOSLaunchOptions extends BugseeLaunchOptions { this.$set(IOS_ENDPOINT_KEY, payload[IOS_ENDPOINT_KEY]); } + /** + * Capture `AVPlayer` content. + */ get captureAVPlayer(): boolean | undefined { return this.$get('com.bugsee.option.capture.avplayer'); } @@ -26,15 +29,23 @@ export class IOSLaunchOptions extends BugseeLaunchOptions { } /** - * The fatal signals the crash reporter intercepts, as the iOS SDK's - * `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, - * TRAP 32. Unset leaves the SDK default (every signal). Added in 7.0.0-beta7. + * Record the Bluetooth status. */ - get crashSignals(): number | undefined { - return this.$get('com.bugsee.option.capture.crash-signals'); + get captureBluetoothStatus(): boolean | undefined { + return this.$get('com.bugsee.option.capture.bluetooth-status'); } - set crashSignals(value: number | undefined) { - this.$set('com.bugsee.option.capture.crash-signals', value); + set captureBluetoothStatus(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.bluetooth-status', value); + } + + /** + * Capture camera preview layers. Read the iOS SDK's privacy and overhead notes before enabling. + */ + get captureCameraPreview(): boolean | undefined { + return this.$get('com.bugsee.option.capture.camera-preview'); + } + set captureCameraPreview(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.camera-preview', value); } /** @@ -48,10 +59,167 @@ export class IOSLaunchOptions extends BugseeLaunchOptions { this.$set('com.bugsee.option.capture.crash-handler-type', value); } + /** + * The fatal signals the crash reporter intercepts, as the iOS SDK's + * `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, TRAP 32. Unset + * leaves the SDK default (every signal). Added in 7.0.0-beta7. + */ + get crashSignals(): number | undefined { + return this.$get('com.bugsee.option.capture.crash-signals'); + } + set crashSignals(value: number | undefined) { + this.$set('com.bugsee.option.capture.crash-signals', value); + } + + /** + * Record the device and network names. + */ + get captureDeviceAndNetworkNames(): boolean | undefined { + return this.$get('com.bugsee.option.capture.device-network-names'); + } + set captureDeviceAndNetworkNames(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.device-network-names', value); + } + + /** + * Record free disk space. + */ get captureDiskSpace(): boolean | undefined { return this.$get('com.bugsee.option.capture.disk-space'); } set captureDiskSpace(value: boolean | undefined) { this.$set('com.bugsee.option.capture.disk-space', value); } + + /** + * Has no effect: the iOS SDK accepts the key and ignores it. + * + * @deprecated The iOS SDK permanently disables OSLog capture. + */ + get captureOSLogs(): boolean | undefined { + return this.$get('com.bugsee.option.capture.logs.oslog'); + } + set captureOSLogs(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.logs.oslog', value); + } + + /** + * Symbolicate stack traces on the device. + */ + get captureOnDeviceSymbolication(): boolean | undefined { + return this.$get('com.bugsee.option.capture.on-device-symbolication'); + } + set captureOnDeviceSymbolication(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.on-device-symbolication', value); + } + + /** + * Capture `AVSampleBufferDisplayLayer` content. + */ + get captureSampleBufferDisplayLayer(): boolean | undefined { + return this.$get('com.bugsee.option.capture.sample-buffer-display-layer'); + } + set captureSampleBufferDisplayLayer(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.sample-buffer-display-layer', value); + } + + /** + * Show capture status in the status bar. Debug builds only; ignored in release. + */ + get captureStatusBarInfo(): boolean | undefined { + return this.$get('com.bugsee.option.capture.status-bar-info'); + } + set captureStatusBarInfo(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.status-bar-info', value); + } + + /** + * Highest frame rate captured, `0` to `30`; `0` leaves it to {@link captureVideoFrameRate}. + */ + get captureVideoMaxFramerate(): number | undefined { + return this.$get('com.bugsee.option.capture.video.max-frame-rate'); + } + set captureVideoMaxFramerate(value: number | undefined) { + this.$set('com.bugsee.option.capture.video.max-frame-rate', value); + } + + /** + * Lowest frame rate captured, `0` to `30`; `0` leaves it to {@link captureVideoFrameRate}. + */ + get captureVideoMinFramerate(): number | undefined { + return this.$get('com.bugsee.option.capture.video.min-frame-rate'); + } + set captureVideoMinFramerate(value: number | undefined) { + this.$set('com.bugsee.option.capture.video.min-frame-rate', value); + } + + /** + * Blur transition frames instead of skipping them. + */ + get captureVideoPrivacyBlur(): boolean | undefined { + return this.$get('com.bugsee.option.capture.video.privacy-blur'); + } + set captureVideoPrivacyBlur(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.video.privacy-blur', value); + } + + /** + * Capture WebSocket traffic. + */ + get captureWebSocket(): boolean | undefined { + return this.$get('com.bugsee.option.capture.websocket'); + } + set captureWebSocket(value: boolean | undefined) { + this.$set('com.bugsee.option.capture.websocket', value); + } + + /** + * Build target name attached to reports. + */ + get buildTarget(): string | undefined { + return this.$get('com.bugsee.option.config.build-target'); + } + set buildTarget(value: string | undefined) { + this.$set('com.bugsee.option.config.build-target', value); + } + + /** + * Build type attached to reports. + */ + get buildType(): string | undefined { + return this.$get('com.bugsee.option.config.build-type'); + } + set buildType(value: string | undefined) { + this.$set('com.bugsee.option.config.build-type', value); + } + + /** + * Fill the stack of an uncaught `NSException` that has none, which can change crash grouping. + */ + get detectCrashFillEmptyExceptionStacks(): boolean | undefined { + return this.$get('com.bugsee.option.detect.crash.fill_empty_exception_stacks'); + } + set detectCrashFillEmptyExceptionStacks(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.crash.fill_empty_exception_stacks', value); + } + + /** + * Stitch Swift async frames into C++ throw stacks (iOS 15+). + */ + get detectCrashSwiftAsyncStackTraces(): boolean | undefined { + return this.$get('com.bugsee.option.detect.crash.swift_async_stacktraces'); + } + set detectCrashSwiftAsyncStackTraces(value: boolean | undefined) { + this.$set('com.bugsee.option.detect.crash.swift_async_stacktraces', value); + } + + /** + * Appearance of the report dialog; see {@link ReportingUIStyle}. + */ + get reportingUIStyle(): ReportingUIStyle | undefined { + return this.$get('com.bugsee.option.reporting.ui.style'); + } + set reportingUIStyle(value: ReportingUIStyle | undefined) { + this.$set('com.bugsee.option.reporting.ui.style', value); + } } diff --git a/packages/react-native/src/options/__tests__/accessors.test.ts b/packages/react-native/src/options/__tests__/accessors.test.ts index aaf098fb..653efa9a 100644 --- a/packages/react-native/src/options/__tests__/accessors.test.ts +++ b/packages/react-native/src/options/__tests__/accessors.test.ts @@ -12,49 +12,116 @@ import { ANDROID_ONLY_KEYS, IOS_ONLY_KEYS, SHARED_KEYS } from '../keys'; * the only thing that catches it. */ const SHARED: [string, string, unknown][] = [ - ['captureLogs', 'com.bugsee.option.capture.logs', true], + ['captureLogs', 'com.bugsee.option.capture.logs', false], ['captureLogsLevel', 'com.bugsee.option.capture.logs.level', 2], - ['captureNetwork', 'com.bugsee.option.capture.network', true], - ['captureBreadcrumbs', 'com.bugsee.option.capture.breadcrumbs', true], + ['captureNetwork', 'com.bugsee.option.capture.network', false], + ['captureNetworkBodySizeLimit', 'com.bugsee.option.capture.network.body-size-limit', 7], + ['captureNetworkBodyWithoutType', 'com.bugsee.option.capture.network.body-without-type', false], + ['captureNetworkUseDefaultSanitizer', 'com.bugsee.option.capture.network.default-sanitizer', false], + ['captureNetworkOnLaunch', 'com.bugsee.option.capture.network.on-launch', false], + ['captureBreadcrumbs', 'com.bugsee.option.capture.breadcrumbs', false], + ['captureBreadcrumbsExtras', 'com.bugsee.option.capture.breadcrumbs.extras', false], + ['captureScreenshot', 'com.bugsee.option.capture.screenshot', false], + ['captureScreenshotScale', 'com.bugsee.option.capture.screenshot.scale', 0.5], ['captureVideo', 'com.bugsee.option.capture.video', false], - ['detectAndReportCrash', 'com.bugsee.option.detect.crash', true], - ['detectAndReportHang', 'com.bugsee.option.detect.hang', true], - ['wifiOnlyUpload', 'com.bugsee.option.config.wifi-only-upload', true], - ['duration', 'com.bugsee.option.config.duration', 90], - // iOS-only until Android 7.3.0 registered the same key, in the same unit - // (megabytes) -- only the defaults differ (iOS 50, Android 150). - ['maxDataSize', 'com.bugsee.option.config.max-data-size', 100], - // Android 7.3.0, iOS 7.0.0: the same keys and units on both. - ['maxPendingReports', 'com.bugsee.option.config.max-pending-reports', 12], + ['captureVideoAdaptive', 'com.bugsee.option.capture.video.adaptive', false], + ['captureVideoFrameRate', 'com.bugsee.option.capture.video.frame-rate', 2], + ['captureVideoQuality', 'com.bugsee.option.capture.video.quality', 1], + ['captureVideoScale', 'com.bugsee.option.capture.video.scale', 0.5], + ['captureViewHierarchy', 'com.bugsee.option.capture.view-hierarchy', false], + ['captureWebViewAdvanced', 'com.bugsee.option.capture.webview.advanced', false], + ['captureWebViewReportTrigger', 'com.bugsee.option.capture.webview.report-trigger', false], + ['duration', 'com.bugsee.option.config.duration', 7], + ['maxDataSize', 'com.bugsee.option.config.max-data-size', 7], + ['maxPendingReports', 'com.bugsee.option.config.max-pending-reports', 7], ['maxPendingReportAge', 'com.bugsee.option.config.max-pending-report-age', 7], + ['notifyFlushDelay', 'com.bugsee.option.config.notify-flush-delay', 7], + ['wifiOnlyUpload', 'com.bugsee.option.config.wifi-only-upload', false], + ['detectAndReportAnomaly', 'com.bugsee.option.detect.anomaly', false], + ['detectAndReportCrash', 'com.bugsee.option.detect.crash', false], + ['detectAndReportEarlyCrash', 'com.bugsee.option.detect.early-crash', false], + ['detectAndReportExit', 'com.bugsee.option.detect.exit', false], + ['detectFrustration', 'com.bugsee.option.detect.frustration', false], + ['detectAndReportHang', 'com.bugsee.option.detect.hang', false], + ['detectAndReportHangFairLevel', 'com.bugsee.option.detect.hang.level.fair', 7], + ['detectAndReportHangMediumLevel', 'com.bugsee.option.detect.hang.level.medium', 7], + ['detectAndReportHangSevereLevel', 'com.bugsee.option.detect.hang.level.severe', 7], + ['detectAndReportHttpErrors', 'com.bugsee.option.detect.http-errors', false], + ['detectAndReportMainThreadMisuse', 'com.bugsee.option.detect.main_thread_misuse', false], + ['performanceAdaptiveSampling', 'com.bugsee.option.performance.adaptive-sampling', false], + ['performanceMonitoring', 'com.bugsee.option.performance.enabled', false], + ['performanceSampleRate', 'com.bugsee.option.performance.sample-rate', 0.5], + ['reportingDefaultBugPriority', 'com.bugsee.option.reporting.defaults.bug-priority', 4], + ['reportingDefaultCrashPriority', 'com.bugsee.option.reporting.defaults.crash-priority', 4], + ['reportingDefaultErrorPriority', 'com.bugsee.option.reporting.defaults.error-priority', 4], + ['triggerByShake', 'com.bugsee.option.reporting.triggers.shake', false], + ['triggerByScreenshot', 'com.bugsee.option.reporting.triggers.screenshot', false], + ['reportingUIDescriptionRequired', 'com.bugsee.option.reporting.ui.description-required', false], + ['reportingUIEmailRequired', 'com.bugsee.option.reporting.ui.email-required', false], + ['reportingUILabelsEnabled', 'com.bugsee.option.reporting.ui.labels-enabled', false], + ['reportingUILabelsRequired', 'com.bugsee.option.reporting.ui.labels-required', false], + ['reportingUIPrioritySelectorEnabled', 'com.bugsee.option.reporting.ui.priority-selector-enabled', false], + ['reportingUISummaryRequired', 'com.bugsee.option.reporting.ui.summary-required', false], ]; const IOS: [string, string, unknown][] = [ - ['captureAVPlayer', 'com.bugsee.option.capture.avplayer', true], - ['crashSignals', 'com.bugsee.option.capture.crash-signals', 11], - ['crashHandlerType', 'com.bugsee.option.capture.crash-handler-type', 1], - ['captureDiskSpace', 'com.bugsee.option.capture.disk-space', true], + ['captureAVPlayer', 'com.bugsee.option.capture.avplayer', false], + ['captureBluetoothStatus', 'com.bugsee.option.capture.bluetooth-status', false], + ['captureCameraPreview', 'com.bugsee.option.capture.camera-preview', false], + ['crashHandlerType', 'com.bugsee.option.capture.crash-handler-type', 2], + ['crashSignals', 'com.bugsee.option.capture.crash-signals', 7], + ['captureDeviceAndNetworkNames', 'com.bugsee.option.capture.device-network-names', false], + ['captureDiskSpace', 'com.bugsee.option.capture.disk-space', false], + ['captureOSLogs', 'com.bugsee.option.capture.logs.oslog', false], + ['captureOnDeviceSymbolication', 'com.bugsee.option.capture.on-device-symbolication', false], + ['captureSampleBufferDisplayLayer', 'com.bugsee.option.capture.sample-buffer-display-layer', false], + ['captureStatusBarInfo', 'com.bugsee.option.capture.status-bar-info', false], + ['captureVideoMaxFramerate', 'com.bugsee.option.capture.video.max-frame-rate', 7], + ['captureVideoMinFramerate', 'com.bugsee.option.capture.video.min-frame-rate', 7], + ['captureVideoPrivacyBlur', 'com.bugsee.option.capture.video.privacy-blur', false], + ['captureWebSocket', 'com.bugsee.option.capture.websocket', false], + ['buildTarget', 'com.bugsee.option.config.build-target', 'probe'], + ['buildType', 'com.bugsee.option.config.build-type', 'probe'], + ['detectCrashFillEmptyExceptionStacks', 'com.bugsee.option.detect.crash.fill_empty_exception_stacks', false], + ['detectCrashSwiftAsyncStackTraces', 'com.bugsee.option.detect.crash.swift_async_stacktraces', false], + ['reportingUIStyle', 'com.bugsee.option.reporting.ui.style', 1], ]; const ANDROID: [string, string, unknown][] = [ + ['logsUseAllSources', 'com.bugsee.option.capture.logs.allsources', false], + ['captureRespectFlagSecure', 'com.bugsee.option.capture.respect-flag-secure', false], + ['captureVideoUsingCustomMuxer', 'com.bugsee.option.capture.video.custom-muxer', false], + ['captureVideoFullscreenKeepRunning', 'com.bugsee.option.capture.video.fullscreen-keep-running', false], + ['captureVideoFullscreenRememberUserDecision', 'com.bugsee.option.capture.video.fullscreen-remember-decision', false], ['videoMode', 'com.bugsee.option.capture.video.mode', 20], - ['logsUseAllSources', 'com.bugsee.option.capture.logs.allsources', true], - [ - 'detectAndReportExitLowMemory', - 'com.bugsee.option.detect.exit.low_memory', - true, - ], - [ - 'triggerByNotification', - 'com.bugsee.option.reporting.triggers.notification-bar', - true, - ], - // Added in Android 7.3.0. - [ - 'detectAndReportExitLowMemoryBackgroundAsError', - 'com.bugsee.option.detect.exit.bg_low_memory_as_error', - true, - ], + ['captureVideoSecureScrolling', 'com.bugsee.option.capture.video.secure-scrolling', false], + ['captureWebViewDomainAllowlist', 'com.bugsee.option.capture.webview.domain-allowlist', 'probe'], + ['reportHandlerCallbackTimeout', 'com.bugsee.option.config.report-handler-callback-timeout', 7], + ['reportProcessingInProcess', 'com.bugsee.option.config.report-processing-in-process', false], + ['detectAndReportAnrSampling', 'com.bugsee.option.detect.anr.sampling', false], + ['detectAndReportExitLowMemoryBackgroundAsError', 'com.bugsee.option.detect.exit.bg_low_memory_as_error', false], + ['detectAndReportExitDependencyDied', 'com.bugsee.option.detect.exit.dependency_died', false], + ['detectAndReportExitExcessiveResourceUsage', 'com.bugsee.option.detect.exit.excessive_resource_usage', false], + ['detectAndReportExitLowMemory', 'com.bugsee.option.detect.exit.low_memory', false], + ['detectAndReportExitNotResponding', 'com.bugsee.option.detect.exit.not_responding', false], + ['detectAndReportExitNotRespondingAsCrash', 'com.bugsee.option.detect.exit.not_responding.as_crash', false], + ['detectAndReportExitOther', 'com.bugsee.option.detect.exit.other', false], + ['detectAndReportExitPackageStateChanged', 'com.bugsee.option.detect.exit.package_state_changed', false], + ['detectAndReportExitPackageUpdated', 'com.bugsee.option.detect.exit.package_updated', false], + ['detectAndReportExitPermissionChanged', 'com.bugsee.option.detect.exit.permission_changed', false], + ['detectAndReportExitUnknown', 'com.bugsee.option.detect.exit.unknown', false], + ['detectAndReportExitUserRequested', 'com.bugsee.option.detect.exit.user_requested', false], + ['detectAndReportExitUserWasStopped', 'com.bugsee.option.detect.exit.user_was_stopped', false], + ['detectAndReportHangSampling', 'com.bugsee.option.detect.hang.sampling', false], + ['performanceUploadMode', 'com.bugsee.option.performance.upload-mode', 'realtime'], + ['triggerByBroadcast', 'com.bugsee.option.reporting.triggers.broadcast', false], + ['triggerByNotification', 'com.bugsee.option.reporting.triggers.notification-bar', false], + ['detectAndReportNdkCrash', 'com.bugsee.option.detect.crash-ndk', false], + ['ndkIncludeTombstoneLogs', 'com.bugsee.option.crash-ndk.tombstone-logs', false], + ['detectMemoryLeaks', 'com.bugsee.option.detect.memory_leaks', false], + ['detectMemoryLeaksMode', 'com.bugsee.option.detect.memory_leaks.mode', 'DEEP_DEBUG_ONLY'], + ['detectMemoryLeaksDeepSampleRate', 'com.bugsee.option.detect.memory_leaks.deep_sample_rate', 0.5], + ['detectThreadLeaks', 'com.bugsee.option.detect.thread_leaks', false], ]; type Bag = Record; diff --git a/packages/react-native/src/options/__tests__/coverage.test.ts b/packages/react-native/src/options/__tests__/coverage.test.ts new file mode 100644 index 00000000..4edc8dc0 --- /dev/null +++ b/packages/react-native/src/options/__tests__/coverage.test.ts @@ -0,0 +1,71 @@ +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); + +import { BugseeLaunchOptions } from '../BugseeLaunchOptions'; +import { AndroidLaunchOptions } from '../AndroidLaunchOptions'; +import { IOSLaunchOptions } from '../IOSLaunchOptions'; +import { NO_ACCESSOR, keysFor } from '../keys'; + +/** Every settable accessor on the instance's prototype chain. */ +function setters(instance: object): string[] { + const names: string[] = []; + for ( + let proto = Object.getPrototypeOf(instance); + proto && proto !== Object.prototype; + proto = Object.getPrototypeOf(proto) + ) { + for (const [name, d] of Object.entries(Object.getOwnPropertyDescriptors(proto))) { + if (d.set !== undefined && !names.includes(name)) { + names.push(name); + } + } + } + return names; +} + +/** The keys the instance's accessors can write, found by calling each one. */ +function reachableKeys(make: () => BugseeLaunchOptions): Set { + const reached = new Set(); + for (const name of setters(make())) { + const options = make(); + try { + (options as unknown as Record)[name] = 'https://example.invalid'; + } catch { + continue; + } + for (const key of Object.keys(BugseeLaunchOptions.serialize(options))) { + reached.add(key); + } + } + return reached; +} + +/** + * The guard that stops this drifting again: every option a pinned SDK + * registers is reachable through a typed accessor, or is listed in + * `NO_ACCESSOR` with the reason it is not. A key added to `option-keys.json` + * (by regenerating it for a new SDK) fails here until someone decides. + * + * Before this existed 21 of 109 options had an accessor, and shake-to-report + * was reachable only through `setCustomOption`. + */ +describe.each([ + ['android', () => new AndroidLaunchOptions()], + ['ios', () => new IOSLaunchOptions()], +] as const)('%s: every known option has a typed accessor', (platform, make) => { + it('leaves no key reachable only through setCustomOption', () => { + const reachable = reachableKeys(make); + const missing = [...keysFor(platform)].filter( + (key) => !reachable.has(key) && !(key in NO_ACCESSOR), + ); + expect(missing).toEqual([]); + }); + + it('keeps NO_ACCESSOR honest: nothing listed there also has an accessor', () => { + const reachable = reachableKeys(make); + const stale = Object.keys(NO_ACCESSOR).filter( + (key) => keysFor(platform).has(key) && reachable.has(key), + ); + // `endpoint` is the one deliberate overlap: it IS reachable, through its own accessor. + expect(stale.filter((key) => !/endpoint/i.test(key))).toEqual([]); + }); +}); diff --git a/packages/react-native/src/options/__tests__/enums.test.ts b/packages/react-native/src/options/__tests__/enums.test.ts index 0516057b..a10bd92d 100644 --- a/packages/react-native/src/options/__tests__/enums.test.ts +++ b/packages/react-native/src/options/__tests__/enums.test.ts @@ -5,6 +5,8 @@ import { FrameRate, IssueSeverity, LogLevel, + MemoryLeakMode, + ReportingUIStyle, VideoMode, VideoQuality, WITHHELD_FROM_JS, @@ -116,3 +118,23 @@ describe('CrashHandlerType matches the iOS SDK', () => { expect(CrashHandlerType).toEqual(bare); }); }); + +describe('ReportingUIStyle matches the iOS SDK', () => { + it('has the members and values of BugseeStyle', () => { + const ios = (iosFixture as Record).ReportingUIStyle ?? {}; + const bare = Object.fromEntries( + Object.entries(ios).map(([member, value]) => [member.replace(/^BugseeStyle/, ''), value]) + ); + expect(ReportingUIStyle).toEqual(bare); + }); +}); + +describe('MemoryLeakMode', () => { + // Android's `MemoryLeakMode` (bugsee-android-leak) is a string-valued enum + // whose constants the Map launch path resolves BY NAME, so the wire value is + // the Java constant name. The extractor reads numeric enums only; pinned + // here against Android 7.4.2's `FAST`, `DEEP_DEBUG_ONLY`, `DEEP_EVERYWHERE`. + it('sends the Java constant names', () => { + expect(Object.values(MemoryLeakMode)).toEqual(['FAST', 'DEEP_DEBUG_ONLY', 'DEEP_EVERYWHERE']); + }); +}); diff --git a/packages/react-native/src/options/__tests__/unknownKeys.test.ts b/packages/react-native/src/options/__tests__/unknownKeys.test.ts new file mode 100644 index 00000000..e10b6f62 --- /dev/null +++ b/packages/react-native/src/options/__tests__/unknownKeys.test.ts @@ -0,0 +1,97 @@ +import { + LEGACY_OPTION_KEYS, + describeUnknownKey, + resetUnknownOptionWarnings, + unknownOptionKeys, + warnUnknownOptions, +} from '../unknownKeys'; +import { keysFor } from '../keys'; + +beforeEach(resetUnknownOptionWarnings); + +describe('unknownOptionKeys', () => { + it('accepts every key the platform declares', () => { + for (const platform of ['ios', 'android'] as const) { + const all = Object.fromEntries([...keysFor(platform)].map((key) => [key, true])); + expect(unknownOptionKeys(platform, all)).toEqual([]); + } + }); + + it('accepts the shake key on both platforms, the option behind the original report', () => { + const options = { 'com.bugsee.option.reporting.triggers.shake': false }; + expect(unknownOptionKeys('android', options)).toEqual([]); + expect(unknownOptionKeys('ios', options)).toEqual([]); + }); + + it('rejects a key only the other platform declares', () => { + expect( + unknownOptionKeys('android', { 'com.bugsee.option.capture.avplayer': true }), + ).toEqual(['com.bugsee.option.capture.avplayer']); + expect( + unknownOptionKeys('ios', { 'com.bugsee.option.detect.exit.low_memory': true }), + ).toEqual(['com.bugsee.option.detect.exit.low_memory']); + }); + + it('rejects an unknown key without looking at its value', () => { + expect(unknownOptionKeys('android', { nope: undefined })).toEqual(['nope']); + }); +}); + +describe('describeUnknownKey', () => { + it('names the 7.x key for a 6.x name and says Android ignores it', () => { + const message = describeUnknownKey('android', 'ShakeToReport'); + expect(message).toContain('"ShakeToReport"'); + expect(message).toContain('com.bugsee.option.reporting.triggers.shake'); + expect(message).toMatch(/Android SDK ignores it/); + }); + + it('says a 6.x name still works on iOS but not Android', () => { + expect(describeUnknownKey('ios', 'ShakeToReport')).toMatch(/Android SDK ignores it/); + }); + + it('suggests the nearest key for a typo', () => { + expect( + describeUnknownKey('android', 'com.bugsee.option.reporting.triggers.shak'), + ).toContain('Did you mean "com.bugsee.option.reporting.triggers.shake"?'); + }); + + it('offers no suggestion when nothing is close', () => { + expect(describeUnknownKey('ios', 'zzzzzzzzzzzzzzzz')).not.toContain('Did you mean'); + }); + + it('only maps 6.x names to keys that exist', () => { + for (const [legacy, key] of Object.entries(LEGACY_OPTION_KEYS)) { + const known = keysFor('ios').has(key) || keysFor('android').has(key); + expect({ legacy, known }).toEqual({ legacy, known: true }); + } + }); +}); + +describe('warnUnknownOptions', () => { + it('warns once per unknown key and stays quiet for known ones', () => { + const warn = jest.fn(); + const options = { + 'com.bugsee.option.capture.logs': true, + ShakeToReport: false, + nope: 1, + }; + warnUnknownOptions('android', options, warn); + warnUnknownOptions('android', options, warn); + expect(warn).toHaveBeenCalledTimes(2); + expect(warn.mock.calls.map(([m]) => m).join('\n')).toMatch(/ShakeToReport[\s\S]*nope/); + }); + + it('warns per platform, since each SDK knows different keys', () => { + const warn = jest.fn(); + const options = { 'com.bugsee.option.capture.avplayer': true }; + warnUnknownOptions('ios', options, warn); + warnUnknownOptions('android', options, warn); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it('does not warn for an empty map', () => { + const warn = jest.fn(); + warnUnknownOptions('ios', {}, warn); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/react-native/src/options/android-options-manifest.json b/packages/react-native/src/options/android-options-manifest.json index ecac0f07..1294187d 100644 --- a/packages/react-native/src/options/android-options-manifest.json +++ b/packages/react-native/src/options/android-options-manifest.json @@ -3,7 +3,7 @@ "sdk": "android", "sdkVersion": "7.4.2", "buildConfiguration": "release", - "generatedAt": "2026-10-13T15:48:14Z", + "generatedAt": "2026-11-16T05:30:59Z", "options": [ { "key": "com.bugsee.option.config.duration", @@ -641,6 +641,56 @@ "deprecated": { "since": "7.1.2" } + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.crash-ndk.tombstone-logs", + "module": "bugsee-android-ndk", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.crash-ndk", + "module": "bugsee-android-ndk", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.memory_leaks", + "module": "bugsee-android-leak", + "type": "boolean" + }, + { + "default": 1, + "hidden": false, + "key": "com.bugsee.option.detect.memory_leaks.deep_sample_rate", + "module": "bugsee-android-leak", + "type": "float" + }, + { + "default": "FAST", + "enum": { + "name": "MemoryLeakMode", + "values": { + "DEEP_DEBUG_ONLY": "DeepDebugOnly", + "DEEP_EVERYWHERE": "DeepEverywhere", + "FAST": "Fast" + } + }, + "hidden": false, + "key": "com.bugsee.option.detect.memory_leaks.mode", + "module": "bugsee-android-leak", + "type": "enum" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.thread_leaks", + "module": "bugsee-android-leak", + "type": "boolean" } ] } diff --git a/packages/react-native/src/options/enums.ts b/packages/react-native/src/options/enums.ts index 5463087a..83252ffe 100644 --- a/packages/react-native/src/options/enums.ts +++ b/packages/react-native/src/options/enums.ts @@ -74,6 +74,34 @@ export const CrashHandlerType = { } as const; export type CrashHandlerType = (typeof CrashHandlerType)[keyof typeof CrashHandlerType]; +/** + * How deep Android's leak detector looks. Android only, and honoured only when + * the app depends on `com.bugsee:bugsee-android-leak`. + * + * Unlike the others these cross the bridge as the Android enum's constant + * NAME: the SDK's `Map` launch path resolves a string against `name()`, and the + * module has no numeric value to send. + */ +export const MemoryLeakMode = { + Fast: 'FAST', + DeepDebugOnly: 'DEEP_DEBUG_ONLY', + DeepEverywhere: 'DEEP_EVERYWHERE', +} as const; +export type MemoryLeakMode = (typeof MemoryLeakMode)[keyof typeof MemoryLeakMode]; + +/** + * Appearance of the report dialog. iOS only. These are the `BugseeStyle` + * values in declaration order; checked against the header through + * `ios-enums.json`. + */ +export const ReportingUIStyle = { + Light: 0, + Dusk: 1, + BasedOnStatusBar: 2, + System: 3, +} as const; +export type ReportingUIStyle = (typeof ReportingUIStyle)[keyof typeof ReportingUIStyle]; + /** * SDK enum members this package deliberately does not expose, with the value * they carry natively. diff --git a/packages/react-native/src/options/ios-enums.json b/packages/react-native/src/options/ios-enums.json index fc9f5b0c..6dffc208 100644 --- a/packages/react-native/src/options/ios-enums.json +++ b/packages/react-native/src/options/ios-enums.json @@ -10,5 +10,11 @@ "BugseeCrashHandlerTypeBSD": 1, "BugseeCrashHandlerTypeMach": 2, "BugseeCrashHandlerTypeMachAndBSD": 3 + }, + "ReportingUIStyle": { + "BugseeStyleLight": 0, + "BugseeStyleDusk": 1, + "BugseeStyleBasedOnStatusBar": 2, + "BugseeStyleSystem": 3 } } diff --git a/packages/react-native/src/options/keys.ts b/packages/react-native/src/options/keys.ts index 895cca82..64ec1b11 100644 --- a/packages/react-native/src/options/keys.ts +++ b/packages/react-native/src/options/keys.ts @@ -27,7 +27,30 @@ export const ANDROID_ONLY_KEYS: readonly string[] = keys.android; */ export const UNDECLARED_KEYS: Readonly> = { ios: ['endpoint'], - android: ['com.bugsee.option.$$ENDPOINT'], + // `$$DEBUG` and `$$WRAPPER` are internal: the wrapper owns them (it registers + // itself as the wrapper), and an app has no business setting them. + android: [ + 'com.bugsee.option.$$ENDPOINT', + 'com.bugsee.option.$$DEBUG', + 'com.bugsee.option.$$WRAPPER', + ], +}; + +/** + * Keys an SDK registers that have NO first-class accessor on purpose. The + * coverage test requires every known key to have an accessor or an entry here + * with a reason, so a new SDK option cannot be silently left unreachable. + * + * Keys whose accessor has a different shape than "one setter, one key" (the + * endpoint override) are covered by {@link UNDECLARED_KEYS}. + */ +export const NO_ACCESSOR: Readonly> = { + 'com.bugsee.option.config.data-encryption': + 'declared in the iOS SDK\'s private header (BGSOptionsPrivate.h), not its public API', + 'com.bugsee.option.$$DEBUG': 'internal', + 'com.bugsee.option.$$WRAPPER': 'internal; the wrapper registers itself', + 'com.bugsee.option.$$ENDPOINT': 'reached through the `endpoint` accessor', + endpoint: 'reached through the `endpoint` accessor', }; export function keysFor(platform: 'ios' | 'android'): ReadonlySet { diff --git a/packages/react-native/src/options/option-keys.json b/packages/react-native/src/options/option-keys.json index 0800232a..2ba71c09 100644 --- a/packages/react-native/src/options/option-keys.json +++ b/packages/react-native/src/options/option-keys.json @@ -85,7 +85,9 @@ "com.bugsee.option.capture.webview.domain-allowlist", "com.bugsee.option.config.report-handler-callback-timeout", "com.bugsee.option.config.report-processing-in-process", + "com.bugsee.option.crash-ndk.tombstone-logs", "com.bugsee.option.detect.anr.sampling", + "com.bugsee.option.detect.crash-ndk", "com.bugsee.option.detect.exit.bg_low_memory_as_error", "com.bugsee.option.detect.exit.dependency_died", "com.bugsee.option.detect.exit.excessive_resource_usage", @@ -100,6 +102,10 @@ "com.bugsee.option.detect.exit.user_requested", "com.bugsee.option.detect.exit.user_was_stopped", "com.bugsee.option.detect.hang.sampling", + "com.bugsee.option.detect.memory_leaks", + "com.bugsee.option.detect.memory_leaks.deep_sample_rate", + "com.bugsee.option.detect.memory_leaks.mode", + "com.bugsee.option.detect.thread_leaks", "com.bugsee.option.performance.upload-mode", "com.bugsee.option.reporting.triggers.broadcast", "com.bugsee.option.reporting.triggers.notification-bar" diff --git a/packages/react-native/src/options/unknownKeys.ts b/packages/react-native/src/options/unknownKeys.ts new file mode 100644 index 00000000..63cc12e7 --- /dev/null +++ b/packages/react-native/src/options/unknownKeys.ts @@ -0,0 +1,159 @@ +import { keysFor } from './keys'; + +type Platform = 'ios' | 'android'; + +/** + * 6.x option names mapped to their 7.x keys. + * + * Neither SDK treats these the same way, and that is the trap: the iOS SDK still + * maps its own legacy aliases onto the 7.x keys, while the Android SDK silently + * DROPS any key it does not know. A 6.x name such as `ShakeToReport` therefore + * works on iOS and does nothing on Android, with no error on either. + * + * The list is the iOS SDK's alias table plus the 6.x Android names the wrapper + * spec records. It only feeds the message: whether a key warns is decided by + * {@link keysFor}, never by this table. + */ +export const LEGACY_OPTION_KEYS: Readonly> = { + MaxRecordingTime: 'com.bugsee.option.config.duration', + WifiOnlyUpload: 'com.bugsee.option.config.wifi-only-upload', + NotifyFlushDelay: 'com.bugsee.option.config.notify-flush-delay', + MaxDataSize: 'com.bugsee.option.config.max-data-size', + CrashReport: 'com.bugsee.option.detect.crash', + DetectAppExit: 'com.bugsee.option.detect.exit', + DetectAppLaunchCrash: 'com.bugsee.option.detect.early-crash', + HandleAnr: 'com.bugsee.option.detect.hang', + MonitorNetwork: 'com.bugsee.option.capture.network', + bodySizeLimit: 'com.bugsee.option.capture.network.body-size-limit', + MaxNetworkBodySize: 'com.bugsee.option.capture.network.body-size-limit', + RecordHttpBodyWithoutType: 'com.bugsee.option.capture.network.body-without-type', + SanitizeNetworkData: 'com.bugsee.option.capture.network.default-sanitizer', + VideoEnabled: 'com.bugsee.option.capture.video', + ScreenshotEnabled: 'com.bugsee.option.capture.screenshot', + VideoScale: 'com.bugsee.option.capture.video.scale', + VideoQuality: 'com.bugsee.option.capture.video.quality', + VideoMode: 'com.bugsee.option.capture.video.mode', + FrameRate: 'com.bugsee.option.capture.video.frame-rate', + ViewHierarchyEnabled: 'com.bugsee.option.capture.view-hierarchy', + CaptureLogs: 'com.bugsee.option.capture.logs', + LogLevel: 'com.bugsee.option.capture.logs.level', + ShakeToReport: 'com.bugsee.option.reporting.triggers.shake', + ShakeToTrigger: 'com.bugsee.option.reporting.triggers.shake', + ScreenshotToReport: 'com.bugsee.option.reporting.triggers.screenshot', + ScreenshotToTrigger: 'com.bugsee.option.reporting.triggers.screenshot', + NotificationBarTrigger: 'com.bugsee.option.reporting.triggers.notification-bar', + BugseeDefaultCrashPriority: 'com.bugsee.option.reporting.defaults.crash-priority', + BugseeDefaultBugPriority: 'com.bugsee.option.reporting.defaults.bug-priority', + BugseeDefaultErrorPriority: 'com.bugsee.option.reporting.defaults.error-priority', + ReportSummaryRequired: 'com.bugsee.option.reporting.ui.summary-required', + ReportDescriptionRequired: 'com.bugsee.option.reporting.ui.description-required', + ReportEmailRequired: 'com.bugsee.option.reporting.ui.email-required', + ReportLabelsEnabled: 'com.bugsee.option.reporting.ui.labels-enabled', + ReportLabelsRequired: 'com.bugsee.option.reporting.ui.labels-required', + BugseeReportPrioritySelector: 'com.bugsee.option.reporting.ui.priority-selector-enabled', + BugseeStyle: 'com.bugsee.option.reporting.ui.style', + PerformanceMonitoring: 'com.bugsee.option.performance.enabled', + PerformanceSampleRate: 'com.bugsee.option.performance.sample-rate', + PerformanceAdaptiveSampling: 'com.bugsee.option.performance.adaptive-sampling', +}; + +/** Edit distance, capped: a distance past `limit` is as good as any other. */ +function distance(a: string, b: string, limit: number): number { + if (Math.abs(a.length - b.length) > limit) { + return limit + 1; + } + let previous = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + const row = [i]; + for (let j = 1; j <= b.length; j++) { + row[j] = Math.min( + (previous[j] as number) + 1, + (row[j - 1] as number) + 1, + (previous[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1), + ); + } + previous = row; + } + return previous[b.length] as number; +} + +function closestKey(platform: Platform, key: string): string | undefined { + let best: string | undefined; + let bestDistance = 4; + for (const known of keysFor(platform)) { + const d = distance(key, known, 3); + if (d < bestDistance) { + best = known; + bestDistance = d; + } + } + return best; +} + +/** The keys of `options` that `platform`'s SDK does not know. */ +export function unknownOptionKeys( + platform: Platform, + options: Readonly>, +): string[] { + const known = keysFor(platform); + return Object.keys(options).filter((key) => !known.has(key)); +} + +/** One sentence naming the key, what the SDK does with it, and what to use. */ +export function describeUnknownKey(platform: Platform, key: string): string { + const sdk = platform === 'ios' ? 'iOS' : 'Android'; + const legacy = LEGACY_OPTION_KEYS[key]; + if (legacy !== undefined) { + const effect = + platform === 'android' + ? 'The Android SDK ignores it, so the setting has NO effect there' + : 'The iOS SDK still maps it, but the Android SDK ignores it'; + return `[Bugsee] "${key}" is a 6.x option name. ${effect}. Use "${legacy}" (or its accessor on the launch options object).`; + } + const suggestion = closestKey(platform, key); + const hint = suggestion === undefined ? '' : ` Did you mean "${suggestion}"?`; + return ( + `[Bugsee] "${key}" is not a launch option the ${sdk} SDK knows, so the SDK ignores it.` + + hint + ); +} + +const warned = new Set(); + +/** + * The warning's only sink. Audited by name in `scripts/raw-messages.ts`: its + * message comes from {@link describeUnknownKey}, which sees the option KEY and + * the wrapper's own key tables and is never handed a value. + */ +function emitUnknownOptionWarning(message: string): void { + console.warn(message); +} + +/** + * Warns once per key for every option `platform`'s SDK would silently drop. + * + * Both SDKs accept an unknown key without complaint, and the customer who sets + * one is left believing the setting is applied -- the case that prompted this + * was shake-to-report staying on. The launch itself proceeds unchanged: a key + * this build does not know may belong to a newer SDK than the one the wrapper + * was checked against, and refusing it would make `setCustomOption` useless. + */ +export function warnUnknownOptions( + platform: Platform, + options: Readonly>, + warn: (message: string) => void = emitUnknownOptionWarning, +): void { + for (const key of unknownOptionKeys(platform, options)) { + const id = `${platform}:${key}`; + if (warned.has(id)) { + continue; + } + warned.add(id); + warn(describeUnknownKey(platform, key)); + } +} + +/** Forgets what was warned about. For tests. */ +export function resetUnknownOptionWarnings(): void { + warned.clear(); +} diff --git a/scripts/__tests__/option-manifest-parity.test.ts b/scripts/__tests__/option-manifest-parity.test.ts index 46ab9533..c01cc516 100644 --- a/scripts/__tests__/option-manifest-parity.test.ts +++ b/scripts/__tests__/option-manifest-parity.test.ts @@ -5,6 +5,7 @@ import type { OptionsManifest } from '../option-keys'; import enumFixture from '../../packages/react-native/src/options/option-enums.json'; import { readNativeVersions } from '../native-versions'; import { ANDROID_ONLY_KEYS, SHARED_KEYS } from '../../packages/react-native/src/options/keys'; +import { MemoryLeakMode } from '../../packages/react-native/src/options/enums'; /** * The option-manifest parity gate (plan Task 2.7). @@ -66,8 +67,15 @@ describe('the manifest describes the SDK we actually target', () => { }); describe('every enum-typed option can be coerced', () => { + // String-valued enums (MemoryLeakMode) need no table entry: the SDK's Map path + // resolves a constant-name String itself, so the wrapper forwards it untouched. + // The TS constants are checked against the manifest's constant names below. const manifestEnumKeys = manifest.options - .filter((o) => o.type === 'enum') + .filter( + (o) => + o.type === 'enum' && + Object.values(o.enum?.values ?? {}).every((v) => typeof v === 'number'), + ) .map((o) => o.key); it('finds enum options to check', () => { @@ -90,6 +98,12 @@ describe('the TypeScript enum values match the manifest', () => { it.each([...new Map(manifestEnums.map((e) => [e.name, e])).values()])( '$name', (declared) => { + if (declared.name === 'MemoryLeakMode') { + // The manifest maps each Java constant NAME to its display string; the + // Map launch path takes the name, which is what the wrapper sends. + expect(Object.values(MemoryLeakMode).sort()).toEqual(Object.keys(declared.values).sort()); + return; + } const ours = (enumFixture as Record>)[ declared.name ]; diff --git a/scripts/cli-extract-option-keys.ts b/scripts/cli-extract-option-keys.ts index edb11546..09bf2580 100644 --- a/scripts/cli-extract-option-keys.ts +++ b/scripts/cli-extract-option-keys.ts @@ -2,9 +2,11 @@ * Regenerates the committed option-key fixture from the native SDK sources. * * Usage: cli-extract-option-keys.ts [iosSdkRoot] [androidSdkRoot] - * Defaults to the sibling Bugsee checkouts. + * Defaults to the sibling Bugsee checkouts. Point both at checkouts of the PINNED + * versions (native-versions.json): the key lists gate what the wrapper warns about, + * so a newer SDK tree would bless options the pinned release silently drops. */ -import { readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { readObjcEnum } from './ios-enums.ts'; import { join } from 'node:path'; import { @@ -26,9 +28,19 @@ const androidSource = join( 'library/src/main/java/com/bugsee/library/contracts/options/Options.java', ); +// Android declares its options in three modules. The extension holders matter: +// NDK crash detection is bundled by this package and the leak module is one +// dependency away, and a key missing from this list would draw the unknown-key +// warning for an option the SDK honours. +const androidSources = [ + androidSource, + join(androidRoot, 'ndk/src/main/java/com/bugsee/library/contracts/options/NdkOptions.java'), + join(androidRoot, 'leak/src/main/java/com/bugsee/library/contracts/options/LeakOptions.java'), +]; + const keys = splitByPlatform( parseIosKeys(readFileSync(iosSource, 'utf8')), - parseAndroidKeys(readFileSync(androidSource, 'utf8')), + parseAndroidKeys(androidSources.map((file) => readFileSync(file, 'utf8')).join('\n')), ); const out = join( @@ -63,6 +75,7 @@ writeFileSync(enumsOut, `${JSON.stringify(enums, null, 2)}\n`); const iosEnumHeaders = { IssueSeverity: ['BugseeConstants.h', 'BugseeSeverityLevel'], CrashHandlerType: ['BugseeConstants.h', 'BugseeCrashHandlerType'], + ReportingUIStyle: ['BugseeConstants.h', 'BugseeStyle'], } as const; const iosEnums = Object.fromEntries( Object.entries(iosEnumHeaders).map(([name, [header, objcName]]) => { @@ -101,19 +114,33 @@ const nativeVersions = JSON.parse( readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), ) as { android: { sdk: string }; ios: { sdk: string } }; -const manifest: OptionsManifest = { - manifestVersion: 1, - sdk: 'android', - sdkVersion: nativeVersions.android.sdk, - buildConfiguration: 'release', - generatedAt: new Date().toISOString().replace(/\.\d+Z$/, 'Z'), - options: parseAndroidDescriptors( +// The core library's options come from its descriptors. The extension modules (NDK, leak) +// register theirs elsewhere, so reading OptionsDescriptors.java alone would leave out options +// the wrapper exposes. The SDK's golden manifest covers every module, so the extension rows +// are taken from it when the SDK tree has one. +const goldenPath = join(androidRoot, 'options-manifest/options-manifest.golden.json'); +const extensionOptions: OptionsManifest['options'] = existsSync(goldenPath) + ? (JSON.parse(readFileSync(goldenPath, 'utf8')) as { options: OptionsManifest['options'] }) + .options.filter((option) => option.module !== 'bugsee-android') + : []; +const options: OptionsManifest['options'] = [ + ...parseAndroidDescriptors( readFileSync(join( androidRoot, 'library/src/main/java/com/bugsee/library/options/OptionsDescriptors.java', ), 'utf8'), androidConstants, enums, ), + ...extensionOptions, +]; + +const manifest: OptionsManifest = { + manifestVersion: 1, + sdk: 'android', + sdkVersion: nativeVersions.android.sdk, + buildConfiguration: 'release', + generatedAt: new Date().toISOString().replace(/\.\d+Z$/, 'Z'), + options, }; const manifestOut = join( import.meta.dirname, '..', 'packages', 'react-native', 'src', 'options', diff --git a/scripts/raw-messages.ts b/scripts/raw-messages.ts index 15704bc9..427849c7 100644 --- a/scripts/raw-messages.ts +++ b/scripts/raw-messages.ts @@ -875,8 +875,13 @@ const TS_IDENTIFIER_NAMES = new Set(['name', 'key', 'field', 'method', 'kind', ' * Bodies not checked: the two that forward a native rejection's own message * (the native rules keep it value-free), and the `badArgument` helpers, which * only forward their parameter -- every CALL of `badArgument` is checked. + * `emitUnknownOptionWarning` is the one sink of the unknown-launch-option + * warning; its message is built by `describeUnknownKey` from the developer's + * own option key (an identifier, as the rules above allow) and the wrapper's + * own key tables -- never from an option VALUE, which that function does not + * receive. */ -const TS_AUDITED_FUNCTIONS = ['toReportError', 'toAttributeError', 'badArgument']; +const TS_AUDITED_FUNCTIONS = ['toReportError', 'toAttributeError', 'badArgument', 'emitUnknownOptionWarning']; const TS_SINKS = /\bnew\s+\w*Error\s*\(|\bbadArgument\s*\(|\breject\s*\(|\bconsole\s*(?:\.\s*\w+|\[[^\]]*\])\s*\(/g; From 1def1ef4d24d125865543153fb46915c3a757c78 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 10:41:47 +0500 Subject: [PATCH 02/16] API parity: bridge the native methods RN was missing, and guard the rest Compared the public API of the Android Bugsee class (7.4.2) and the iOS Bugsee interface (7.0.x) with what this package exposes. New: - getHostLaunchOptions() on both platforms: only what the app supplied. - relaunch() with no argument now keeps the app's options by replaying getHostLaunchOptions(); the native SDKs' bare relaunch restarts with defaults, which silently reset every setting. relaunch(options), including {}, still sends exactly what it is given. If the host options cannot be read it does not relaunch rather than resetting. - Android: resetVideoCapturePermission, addSecureActivity, removeSecureActivity, isSecureActivity. iOS: showVideoCapturePreview, hideVideoCapturePreview. The other platform treats them as no-ops (isSecureActivity answers false on iOS). Guard: scripts/sdk-api.json holds the public method names of the pinned SDKs (cli-extract-sdk-api.ts regenerates it), scripts/sdk-api-map.ts maps each to an RN member or an exemption with a reason, and a test fails on a method with no entry, an entry for nothing, or a mapping to a member that does not exist. docs/native-api-parity.md lists what is not exposed and why. Human guided, AI implemented --- docs/launch-options.md | 5 +- docs/native-api-parity.md | 36 ++ packages/react-native/README.md | 13 +- .../com/bugsee/reactnative/BugseeModule.java | 36 ++ packages/react-native/ios/BugseeModule.mm | 40 ++ packages/react-native/src/NativeBugsee.ts | 23 + packages/react-native/src/__mocks__/native.ts | 9 + .../src/__tests__/native-api.test.ts | 91 ++++ .../src/__tests__/sdk-api-parity.test.ts | 94 ++++ packages/react-native/src/index.ts | 63 ++- scripts/cli-extract-sdk-api.ts | 22 + scripts/sdk-api-map.ts | 152 ++++++ scripts/sdk-api.json | 486 ++++++++++++++++++ scripts/sdk-api.ts | 64 +++ 14 files changed, 1127 insertions(+), 7 deletions(-) create mode 100644 docs/native-api-parity.md create mode 100644 packages/react-native/src/__tests__/native-api.test.ts create mode 100644 packages/react-native/src/__tests__/sdk-api-parity.test.ts create mode 100644 scripts/cli-extract-sdk-api.ts create mode 100644 scripts/sdk-api-map.ts create mode 100644 scripts/sdk-api.json create mode 100644 scripts/sdk-api.ts diff --git a/docs/launch-options.md b/docs/launch-options.md index a4e5b82c..9eb0d9dc 100644 --- a/docs/launch-options.md +++ b/docs/launch-options.md @@ -28,8 +28,9 @@ iOS, does nothing on Android, and reports nothing on either. `launch()` and `rel - `launch(token, options)` starts the SDK with `options`. If the SDK is **already running** (iOS, or an Android process the SDK relaunched itself after the OS killed it) the new options are **ignored**. Do not treat `true` as proof they were applied: check `getStatus()` before the call if the difference matters. Android SDK 7.5.1 resolves `false` in this case, earlier SDKs `true`. -- `relaunch(options)` restarts with **exactly** the options you pass. Anything you leave out goes back to the SDK default; - it does **not** keep what the previous launch set. Pass the full set each time. +- `relaunch()` with **no argument** keeps your options: it replays `getHostLaunchOptions()`, the SDK's record of what the + app supplied. (The native SDKs' bare relaunch restarts with defaults.) `relaunch(options)`, including `relaunch({})`, + restarts with **exactly** the options you pass; anything you leave out goes back to the SDK default. ## Reference diff --git a/docs/native-api-parity.md b/docs/native-api-parity.md new file mode 100644 index 00000000..60c71b6a --- /dev/null +++ b/docs/native-api-parity.md @@ -0,0 +1,36 @@ +# Native API parity + +Every public method of the Android `Bugsee` class (7.4.2) and the iOS `Bugsee` interface (7.0.x) is either exposed +by `@bugsee/react-native` or deliberately not, with a reason. The mapping is +[`scripts/sdk-api-map.ts`](../scripts/sdk-api-map.ts); `scripts/sdk-api.json` holds the SDKs' method names, and a test +fails when either side drifts (a method a new SDK release adds, an entry naming nothing, or a mapping pointing at an RN +member that does not exist). Regenerate the names with `scripts/cli-extract-sdk-api.ts`, pointing it at checkouts of the +versions in `native-versions.json`. + +## Platform-specific calls + +These exist in only one SDK. They are no-ops on the other platform, like `startBlackout` before launch is a no-op where +the SDK cannot honour it. + +| Method | Android | iOS | +|---|---|---| +| `resetVideoCapturePermission()` | forgets the stored fullscreen-capture consent | no-op | +| `addSecureActivity(className)`, `removeSecureActivity(className)` | hides the activity from capture | no-op | +| `isSecureActivity(className)` | whether the activity is secure | `false` | +| `showVideoCapturePreview()`, `hideVideoCapturePreview()` | no-op | debug overlay of what video capture records | + +## Not exposed, and why + +| SDK method | Reason | +|---|---| +| `addSecureWebView` | needs a native WebView instance, which JavaScript never holds. Cover web content with `` or `setSecureRectangles`. | +| `getAllSecureRectangles` | the wrapper owns the rectangles it publishes (`setSecureRectangles` replaces them); the SDK's list is not read back. | +| `ext`, `registerExt` | native extension lookup and registration. Extension SPIs (Leak's `watchObject`, the OkHttp interceptor) take native objects. | +| `getDefaultNetworkSanitizer`, `getExchangeFactory` | used inside the wrapper's own filter and event bridges. | +| `getVideoFrameConsumer` | SPI for wrappers that feed their own video frames; this one records natively. | +| `setWrapper`, `onUncaughtException`, `delegate`, `sharedInstance` | the wrapper's own plumbing. | +| `getLaunched`, `launched` | `await getStatus()` against `Status.Launched`. | +| `addSecureViews`, `setLogFilter` (Android) | deprecated in the SDK. | + +`relaunch()` with no argument keeps the options the app supplied (it replays `getHostLaunchOptions()`); the native SDKs' +bare relaunch restarts with defaults. diff --git a/packages/react-native/README.md b/packages/react-native/README.md index e7a292fe..b6d3ea9a 100644 --- a/packages/react-native/README.md +++ b/packages/react-native/README.md @@ -113,12 +113,21 @@ options.reportingUIEmailRequired = true; `relaunch` log one `console.warn` per unknown key and name the key to use. - **`launch` while the SDK is already running ignores the options** you pass: an iOS session that is already up, or an Android process the SDK relaunched itself after the OS killed it. Check `getStatus()` first. -- **`relaunch(options)` restarts with exactly the options you pass.** Options you omit return to the SDK - default; the previous launch's are not kept. +- **`relaunch()` keeps your options; `relaunch(options)` replaces them.** With no argument it replays + `getHostLaunchOptions()`, the options the app supplied, so nothing resets. With an argument, including `{}`, + it restarts with exactly those options and whatever you leave out returns to the SDK default. The full list, with keys, types and platforms, is in [`docs/launch-options.md`](https://github.com/bugsee/bugsee-react-native/blob/main/docs/launch-options.md). +### Methods that exist on one platform + +`getHostLaunchOptions()` returns only what your app supplied to `launch`. Android-only: `resetVideoCapturePermission()`, +`addSecureActivity(className)`, `removeSecureActivity(className)`, `isSecureActivity(className)`. iOS-only: +`showVideoCapturePreview()`, `hideVideoCapturePreview()`. The other platform treats these as no-ops. Which native methods +this package does not expose, and why, is in +[`docs/native-api-parity.md`](https://github.com/bugsee/bugsee-react-native/blob/main/docs/native-api-parity.md). + ### Reporting render errors Wrap part of the tree (or the whole app) in `` to report an error thrown while rendering diff --git a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java index c685f1e1..2a3e03cf 100644 --- a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +++ b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java @@ -493,11 +493,47 @@ public void getLaunchOptions(final Promise promise) { promise.resolve(toWritableMap(Bugsee.getLaunchOptions().toMap())); } + @Override + public void getHostLaunchOptions(final Promise promise) { + // Only what the app itself supplied, not the SDK's defaults. + promise.resolve(toWritableMap(Bugsee.getHostLaunchOptions())); + } + @Override public void testCrash() { Bugsee.testCrash(); } + @Override + public void resetVideoCapturePermission() { + Bugsee.resetVideoCapturePermission(); + } + + @Override + public void addSecureActivity(final String className) { + Bugsee.addSecureActivity(className); + } + + @Override + public void removeSecureActivity(final String className) { + Bugsee.removeSecureActivity(className); + } + + @Override + public void isSecureActivity(final String className, final Promise promise) { + promise.resolve(Bugsee.isSecureActivity(className)); + } + + @Override + public void showVideoCapturePreview() { + // iOS-only debug overlay. + } + + @Override + public void hideVideoCapturePreview() { + // iOS-only debug overlay. + } + /** * A handled JS exception. Posted onto {@link ExceptionExecutors#HANDLED}: * the SDK must not run on the native-modules thread. diff --git a/packages/react-native/ios/BugseeModule.mm b/packages/react-native/ios/BugseeModule.mm index fd0bda01..00d90f9a 100644 --- a/packages/react-native/ios/BugseeModule.mm +++ b/packages/react-native/ios/BugseeModule.mm @@ -1432,12 +1432,52 @@ - (void)getLaunchOptions:(RCTPromiseResolveBlock)resolve }); } +- (void)getHostLaunchOptions:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject { + BGSRNRunOnMain(^{ + // Only what the app itself supplied, not the SDK's defaults. + resolve([Bugsee getHostLaunchOptions] ?: @{}); + }); +} + - (void)testCrash { BGSRNRunOnMain(^{ [Bugsee testCrash]; }); } +#pragma mark - Android-only and iOS-only calls + +// iOS has no MediaProjection consent and no secure activities: these are +// no-ops here, and isSecureActivity answers NO. + +- (void)resetVideoCapturePermission { +} + +- (void)addSecureActivity:(NSString *)className { +} + +- (void)removeSecureActivity:(NSString *)className { +} + +- (void)isSecureActivity:(NSString *)className + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject { + resolve(@NO); +} + +- (void)showVideoCapturePreview { + BGSRNRunOnMain(^{ + [Bugsee showVideoCapturePreview]; + }); +} + +- (void)hideVideoCapturePreview { + BGSRNRunOnMain(^{ + [Bugsee hideVideoCapturePreview]; + }); +} + /// A handled JS exception. `payloadJson` is the Task 7.1a payload, forwarded /// verbatim as the reason; `optionsJson` is `{domain?}` or null. Unparseable /// options are logged and the exception is still sent, without a domain — a diff --git a/packages/react-native/src/NativeBugsee.ts b/packages/react-native/src/NativeBugsee.ts index a849276f..7610d9e8 100644 --- a/packages/react-native/src/NativeBugsee.ts +++ b/packages/react-native/src/NativeBugsee.ts @@ -150,8 +150,31 @@ export interface Spec extends TurboModule { getStatus(): Promise; /** The options the SDK reports as being in effect. */ getLaunchOptions(): Promise; + /** + * Only the options the host app supplied to `launch`, without the SDK's + * defaults that {@link getLaunchOptions} merges them over. What `relaunch()` + * with no argument replays. + */ + getHostLaunchOptions(): Promise; testCrash(): void; + /** + * Android: forgets the stored MediaProjection (fullscreen capture) consent so + * the user is asked again. No-op on iOS, which has no such permission. + */ + resetVideoCapturePermission(): void; + /** + * Android: hides every window of the activity with this fully qualified class + * name from capture. No-op on iOS. + */ + addSecureActivity(className: string): void; + removeSecureActivity(className: string): void; + /** Whether the activity is currently secure. Always `false` on iOS. */ + isSecureActivity(className: string): Promise; + /** iOS: shows the debug overlay of what video capture is recording. No-op on Android. */ + showVideoCapturePreview(): void; + hideVideoCapturePreview(): void; + /** * Creates and uploads a bug report immediately, without showing any UI. * diff --git a/packages/react-native/src/__mocks__/native.ts b/packages/react-native/src/__mocks__/native.ts index 3e6f72bc..90b66828 100644 --- a/packages/react-native/src/__mocks__/native.ts +++ b/packages/react-native/src/__mocks__/native.ts @@ -30,6 +30,8 @@ const DEFAULTS: Record = { stop: true, getStatus: 0, getLaunchOptions: {}, + getHostLaunchOptions: {}, + isSecureActivity: false, reportRead: EMPTY_REPORT_SNAPSHOT, createReport: null, getAttribute: {}, @@ -267,6 +269,13 @@ export const native = { stop: jest.fn, []>(), getStatus: jest.fn, []>(), getLaunchOptions: jest.fn>, []>(), + getHostLaunchOptions: jest.fn>, []>(), + resetVideoCapturePermission: jest.fn(), + addSecureActivity: jest.fn(), + removeSecureActivity: jest.fn(), + isSecureActivity: jest.fn, [string]>(), + showVideoCapturePreview: jest.fn(), + hideVideoCapturePreview: jest.fn(), testCrash: jest.fn(), upload: jest.fn(), showReportDialog: diff --git a/packages/react-native/src/__tests__/native-api.test.ts b/packages/react-native/src/__tests__/native-api.test.ts new file mode 100644 index 00000000..8cf640c4 --- /dev/null +++ b/packages/react-native/src/__tests__/native-api.test.ts @@ -0,0 +1,91 @@ +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('../exceptions/handlers', () => ({ + installExceptionHandlers: jest.fn(), + setExceptionCaptureEnabled: jest.fn(), + setCrashDetectionOptedOut: jest.fn(), +})); +jest.mock('../console/capture', () => ({ installConsoleCapture: jest.fn() })); +jest.mock('../NativeBugsee', () => require('../__mocks__/native').nativeMock); + +import Bugsee from '../index'; +import { native } from '../__mocks__/native'; + +beforeEach(() => native.reset()); + +describe('getHostLaunchOptions', () => { + it('returns what native reports', async () => { + native.getHostLaunchOptions.mockResolvedValue({ + 'com.bugsee.option.reporting.triggers.shake': false, + }); + await expect(Bugsee.getHostLaunchOptions()).resolves.toEqual({ + 'com.bugsee.option.reporting.triggers.shake': false, + }); + }); +}); + +describe('relaunch', () => { + const hosted = { + 'com.bugsee.option.reporting.triggers.shake': false, + 'com.bugsee.option.capture.logs.level': 2, + }; + + it('with no argument replays the options the app supplied, so nothing resets', async () => { + native.getHostLaunchOptions.mockResolvedValue(hosted); + await Bugsee.relaunch(); + expect(native.relaunch).toHaveBeenCalledWith(hosted); + }); + + it('with an argument sends exactly that and never asks for the host options', async () => { + native.getHostLaunchOptions.mockResolvedValue(hosted); + const next = { 'com.bugsee.option.capture.logs': false }; + await Bugsee.relaunch(next); + expect(native.relaunch).toHaveBeenCalledWith(next); + expect(native.getHostLaunchOptions).not.toHaveBeenCalled(); + }); + + it('with an explicit empty map still resets to the SDK defaults', async () => { + native.getHostLaunchOptions.mockResolvedValue(hosted); + await Bugsee.relaunch({}); + expect(native.relaunch).toHaveBeenCalledWith({}); + expect(native.getHostLaunchOptions).not.toHaveBeenCalled(); + }); + + it('sends an empty map when the app supplied nothing', async () => { + native.getHostLaunchOptions.mockResolvedValue({}); + await Bugsee.relaunch(); + expect(native.relaunch).toHaveBeenCalledWith({}); + }); + + it('does not relaunch when the host options cannot be read, rather than resetting every setting', async () => { + native.getHostLaunchOptions.mockRejectedValue(new Error('x')); + await expect(Bugsee.relaunch()).rejects.toThrow(); + expect(native.relaunch).not.toHaveBeenCalled(); + }); +}); + +describe('platform-specific calls forward to native', () => { + it('resetVideoCapturePermission', () => { + Bugsee.resetVideoCapturePermission(); + expect(native.resetVideoCapturePermission).toHaveBeenCalledTimes(1); + }); + + it('addSecureActivity and removeSecureActivity pass the class name', () => { + Bugsee.addSecureActivity('com.example.MainActivity'); + Bugsee.removeSecureActivity('com.example.MainActivity'); + expect(native.addSecureActivity).toHaveBeenCalledWith('com.example.MainActivity'); + expect(native.removeSecureActivity).toHaveBeenCalledWith('com.example.MainActivity'); + }); + + it('isSecureActivity returns the native answer', async () => { + native.isSecureActivity.mockResolvedValue(true); + await expect(Bugsee.isSecureActivity('com.example.A')).resolves.toBe(true); + expect(native.isSecureActivity).toHaveBeenCalledWith('com.example.A'); + }); + + it('showVideoCapturePreview and hideVideoCapturePreview', () => { + Bugsee.showVideoCapturePreview(); + Bugsee.hideVideoCapturePreview(); + expect(native.showVideoCapturePreview).toHaveBeenCalledTimes(1); + expect(native.hideVideoCapturePreview).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/react-native/src/__tests__/sdk-api-parity.test.ts b/packages/react-native/src/__tests__/sdk-api-parity.test.ts new file mode 100644 index 00000000..d963643b --- /dev/null +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -0,0 +1,94 @@ +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('../NativeBugsee', () => require('../__mocks__/native').nativeMock); + +import * as pkg from '../index'; +import Bugsee from '../index'; +import api from '../../../../scripts/sdk-api.json'; +import { ANDROID, IOS, type Mapping } from '../../../../scripts/sdk-api-map'; +import { parseAndroidApi, parseIosApi } from '../../../../scripts/sdk-api'; + +/** + * The public methods of the pinned native SDKs (`sdk-api.json`, regenerated by + * `cli-extract-sdk-api.ts`) against where this package exposes each one. + * + * Fails in three directions: an SDK method with no entry (a new method nobody + * has decided about), an entry naming nothing in the SDK (stale), and an entry + * pointing at an RN member that does not exist (a mapping that lies). + */ +const platforms = [ + ['android', api.android, ANDROID], + ['ios', api.ios, IOS], +] as const; + +describe.each(platforms)('%s SDK API parity', (_platform, methods, map) => { + const names = methods.map((m) => m.name); + + it('maps or exempts every public SDK method', () => { + expect(names.filter((name) => !(name in map))).toEqual([]); + }); + + it('has no entry for a method the SDK does not have', () => { + expect(Object.keys(map).filter((name) => !names.includes(name))).toEqual([]); + }); + + it('points every mapping at a member that exists', () => { + const broken = Object.entries(map as Record).filter(([, mapping]) => { + if ('rn' in mapping) { + return !(mapping.rn in (Bugsee as unknown as Record)); + } + if ('export' in mapping) { + return !(mapping.export in pkg); + } + return false; + }); + expect(broken.map(([name]) => name)).toEqual([]); + }); + + it('gives every exemption a reason', () => { + for (const mapping of Object.values(map as Record)) { + if ('skip' in mapping) { + expect(mapping.skip.length).toBeGreaterThan(10); + } + } + }); +}); + +describe('the extractors', () => { + it('read overloads once and flag a deprecated name only when every overload is', () => { + const source = ` + public final class Bugsee { + @Deprecated + public static void old(int a) {} + public static void old(String a) {} + @Deprecated + public static void gone() {} + public static T ext(Class type) { return null; } + private static void hidden() {} + }`; + expect(parseAndroidApi(source)).toEqual([ + { name: 'ext', deprecated: false }, + { name: 'gone', deprecated: true }, + { name: 'old', deprecated: false }, + ]); + }); + + it('read the class methods and properties of the iOS Bugsee interface only', () => { + const header = ` + @interface Other : NSObject + + (void)notMine; + @end + @interface Bugsee : NSObject + @property (nonatomic, weak) id delegate; + + (void)launchWithToken:(NSString *)token; + + (nullable id)ext:(Class)type; + - (void)instanceOnly; + @end`; + expect(parseIosApi(header).map((m) => m.name)).toEqual(['delegate', 'ext', 'launchWithToken']); + }); + + it('refuse a source that holds nothing, rather than reporting an empty API', () => { + expect(() => parseAndroidApi('class X {}')).toThrow(); + expect(() => parseIosApi('@interface Bugsee : NSObject\n@end')).toThrow(); + expect(() => parseIosApi('nothing')).toThrow(); + }); +}); diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index c71ecfb3..90941435 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -182,13 +182,21 @@ class Bugsee { } /** - * Restarts an already-launched session with a new set of options. + * Restarts an already-launched session. + * + * With **no argument** it keeps the options the app supplied: it replays + * {@link getHostLaunchOptions}, the SDK's own record of them, so a plain + * `relaunch()` does not reset every setting. (The native SDKs' bare relaunch + * restarts with defaults.) With an argument, including `{}`, it restarts with + * exactly those options: whatever you leave out returns to the SDK default. * * Installs the console patch after the native call resolves, same as * {@link launch}. A second install does not wrap again. */ - async relaunch(options: LaunchOptionsInput = {}): Promise { - const nativeOptions = nativeOptionsOf(options); + async relaunch(options?: LaunchOptionsInput): Promise { + const nativeOptions = nativeOptionsOf( + options === undefined ? await this.getHostLaunchOptions() : options, + ); this.registerWrapper(); installExceptionHandlers(); applyExceptionCaptureFromOptions(nativeOptions); @@ -783,6 +791,55 @@ class Bugsee { return (await NativeBugsee.getLaunchOptions()) as Record; } + /** + * Only the options the app supplied to `launch`/`relaunch`, without the SDK's + * defaults that {@link getLaunchOptions} merges them over. Never contains a key + * the SDK did not accept. This is what `relaunch()` with no argument replays. + */ + async getHostLaunchOptions(): Promise> { + return (await NativeBugsee.getHostLaunchOptions()) as Record; + } + + /** + * Android: forgets the stored fullscreen-capture (MediaProjection) consent, so the + * user is asked again at the next fullscreen capture. No-op on iOS. + */ + resetVideoCapturePermission(): void { + NativeBugsee.resetVideoCapturePermission(); + } + + /** + * Android: hides every window of the activity with this fully qualified class name + * (for example `com.example.MainActivity`) from video and screenshots. Works before + * `launch()`. No-op on iOS; use `` or `setSecureRectangles` there. + */ + addSecureActivity(className: string): void { + NativeBugsee.addSecureActivity(className); + } + + /** Android: undoes {@link addSecureActivity}. No-op on iOS. */ + removeSecureActivity(className: string): void { + NativeBugsee.removeSecureActivity(className); + } + + /** Android: whether the activity is secure. Always `false` on iOS. */ + async isSecureActivity(className: string): Promise { + return NativeBugsee.isSecureActivity(className); + } + + /** + * iOS: shows a debug overlay of what video capture is recording, to check that + * secure regions are covered. No-op on Android. + */ + showVideoCapturePreview(): void { + NativeBugsee.showVideoCapturePreview(); + } + + /** iOS: hides the overlay {@link showVideoCapturePreview} showed. No-op on Android. */ + hideVideoCapturePreview(): void { + NativeBugsee.hideVideoCapturePreview(); + } + /** * The SDK's own test crash: a Java `RuntimeException` on Android, an * `NSException` on iOS. For a real native (signal) crash, see the bare diff --git a/scripts/cli-extract-sdk-api.ts b/scripts/cli-extract-sdk-api.ts new file mode 100644 index 00000000..7ab59f8f --- /dev/null +++ b/scripts/cli-extract-sdk-api.ts @@ -0,0 +1,22 @@ +/** + * Regenerates `scripts/sdk-api.json`, the public method names of the native + * SDKs, from SDK checkouts at the PINNED versions (native-versions.json). + * + * Usage: cli-extract-sdk-api.ts [iosSdkRoot] [androidSdkRoot] + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseAndroidApi, parseIosApi } from './sdk-api.ts'; + +const home = process.env.HOME ?? ''; +const [iosRoot = join(home, 'Projects/Bugsee/ios/sdk'), + androidRoot = join(home, 'Projects/Bugsee/android/sdk')] = process.argv.slice(2); + +const android = parseAndroidApi(readFileSync( + join(androidRoot, 'library/src/main/java/com/bugsee/library/Bugsee.java'), 'utf8')); +const ios = parseIosApi(readFileSync( + join(iosRoot, 'BugseeDev/BugseeLib/BugseeLib/Bugsee.h'), 'utf8')); + +const out = join(import.meta.dirname, 'sdk-api.json'); +writeFileSync(out, `${JSON.stringify({ android, ios }, null, 2)}\n`); +console.log(`android ${android.length} methods, ios ${ios.length} -> ${out}`); diff --git a/scripts/sdk-api-map.ts b/scripts/sdk-api-map.ts new file mode 100644 index 00000000..50350d25 --- /dev/null +++ b/scripts/sdk-api-map.ts @@ -0,0 +1,152 @@ +/** + * Where each public native SDK method lives in `@bugsee/react-native`, or why it + * does not. + * + * `scripts/sdk-api.json` holds the method names of the pinned SDKs; the parity + * test fails when a name there has no entry here (a method a new SDK release + * added, which someone must either bridge or exempt with a reason) or an entry + * here names nothing in the SDK (stale). + * + * - `rn`: a member of the default `Bugsee` export that covers it. + * - `export`: a named export of the package that covers it. + * - `skip`: deliberately not exposed, and why. + */ +export type Mapping = { rn: string } | { export: string } | { skip: string }; + +const rn = (member: string): Mapping => ({ rn: member }); +const component = (name: string): Mapping => ({ export: name }); +const skip = (reason: string): Mapping => ({ skip: reason }); + +const SECURE_VIEWS = component('BugseeSecure'); +const WEBVIEW = skip('needs a native WKWebView/WebView instance, which JavaScript never holds'); +const NOT_READ_BACK = skip('the wrapper owns the rectangles it publishes; the SDK list is not read back'); +const EXT = skip('native extension lookup and registration; extension SPIs are not callable from JavaScript'); +const SANITIZER = skip('used inside the wrapper\'s own network-filter bridge, not callable from JavaScript'); +const EXCHANGE = skip('internal: builds the events addNetworkEvent and addBreadcrumb take'); +const STATUS = skip('derivable: `await getStatus()` against `Status.Launched`'); + +export const ANDROID: Readonly> = { + addBreadcrumb: rn('addBreadcrumb'), + addNetworkEvent: rn('addNetworkEvent'), + addSecureActivity: rn('addSecureActivity'), + addSecureRectangle: rn('setSecureRectangles'), + addSecureView: SECURE_VIEWS, + addSecureViews: skip('deprecated in the SDK (layout-id based)'), + addSecureWebView: WEBVIEW, + captureViewHierarchy: rn('captureViewHierarchy'), + clearAllAttributes: rn('clearAllAttributes'), + clearAttribute: rn('clearAttribute'), + clearUserIdentifier: rn('clearUserIdentifier'), + createReport: rn('createReport'), + deleteCollectedDataOnDevice: rn('deleteCollectedDataOnDevice'), + endBlackout: rn('endBlackout'), + event: rn('event'), + ext: EXT, + getActiveSpan: rn('getActiveSpan'), + getAllAttributes: rn('getAllAttributes'), + getAllSecureRectangles: NOT_READ_BACK, + getAppearance: rn('appearance'), + getAttribute: rn('getAttribute'), + getDefaultNetworkSanitizer: SANITIZER, + getExchangeFactory: EXCHANGE, + getHostLaunchOptions: rn('getHostLaunchOptions'), + getLaunchOptions: rn('getLaunchOptions'), + getLaunched: STATUS, + getStatus: rn('getStatus'), + getUserIdentifier: rn('getUserIdentifier'), + getVideoFrameConsumer: skip('SPI for wrappers that feed their own video frames; this wrapper records natively'), + isBlackout: rn('isBlackout'), + isSecureActivity: rn('isSecureActivity'), + launch: rn('launch'), + log: rn('log'), + logException: rn('logException'), + logUnhandledException: rn('logUnhandledException'), + notify: rn('notify'), + onUncaughtException: skip('the wrapper\'s own exception handlers call logUnhandledException'), + registerExt: EXT, + relaunch: rn('relaunch'), + removeAllSecureRectangles: rn('setSecureRectangles'), + removeSecureActivity: rn('removeSecureActivity'), + removeSecureRectangle: rn('setSecureRectangles'), + removeSecureView: SECURE_VIEWS, + resetVideoCapturePermission: rn('resetVideoCapturePermission'), + setAttribute: rn('setAttribute'), + setBreadcrumbFilter: rn('setBreadcrumbFilter'), + setLifecycleEventsListener: rn('onLifecycleEvent'), + setLogEventFilter: rn('setLogFilter'), + setLogFilter: skip('deprecated in the SDK; replaced by setLogEventFilter'), + setNetworkEventFilter: rn('setNetworkFilter'), + setReportHandler: rn('setReportHandler'), + setUserIdentifier: rn('setUserIdentifier'), + setWrapper: skip('the wrapper registers itself (setWrapperInfo, and at process start on Android)'), + showReportDialog: rn('showReportDialog'), + startBlackout: rn('startBlackout'), + startSpan: rn('startSpan'), + startTransaction: rn('startTransaction'), + stop: rn('stop'), + testCrash: rn('testNativeCrash'), + trace: rn('trace'), + upload: rn('upload'), +}; + +export const IOS: Readonly> = { + addBreadcrumb: rn('addBreadcrumb'), + addNetworkEvent: rn('addNetworkEvent'), + addSecureRectangle: rn('setSecureRectangles'), + addSecureView: SECURE_VIEWS, + addSecureWebView: WEBVIEW, + captureViewHierarchy: rn('captureViewHierarchy'), + clearAllAttributes: rn('clearAllAttributes'), + clearAttribute: rn('clearAttribute'), + clearUserIdentifier: rn('clearUserIdentifier'), + createReportWithCompletion: rn('createReport'), + defaultNetworkSanitizer: SANITIZER, + delegate: skip('BugseeDelegate belongs to the wrapper: its callbacks reach JavaScript as onLifecycleEvent, setReportHandler and the filters'), + deleteCollectedDataOnDevice: rn('deleteCollectedDataOnDevice'), + endBlackout: rn('endBlackout'), + event: rn('event'), + ext: EXT, + getActiveSpan: rn('getActiveSpan'), + getAllAttributes: rn('getAllAttributes'), + getAllSecureRectangles: NOT_READ_BACK, + getAppearance: rn('appearance'), + getAttribute: rn('getAttribute'), + getExchangeFactory: EXCHANGE, + getHostLaunchOptions: rn('getHostLaunchOptions'), + getLaunchOptions: rn('getLaunchOptions'), + getUserIdentifier: rn('getUserIdentifier'), + hideVideoCapturePreview: rn('hideVideoCapturePreview'), + isBlackout: rn('isBlackout'), + launchWithToken: rn('launch'), + launched: STATUS, + log: rn('log'), + logError: rn('logException'), + logException: rn('logException'), + logUnhandledException: rn('logUnhandledException'), + notifyWithTitle: rn('notify'), + relaunch: rn('relaunch'), + relaunchWithDictionaryOptions: rn('relaunch'), + relaunchWithOptions: rn('relaunch'), + removeAllSecureRectangles: rn('setSecureRectangles'), + removeSecureRectangle: rn('setSecureRectangles'), + removeSecureView: SECURE_VIEWS, + setAttribute: rn('setAttribute'), + setBreadcrumbFilter: rn('setBreadcrumbFilter'), + setLogEventFilter: rn('setLogFilter'), + setNetworkEventFilter: rn('setNetworkFilter'), + setReportHandler: rn('setReportHandler'), + setUserIdentifier: rn('setUserIdentifier'), + sharedInstance: skip('singleton accessor; the wrapper calls the class methods directly'), + showReportDialog: rn('showReportDialog'), + showReportDialogWithSummary: rn('showReportDialog'), + showVideoCapturePreview: rn('showVideoCapturePreview'), + startBlackout: rn('startBlackout'), + startSpanWithOperation: rn('startSpan'), + startTransactionWithName: rn('startTransaction'), + status: rn('getStatus'), + stop: rn('stop'), + testCrash: rn('testNativeCrash'), + trace: rn('trace'), + uploadReport: rn('createReport'), + uploadWithSummary: rn('upload'), +}; diff --git a/scripts/sdk-api.json b/scripts/sdk-api.json new file mode 100644 index 00000000..49535f00 --- /dev/null +++ b/scripts/sdk-api.json @@ -0,0 +1,486 @@ +{ + "android": [ + { + "name": "addBreadcrumb", + "deprecated": false + }, + { + "name": "addNetworkEvent", + "deprecated": false + }, + { + "name": "addSecureActivity", + "deprecated": false + }, + { + "name": "addSecureRectangle", + "deprecated": false + }, + { + "name": "addSecureView", + "deprecated": false + }, + { + "name": "addSecureViews", + "deprecated": true + }, + { + "name": "addSecureWebView", + "deprecated": false + }, + { + "name": "captureViewHierarchy", + "deprecated": false + }, + { + "name": "clearAllAttributes", + "deprecated": false + }, + { + "name": "clearAttribute", + "deprecated": false + }, + { + "name": "clearUserIdentifier", + "deprecated": false + }, + { + "name": "createReport", + "deprecated": false + }, + { + "name": "deleteCollectedDataOnDevice", + "deprecated": false + }, + { + "name": "endBlackout", + "deprecated": false + }, + { + "name": "event", + "deprecated": false + }, + { + "name": "ext", + "deprecated": false + }, + { + "name": "getActiveSpan", + "deprecated": false + }, + { + "name": "getAllAttributes", + "deprecated": false + }, + { + "name": "getAllSecureRectangles", + "deprecated": false + }, + { + "name": "getAppearance", + "deprecated": false + }, + { + "name": "getAttribute", + "deprecated": false + }, + { + "name": "getDefaultNetworkSanitizer", + "deprecated": false + }, + { + "name": "getExchangeFactory", + "deprecated": false + }, + { + "name": "getHostLaunchOptions", + "deprecated": false + }, + { + "name": "getLaunched", + "deprecated": false + }, + { + "name": "getLaunchOptions", + "deprecated": false + }, + { + "name": "getStatus", + "deprecated": false + }, + { + "name": "getUserIdentifier", + "deprecated": false + }, + { + "name": "getVideoFrameConsumer", + "deprecated": false + }, + { + "name": "isBlackout", + "deprecated": false + }, + { + "name": "isSecureActivity", + "deprecated": false + }, + { + "name": "launch", + "deprecated": false + }, + { + "name": "log", + "deprecated": false + }, + { + "name": "logException", + "deprecated": false + }, + { + "name": "logUnhandledException", + "deprecated": false + }, + { + "name": "notify", + "deprecated": false + }, + { + "name": "onUncaughtException", + "deprecated": false + }, + { + "name": "registerExt", + "deprecated": false + }, + { + "name": "relaunch", + "deprecated": false + }, + { + "name": "removeAllSecureRectangles", + "deprecated": false + }, + { + "name": "removeSecureActivity", + "deprecated": false + }, + { + "name": "removeSecureRectangle", + "deprecated": false + }, + { + "name": "removeSecureView", + "deprecated": false + }, + { + "name": "resetVideoCapturePermission", + "deprecated": false + }, + { + "name": "setAttribute", + "deprecated": false + }, + { + "name": "setBreadcrumbFilter", + "deprecated": false + }, + { + "name": "setLifecycleEventsListener", + "deprecated": false + }, + { + "name": "setLogEventFilter", + "deprecated": false + }, + { + "name": "setLogFilter", + "deprecated": true + }, + { + "name": "setNetworkEventFilter", + "deprecated": false + }, + { + "name": "setReportHandler", + "deprecated": false + }, + { + "name": "setUserIdentifier", + "deprecated": false + }, + { + "name": "setWrapper", + "deprecated": false + }, + { + "name": "showReportDialog", + "deprecated": false + }, + { + "name": "startBlackout", + "deprecated": false + }, + { + "name": "startSpan", + "deprecated": false + }, + { + "name": "startTransaction", + "deprecated": false + }, + { + "name": "stop", + "deprecated": false + }, + { + "name": "testCrash", + "deprecated": false + }, + { + "name": "trace", + "deprecated": false + }, + { + "name": "upload", + "deprecated": false + } + ], + "ios": [ + { + "name": "addBreadcrumb", + "deprecated": false + }, + { + "name": "addNetworkEvent", + "deprecated": false + }, + { + "name": "addSecureRectangle", + "deprecated": false + }, + { + "name": "addSecureView", + "deprecated": false + }, + { + "name": "addSecureWebView", + "deprecated": false + }, + { + "name": "captureViewHierarchy", + "deprecated": false + }, + { + "name": "clearAllAttributes", + "deprecated": false + }, + { + "name": "clearAttribute", + "deprecated": false + }, + { + "name": "clearUserIdentifier", + "deprecated": false + }, + { + "name": "createReportWithCompletion", + "deprecated": false + }, + { + "name": "defaultNetworkSanitizer", + "deprecated": false + }, + { + "name": "delegate", + "deprecated": false + }, + { + "name": "deleteCollectedDataOnDevice", + "deprecated": false + }, + { + "name": "endBlackout", + "deprecated": false + }, + { + "name": "event", + "deprecated": false + }, + { + "name": "ext", + "deprecated": false + }, + { + "name": "getActiveSpan", + "deprecated": false + }, + { + "name": "getAllAttributes", + "deprecated": false + }, + { + "name": "getAllSecureRectangles", + "deprecated": false + }, + { + "name": "getAppearance", + "deprecated": false + }, + { + "name": "getAttribute", + "deprecated": false + }, + { + "name": "getExchangeFactory", + "deprecated": false + }, + { + "name": "getHostLaunchOptions", + "deprecated": false + }, + { + "name": "getLaunchOptions", + "deprecated": false + }, + { + "name": "getUserIdentifier", + "deprecated": false + }, + { + "name": "hideVideoCapturePreview", + "deprecated": false + }, + { + "name": "isBlackout", + "deprecated": false + }, + { + "name": "launched", + "deprecated": false + }, + { + "name": "launchWithToken", + "deprecated": false + }, + { + "name": "log", + "deprecated": false + }, + { + "name": "logError", + "deprecated": false + }, + { + "name": "logException", + "deprecated": false + }, + { + "name": "logUnhandledException", + "deprecated": false + }, + { + "name": "notifyWithTitle", + "deprecated": false + }, + { + "name": "relaunch", + "deprecated": false + }, + { + "name": "relaunchWithDictionaryOptions", + "deprecated": false + }, + { + "name": "relaunchWithOptions", + "deprecated": false + }, + { + "name": "removeAllSecureRectangles", + "deprecated": false + }, + { + "name": "removeSecureRectangle", + "deprecated": false + }, + { + "name": "removeSecureView", + "deprecated": false + }, + { + "name": "setAttribute", + "deprecated": false + }, + { + "name": "setBreadcrumbFilter", + "deprecated": false + }, + { + "name": "setLogEventFilter", + "deprecated": false + }, + { + "name": "setNetworkEventFilter", + "deprecated": false + }, + { + "name": "setReportHandler", + "deprecated": false + }, + { + "name": "setUserIdentifier", + "deprecated": false + }, + { + "name": "sharedInstance", + "deprecated": false + }, + { + "name": "showReportDialog", + "deprecated": false + }, + { + "name": "showReportDialogWithSummary", + "deprecated": false + }, + { + "name": "showVideoCapturePreview", + "deprecated": false + }, + { + "name": "startBlackout", + "deprecated": false + }, + { + "name": "startSpanWithOperation", + "deprecated": false + }, + { + "name": "startTransactionWithName", + "deprecated": false + }, + { + "name": "status", + "deprecated": false + }, + { + "name": "stop", + "deprecated": false + }, + { + "name": "testCrash", + "deprecated": false + }, + { + "name": "trace", + "deprecated": false + }, + { + "name": "uploadReport", + "deprecated": false + }, + { + "name": "uploadWithSummary", + "deprecated": false + } + ] +} diff --git a/scripts/sdk-api.ts b/scripts/sdk-api.ts new file mode 100644 index 00000000..c3f1709c --- /dev/null +++ b/scripts/sdk-api.ts @@ -0,0 +1,64 @@ +/** + * Extracts the public API surface of the two native SDKs: the method names of + * the Android `Bugsee` class and the class methods of the iOS `Bugsee` + * interface. Names only: this exists so a method a new SDK release adds cannot + * go unnoticed, not to describe signatures. + */ + +export interface SdkMethod { + name: string; + deprecated: boolean; +} + +/** Public static methods of the Android `Bugsee` class, deduplicated across overloads. */ +export function parseAndroidApi(source: string): SdkMethod[] { + const lines = source.split('\n'); + const methods = new Map(); + lines.forEach((line, index) => { + const match = /^\s*public\s+static\s+(?:<[^>]+>\s+)?[\w<>[\],.? ]+?\s+(\w+)\s*\(/.exec(line); + if (!match) { + return; + } + const name = match[1] as string; + // Only the annotations and comments directly above this method: a wider window reads + // the previous method's @Deprecated as this one's. + let deprecated = false; + for (let up = index - 1; up >= 0; up--) { + const above = (lines[up] as string).trim(); + if (/^@Deprecated\b/.test(above)) { + deprecated = true; + } + if (above !== '' && !/^(?:@|\/\*|\*|\/\/)/.test(above)) { + break; + } + } + const previous = methods.get(name); + // A name is deprecated only when every overload is. + methods.set(name, { name, deprecated: previous ? previous.deprecated && deprecated : deprecated }); + }); + if (methods.size === 0) { + throw new Error('no public static methods found; the parser missed the source'); + } + return [...methods.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** Class methods (`+`) and properties of the iOS `Bugsee` interface; the first selector part names a method. */ +export function parseIosApi(header: string): SdkMethod[] { + const start = header.search(/@interface\s+Bugsee\s*:/); + if (start === -1) { + throw new Error('no @interface Bugsee found; the parser missed the source'); + } + const end = header.indexOf('@end', start); + const body = header.slice(start, end === -1 ? undefined : end); + const methods = new Map(); + for (const m of body.matchAll(/^\s*\+\s*\([^)]*\)\s*(\w+)/gm)) { + methods.set(m[1] as string, { name: m[1] as string, deprecated: false }); + } + for (const m of body.matchAll(/^\s*@property\b[^;]*?\b(\w+)\s*;/gm)) { + methods.set(m[1] as string, { name: m[1] as string, deprecated: false }); + } + if (methods.size === 0) { + throw new Error('no methods found in @interface Bugsee; the parser missed the source'); + } + return [...methods.values()].sort((a, b) => a.name.localeCompare(b.name)); +} From 4c2d8a04ee22d8fca190fd552b22a12202fd5610 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 11:04:06 +0500 Subject: [PATCH 03/16] Address review: own-key legacy lookup, number-compatible enum setters, extractor prerequisite - unknownKeys: look 6.x names up by own property, so `constructor` or `toString` are ordinary unknown keys and not "6.x names" (test added). - captureLogsLevel and videoMode keep accepting a plain number, as they did before the enum types, so a value read from config still compiles. - The extractor fails when the Android golden manifest is missing instead of silently generating a manifest without the NDK and leak options. Human guided, AI implemented --- .../src/options/AndroidLaunchOptions.ts | 7 ++++--- .../src/options/BugseeLaunchOptions.ts | 7 ++++--- .../src/options/__tests__/unknownKeys.test.ts | 9 +++++++++ packages/react-native/src/options/unknownKeys.ts | 6 +++++- scripts/cli-extract-option-keys.ts | 15 +++++++++++---- 5 files changed, 33 insertions(+), 11 deletions(-) diff --git a/packages/react-native/src/options/AndroidLaunchOptions.ts b/packages/react-native/src/options/AndroidLaunchOptions.ts index 8708fc31..98c66b9e 100644 --- a/packages/react-native/src/options/AndroidLaunchOptions.ts +++ b/packages/react-native/src/options/AndroidLaunchOptions.ts @@ -69,12 +69,13 @@ export class AndroidLaunchOptions extends BugseeLaunchOptions { } /** - * Screen-capture mode; see {@link VideoMode}. + * Screen-capture mode; see {@link VideoMode}. Also accepts a plain `number`, which this accessor + * always took, so a value read from config still compiles. */ - get videoMode(): VideoMode | undefined { + get videoMode(): VideoMode | number | undefined { return this.$get('com.bugsee.option.capture.video.mode'); } - set videoMode(value: VideoMode | undefined) { + set videoMode(value: VideoMode | number | undefined) { this.$set('com.bugsee.option.capture.video.mode', value); } diff --git a/packages/react-native/src/options/BugseeLaunchOptions.ts b/packages/react-native/src/options/BugseeLaunchOptions.ts index b4ab216e..a8c687cb 100644 --- a/packages/react-native/src/options/BugseeLaunchOptions.ts +++ b/packages/react-native/src/options/BugseeLaunchOptions.ts @@ -88,12 +88,13 @@ export abstract class BugseeLaunchOptions { } /** - * Least severe level captured; see {@link LogLevel}. + * Least severe level captured; see {@link LogLevel}. Also accepts a plain `number`, which this + * accessor always took, so a level read from config still compiles. */ - get captureLogsLevel(): LogLevel | undefined { + get captureLogsLevel(): LogLevel | number | undefined { return this.$get('com.bugsee.option.capture.logs.level'); } - set captureLogsLevel(value: LogLevel | undefined) { + set captureLogsLevel(value: LogLevel | number | undefined) { this.$set('com.bugsee.option.capture.logs.level', value); } diff --git a/packages/react-native/src/options/__tests__/unknownKeys.test.ts b/packages/react-native/src/options/__tests__/unknownKeys.test.ts index e10b6f62..f97c9971 100644 --- a/packages/react-native/src/options/__tests__/unknownKeys.test.ts +++ b/packages/react-native/src/options/__tests__/unknownKeys.test.ts @@ -55,6 +55,15 @@ describe('describeUnknownKey', () => { ).toContain('Did you mean "com.bugsee.option.reporting.triggers.shake"?'); }); + it('treats Object.prototype member names as ordinary unknown keys, not 6.x names', () => { + for (const key of ['constructor', 'toString', 'valueOf', 'hasOwnProperty', '__proto__']) { + const message = describeUnknownKey('android', key); + expect(message).toContain('is not a launch option'); + expect(message).not.toContain('6.x'); + expect(message).not.toContain('native code'); + } + }); + it('offers no suggestion when nothing is close', () => { expect(describeUnknownKey('ios', 'zzzzzzzzzzzzzzzz')).not.toContain('Did you mean'); }); diff --git a/packages/react-native/src/options/unknownKeys.ts b/packages/react-native/src/options/unknownKeys.ts index 63cc12e7..06b643b0 100644 --- a/packages/react-native/src/options/unknownKeys.ts +++ b/packages/react-native/src/options/unknownKeys.ts @@ -102,7 +102,11 @@ export function unknownOptionKeys( /** One sentence naming the key, what the SDK does with it, and what to use. */ export function describeUnknownKey(platform: Platform, key: string): string { const sdk = platform === 'ios' ? 'iOS' : 'Android'; - const legacy = LEGACY_OPTION_KEYS[key]; + // Own keys only: a plain-object lookup also resolves `constructor`, `toString` and the rest of + // Object.prototype, which would turn those unknown keys into a nonsense "6.x name" message. + const legacy = Object.prototype.hasOwnProperty.call(LEGACY_OPTION_KEYS, key) + ? LEGACY_OPTION_KEYS[key] + : undefined; if (legacy !== undefined) { const effect = platform === 'android' diff --git a/scripts/cli-extract-option-keys.ts b/scripts/cli-extract-option-keys.ts index 09bf2580..9d5672fd 100644 --- a/scripts/cli-extract-option-keys.ts +++ b/scripts/cli-extract-option-keys.ts @@ -119,10 +119,17 @@ const nativeVersions = JSON.parse( // the wrapper exposes. The SDK's golden manifest covers every module, so the extension rows // are taken from it when the SDK tree has one. const goldenPath = join(androidRoot, 'options-manifest/options-manifest.golden.json'); -const extensionOptions: OptionsManifest['options'] = existsSync(goldenPath) - ? (JSON.parse(readFileSync(goldenPath, 'utf8')) as { options: OptionsManifest['options'] }) - .options.filter((option) => option.module !== 'bugsee-android') - : []; +// No golden manifest means the generated manifest would lose the NDK and leak options while the key +// list (read from their sources above) still includes them, so the two artifacts would disagree. +if (!existsSync(goldenPath)) { + throw new Error( + `${goldenPath} is missing. Point the extractor at an Android SDK checkout that has ` + + 'options-manifest/options-manifest.golden.json (every pinned release does).', + ); +} +const extensionOptions: OptionsManifest['options'] = ( + JSON.parse(readFileSync(goldenPath, 'utf8')) as { options: OptionsManifest['options'] } +).options.filter((option) => option.module !== 'bugsee-android'); const options: OptionsManifest['options'] = [ ...parseAndroidDescriptors( readFileSync(join( From 83809c0bfee3ace534d80b6e0c4a9f919385f4fe Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 11:05:07 +0500 Subject: [PATCH 04/16] Address review: tie the SDK API snapshot to the pinned versions sdk-api.json now records the SDK versions it was extracted at, and the parity test fails when they differ from native-versions.json, so a pin bump cannot pass until the snapshot is regenerated and any new method is mapped or exempted. Human guided, AI implemented --- .../src/__tests__/sdk-api-parity.test.ts | 12 ++++++++++++ scripts/cli-extract-sdk-api.ts | 10 +++++++++- scripts/sdk-api.json | 4 ++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/react-native/src/__tests__/sdk-api-parity.test.ts b/packages/react-native/src/__tests__/sdk-api-parity.test.ts index d963643b..bb61fb08 100644 --- a/packages/react-native/src/__tests__/sdk-api-parity.test.ts +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -4,6 +4,7 @@ jest.mock('../NativeBugsee', () => require('../__mocks__/native').nativeMock); import * as pkg from '../index'; import Bugsee from '../index'; import api from '../../../../scripts/sdk-api.json'; +import nativeVersions from '../../../../native-versions.json'; import { ANDROID, IOS, type Mapping } from '../../../../scripts/sdk-api-map'; import { parseAndroidApi, parseIosApi } from '../../../../scripts/sdk-api'; @@ -20,6 +21,17 @@ const platforms = [ ['ios', api.ios, IOS], ] as const; +describe('the snapshot describes the pinned SDKs', () => { + it('was extracted at the versions in native-versions.json', () => { + // A native-versions bump fails here until `cli-extract-sdk-api.ts` is re-run against the new + // release, which is when a method the release added gets its mapping or exemption. + expect(api.sdk).toEqual({ + android: nativeVersions.android.sdk, + ios: nativeVersions.ios.sdk, + }); + }); +}); + describe.each(platforms)('%s SDK API parity', (_platform, methods, map) => { const names = methods.map((m) => m.name); diff --git a/scripts/cli-extract-sdk-api.ts b/scripts/cli-extract-sdk-api.ts index 7ab59f8f..aa31f1fb 100644 --- a/scripts/cli-extract-sdk-api.ts +++ b/scripts/cli-extract-sdk-api.ts @@ -17,6 +17,14 @@ const android = parseAndroidApi(readFileSync( const ios = parseIosApi(readFileSync( join(iosRoot, 'BugseeDev/BugseeLib/BugseeLib/Bugsee.h'), 'utf8')); +// Recorded so a test can tell when the snapshot no longer describes the pinned SDKs. +const pinned = JSON.parse( + readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), +) as { android: { sdk: string }; ios: { sdk: string } }; + const out = join(import.meta.dirname, 'sdk-api.json'); -writeFileSync(out, `${JSON.stringify({ android, ios }, null, 2)}\n`); +writeFileSync( + out, + `${JSON.stringify({ sdk: { android: pinned.android.sdk, ios: pinned.ios.sdk }, android, ios }, null, 2)}\n`, +); console.log(`android ${android.length} methods, ios ${ios.length} -> ${out}`); diff --git a/scripts/sdk-api.json b/scripts/sdk-api.json index 49535f00..46a4e2a4 100644 --- a/scripts/sdk-api.json +++ b/scripts/sdk-api.json @@ -1,4 +1,8 @@ { + "sdk": { + "android": "7.4.2", + "ios": "7.0.0" + }, "android": [ { "name": "addBreadcrumb", From 4cfa03ad4762cc11fc9d2f0c1dfcd69cd95aea12 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 11:38:22 +0500 Subject: [PATCH 05/16] Address review: refuse before writing, and measure the SDK version The extractor ran its golden-manifest check after it had already rewritten three fixtures, so a refusal left the working tree half regenerated. Every check now runs before the first write. It also now refuses a checkout that is not at the version native-versions.json pins, reading each SDK's root version.txt, so a tree a release ahead cannot bless options the pinned SDK lacks. Verified: the pinned checkouts reproduce the committed fixtures byte for byte. Human guided, AI implemented --- scripts/__tests__/sdk-version.test.ts | 30 +++++++++++++++++++++++ scripts/cli-extract-option-keys.ts | 34 ++++++++++++++++----------- scripts/sdk-version.ts | 28 ++++++++++++++++++++++ 3 files changed, 78 insertions(+), 14 deletions(-) create mode 100644 scripts/__tests__/sdk-version.test.ts create mode 100644 scripts/sdk-version.ts diff --git a/scripts/__tests__/sdk-version.test.ts b/scripts/__tests__/sdk-version.test.ts new file mode 100644 index 00000000..3e1d977c --- /dev/null +++ b/scripts/__tests__/sdk-version.test.ts @@ -0,0 +1,30 @@ +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { assertAtPinnedVersion, readSdkVersion } from '../sdk-version'; + +const checkout = (version: string): string => { + const root = mkdtempSync(join(tmpdir(), 'sdk-version-')); + writeFileSync(join(root, 'version.txt'), `${version}\n`); + return root; +}; + +describe('sdk-version', () => { + it('reads the version a checkout declares, without the trailing newline', () => { + expect(readSdkVersion(checkout('7.4.2'))).toBe('7.4.2'); + }); + + it('accepts a checkout at the pinned version', () => { + expect(() => assertAtPinnedVersion('android', checkout('7.4.2'), '7.4.2')).not.toThrow(); + }); + + it('refuses a checkout a release ahead of the pin, naming both versions', () => { + expect(() => assertAtPinnedVersion('ios', checkout('7.0.1'), '7.0.0')).toThrow( + /ios SDK checkout .* is 7\.0\.1, but native-versions\.json pins 7\.0\.0/, + ); + }); + + it('refuses a checkout with no version.txt rather than assuming it matches', () => { + expect(() => readSdkVersion(mkdtempSync(join(tmpdir(), 'sdk-version-')))).toThrow(); + }); +}); diff --git a/scripts/cli-extract-option-keys.ts b/scripts/cli-extract-option-keys.ts index 9d5672fd..49873bfc 100644 --- a/scripts/cli-extract-option-keys.ts +++ b/scripts/cli-extract-option-keys.ts @@ -8,6 +8,7 @@ */ import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { readObjcEnum } from './ios-enums.ts'; +import { assertAtPinnedVersion } from './sdk-version.ts'; import { join } from 'node:path'; import { parseAndroidDescriptors, @@ -22,6 +23,24 @@ const home = process.env.HOME ?? ''; const [iosRoot = join(home, 'Projects/Bugsee/ios/sdk'), androidRoot = join(home, 'Projects/Bugsee/android/sdk')] = process.argv.slice(2); +// Everything that can refuse runs before the first write, so a refusal never leaves some of the +// generated fixtures regenerated and others stale. +const nativeVersions = JSON.parse( + readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), +) as { android: { sdk: string }; ios: { sdk: string } }; +assertAtPinnedVersion('ios', iosRoot, nativeVersions.ios.sdk); +assertAtPinnedVersion('android', androidRoot, nativeVersions.android.sdk); + +// No golden manifest means the generated manifest would lose the NDK and leak options while the key +// list (read from their sources) still includes them, so the two artifacts would disagree. +const goldenPath = join(androidRoot, 'options-manifest/options-manifest.golden.json'); +if (!existsSync(goldenPath)) { + throw new Error( + `${goldenPath} is missing. Point the extractor at an Android SDK checkout that has ` + + 'options-manifest/options-manifest.golden.json (every pinned release does).', + ); +} + const iosSource = join(iosRoot, 'BugseeDev/BugseeLib/BugseeLib/BugseeOptions.m'); const androidSource = join( androidRoot, @@ -110,23 +129,10 @@ const androidConstants = Object.fromEntries( .map((m) => [m[1] as string, m[2] as string]), ); -const nativeVersions = JSON.parse( - readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), -) as { android: { sdk: string }; ios: { sdk: string } }; - // The core library's options come from its descriptors. The extension modules (NDK, leak) // register theirs elsewhere, so reading OptionsDescriptors.java alone would leave out options // the wrapper exposes. The SDK's golden manifest covers every module, so the extension rows -// are taken from it when the SDK tree has one. -const goldenPath = join(androidRoot, 'options-manifest/options-manifest.golden.json'); -// No golden manifest means the generated manifest would lose the NDK and leak options while the key -// list (read from their sources above) still includes them, so the two artifacts would disagree. -if (!existsSync(goldenPath)) { - throw new Error( - `${goldenPath} is missing. Point the extractor at an Android SDK checkout that has ` + - 'options-manifest/options-manifest.golden.json (every pinned release does).', - ); -} +// are taken from it (its presence was checked up front, before anything was written). const extensionOptions: OptionsManifest['options'] = ( JSON.parse(readFileSync(goldenPath, 'utf8')) as { options: OptionsManifest['options'] } ).options.filter((option) => option.module !== 'bugsee-android'); diff --git a/scripts/sdk-version.ts b/scripts/sdk-version.ts new file mode 100644 index 00000000..cb602931 --- /dev/null +++ b/scripts/sdk-version.ts @@ -0,0 +1,28 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +/** The version an SDK checkout declares in its root `version.txt` (both SDKs keep one). */ +export function readSdkVersion(root: string): string { + return readFileSync(join(root, 'version.txt'), 'utf8').trim(); +} + +/** + * Aborts when a checkout is not at the version `native-versions.json` pins. + * + * The extractors stamp what they extract and the tests trust the stamp, so it has to be measured + * from the tree that was read: a checkout a release ahead of the pin would otherwise bless + * options and methods the pinned SDK does not have. + */ +export function assertAtPinnedVersion( + platform: 'android' | 'ios', + root: string, + pinned: string, +): void { + const found = readSdkVersion(root); + if (found !== pinned) { + throw new Error( + `${platform} SDK checkout at ${root} is ${found}, but native-versions.json pins ${pinned}. ` + + 'Check out the pinned release (or bump the pin) before extracting.', + ); + } +} From 4db1477ff29802821ac20d867ee4b29f98afe6a9 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 11:39:24 +0500 Subject: [PATCH 06/16] Address review: stamp the SDK API snapshot with the measured version The snapshot's version was copied from native-versions.json, so the test that compared the two compared a file with itself. The extractor now reads each SDK checkout's version.txt, refuses a tree that is not at the pin, and stamps what it measured. Regenerated from the iOS 7.0.0 commit and Android v7.4.2; the output is unchanged, which also confirms the iOS selectors are in 7.0.0. Human guided, AI implemented --- scripts/cli-extract-sdk-api.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/scripts/cli-extract-sdk-api.ts b/scripts/cli-extract-sdk-api.ts index aa31f1fb..4a62290f 100644 --- a/scripts/cli-extract-sdk-api.ts +++ b/scripts/cli-extract-sdk-api.ts @@ -7,24 +7,28 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { parseAndroidApi, parseIosApi } from './sdk-api.ts'; +import { assertAtPinnedVersion, readSdkVersion } from './sdk-version.ts'; const home = process.env.HOME ?? ''; const [iosRoot = join(home, 'Projects/Bugsee/ios/sdk'), androidRoot = join(home, 'Projects/Bugsee/android/sdk')] = process.argv.slice(2); +// Refuse before reading anything: the snapshot is stamped with the version MEASURED from the +// checkouts, and a tree that is not at the pin would bless methods the pinned SDK lacks. +const pinned = JSON.parse( + readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), +) as { android: { sdk: string }; ios: { sdk: string } }; +assertAtPinnedVersion('ios', iosRoot, pinned.ios.sdk); +assertAtPinnedVersion('android', androidRoot, pinned.android.sdk); + const android = parseAndroidApi(readFileSync( join(androidRoot, 'library/src/main/java/com/bugsee/library/Bugsee.java'), 'utf8')); const ios = parseIosApi(readFileSync( join(iosRoot, 'BugseeDev/BugseeLib/BugseeLib/Bugsee.h'), 'utf8')); -// Recorded so a test can tell when the snapshot no longer describes the pinned SDKs. -const pinned = JSON.parse( - readFileSync(join(import.meta.dirname, '..', 'native-versions.json'), 'utf8'), -) as { android: { sdk: string }; ios: { sdk: string } }; - const out = join(import.meta.dirname, 'sdk-api.json'); writeFileSync( out, - `${JSON.stringify({ sdk: { android: pinned.android.sdk, ios: pinned.ios.sdk }, android, ios }, null, 2)}\n`, + `${JSON.stringify({ sdk: { android: readSdkVersion(androidRoot), ios: readSdkVersion(iosRoot) }, android, ios }, null, 2)}\n`, ); console.log(`android ${android.length} methods, ios ${ios.length} -> ${out}`); From 1d74d50ddb858558eddb33a4aa315cdd8d9184fd Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 12:06:24 +0500 Subject: [PATCH 07/16] Address review: compute every fixture first, write them together The earlier fix moved two checks ahead of the first write, but an enum a header no longer declares, or a golden manifest that exists and does not parse, still threw after some fixtures had been rewritten. The extractor now computes every artifact first and writes all four at the end. Verified with an invalid golden manifest and a renamed iOS enum: both fail and leave the tree untouched; the pinned checkouts still reproduce the committed fixtures. Human guided, AI implemented --- scripts/cli-extract-option-keys.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/cli-extract-option-keys.ts b/scripts/cli-extract-option-keys.ts index 49873bfc..1370e677 100644 --- a/scripts/cli-extract-option-keys.ts +++ b/scripts/cli-extract-option-keys.ts @@ -41,6 +41,11 @@ if (!existsSync(goldenPath)) { ); } +// Every fixture is computed first and written together at the end, so a failure anywhere (an enum a +// header no longer declares, a golden manifest that does not parse) leaves no fixture regenerated +// and the others stale. +const pending: [path: string, content: string][] = []; + const iosSource = join(iosRoot, 'BugseeDev/BugseeLib/BugseeLib/BugseeOptions.m'); const androidSource = join( androidRoot, @@ -66,7 +71,7 @@ const out = join( import.meta.dirname, '..', 'packages', 'react-native', 'src', 'options', 'option-keys.json', ); -writeFileSync(out, `${JSON.stringify(keys, null, 2)}\n`); +pending.push([out, `${JSON.stringify(keys, null, 2)}\n`]); // The option enums, read from the same sources. These cross the bridge as // numbers, so a wrong one is honoured by the SDK as a different setting. @@ -82,7 +87,7 @@ const enumsOut = join( import.meta.dirname, '..', 'packages', 'react-native', 'src', 'options', 'option-enums.json', ); -writeFileSync(enumsOut, `${JSON.stringify(enums, null, 2)}\n`); +pending.push([enumsOut, `${JSON.stringify(enums, null, 2)}\n`]); // The SAME enums read from the iOS headers, so the two platforms can be // compared. Extracted rather than hand-copied because the value that matters @@ -115,7 +120,7 @@ const iosEnumsOut = join( import.meta.dirname, '..', 'packages', 'react-native', 'src', 'options', 'ios-enums.json', ); -writeFileSync(iosEnumsOut, `${JSON.stringify(iosEnums, null, 2)}\n`); +pending.push([iosEnumsOut, `${JSON.stringify(iosEnums, null, 2)}\n`]); // An Android manifest in the shape bugsee/specs sdk/options/manifest.md // defines, so that swapping to the SDK's own published manifest is a change of @@ -159,7 +164,10 @@ const manifestOut = join( import.meta.dirname, '..', 'packages', 'react-native', 'src', 'options', 'android-options-manifest.json', ); -writeFileSync(manifestOut, `${JSON.stringify(manifest, null, 2)}\n`); +pending.push([manifestOut, `${JSON.stringify(manifest, null, 2)}\n`]); +for (const [path, content] of pending) { + writeFileSync(path, content); +} console.log(`android manifest: ${manifest.options.length} options -> ${manifestOut}`); console.log( From a35eb284a245f6d0bd5fd73134a7f4cef931c1e9 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 13:29:30 +0500 Subject: [PATCH 08/16] Gate build and publish on the option manifests the SDK releases publish Each SDK release publishes an immutable option manifest at download.bugsee.com/sdk/options//.json. The fixtures here are extracted from SDK sources, so they could drift from what a release really registers. `yarn check:options-manifests` fetches the manifest for each pinned version and fails when: - the SDK registers an option this package does not list, or the package lists one the SDK does not register (a key it would silently ignore); - the committed Android manifest differs from the published one in type, hidden flag, deprecation or enum constants; - the manifest cannot be fetched (retried; a gate that passes when it cannot look is not a gate), is for another platform or version, or is malformed. It runs in CI's js job and in the release workflow before publishing. First run found a real misalignment: the descriptor parser typed `$$WRAPPER` (HashMap.class) as a string where the SDK publishes a map. Fixed and the manifest fixture regenerated from the pinned checkouts. Human guided, AI implemented --- .github/workflows/ci.yml | 3 + .github/workflows/release.yml | 5 + docs/launch-options.md | 4 +- package.json | 1 + .../src/options/android-options-manifest.json | 4 +- scripts/__tests__/option-keys.test.ts | 3 + scripts/__tests__/published-manifest.test.ts | 198 ++++++++++++++++++ scripts/cli-check-published-manifests.ts | 93 ++++++++ scripts/option-keys.ts | 1 + scripts/published-manifest.ts | 150 +++++++++++++ 10 files changed, 459 insertions(+), 3 deletions(-) create mode 100644 scripts/__tests__/published-manifest.test.ts create mode 100644 scripts/cli-check-published-manifests.ts create mode 100644 scripts/published-manifest.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f9324b2..d46eac2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,9 @@ jobs: - run: yarn lint - run: yarn typecheck - run: yarn test + # What each native SDK published for the pinned version against the option fixtures this package + # ships. Needs the network (download.bugsee.com) and fails when it cannot look. + - run: yarn check:options-manifests # Mutation gates. Each fails the build under its config's break threshold. # The point is not the number: tests that assert nothing still pass, and diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 33ac1b35..cf1c3591 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -101,6 +101,11 @@ jobs: - name: Release gate (metadata, one version, peer ranges) run: node scripts/check-publishable.mjs + # Never publish options the pinned SDKs do not agree with: a key the SDK does not register is + # silently ignored, and one it added without an accessor is unreachable. + - name: Option manifests (published by each pinned SDK release) + run: yarn check:options-manifests + # Inputs go in through the environment, never interpolated into the script text: a `${{ }}` # inside `run:` is textually pasted into the shell. - name: Dry-run publish diff --git a/docs/launch-options.md b/docs/launch-options.md index a4e5b82c..b32c6977 100644 --- a/docs/launch-options.md +++ b/docs/launch-options.md @@ -13,7 +13,9 @@ await Bugsee.launch('', options); ``` The tables are checked against the SDK versions pinned in `native-versions.json` (Android 7.4.2, iOS 7.0.0): -a test fails when either SDK registers an option this package has no accessor for. Options a +a test fails when either SDK registers an option this package has no accessor for, and `yarn check:options-manifests` +(run in CI and before every publish) compares the option manifest each SDK release published at +`download.bugsee.com/sdk/options//.json` with this package's fixtures and fails on any difference. Options a *newer* SDK adds are reachable with `options.setCustomOption(key, value)` until the package catches up. ## Keys the SDK drops diff --git a/package.json b/package.json index a71e7cab..cbd5db10 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "test": "jest", "test:release": "BUGSEE_RELEASE=1 yarn test", "check:publishable": "node scripts/check-publishable.mjs", + "check:options-manifests": "node scripts/cli-check-published-manifests.ts", "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.example.json", "lint": "eslint . && node scripts/cli-check-no-internal-hosts.ts", "playground": "yarn workspace bugsee-playground", diff --git a/packages/react-native/src/options/android-options-manifest.json b/packages/react-native/src/options/android-options-manifest.json index 1294187d..3727ac4d 100644 --- a/packages/react-native/src/options/android-options-manifest.json +++ b/packages/react-native/src/options/android-options-manifest.json @@ -3,7 +3,7 @@ "sdk": "android", "sdkVersion": "7.4.2", "buildConfiguration": "release", - "generatedAt": "2026-11-16T05:30:59Z", + "generatedAt": "2026-11-16T08:27:30Z", "options": [ { "key": "com.bugsee.option.config.duration", @@ -627,7 +627,7 @@ }, { "key": "com.bugsee.option.$$WRAPPER", - "type": "string", + "type": "map", "default": null, "module": "bugsee-android", "hidden": true diff --git a/scripts/__tests__/option-keys.test.ts b/scripts/__tests__/option-keys.test.ts index 35a5afbf..432d87eb 100644 --- a/scripts/__tests__/option-keys.test.ts +++ b/scripts/__tests__/option-keys.test.ts @@ -266,6 +266,9 @@ describe('parseAndroidDescriptors', () => { ['lowercase float', 'float.class', '0.5f', 'float', 0.5], ['lowercase double', 'double.class', '1.5', 'float', 1.5], ['Map', 'Map.class', 'null', 'map', null], + // Android declares `$$WRAPPER` as HashMap.class and publishes it as a map; reading it as a string + // is what the published-manifest check caught. + ['HashMap', 'HashMap.class', 'null', 'map', null], ['List', 'List.class', 'null', 'list', null], // Each of these pins one literal-parsing regex to the exact text it is // meant to match, not merely a substring of it -- the literal is left as diff --git a/scripts/__tests__/published-manifest.test.ts b/scripts/__tests__/published-manifest.test.ts new file mode 100644 index 00000000..6771ffae --- /dev/null +++ b/scripts/__tests__/published-manifest.test.ts @@ -0,0 +1,198 @@ +import { + MANIFEST_BASE, + checkPublished, + manifestUrl, + parseManifest, + type CheckInput, + type PublishedManifest, + type PublishedOption, +} from '../published-manifest'; + +const option = (key: string, extra: Partial = {}): PublishedOption => ({ + key, + type: 'boolean', + ...extra, +}); + +const manifest = ( + options: PublishedOption[], + extra: Partial = {}, +): PublishedManifest => ({ + manifestVersion: 1, + sdk: 'android', + sdkVersion: '7.4.2', + options, + ...extra, +}); + +const input = (extra: Partial = {}): CheckInput => ({ + platform: 'android', + pinnedVersion: '7.4.2', + published: manifest([option('a'), option('b')]), + knownKeys: ['a', 'b'], + ...extra, +}); + +describe('manifestUrl', () => { + it('points at the immutable per-release file', () => { + expect(manifestUrl(MANIFEST_BASE, 'ios', '7.0.0')).toBe( + 'https://download.bugsee.com/sdk/options/ios/7.0.0.json', + ); + }); + + it('does not double the slash when the base ends in one', () => { + expect(manifestUrl('http://x/y/', 'android', '1')).toBe('http://x/y/android/1.json'); + expect(manifestUrl('http://x/y///', 'android', '1')).toBe('http://x/y/android/1.json'); + }); +}); + +describe('parseManifest', () => { + it('reads a manifest', () => { + expect(parseManifest(JSON.stringify(manifest([option('a')])), 'm').options).toHaveLength(1); + }); + + it.each([ + ['not JSON', '{ nope'], + ['null', 'null'], + ['a number', '3'], + ['no sdk', JSON.stringify({ sdkVersion: '1', options: [] })], + ['no version', JSON.stringify({ sdk: 'ios', options: [] })], + ['no options', JSON.stringify({ sdk: 'ios', sdkVersion: '1' })], + ['options that are not a list', JSON.stringify({ sdk: 'ios', sdkVersion: '1', options: {} })], + ])('refuses %s, naming the source', (_name, text) => { + expect(() => parseManifest(text, 'the-source')).toThrow(/the-source/); + }); +}); + +describe('checkPublished', () => { + it('is empty when the published manifest and the package agree', () => { + expect(checkPublished(input())).toEqual([]); + }); + + it('reports a manifest for another platform', () => { + expect(checkPublished(input({ published: manifest([option('a'), option('b')], { sdk: 'ios' }) }))).toEqual([ + 'the manifest is for sdk "ios", not "android"', + ]); + }); + + it('reports a manifest for another version than the pin', () => { + expect( + checkPublished(input({ published: manifest([option('a'), option('b')], { sdkVersion: '7.5.0' }) })), + ).toEqual(['the manifest is for 7.5.0, but native-versions.json pins 7.4.2']); + }); + + it('reports an option the SDK registers and the package does not list', () => { + const problems = checkPublished(input({ published: manifest([option('a'), option('b'), option('c')]) })); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('the android SDK registers c'); + expect(problems[0]).toContain('option-keys.json'); + }); + + it('reports a key the package lists and the SDK does not register', () => { + const problems = checkPublished(input({ knownKeys: ['a', 'b', 'gone'] })); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('lists gone for android'); + expect(problems[0]).toContain('silently ignored'); + }); + + it('lists several problems in key order', () => { + const problems = checkPublished( + input({ published: manifest([option('z'), option('y')]), knownKeys: ['b', 'a'] }), + ); + expect(problems.map((p) => p.match(/\b(registers|lists) (\w+)/)?.[2])).toEqual(['y', 'z', 'a', 'b']); + }); + + it('leaves hidden internals out of the key comparison, in both directions', () => { + expect( + checkPublished( + input({ published: manifest([option('a'), option('b'), option('$$WRAPPER', { hidden: true })]) }), + ), + ).toEqual([]); + }); + + it('still counts a published option whose hidden flag is false', () => { + expect( + checkPublished(input({ published: manifest([option('a'), option('b'), option('c', { hidden: false })]) })), + ).toHaveLength(1); + }); + + describe('against the committed Android manifest', () => { + const committed = (options: PublishedOption[]) => input({ committed: options }); + + it('is empty when every option matches', () => { + expect(checkPublished(committed([option('a'), option('b')]))).toEqual([]); + }); + + it('reports an option the committed manifest lacks', () => { + expect(checkPublished(committed([option('a')]))).toEqual([ + 'android-options-manifest.json is missing b', + ]); + }); + + it('reports an option the published manifest lacks', () => { + expect(checkPublished(committed([option('a'), option('b'), option('x')]))).toEqual([ + 'android-options-manifest.json has x, which the published manifest does not', + ]); + }); + + it('reports a type that differs, which is what a parser misreading looks like', () => { + const problems = checkPublished(committed([option('a'), option('b', { type: 'string' })])); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('differs from the published manifest for b'); + expect(problems[0]).toContain('"type":"string"'); + }); + + it('reports a hidden flag that differs', () => { + expect(checkPublished(committed([option('a'), option('b', { hidden: true })]))).toHaveLength(1); + }); + + it('reports a deprecation the committed manifest does not carry', () => { + const published = manifest([option('a'), option('b', { deprecated: { since: '7.1.2' } })]); + expect(checkPublished({ ...input({ published }), committed: [option('a'), option('b')] })).toHaveLength(1); + }); + + it('treats a deprecation as a flag, not by its text', () => { + const published = manifest([option('a'), option('b', { deprecated: { since: '7.1.2' } })]); + expect( + checkPublished({ + ...input({ published }), + committed: [option('a'), option('b', { deprecated: { since: '7.2.0' } })], + }), + ).toEqual([]); + }); + + it('reports an enum whose constants differ', () => { + const withEnum = (values: Record) => + option('b', { type: 'enum', enum: { name: 'E', values } }); + const published = manifest([option('a'), withEnum({ A: 1, B: 2 })]); + expect(checkPublished({ ...input({ published }), committed: [option('a'), withEnum({ A: 1, B: 3 })] })).toHaveLength(1); + }); + + it('ignores the order an enum lists its constants in', () => { + const withEnum = (values: Record) => + option('b', { type: 'enum', enum: { name: 'E', values } }); + const published = manifest([option('a'), withEnum({ A: 1, B: 2 })]); + expect(checkPublished({ ...input({ published }), committed: [option('a'), withEnum({ B: 2, A: 1 })] })).toEqual([]); + }); + + it('reports an enum that is missing, and one that is renamed', () => { + const published = manifest([option('a'), option('b', { type: 'enum', enum: { name: 'E', values: { A: 1 } } })]); + expect( + checkPublished({ ...input({ published }), committed: [option('a'), option('b', { type: 'enum' })] }), + ).toHaveLength(1); + expect( + checkPublished({ + ...input({ published }), + committed: [option('a'), option('b', { type: 'enum', enum: { name: 'Other', values: { A: 1 } } })], + }), + ).toHaveLength(1); + }); + + it('compares hidden options too, since the committed manifest carries them', () => { + const published = manifest([option('a'), option('b'), option('$$X', { hidden: true })]); + expect(checkPublished({ ...input({ published }), committed: [option('a'), option('b')] })).toEqual([ + 'android-options-manifest.json is missing $$X', + ]); + }); + }); +}); diff --git a/scripts/cli-check-published-manifests.ts b/scripts/cli-check-published-manifests.ts new file mode 100644 index 00000000..88a46db9 --- /dev/null +++ b/scripts/cli-check-published-manifests.ts @@ -0,0 +1,93 @@ +/** + * Fails when the option manifest each native SDK published for the PINNED version disagrees with the + * option fixtures this package ships. Run in CI and before a publish. + * + * Usage: cli-check-published-manifests.ts [--dir ] + * + * By default the manifests are fetched from download.bugsee.com (override the base with + * BUGSEE_OPTIONS_MANIFEST_BASE). `--dir` reads `//.json` instead, for + * working offline. An unreachable manifest FAILS the check: a gate that passes when it cannot look is + * not a gate. The fetch is retried, since the file is immutable and only the network can be flaky. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { + MANIFEST_BASE, + checkPublished, + manifestUrl, + parseManifest, + type Platform, + type PublishedOption, +} from './published-manifest.ts'; + +const root = join(import.meta.dirname, '..'); +const options = join(root, 'packages', 'react-native', 'src', 'options'); +const readJson = (path: string): T => JSON.parse(readFileSync(path, 'utf8')) as T; + +const pinned = readJson<{ android: { sdk: string }; ios: { sdk: string } }>( + join(root, 'native-versions.json'), +); +const keys = readJson<{ shared: string[]; ios: string[]; android: string[] }>( + join(options, 'option-keys.json'), +); +const androidManifest = readJson<{ options: PublishedOption[] }>( + join(options, 'android-options-manifest.json'), +); + +const dirFlag = process.argv.indexOf('--dir'); +const dir = dirFlag === -1 ? undefined : process.argv[dirFlag + 1]; +const base = process.env.BUGSEE_OPTIONS_MANIFEST_BASE ?? MANIFEST_BASE; + +async function load(platform: Platform, version: string): Promise { + if (dir !== undefined) { + return readFileSync(join(dir, platform, `${version}.json`), 'utf8'); + } + const url = manifestUrl(base, platform, version); + let failure = ''; + for (let attempt = 1; attempt <= 4; attempt++) { + try { + const response = await fetch(url, { signal: AbortSignal.timeout(20_000) }); + if (response.ok) { + return await response.text(); + } + failure = `HTTP ${response.status}`; + // A manifest that is not there will not appear by asking again (the CDN answers a missing + // key with 403 or 404). + if (response.status === 403 || response.status === 404) { + break; + } + } catch (error) { + failure = (error as Error).message; + } + await new Promise((resolve) => setTimeout(resolve, attempt * 2_000)); + } + throw new Error(`could not fetch ${url}: ${failure}`); +} + +let failed = false; +for (const platform of ['android', 'ios'] as const) { + const version = pinned[platform].sdk; + try { + const published = parseManifest(await load(platform, version), `${platform} ${version} manifest`); + const problems = checkPublished({ + platform, + pinnedVersion: version, + published, + knownKeys: [...keys.shared, ...keys[platform]], + committed: platform === 'android' ? androidManifest.options : undefined, + }); + if (problems.length === 0) { + console.log(`${platform} ${version}: aligned (${published.options.length} published options)`); + } else { + failed = true; + console.error(`${platform} ${version}: ${problems.length} misalignment(s)`); + for (const problem of problems) { + console.error(` - ${problem}`); + } + } + } catch (error) { + failed = true; + console.error(`${platform} ${version}: ${(error as Error).message}`); + } +} +process.exit(failed ? 1 : 0); diff --git a/scripts/option-keys.ts b/scripts/option-keys.ts index e9e1268d..0edc193e 100644 --- a/scripts/option-keys.ts +++ b/scripts/option-keys.ts @@ -116,6 +116,7 @@ const JAVA_TYPES: Record = { 'Double': 'float', 'String': 'string', 'Map': 'map', + 'HashMap': 'map', 'List': 'list', }; diff --git a/scripts/published-manifest.ts b/scripts/published-manifest.ts new file mode 100644 index 00000000..d3a9a7e5 --- /dev/null +++ b/scripts/published-manifest.ts @@ -0,0 +1,150 @@ +/** + * Compares what each native SDK PUBLISHES about its launch options against what this package + * committed. + * + * Every SDK release publishes an immutable option manifest at + * `download.bugsee.com/sdk/options//.json`. The fixtures this package ships + * (`option-keys.json`, `android-options-manifest.json`) are extracted from SDK sources and could + * drift from what a release really registers; this is the check against the release itself, run at + * build and publish time so a misalignment fails the build instead of reaching a customer as an + * option that is silently ignored. + */ + +export interface PublishedOption { + key: string; + type: string; + hidden?: boolean; + deprecated?: unknown; + enum?: { name: string; values: unknown }; +} + +export interface PublishedManifest { + manifestVersion: number; + sdk: string; + sdkVersion: string; + options: PublishedOption[]; +} + +export type Platform = 'android' | 'ios'; + +export const MANIFEST_BASE = 'https://download.bugsee.com/sdk/options'; + +export function manifestUrl(base: string, platform: Platform, version: string): string { + return `${base.replace(/\/+$/, '')}/${platform}/${version}.json`; +} + +/** Rejects anything that is not a version-1 manifest, rather than comparing against a half-read one. */ +export function parseManifest(text: string, source: string): PublishedManifest { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new Error(`${source} is not valid JSON`); + } + const manifest = parsed as Partial | null; + if ( + manifest === null || + typeof manifest !== 'object' || + typeof manifest.sdk !== 'string' || + typeof manifest.sdkVersion !== 'string' || + !Array.isArray(manifest.options) + ) { + throw new Error(`${source} is not an option manifest (needs sdk, sdkVersion and options)`); + } + return manifest as PublishedManifest; +} + +/** The fields the committed manifest and the published one must agree on, in a comparable form. */ +function describe(option: PublishedOption): string { + return JSON.stringify({ + type: option.type, + hidden: option.hidden === true, + deprecated: option.deprecated !== undefined, + enum: option.enum === undefined ? null : { name: option.enum.name, values: sorted(option.enum.values) }, + }); +} + +function sorted(values: unknown): unknown { + if (values === null || typeof values !== 'object') { + return values; + } + return Object.fromEntries( + Object.entries(values as Record).sort(([a], [b]) => a.localeCompare(b)), + ); +} + +export interface CheckInput { + platform: Platform; + /** The version native-versions.json pins. */ + pinnedVersion: string; + published: PublishedManifest; + /** Every user-facing key the package lists for the platform: the shared keys plus its own. */ + knownKeys: readonly string[]; + /** The committed Android manifest, compared option by option. iOS has none. */ + committed?: readonly PublishedOption[]; +} + +/** + * Every way the published manifest and the committed fixtures disagree; empty means aligned. + * + * Hidden options are internals (`$$ENDPOINT`, `$$WRAPPER`): they are not part of the user-facing + * key lists, so they are left out of the key comparison. The committed Android manifest does + * include them, and is compared in full. + */ +export function checkPublished(input: CheckInput): string[] { + const { platform, pinnedVersion, published, knownKeys, committed } = input; + const problems: string[] = []; + + if (published.sdk !== platform) { + problems.push(`the manifest is for sdk "${published.sdk}", not "${platform}"`); + } + if (published.sdkVersion !== pinnedVersion) { + problems.push( + `the manifest is for ${published.sdkVersion}, but native-versions.json pins ${pinnedVersion}`, + ); + } + + const publishedKeys = new Set( + published.options.filter((option) => option.hidden !== true).map((option) => option.key), + ); + const known = new Set(knownKeys); + for (const key of [...publishedKeys].sort()) { + if (!known.has(key)) { + problems.push( + `the ${platform} SDK registers ${key}, which this package does not list: add it to ` + + 'option-keys.json (cli-extract-option-keys.ts) and give it an accessor', + ); + } + } + for (const key of [...known].sort()) { + if (!publishedKeys.has(key)) { + problems.push( + `this package lists ${key} for ${platform}, which the ${pinnedVersion} SDK does not register, ` + + 'so setting it would be silently ignored', + ); + } + } + + if (committed !== undefined) { + const have = new Map(committed.map((option) => [option.key, option])); + const want = new Map(published.options.map((option) => [option.key, option])); + for (const [key, option] of [...want].sort(([a], [b]) => a.localeCompare(b))) { + const ours = have.get(key); + if (ours === undefined) { + problems.push(`android-options-manifest.json is missing ${key}`); + } else if (describe(ours) !== describe(option)) { + problems.push( + `android-options-manifest.json differs from the published manifest for ${key}: ` + + `committed ${describe(ours)}, published ${describe(option)}`, + ); + } + } + for (const key of [...have.keys()].sort()) { + if (!want.has(key)) { + problems.push(`android-options-manifest.json has ${key}, which the published manifest does not`); + } + } + } + + return problems; +} From c8945dd4c771144380e91733d849509b870cef9d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 13:31:36 +0500 Subject: [PATCH 09/16] Address review: 6.x warning advice follows the running platform The legacy-name message claimed the iOS SDK still maps every 6.x name and recommended the 7.x key even when only the other platform has it. It now: - says the iOS SDK maps only the names in its own alias table (copied from the 7.0.0 source into IOS_MAPPED_LEGACY_KEYS); the 6.x Android names (ShakeToTrigger, LogLevel, VideoQuality, HandleAnr, ...) are ignored by both SDKs; - gives no "use this key" advice when the 7.x key is the other platform's (NotificationBarTrigger and VideoMode on iOS, BugseeStyle on Android), and says there is no equivalent option; - is tested to recommend only keys the running platform accepts. Human guided, AI implemented --- .../src/options/__tests__/unknownKeys.test.ts | 41 +++++++++++++++++ .../react-native/src/options/unknownKeys.ts | 45 ++++++++++++++++--- 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/packages/react-native/src/options/__tests__/unknownKeys.test.ts b/packages/react-native/src/options/__tests__/unknownKeys.test.ts index f97c9971..e2d7d927 100644 --- a/packages/react-native/src/options/__tests__/unknownKeys.test.ts +++ b/packages/react-native/src/options/__tests__/unknownKeys.test.ts @@ -49,6 +49,47 @@ describe('describeUnknownKey', () => { expect(describeUnknownKey('ios', 'ShakeToReport')).toMatch(/Android SDK ignores it/); }); + it('reports that neither SDK maps a 6.x name the iOS SDK has no alias for', () => { + // ShakeToTrigger, VideoQuality and LogLevel are 6.x Android names; the iOS alias table lacks them. + for (const key of ['ShakeToTrigger', 'VideoQuality', 'LogLevel', 'HandleAnr']) { + const message = describeUnknownKey('ios', key); + expect(message).toContain('Neither SDK maps it'); + expect(message).not.toContain('iOS SDK still maps it'); + } + }); + + it('does not send a platform to a 7.x key only the other platform has', () => { + // NotificationBarTrigger -> notification-bar is Android-only; BugseeStyle -> ui.style is iOS-only. + const onIos = describeUnknownKey('ios', 'NotificationBarTrigger'); + expect(onIos).toContain('no equivalent 7.x option'); + expect(onIos).toContain('Android-only'); + expect(onIos).not.toContain('Use "'); + expect(onIos).not.toContain('still maps'); + + const onAndroid = describeUnknownKey('android', 'BugseeStyle'); + expect(onAndroid).toContain('no equivalent 7.x option'); + expect(onAndroid).toContain('iOS-only'); + expect(onAndroid).not.toContain('Use "'); + + expect(describeUnknownKey('ios', 'VideoMode')).toContain('no equivalent 7.x option'); + }); + + it('only recommends a key the running platform accepts', () => { + for (const platform of ['ios', 'android'] as const) { + for (const key of Object.keys(LEGACY_OPTION_KEYS)) { + const recommended = /Use "([^"]+)"/.exec(describeUnknownKey(platform, key))?.[1]; + if (recommended !== undefined) { + expect(keysFor(platform).has(recommended)).toBe(true); + } + } + } + }); + + it('still says a mapped 6.x name works on iOS but not Android, and an Android name is ignored on both', () => { + expect(describeUnknownKey('ios', 'ScreenshotToReport')).toContain('iOS SDK still maps it'); + expect(describeUnknownKey('android', 'ShakeToTrigger')).toContain('Android SDK ignores it'); + }); + it('suggests the nearest key for a typo', () => { expect( describeUnknownKey('android', 'com.bugsee.option.reporting.triggers.shak'), diff --git a/packages/react-native/src/options/unknownKeys.ts b/packages/react-native/src/options/unknownKeys.ts index 06b643b0..4fbd2823 100644 --- a/packages/react-native/src/options/unknownKeys.ts +++ b/packages/react-native/src/options/unknownKeys.ts @@ -57,6 +57,22 @@ export const LEGACY_OPTION_KEYS: Readonly> = { PerformanceAdaptiveSampling: 'com.bugsee.option.performance.adaptive-sampling', }; +/** + * The 6.x names the iOS SDK itself maps onto 7.x keys (its `legacyKeyAliases`, read from the 7.0.0 + * source). Only these keep working on iOS; every other name in {@link LEGACY_OPTION_KEYS} is ignored + * there as well. Copied rather than derived because the SDK does not publish it. + */ +const IOS_MAPPED_LEGACY_KEYS: ReadonlySet = new Set([ + 'MaxRecordingTime', 'WifiOnlyUpload', 'NotifyFlushDelay', 'MaxDataSize', + 'CrashReport', 'DetectAppExit', 'MonitorNetwork', 'bodySizeLimit', 'SanitizeNetworkData', + 'VideoEnabled', 'ScreenshotEnabled', 'VideoScale', 'FrameRate', 'ViewHierarchyEnabled', 'CaptureLogs', + 'ShakeToReport', 'ScreenshotToReport', + 'BugseeDefaultCrashPriority', 'BugseeDefaultBugPriority', 'BugseeDefaultErrorPriority', + 'ReportSummaryRequired', 'ReportDescriptionRequired', 'ReportEmailRequired', + 'ReportLabelsEnabled', 'ReportLabelsRequired', 'BugseeReportPrioritySelector', 'BugseeStyle', + 'PerformanceMonitoring', 'PerformanceSampleRate', 'PerformanceAdaptiveSampling', +]); + /** Edit distance, capped: a distance past `limit` is as good as any other. */ function distance(a: string, b: string, limit: number): number { if (Math.abs(a.length - b.length) > limit) { @@ -99,6 +115,29 @@ export function unknownOptionKeys( return Object.keys(options).filter((key) => !known.has(key)); } +/** + * What happens to a 6.x name on this platform, and what to use instead. The advice depends on the + * platform twice over: the iOS SDK maps only some of these names, and the 7.x key a name points at may + * exist on the other platform only (`NotificationBarTrigger` is Android's, `BugseeStyle` is iOS's). + */ +function describeLegacyKey(platform: Platform, key: string, replacement: string): string { + const sdk = platform === 'ios' ? 'iOS' : 'Android'; + const usable = keysFor(platform).has(replacement); + if (!usable) { + return ( + `[Bugsee] "${key}" is a 6.x option name, and the ${sdk} SDK has no equivalent 7.x option ` + + `("${replacement}" is ${platform === 'ios' ? 'Android' : 'iOS'}-only), so it has no effect.` + ); + } + const effect = + platform === 'android' + ? 'The Android SDK ignores it, so the setting has NO effect there' + : IOS_MAPPED_LEGACY_KEYS.has(key) + ? 'The iOS SDK still maps it, but the Android SDK ignores it' + : 'Neither SDK maps it, so the setting has NO effect'; + return `[Bugsee] "${key}" is a 6.x option name. ${effect}. Use "${replacement}" (or its accessor on the launch options object).`; +} + /** One sentence naming the key, what the SDK does with it, and what to use. */ export function describeUnknownKey(platform: Platform, key: string): string { const sdk = platform === 'ios' ? 'iOS' : 'Android'; @@ -108,11 +147,7 @@ export function describeUnknownKey(platform: Platform, key: string): string { ? LEGACY_OPTION_KEYS[key] : undefined; if (legacy !== undefined) { - const effect = - platform === 'android' - ? 'The Android SDK ignores it, so the setting has NO effect there' - : 'The iOS SDK still maps it, but the Android SDK ignores it'; - return `[Bugsee] "${key}" is a 6.x option name. ${effect}. Use "${legacy}" (or its accessor on the launch options object).`; + return describeLegacyKey(platform, key, legacy); } const suggestion = closestKey(platform, key); const hint = suggestion === undefined ? '' : ` Did you mean "${suggestion}"?`; From 7a6056b6408cdf6f572ad9a66cfc22377a4552c0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 13:38:32 +0500 Subject: [PATCH 10/16] Check the accessors, types and defaults against the published manifests The published-manifest gate compared key lists only. It now also fails, naming the option, when an SDK publishes something this package does not match: - an option with no accessor on the options classes ("MISSING OPTION (, default ) is in the android SDK 7.4.2 manifest but AndroidLaunchOptions has no accessor for it"), an accessor with no setter, or one whose declared type cannot hold the SDK's; - an enum whose TypeScript constants differ from the SDK's; - a committed manifest (now both android-options-manifest.json and the new ios-options-manifest.json) whose type, DEFAULT, hidden flag, deprecation or enum constants differ from the published one; - docs/launch-options.md out of date: it is now generated from the accessors and the manifests, so its type, platform and default for every option are the SDK's. It is deliberately one-directional. An option or accessor this package has and the SDK does not publish is never reported: the package may define options of its own, sent to the SDK (which ignores them) and acted on only in React Native (RN_OPTION_KEYS keeps the unknown-key warning quiet for them; the doc marks them "React Native only"). Adding defaults to the comparison found a real defect: the descriptor parser stored the Java expression "1024 * 20" as the network body limit's default where the SDK publishes 20480. Fixed and regenerated. Human guided, AI implemented --- docs/launch-options.md | 242 +++---- .../src/options/BugseeLaunchOptions.ts | 2 +- .../src/options/__tests__/keys.test.ts | 15 + .../src/options/android-options-manifest.json | 4 +- .../src/options/ios-options-manifest.json | 594 ++++++++++++++++++ packages/react-native/src/options/keys.ts | 21 +- .../react-native/src/options/noAccessor.ts | 16 + scripts/__tests__/launch-options-doc.test.ts | 166 +++++ scripts/__tests__/option-accessors.test.ts | 110 ++++ scripts/__tests__/option-keys.test.ts | 4 + scripts/__tests__/published-manifest.test.ts | 244 ++++++- scripts/cli-check-published-manifests.ts | 142 +++-- scripts/cli-generate-launch-options-doc.ts | 20 + scripts/cli-options-sources.ts | 64 ++ scripts/launch-options-doc.ts | 122 ++++ scripts/option-accessors.ts | 67 ++ scripts/option-keys.ts | 6 + scripts/published-manifest.ts | 186 +++++- 18 files changed, 1826 insertions(+), 199 deletions(-) create mode 100644 packages/react-native/src/options/ios-options-manifest.json create mode 100644 packages/react-native/src/options/noAccessor.ts create mode 100644 scripts/__tests__/launch-options-doc.test.ts create mode 100644 scripts/__tests__/option-accessors.test.ts create mode 100644 scripts/cli-generate-launch-options-doc.ts create mode 100644 scripts/cli-options-sources.ts create mode 100644 scripts/launch-options-doc.ts create mode 100644 scripts/option-accessors.ts diff --git a/docs/launch-options.md b/docs/launch-options.md index b32c6977..be79c010 100644 --- a/docs/launch-options.md +++ b/docs/launch-options.md @@ -15,7 +15,11 @@ await Bugsee.launch('', options); The tables are checked against the SDK versions pinned in `native-versions.json` (Android 7.4.2, iOS 7.0.0): a test fails when either SDK registers an option this package has no accessor for, and `yarn check:options-manifests` (run in CI and before every publish) compares the option manifest each SDK release published at -`download.bugsee.com/sdk/options//.json` with this package's fixtures and fails on any difference. Options a +`download.bugsee.com/sdk/options//.json` with this package. It fails when an SDK publishes an option +this package lacks (named in the message), or an option whose type, default or enum constants differ. It does not +complain about an option this package has and the SDK does not publish: the package may define options of its own, +which the SDK ignores. The tables below are generated from the accessors and those manifests +(`node scripts/cli-generate-launch-options-doc.ts`), and the check fails when they are stale. Options a *newer* SDK adds are reachable with `options.setCustomOption(key, value)` until the package catches up. ## Keys the SDK drops @@ -39,135 +43,137 @@ iOS, does nothing on Android, and reports nothing on either. `launch()` and `rel ### Reporting triggers and dialog -| Accessor | Option key | Type | Platforms | Notes | -|---|---|---|---|---| -| `reportingDefaultBugPriority` | `com.bugsee.option.reporting.defaults.bug-priority` | `IssueSeverity` | iOS, Android | Default priority of bug reports; see `IssueSeverity`. | -| `reportingDefaultCrashPriority` | `com.bugsee.option.reporting.defaults.crash-priority` | `IssueSeverity` | iOS, Android | Default priority of crash reports; see `IssueSeverity`. | -| `reportingDefaultErrorPriority` | `com.bugsee.option.reporting.defaults.error-priority` | `IssueSeverity` | iOS, Android | Default priority of error reports; see `IssueSeverity`. | -| `triggerByBroadcast` | `com.bugsee.option.reporting.triggers.broadcast` | `boolean` | Android | Let a broadcast open the report dialog. | -| `triggerByNotification` | `com.bugsee.option.reporting.triggers.notification-bar` | `boolean` | Android | Let the user open the report dialog from the notification bar. The SDK default is on. | -| `triggerByScreenshot` | `com.bugsee.option.reporting.triggers.screenshot` | `boolean` | iOS, Android | Let the user open the report dialog by taking a screenshot. | -| `triggerByShake` | `com.bugsee.option.reporting.triggers.shake` | `boolean` | iOS, Android | Let the user open the report dialog by shaking the device. **The SDK default is on:** set this to `false` to turn shake-to-report off. | -| `reportingUIDescriptionRequired` | `com.bugsee.option.reporting.ui.description-required` | `boolean` | iOS, Android | Make the Description field mandatory in the report dialog. | -| `reportingUIEmailRequired` | `com.bugsee.option.reporting.ui.email-required` | `boolean` | iOS, Android | Make the Email field mandatory in the report dialog. | -| `reportingUILabelsEnabled` | `com.bugsee.option.reporting.ui.labels-enabled` | `boolean` | iOS, Android | Show the Labels field in the report dialog. | -| `reportingUILabelsRequired` | `com.bugsee.option.reporting.ui.labels-required` | `boolean` | iOS, Android | Make the Labels field mandatory in the report dialog. | -| `reportingUIPrioritySelectorEnabled` | `com.bugsee.option.reporting.ui.priority-selector-enabled` | `boolean` | iOS, Android | Let the user change the priority in the report dialog. | -| `reportingUIStyle` | `com.bugsee.option.reporting.ui.style` | `ReportingUIStyle` | iOS | Appearance of the report dialog; see `ReportingUIStyle`. | -| `reportingUISummaryRequired` | `com.bugsee.option.reporting.ui.summary-required` | `boolean` | iOS, Android | Make the Summary field mandatory in the report dialog. | +| Accessor | Option key | Type | Platforms | Default | Notes | +|---|---|---|---|---|---| +| `reportingDefaultBugPriority` | `com.bugsee.option.reporting.defaults.bug-priority` | `enum IssueSeverity` | iOS, Android | `High` | Default priority of bug reports; see `IssueSeverity`. | +| `reportingDefaultCrashPriority` | `com.bugsee.option.reporting.defaults.crash-priority` | `enum IssueSeverity` | iOS, Android | `Blocker` | Default priority of crash reports; see `IssueSeverity`. | +| `reportingDefaultErrorPriority` | `com.bugsee.option.reporting.defaults.error-priority` | `enum IssueSeverity` | iOS, Android | `High` | Default priority of error reports; see `IssueSeverity`. | +| `triggerByBroadcast` | `com.bugsee.option.reporting.triggers.broadcast` | `boolean` | Android | `false` | Let a broadcast open the report dialog. | +| `triggerByNotification` | `com.bugsee.option.reporting.triggers.notification-bar` | `boolean` | Android | `true` | Let the user open the report dialog from the notification bar. The SDK default is on. | +| `triggerByScreenshot` | `com.bugsee.option.reporting.triggers.screenshot` | `boolean` | iOS, Android | `false` | Let the user open the report dialog by taking a screenshot. | +| `triggerByShake` | `com.bugsee.option.reporting.triggers.shake` | `boolean` | iOS, Android | `true` | Let the user open the report dialog by shaking the device. **The SDK default is on:** set this to `false` to turn shake-to-report off. | +| `reportingUIDescriptionRequired` | `com.bugsee.option.reporting.ui.description-required` | `boolean` | iOS, Android | `false` | Make the Description field mandatory in the report dialog. | +| `reportingUIEmailRequired` | `com.bugsee.option.reporting.ui.email-required` | `boolean` | iOS, Android | `false` | Make the Email field mandatory in the report dialog. | +| `reportingUILabelsEnabled` | `com.bugsee.option.reporting.ui.labels-enabled` | `boolean` | iOS, Android | `false` | Show the Labels field in the report dialog. | +| `reportingUILabelsRequired` | `com.bugsee.option.reporting.ui.labels-required` | `boolean` | iOS, Android | `false` | Make the Labels field mandatory in the report dialog. | +| `reportingUIPrioritySelectorEnabled` | `com.bugsee.option.reporting.ui.priority-selector-enabled` | `boolean` | iOS, Android | `false` | Let the user change the priority in the report dialog. | +| `reportingUIStyle` | `com.bugsee.option.reporting.ui.style` | `enum BugseeStyle` | iOS | `System` | Appearance of the report dialog; see `ReportingUIStyle`. | +| `reportingUISummaryRequired` | `com.bugsee.option.reporting.ui.summary-required` | `boolean` | iOS, Android | `false` | Make the Summary field mandatory in the report dialog. | ### Capture -| Accessor | Option key | Type | Platforms | Notes | -|---|---|---|---|---| -| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | Capture `AVPlayer` content. | -| `captureBluetoothStatus` | `com.bugsee.option.capture.bluetooth-status` | `boolean` | iOS | Record the Bluetooth status. | -| `captureBreadcrumbs` | `com.bugsee.option.capture.breadcrumbs` | `boolean` | iOS, Android | Capture breadcrumbs (user and system events). | -| `captureBreadcrumbsExtras` | `com.bugsee.option.capture.breadcrumbs.extras` | `boolean` | iOS, Android | Attach the extra detail of automatically collected device-event breadcrumbs. | -| `captureCameraPreview` | `com.bugsee.option.capture.camera-preview` | `boolean` | iOS | Capture camera preview layers. Read the iOS SDK's privacy and overhead notes before enabling. | -| `crashHandlerType` | `com.bugsee.option.capture.crash-handler-type` | `CrashHandlerType` | iOS | How the crash reporter intercepts crashes; see `CrashHandlerType`. Unset leaves the SDK default, `CrashHandlerType.MachAndBSD`. | -| `crashSignals` | `com.bugsee.option.capture.crash-signals` | `number` | iOS | The fatal signals the crash reporter intercepts, as the iOS SDK's `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, TRAP 32. Unset leaves the SDK default (every signal). Added in 7.0.0-beta7. | -| `captureDeviceAndNetworkNames` | `com.bugsee.option.capture.device-network-names` | `boolean` | iOS | Record the device and network names. | -| `captureDiskSpace` | `com.bugsee.option.capture.disk-space` | `boolean` | iOS | Record free disk space. | -| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | Capture logs. Lines sent with `Bugsee.log()` are always recorded. | -| `logsUseAllSources` | `com.bugsee.option.capture.logs.allsources` | `boolean` | Android | Query every logging source (system, radio, ...) rather than only the default ones. | -| `captureLogsLevel` | `com.bugsee.option.capture.logs.level` | `LogLevel` | iOS, Android | Least severe level captured; see `LogLevel`. | -| `captureOSLogs` | `com.bugsee.option.capture.logs.oslog` | `boolean` | iOS | Has no effect: the iOS SDK accepts the key and ignores it. | -| `captureNetwork` | `com.bugsee.option.capture.network` | `boolean` | iOS, Android | Capture network events. | -| `captureNetworkBodySizeLimit` | `com.bugsee.option.capture.network.body-size-limit` | `number` | iOS, Android | Largest request or response body captured, in bytes. | -| `captureNetworkBodyWithoutType` | `com.bugsee.option.capture.network.body-without-type` | `boolean` | iOS, Android | Also capture bodies that declare no content type. Off keeps only textual bodies. | -| `captureNetworkUseDefaultSanitizer` | `com.bugsee.option.capture.network.default-sanitizer` | `boolean` | iOS, Android | Redact known-sensitive values (query parameters, headers, JSON bodies) when no network filter is set. | -| `captureNetworkOnLaunch` | `com.bugsee.option.capture.network.on-launch` | `boolean` | iOS, Android | Subscribe network capture synchronously during launch, so requests issued in the launch window are seen. | -| `captureOnDeviceSymbolication` | `com.bugsee.option.capture.on-device-symbolication` | `boolean` | iOS | Symbolicate stack traces on the device. | -| `captureRespectFlagSecure` | `com.bugsee.option.capture.respect-flag-secure` | `boolean` | Android | Honour `FLAG_SECURE`: blank secure windows in capture and treat such an activity as a full blackout. | -| `captureSampleBufferDisplayLayer` | `com.bugsee.option.capture.sample-buffer-display-layer` | `boolean` | iOS | Capture `AVSampleBufferDisplayLayer` content. | -| `captureScreenshot` | `com.bugsee.option.capture.screenshot` | `boolean` | iOS, Android | Capture screenshots for reports, independent of video. | -| `captureScreenshotScale` | `com.bugsee.option.capture.screenshot.scale` | `number` | iOS, Android | Privacy scaling applied to screenshots; below `1` removes fine detail such as text. | -| `captureStatusBarInfo` | `com.bugsee.option.capture.status-bar-info` | `boolean` | iOS | Show capture status in the status bar. Debug builds only; ignored in release. | -| `captureVideo` | `com.bugsee.option.capture.video` | `boolean` | iOS, Android | Record video for reports. | -| `captureVideoAdaptive` | `com.bugsee.option.capture.video.adaptive` | `boolean` | iOS, Android | Skip capture work while the screen is idle. The SDKs' own defaults differ. | -| `captureVideoUsingCustomMuxer` | `com.bugsee.option.capture.video.custom-muxer` | `boolean` | Android | Use a lightweight MP4 muxer instead of `MediaMuxer`. | -| `captureVideoFrameRate` | `com.bugsee.option.capture.video.frame-rate` | `FrameRate` | iOS, Android | How often frames are captured; see `FrameRate`. | -| `captureVideoFullscreenKeepRunning` | `com.bugsee.option.capture.video.fullscreen-keep-running` | `boolean` | Android | Keep fullscreen (MediaProjection) capture running while the app is in the background. | -| `captureVideoFullscreenRememberUserDecision` | `com.bugsee.option.capture.video.fullscreen-remember-decision` | `boolean` | Android | Remember the user's screen-capture consent decision across launches. | -| `captureVideoMaxFramerate` | `com.bugsee.option.capture.video.max-frame-rate` | `number` | iOS | Highest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | -| `captureVideoMinFramerate` | `com.bugsee.option.capture.video.min-frame-rate` | `number` | iOS | Lowest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | -| `videoMode` | `com.bugsee.option.capture.video.mode` | `VideoMode` | Android | Screen-capture mode; see `VideoMode`. | -| `captureVideoPrivacyBlur` | `com.bugsee.option.capture.video.privacy-blur` | `boolean` | iOS | Blur transition frames instead of skipping them. | -| `captureVideoQuality` | `com.bugsee.option.capture.video.quality` | `VideoQuality` | iOS, Android | Quality of the encoded video; see `VideoQuality`. | -| `captureVideoScale` | `com.bugsee.option.capture.video.scale` | `number` | iOS, Android | Extra down-scaling of recorded video; `0.5` halves width and height. | -| `captureVideoSecureScrolling` | `com.bugsee.option.capture.video.secure-scrolling` | `boolean` | Android | In `VideoMode.V1`, skip more frames while secure views are on screen. | -| `captureViewHierarchy` | `com.bugsee.option.capture.view-hierarchy` | `boolean` | iOS, Android | Capture the view hierarchy for reports. | -| `captureWebSocket` | `com.bugsee.option.capture.websocket` | `boolean` | iOS | Capture WebSocket traffic. | -| `captureWebViewAdvanced` | `com.bugsee.option.capture.webview.advanced` | `boolean` | iOS, Android | Inject the advanced WebView SDK into instrumented WebViews for full-fidelity in-page capture. | -| `captureWebViewDomainAllowlist` | `com.bugsee.option.capture.webview.domain-allowlist` | `string` | Android | Has no effect: the SDK no longer scopes WebView capture by domain. | -| `captureWebViewReportTrigger` | `com.bugsee.option.capture.webview.report-trigger` | `boolean` | iOS, Android | Let an incident raised inside an instrumented WebView open a native bug report. | +| Accessor | Option key | Type | Platforms | Default | Notes | +|---|---|---|---|---|---| +| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | `false` | Launch options for iOS, adding the keys only that SDK accepts. */ export class IOSLaunchOptions extends BugseeLaunchOptions { /** The API endpoint override. Reads back what the SDK will actually receive rather than what was assigned, because the two differ on iOS. / get endpoint(): string \| undefined { return this.$get(IOS_ENDPOINT_KEY); } set endpoint(value: string \| undefined) { const payload = endpointFor('ios', value); this.$set(IOS_ENDPOINT_KEY, payload[IOS_ENDPOINT_KEY]); } /** Capture `AVPlayer` content. | +| `captureBluetoothStatus` | `com.bugsee.option.capture.bluetooth-status` | `boolean` | iOS | `false` | Record the Bluetooth status. | +| `captureBreadcrumbs` | `com.bugsee.option.capture.breadcrumbs` | `boolean` | iOS, Android | `false` | Capture breadcrumbs (user and system events). | +| `captureBreadcrumbsExtras` | `com.bugsee.option.capture.breadcrumbs.extras` | `boolean` | iOS, Android | `false` | Attach the extra detail of automatically collected device-event breadcrumbs. | +| `captureCameraPreview` | `com.bugsee.option.capture.camera-preview` | `boolean` | iOS | `false` | Capture camera preview layers. Read the iOS SDK's privacy and overhead notes before enabling. | +| `crashHandlerType` | `com.bugsee.option.capture.crash-handler-type` | `enum BugseeCrashHandlerType` | iOS | `MachAndBSD` | How the crash reporter intercepts crashes; see `CrashHandlerType`. Unset leaves the SDK default, `CrashHandlerType.MachAndBSD`. | +| `crashSignals` | `com.bugsee.option.capture.crash-signals` | `int` | iOS | `128` | The fatal signals the crash reporter intercepts, as the iOS SDK's `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, TRAP 32. Unset leaves the SDK default (every signal). Added in 7.0.0-beta7. | +| `captureDeviceAndNetworkNames` | `com.bugsee.option.capture.device-network-names` | `boolean` | iOS | `false` | Record the device and network names. | +| `captureDiskSpace` | `com.bugsee.option.capture.disk-space` | `boolean` | iOS | `false` | Record free disk space. | +| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | `true` | Launch options, keyed by the SDKs' real 7.x option keys. Both platforms accept the same `com.bugsee.option.*` namespace in 7.x, so there is no translation layer here and no per-platform key mapping — the map IS the payload. That is what makes `BugseeLaunchOptions.setCustomOption` genuinely useful: a custom key and a first-class accessor write to the same namespace, so an option the wrapper has not surfaced yet, including one added in a future 7.x patch, is reachable with no wrapper release. Subclasses add the accessors for their platform; see `AndroidLaunchOptions` and `IOSLaunchOptions`. / export abstract class BugseeLaunchOptions { /** Sent to the native SDK verbatim. */ private readonly nativeOptions = new Map(); /** JS-only settings for the wrapper's own components, kept in a separate map so they cannot reach the native payload. The native SDK never agreed to these keys; one arriving there is at best ignored and at worst rejects the launch. / private readonly localOptions = new Map(); /** What the SDK last said is in effect. Read by getters, never serialised: sending these back would hand the SDK its own defaults as if the app had chosen them. / private reportedOptions = new Map(); /** Writes a native option. `undefined` **deletes** the key rather than storing an empty value: the payload must not carry a key the caller meant to leave alone, or the native side takes it as an explicit override of the SDK's own default. / protected $set(key: string, value: unknown): void { if (value === undefined) { this.nativeOptions.delete(key); return; } this.nativeOptions.set(key, value); } /** What the app set, or failing that what the SDK last reported. The wrapper hardcodes no defaults. The 6.x implementation did, and drifted: it shipped `videoMode = V3` after 7.x removed that value. The SDKs know their own defaults; Android reports them even before launch. / protected $get(key: string): T \| undefined { if (this.nativeOptions.has(key)) { return this.nativeOptions.get(key) as T; } return this.reportedOptions.get(key) as T \| undefined; } /** Writes a JS-only option. `undefined` deletes, as with `$set`. */ protected $setLocal(key: string, value: unknown): void { if (value === undefined) { this.localOptions.delete(key); return; } this.localOptions.set(key, value); } protected $getLocal(key: string): T \| undefined { return this.localOptions.get(key) as T \| undefined; } // Accessors for options BOTH platforms accept. Platform-specific ones // live on the subclasses, so an iOS-only key is not reachable from an // Android options object. /** Capture logs. Lines sent with `Bugsee.log()` are always recorded. | +| `logsUseAllSources` | `com.bugsee.option.capture.logs.allsources` | `boolean` | Android | `false` | Launch options for Android, adding the keys only that SDK accepts. */ export class AndroidLaunchOptions extends BugseeLaunchOptions { /** The API endpoint override. Reads back what the SDK will actually receive rather than what was assigned, because the two differ on iOS. / get endpoint(): string \| undefined { return this.$get(ANDROID_ENDPOINT_KEY); } set endpoint(value: string \| undefined) { const payload = endpointFor('android', value); this.$set(ANDROID_ENDPOINT_KEY, payload[ANDROID_ENDPOINT_KEY]); } /** Query every logging source (system, radio, ...) rather than only the default ones. | +| `captureLogsLevel` | `com.bugsee.option.capture.logs.level` | `enum LogLevel` | iOS, Android | `Verbose` | Least severe level captured; see `LogLevel`. Also accepts a plain `number`, which this accessor always took, so a level read from config still compiles. | +| `captureOSLogs` | `com.bugsee.option.capture.logs.oslog` | `boolean` | iOS | `false` | Has no effect: the iOS SDK accepts the key and ignores it. **Deprecated** — The iOS SDK permanently disables OSLog capture. | +| `captureNetwork` | `com.bugsee.option.capture.network` | `boolean` | iOS, Android | `true` | Capture network events. | +| `captureNetworkBodySizeLimit` | `com.bugsee.option.capture.network.body-size-limit` | `int` | iOS, Android | `20480` | Largest request or response body captured, in bytes. | +| `captureNetworkBodyWithoutType` | `com.bugsee.option.capture.network.body-without-type` | `boolean` | iOS, Android | `false` | Also capture bodies that declare no content type. Off keeps only textual bodies. | +| `captureNetworkUseDefaultSanitizer` | `com.bugsee.option.capture.network.default-sanitizer` | `boolean` | iOS, Android | `true` | Redact known-sensitive values (query parameters, headers, JSON bodies) when no network filter is set. | +| `captureNetworkOnLaunch` | `com.bugsee.option.capture.network.on-launch` | `boolean` | iOS, Android | `false` | Subscribe network capture synchronously during launch, so requests issued in the launch window are seen. | +| `captureOnDeviceSymbolication` | `com.bugsee.option.capture.on-device-symbolication` | `boolean` | iOS | `false` | Symbolicate stack traces on the device. | +| `captureRespectFlagSecure` | `com.bugsee.option.capture.respect-flag-secure` | `boolean` | Android | `true` | Honour `FLAG_SECURE`: blank secure windows in capture and treat such an activity as a full blackout. | +| `captureSampleBufferDisplayLayer` | `com.bugsee.option.capture.sample-buffer-display-layer` | `boolean` | iOS | `false` | Capture `AVSampleBufferDisplayLayer` content. | +| `captureScreenshot` | `com.bugsee.option.capture.screenshot` | `boolean` | iOS, Android | `true` | Capture screenshots for reports, independent of video. | +| `captureScreenshotScale` | `com.bugsee.option.capture.screenshot.scale` | `float` | iOS, Android | `1` | Privacy scaling applied to screenshots; below `1` removes fine detail such as text. | +| `captureStatusBarInfo` | `com.bugsee.option.capture.status-bar-info` | `boolean` | iOS | `false` | Show capture status in the status bar. Debug builds only; ignored in release. | +| `captureVideo` | `com.bugsee.option.capture.video` | `boolean` | iOS, Android | `true` | Record video for reports. | +| `captureVideoAdaptive` | `com.bugsee.option.capture.video.adaptive` | `boolean` | iOS, Android | Android `false` · iOS `true` | Skip capture work while the screen is idle. The SDKs' own defaults differ. | +| `captureVideoUsingCustomMuxer` | `com.bugsee.option.capture.video.custom-muxer` | `boolean` | Android | `false` | Use a lightweight MP4 muxer instead of `MediaMuxer`. | +| `captureVideoFrameRate` | `com.bugsee.option.capture.video.frame-rate` | `enum FrameRate` | iOS, Android | `High` | How often frames are captured; see `FrameRate`. | +| `captureVideoFullscreenKeepRunning` | `com.bugsee.option.capture.video.fullscreen-keep-running` | `boolean` | Android | `true` | Keep fullscreen (MediaProjection) capture running while the app is in the background. | +| `captureVideoFullscreenRememberUserDecision` | `com.bugsee.option.capture.video.fullscreen-remember-decision` | `boolean` | Android | `true` | Remember the user's screen-capture consent decision across launches. | +| `captureVideoMaxFramerate` | `com.bugsee.option.capture.video.max-frame-rate` | `int` | iOS | `0` | Highest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | +| `captureVideoMinFramerate` | `com.bugsee.option.capture.video.min-frame-rate` | `int` | iOS | `0` | Lowest frame rate captured, `0` to `30`; `0` leaves it to `captureVideoFrameRate`. | +| `videoMode` | `com.bugsee.option.capture.video.mode` | `enum VideoMode` | Android | `V2` | Screen-capture mode; see `VideoMode`. Also accepts a plain `number`, which this accessor always took, so a value read from config still compiles. | +| `captureVideoPrivacyBlur` | `com.bugsee.option.capture.video.privacy-blur` | `boolean` | iOS | `true` | Blur transition frames instead of skipping them. | +| `captureVideoQuality` | `com.bugsee.option.capture.video.quality` | `enum VideoQuality` | iOS, Android | `Default` | Quality of the encoded video; see `VideoQuality`. | +| `captureVideoScale` | `com.bugsee.option.capture.video.scale` | `float` | iOS, Android | `1` | Extra down-scaling of recorded video; `0.5` halves width and height. | +| `captureVideoSecureScrolling` | `com.bugsee.option.capture.video.secure-scrolling` | `boolean` | Android | `false` | In `VideoMode.V1`, skip more frames while secure views are on screen. | +| `captureViewHierarchy` | `com.bugsee.option.capture.view-hierarchy` | `boolean` | iOS, Android | `true` | Capture the view hierarchy for reports. | +| `captureWebSocket` | `com.bugsee.option.capture.websocket` | `boolean` | iOS | `true` | Capture WebSocket traffic. | +| `captureWebViewAdvanced` | `com.bugsee.option.capture.webview.advanced` | `boolean` | iOS, Android | `true` | Inject the advanced WebView SDK into instrumented WebViews for full-fidelity in-page capture. | +| `captureWebViewDomainAllowlist` | `com.bugsee.option.capture.webview.domain-allowlist` | `string` | Android | `""` | Has no effect: the SDK no longer scopes WebView capture by domain. **Deprecated** — Android 7.1.2 deprecated this option and the SDK does not honour it. | +| `captureWebViewReportTrigger` | `com.bugsee.option.capture.webview.report-trigger` | `boolean` | iOS, Android | `false` | Let an incident raised inside an instrumented WebView open a native bug report. | ### Detection -| Accessor | Option key | Type | Platforms | Notes | -|---|---|---|---|---| -| `ndkIncludeTombstoneLogs` | `com.bugsee.option.crash-ndk.tombstone-logs` | `boolean` | Android | Attach the Android tombstone logs to NDK crash reports. | -| `detectAndReportAnomaly` | `com.bugsee.option.detect.anomaly` | `boolean` | iOS, Android | Detect and report performance anomalies. | -| `detectAndReportAnrSampling` | `com.bugsee.option.detect.anr.sampling` | `boolean` | Android | Sample the main thread during an ANR to attribute the report to culprit frames. | -| `detectAndReportCrash` | `com.bugsee.option.detect.crash` | `boolean` | iOS, Android | Detect and report crashes. | -| `detectAndReportNdkCrash` | `com.bugsee.option.detect.crash-ndk` | `boolean` | Android | Detect native (NDK) crashes. Needs `detectAndReportCrash`; this package bundles the NDK module. | -| `detectCrashFillEmptyExceptionStacks` | `com.bugsee.option.detect.crash.fill_empty_exception_stacks` | `boolean` | iOS | Fill the stack of an uncaught `NSException` that has none, which can change crash grouping. | -| `detectCrashSwiftAsyncStackTraces` | `com.bugsee.option.detect.crash.swift_async_stacktraces` | `boolean` | iOS | Stitch Swift async frames into C++ throw stacks (iOS 15+). | -| `detectAndReportEarlyCrash` | `com.bugsee.option.detect.early-crash` | `boolean` | iOS, Android | Recover crashes that happen during app start-up. | -| `detectAndReportExit` | `com.bugsee.option.detect.exit` | `boolean` | iOS, Android | Detect and report app exits. | -| `detectAndReportExitLowMemoryBackgroundAsError` | `com.bugsee.option.detect.exit.bg_low_memory_as_error` | `boolean` | Android | Report a low-memory kill of a process that was not in the foreground as a non-fatal error rather than a crash. Applies only while `detectAndReportExitLowMemory` is on. Android 7.3.0. | -| `detectAndReportExitDependencyDied` | `com.bugsee.option.detect.exit.dependency_died` | `boolean` | Android | Report exits caused by a dependency process dying. | -| `detectAndReportExitExcessiveResourceUsage` | `com.bugsee.option.detect.exit.excessive_resource_usage` | `boolean` | Android | Report exits caused by excessive resource usage. | -| `detectAndReportExitLowMemory` | `com.bugsee.option.detect.exit.low_memory` | `boolean` | Android | Report exits caused by low memory (the OOM killer). | -| `detectAndReportExitNotResponding` | `com.bugsee.option.detect.exit.not_responding` | `boolean` | Android | Report exits caused by the app not responding (ANR). | -| `detectAndReportExitNotRespondingAsCrash` | `com.bugsee.option.detect.exit.not_responding.as_crash` | `boolean` | Android | Report ANR exits as crashes instead of non-fatal errors. | -| `detectAndReportExitOther` | `com.bugsee.option.detect.exit.other` | `boolean` | Android | Report exits with an "other" reason. | -| `detectAndReportExitPackageStateChanged` | `com.bugsee.option.detect.exit.package_state_changed` | `boolean` | Android | Report exits caused by a package state change. | -| `detectAndReportExitPackageUpdated` | `com.bugsee.option.detect.exit.package_updated` | `boolean` | Android | Report exits caused by a package update. | -| `detectAndReportExitPermissionChanged` | `com.bugsee.option.detect.exit.permission_changed` | `boolean` | Android | Report exits caused by a runtime permission change. | -| `detectAndReportExitUnknown` | `com.bugsee.option.detect.exit.unknown` | `boolean` | Android | Report exits with an unknown reason. | -| `detectAndReportExitUserRequested` | `com.bugsee.option.detect.exit.user_requested` | `boolean` | Android | Report exits the user requested, such as a force stop. | -| `detectAndReportExitUserWasStopped` | `com.bugsee.option.detect.exit.user_was_stopped` | `boolean` | Android | Report exits caused by the system stopping the app. | -| `detectFrustration` | `com.bugsee.option.detect.frustration` | `boolean` | iOS, Android | Detect and report user-frustration patterns such as rage taps. | -| `detectAndReportHang` | `com.bugsee.option.detect.hang` | `boolean` | iOS, Android | Detect and report hangs. | -| `detectAndReportHangFairLevel` | `com.bugsee.option.detect.hang.level.fair` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "fair" hang. Less than the medium level. | -| `detectAndReportHangMediumLevel` | `com.bugsee.option.detect.hang.level.medium` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "medium" hang. | -| `detectAndReportHangSevereLevel` | `com.bugsee.option.detect.hang.level.severe` | `number` | iOS, Android | Main-thread block, in milliseconds, that raises a "severe" hang. Greater than the medium level. | -| `detectAndReportHangSampling` | `com.bugsee.option.detect.hang.sampling` | `boolean` | Android | Sample the main thread during a hang to attribute the report to culprit frames. Needs `detectAndReportHang`. | -| `detectAndReportHttpErrors` | `com.bugsee.option.detect.http-errors` | `boolean` | iOS, Android | Turn HTTP 5xx responses into error reports. | -| `detectAndReportMainThreadMisuse` | `com.bugsee.option.detect.main_thread_misuse` | `boolean` | iOS, Android | Detect and report blocking work on the main thread. | -| `detectMemoryLeaks` | `com.bugsee.option.detect.memory_leaks` | `boolean` | Android | Detect memory leaks. Honoured only when the app also depends on `com.bugsee:bugsee-android-leak`, which this package does not add. | -| `detectMemoryLeaksDeepSampleRate` | `com.bugsee.option.detect.memory_leaks.deep_sample_rate` | `number` | Android | Fraction of sessions that run the deep leak modes. Needs `bugsee-android-leak`. | -| `detectMemoryLeaksMode` | `com.bugsee.option.detect.memory_leaks.mode` | `MemoryLeakMode` | Android | Leak detection depth; see `MemoryLeakMode`. Needs `bugsee-android-leak`. | -| `detectThreadLeaks` | `com.bugsee.option.detect.thread_leaks` | `boolean` | Android | Detect thread leaks. Needs `bugsee-android-leak`. | +| Accessor | Option key | Type | Platforms | Default | Notes | +|---|---|---|---|---|---| +| `ndkIncludeTombstoneLogs` | `com.bugsee.option.crash-ndk.tombstone-logs` | `boolean` | Android | `false` | Attach the Android tombstone logs to NDK crash reports. | +| `detectAndReportAnomaly` | `com.bugsee.option.detect.anomaly` | `boolean` | iOS, Android | `false` | Detect and report performance anomalies. | +| `detectAndReportAnrSampling` | `com.bugsee.option.detect.anr.sampling` | `boolean` | Android | `true` | Sample the main thread during an ANR to attribute the report to culprit frames. | +| `detectAndReportCrash` | `com.bugsee.option.detect.crash` | `boolean` | iOS, Android | `true` | Detect and report crashes. | +| `detectAndReportNdkCrash` | `com.bugsee.option.detect.crash-ndk` | `boolean` | Android | `true` | Detect native (NDK) crashes. Needs `detectAndReportCrash`; this package bundles the NDK module. | +| `detectCrashFillEmptyExceptionStacks` | `com.bugsee.option.detect.crash.fill_empty_exception_stacks` | `boolean` | iOS | `false` | Fill the stack of an uncaught `NSException` that has none, which can change crash grouping. | +| `detectCrashSwiftAsyncStackTraces` | `com.bugsee.option.detect.crash.swift_async_stacktraces` | `boolean` | iOS | `true` | Stitch Swift async frames into C++ throw stacks (iOS 15+). | +| `detectAndReportEarlyCrash` | `com.bugsee.option.detect.early-crash` | `boolean` | iOS, Android | `true` | Recover crashes that happen during app start-up. | +| `detectAndReportExit` | `com.bugsee.option.detect.exit` | `boolean` | iOS, Android | `true` | Detect and report app exits. | +| `detectAndReportExitLowMemoryBackgroundAsError` | `com.bugsee.option.detect.exit.bg_low_memory_as_error` | `boolean` | Android | `false` | Report a low-memory kill of a process that was not in the foreground as a non-fatal error rather than a crash. Applies only while `detectAndReportExitLowMemory` is on. Android 7.3.0. | +| `detectAndReportExitDependencyDied` | `com.bugsee.option.detect.exit.dependency_died` | `boolean` | Android | `false` | Report exits caused by a dependency process dying. | +| `detectAndReportExitExcessiveResourceUsage` | `com.bugsee.option.detect.exit.excessive_resource_usage` | `boolean` | Android | `false` | Report exits caused by excessive resource usage. | +| `detectAndReportExitLowMemory` | `com.bugsee.option.detect.exit.low_memory` | `boolean` | Android | `true` | Report exits caused by low memory (the OOM killer). | +| `detectAndReportExitNotResponding` | `com.bugsee.option.detect.exit.not_responding` | `boolean` | Android | `true` | Report exits caused by the app not responding (ANR). | +| `detectAndReportExitNotRespondingAsCrash` | `com.bugsee.option.detect.exit.not_responding.as_crash` | `boolean` | Android | `false` | Report ANR exits as crashes instead of non-fatal errors. | +| `detectAndReportExitOther` | `com.bugsee.option.detect.exit.other` | `boolean` | Android | `false` | Report exits with an "other" reason. | +| `detectAndReportExitPackageStateChanged` | `com.bugsee.option.detect.exit.package_state_changed` | `boolean` | Android | `false` | Report exits caused by a package state change. | +| `detectAndReportExitPackageUpdated` | `com.bugsee.option.detect.exit.package_updated` | `boolean` | Android | `false` | Report exits caused by a package update. | +| `detectAndReportExitPermissionChanged` | `com.bugsee.option.detect.exit.permission_changed` | `boolean` | Android | `false` | Report exits caused by a runtime permission change. | +| `detectAndReportExitUnknown` | `com.bugsee.option.detect.exit.unknown` | `boolean` | Android | `false` | Report exits with an unknown reason. | +| `detectAndReportExitUserRequested` | `com.bugsee.option.detect.exit.user_requested` | `boolean` | Android | `false` | Report exits the user requested, such as a force stop. | +| `detectAndReportExitUserWasStopped` | `com.bugsee.option.detect.exit.user_was_stopped` | `boolean` | Android | `false` | Report exits caused by the system stopping the app. | +| `detectFrustration` | `com.bugsee.option.detect.frustration` | `boolean` | iOS, Android | `false` | Detect and report user-frustration patterns such as rage taps. | +| `detectAndReportHang` | `com.bugsee.option.detect.hang` | `boolean` | iOS, Android | `false` | Detect and report hangs. | +| `detectAndReportHangFairLevel` | `com.bugsee.option.detect.hang.level.fair` | `int` | iOS, Android | `3000` | Main-thread block, in milliseconds, that raises a "fair" hang. Less than the medium level. | +| `detectAndReportHangMediumLevel` | `com.bugsee.option.detect.hang.level.medium` | `int` | iOS, Android | `5000` | Main-thread block, in milliseconds, that raises a "medium" hang. | +| `detectAndReportHangSevereLevel` | `com.bugsee.option.detect.hang.level.severe` | `int` | iOS, Android | `10000` | Main-thread block, in milliseconds, that raises a "severe" hang. Greater than the medium level. | +| `detectAndReportHangSampling` | `com.bugsee.option.detect.hang.sampling` | `boolean` | Android | `true` | Sample the main thread during a hang to attribute the report to culprit frames. Needs `detectAndReportHang`. | +| `detectAndReportHttpErrors` | `com.bugsee.option.detect.http-errors` | `boolean` | iOS, Android | `false` | Turn HTTP 5xx responses into error reports. | +| `detectAndReportMainThreadMisuse` | `com.bugsee.option.detect.main_thread_misuse` | `boolean` | iOS, Android | `false` | Detect and report blocking work on the main thread. | +| `detectMemoryLeaks` | `com.bugsee.option.detect.memory_leaks` | `boolean` | Android | `true` | Detect memory leaks. Honoured only when the app also depends on `com.bugsee:bugsee-android-leak`, which this package does not add. | +| `detectMemoryLeaksDeepSampleRate` | `com.bugsee.option.detect.memory_leaks.deep_sample_rate` | `float` | Android | `1` | Fraction of sessions that run the deep leak modes. Needs `bugsee-android-leak`. | +| `detectMemoryLeaksMode` | `com.bugsee.option.detect.memory_leaks.mode` | `enum MemoryLeakMode` | Android | `FAST` | Leak detection depth; see `MemoryLeakMode`. Needs `bugsee-android-leak`. | +| `detectThreadLeaks` | `com.bugsee.option.detect.thread_leaks` | `boolean` | Android | `false` | Detect thread leaks. Needs `bugsee-android-leak`. | ### Configuration -| Accessor | Option key | Type | Platforms | Notes | -|---|---|---|---|---| -| `buildTarget` | `com.bugsee.option.config.build-target` | `string` | iOS | Build target name attached to reports. | -| `buildType` | `com.bugsee.option.config.build-type` | `string` | iOS | Build type attached to reports. | -| `duration` | `com.bugsee.option.config.duration` | `number` | iOS, Android | Seconds of history a report carries. | -| `maxDataSize` | `com.bugsee.option.config.max-data-size` | `number` | iOS, Android | Disk space, in megabytes, that reports waiting to be sent may occupy. Past it the oldest reports are deleted whole. The SDKs' defaults can differ; the wrapper sets neither. | -| `maxPendingReportAge` | `com.bugsee.option.config.max-pending-report-age` | `number` | iOS, Android | Oldest a report waiting to be sent may get, in days; `0` or less keeps reports until they are sent or evicted. Android 7.3.0, iOS 7.0.0. | -| `maxPendingReports` | `com.bugsee.option.config.max-pending-reports` | `number` | iOS, Android | Most reports kept waiting to be sent. Android 7.3.0, iOS 7.0.0. | -| `notifyFlushDelay` | `com.bugsee.option.config.notify-flush-delay` | `number` | iOS, Android | Coalesce window, in milliseconds, before `Bugsee.notify` uploads flush; `0` posts as soon as the item is on disk. | -| `reportHandlerCallbackTimeout` | `com.bugsee.option.config.report-handler-callback-timeout` | `number` | Android | Seconds before a report handler's completion callback is auto-fired; `0` disables the timeout. | -| `reportProcessingInProcess` | `com.bugsee.option.config.report-processing-in-process` | `boolean` | Android | Export and upload reports in-process on background threads instead of through JobScheduler. | -| `wifiOnlyUpload` | `com.bugsee.option.config.wifi-only-upload` | `boolean` | iOS, Android | Upload only over Wi-Fi. | +| Accessor | Option key | Type | Platforms | Default | Notes | +|---|---|---|---|---|---| +| `buildTarget` | `com.bugsee.option.config.build-target` | `string` | iOS | unset | Build target name attached to reports. | +| `buildType` | `com.bugsee.option.config.build-type` | `string` | iOS | unset | Build type attached to reports. | +| `duration` | `com.bugsee.option.config.duration` | `int` | iOS, Android | `60` | Seconds of history a report carries. | +| `maxDataSize` | `com.bugsee.option.config.max-data-size` | `int` | iOS, Android | `150` | Disk space, in megabytes, that reports waiting to be sent may occupy. Past it the oldest reports are deleted whole. | +| `maxPendingReportAge` | `com.bugsee.option.config.max-pending-report-age` | `int` | iOS, Android | `30` | Oldest a report waiting to be sent may get, in days; `0` or less keeps reports until they are sent or evicted. Android 7.3.0, iOS 7.0.0. | +| `maxPendingReports` | `com.bugsee.option.config.max-pending-reports` | `int` | iOS, Android | `30` | Most reports kept waiting to be sent. Android 7.3.0, iOS 7.0.0. | +| `notifyFlushDelay` | `com.bugsee.option.config.notify-flush-delay` | `int` | iOS, Android | `0` | Coalesce window, in milliseconds, before `Bugsee.notify` uploads flush; `0` posts as soon as the item is on disk. | +| `reportHandlerCallbackTimeout` | `com.bugsee.option.config.report-handler-callback-timeout` | `int` | Android | `30` | Seconds before a report handler's completion callback is auto-fired; `0` disables the timeout. | +| `reportProcessingInProcess` | `com.bugsee.option.config.report-processing-in-process` | `boolean` | Android | `true` | Export and upload reports in-process on background threads instead of through JobScheduler. | +| `wifiOnlyUpload` | `com.bugsee.option.config.wifi-only-upload` | `boolean` | iOS, Android | `false` | Upload only over Wi-Fi. | ### Performance -| Accessor | Option key | Type | Platforms | Notes | -|---|---|---|---|---| -| `performanceAdaptiveSampling` | `com.bugsee.option.performance.adaptive-sampling` | `boolean` | iOS, Android | Promote "interesting" transactions that lost the random sampling draw. | -| `performanceMonitoring` | `com.bugsee.option.performance.enabled` | `boolean` | iOS, Android | Enable performance monitoring (APM). | -| `performanceSampleRate` | `com.bugsee.option.performance.sample-rate` | `number` | iOS, Android | Probability, `0` to `1`, that a transaction is sampled. | -| `performanceUploadMode` | `com.bugsee.option.performance.upload-mode` | `string` | Android | Upload mode for performance data: `'batched'` or `'realtime'`. | +| Accessor | Option key | Type | Platforms | Default | Notes | +|---|---|---|---|---|---| +| `performanceAdaptiveSampling` | `com.bugsee.option.performance.adaptive-sampling` | `boolean` | iOS, Android | `true` | Promote "interesting" transactions that lost the random sampling draw. | +| `performanceMonitoring` | `com.bugsee.option.performance.enabled` | `boolean` | iOS, Android | `true` | Enable performance monitoring (APM). | +| `performanceSampleRate` | `com.bugsee.option.performance.sample-rate` | `float` | iOS, Android | `0.01` | Probability, `0` to `1`, that a transaction is sampled. | +| `performanceUploadMode` | `com.bugsee.option.performance.upload-mode` | `string` | Android | `"batched"` | Upload mode for performance data: `'batched'` or `'realtime'`. | ### Not exposed on purpose -- `com.bugsee.option.config.data-encryption` (iOS): declared in the SDK's private header, not its public API. -- `com.bugsee.option.$$DEBUG`, `$$WRAPPER` (Android): internal; the package registers itself as the wrapper. -- `endpoint` / `$$ENDPOINT`: use the `endpoint` accessor, which writes the right key for the platform. +- `com.bugsee.option.config.data-encryption`: declared in the iOS SDK's private header (BGSOptionsPrivate.h), not its public API. +- `com.bugsee.option.$$DEBUG`: internal. +- `com.bugsee.option.$$WRAPPER`: internal; the wrapper registers itself. +- `com.bugsee.option.$$ENDPOINT`: reached through the `endpoint` accessor. +- `endpoint`: reached through the `endpoint` accessor. diff --git a/packages/react-native/src/options/BugseeLaunchOptions.ts b/packages/react-native/src/options/BugseeLaunchOptions.ts index a8c687cb..41c19f6f 100644 --- a/packages/react-native/src/options/BugseeLaunchOptions.ts +++ b/packages/react-native/src/options/BugseeLaunchOptions.ts @@ -280,7 +280,7 @@ export abstract class BugseeLaunchOptions { /** * Disk space, in megabytes, that reports waiting to be sent may occupy. Past it the - * oldest reports are deleted whole. The SDKs' defaults can differ; the wrapper sets neither. + * oldest reports are deleted whole. */ get maxDataSize(): number | undefined { return this.$get('com.bugsee.option.config.max-data-size'); diff --git a/packages/react-native/src/options/__tests__/keys.test.ts b/packages/react-native/src/options/__tests__/keys.test.ts index 92c80556..68fe9643 100644 --- a/packages/react-native/src/options/__tests__/keys.test.ts +++ b/packages/react-native/src/options/__tests__/keys.test.ts @@ -1,5 +1,6 @@ import { ANDROID_ONLY_KEYS, + RN_OPTION_KEYS, IOS_ONLY_KEYS, SHARED_KEYS, keysFor, @@ -45,3 +46,17 @@ describe('the extracted key surface', () => { } }); }); + +describe('options the wrapper defines for itself', () => { + it('are accepted on both platforms, so the unknown-key warning stays quiet for them', () => { + for (const key of RN_OPTION_KEYS) { + expect(keysFor('ios').has(key)).toBe(true); + expect(keysFor('android').has(key)).toBe(true); + } + }); + + it('never collide with a key an SDK registers', () => { + const sdk = new Set([...SHARED_KEYS, ...IOS_ONLY_KEYS, ...ANDROID_ONLY_KEYS]); + expect(RN_OPTION_KEYS.filter((key) => sdk.has(key))).toEqual([]); + }); +}); diff --git a/packages/react-native/src/options/android-options-manifest.json b/packages/react-native/src/options/android-options-manifest.json index 3727ac4d..4c5f44ed 100644 --- a/packages/react-native/src/options/android-options-manifest.json +++ b/packages/react-native/src/options/android-options-manifest.json @@ -3,7 +3,7 @@ "sdk": "android", "sdkVersion": "7.4.2", "buildConfiguration": "release", - "generatedAt": "2026-11-16T08:27:30Z", + "generatedAt": "2026-11-16T08:35:15Z", "options": [ { "key": "com.bugsee.option.config.duration", @@ -298,7 +298,7 @@ { "key": "com.bugsee.option.capture.network.body-size-limit", "type": "int", - "default": "1024 * 20", + "default": 20480, "module": "bugsee-android", "hidden": false }, diff --git a/packages/react-native/src/options/ios-options-manifest.json b/packages/react-native/src/options/ios-options-manifest.json new file mode 100644 index 00000000..fa545d3f --- /dev/null +++ b/packages/react-native/src/options/ios-options-manifest.json @@ -0,0 +1,594 @@ +{ + "buildConfiguration": "release", + "generatedAt": "2026-10-30T19:10:39Z", + "manifestVersion": 1, + "options": [ + { + "default": null, + "hidden": true, + "key": "com.bugsee.option.$$ENDPOINT", + "module": "Bugsee", + "type": "string" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.avplayer", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.bluetooth-status", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.breadcrumbs", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.breadcrumbs.extras", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.camera-preview", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": "MachAndBSD", + "enum": { + "name": "BugseeCrashHandlerType", + "values": { + "BSD": 1, + "Mach": 2, + "MachAndBSD": 3 + } + }, + "hidden": false, + "key": "com.bugsee.option.capture.crash-handler-type", + "module": "Bugsee", + "type": "enum" + }, + { + "default": 128, + "hidden": false, + "key": "com.bugsee.option.capture.crash-signals", + "module": "Bugsee", + "type": "int" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.device-network-names", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.disk-space", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.logs", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": "Verbose", + "enum": { + "name": "BugseeLogLevel", + "values": { + "Debug": 4, + "Error": 1, + "Info": 3, + "Verbose": 5, + "Warning": 2 + } + }, + "hidden": false, + "key": "com.bugsee.option.capture.logs.level", + "module": "Bugsee", + "type": "enum" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.logs.oslog", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.network", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": 20480, + "hidden": false, + "key": "com.bugsee.option.capture.network.body-size-limit", + "module": "Bugsee", + "type": "int" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.network.body-without-type", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.network.default-sanitizer", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.network.on-launch", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.on-device-symbolication", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.sample-buffer-display-layer", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.screenshot", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": 1, + "hidden": false, + "key": "com.bugsee.option.capture.screenshot.scale", + "module": "Bugsee", + "type": "float" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.status-bar-info", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.video", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.video.adaptive", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": "High", + "enum": { + "name": "BugseeFrameRate", + "values": { + "High": 3, + "Low": 1, + "Medium": 2 + } + }, + "hidden": false, + "key": "com.bugsee.option.capture.video.frame-rate", + "module": "Bugsee", + "type": "enum" + }, + { + "default": 0, + "hidden": false, + "key": "com.bugsee.option.capture.video.max-frame-rate", + "module": "Bugsee", + "type": "int" + }, + { + "default": 0, + "hidden": false, + "key": "com.bugsee.option.capture.video.min-frame-rate", + "module": "Bugsee", + "type": "int" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.video.privacy-blur", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": "Default", + "enum": { + "name": "BugseeVideoQuality", + "values": { + "Default": 0, + "High": 2, + "Medium": 1 + } + }, + "hidden": false, + "key": "com.bugsee.option.capture.video.quality", + "module": "Bugsee", + "type": "enum" + }, + { + "default": 1, + "hidden": false, + "key": "com.bugsee.option.capture.video.scale", + "module": "Bugsee", + "type": "float" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.view-hierarchy", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.websocket", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.capture.webview.advanced", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.capture.webview.report-trigger", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": null, + "hidden": false, + "key": "com.bugsee.option.config.build-target", + "module": "Bugsee", + "type": "string" + }, + { + "default": null, + "hidden": false, + "key": "com.bugsee.option.config.build-type", + "module": "Bugsee", + "type": "string" + }, + { + "default": "None", + "enum": { + "name": "BugseeDataEncryptionMode", + "values": { + "EndToEnd": 2, + "None": 0, + "OnDevice": 1 + } + }, + "hidden": false, + "key": "com.bugsee.option.config.data-encryption", + "module": "Bugsee", + "type": "enum" + }, + { + "default": 60, + "hidden": false, + "key": "com.bugsee.option.config.duration", + "module": "Bugsee", + "type": "int" + }, + { + "default": 150, + "hidden": false, + "key": "com.bugsee.option.config.max-data-size", + "module": "Bugsee", + "type": "int" + }, + { + "default": 30, + "hidden": false, + "key": "com.bugsee.option.config.max-pending-report-age", + "module": "Bugsee", + "type": "int" + }, + { + "default": 30, + "hidden": false, + "key": "com.bugsee.option.config.max-pending-reports", + "module": "Bugsee", + "type": "int" + }, + { + "default": 0, + "hidden": false, + "key": "com.bugsee.option.config.notify-flush-delay", + "module": "Bugsee", + "type": "int" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.config.wifi-only-upload", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.anomaly", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.crash", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.crash.fill_empty_exception_stacks", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.crash.swift_async_stacktraces", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.early-crash", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.detect.exit", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.frustration", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.hang", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": 3000, + "hidden": false, + "key": "com.bugsee.option.detect.hang.level.fair", + "module": "Bugsee", + "type": "int" + }, + { + "default": 5000, + "hidden": false, + "key": "com.bugsee.option.detect.hang.level.medium", + "module": "Bugsee", + "type": "int" + }, + { + "default": 10000, + "hidden": false, + "key": "com.bugsee.option.detect.hang.level.severe", + "module": "Bugsee", + "type": "int" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.http-errors", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.detect.main_thread_misuse", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.performance.adaptive-sampling", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.performance.enabled", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": 0.01, + "hidden": false, + "key": "com.bugsee.option.performance.sample-rate", + "module": "Bugsee", + "type": "float" + }, + { + "default": "High", + "enum": { + "name": "BugseeSeverityLevel", + "values": { + "Blocker": 5, + "Critical": 4, + "High": 3, + "Low": 1, + "Medium": 2 + } + }, + "hidden": false, + "key": "com.bugsee.option.reporting.defaults.bug-priority", + "module": "Bugsee", + "type": "enum" + }, + { + "default": "Blocker", + "enum": { + "name": "BugseeSeverityLevel", + "values": { + "Blocker": 5, + "Critical": 4, + "High": 3, + "Low": 1, + "Medium": 2 + } + }, + "hidden": false, + "key": "com.bugsee.option.reporting.defaults.crash-priority", + "module": "Bugsee", + "type": "enum" + }, + { + "default": "High", + "enum": { + "name": "BugseeSeverityLevel", + "values": { + "Blocker": 5, + "Critical": 4, + "High": 3, + "Low": 1, + "Medium": 2 + } + }, + "hidden": false, + "key": "com.bugsee.option.reporting.defaults.error-priority", + "module": "Bugsee", + "type": "enum" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.triggers.screenshot", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": true, + "hidden": false, + "key": "com.bugsee.option.reporting.triggers.shake", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.description-required", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.email-required", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.labels-enabled", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.labels-required", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.priority-selector-enabled", + "module": "Bugsee", + "type": "boolean" + }, + { + "default": "System", + "enum": { + "name": "BugseeStyle", + "values": { + "BasedOnStatusBar": 2, + "Dusk": 1, + "Light": 0, + "System": 3 + } + }, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.style", + "module": "Bugsee", + "type": "enum" + }, + { + "default": false, + "hidden": false, + "key": "com.bugsee.option.reporting.ui.summary-required", + "module": "Bugsee", + "type": "boolean" + } + ], + "sdk": "ios", + "sdkVersion": "7.0.0" +} diff --git a/packages/react-native/src/options/keys.ts b/packages/react-native/src/options/keys.ts index 64ec1b11..9a40a7f1 100644 --- a/packages/react-native/src/options/keys.ts +++ b/packages/react-native/src/options/keys.ts @@ -36,25 +36,20 @@ export const UNDECLARED_KEYS: Readonly> = { - 'com.bugsee.option.config.data-encryption': - 'declared in the iOS SDK\'s private header (BGSOptionsPrivate.h), not its public API', - 'com.bugsee.option.$$DEBUG': 'internal', - 'com.bugsee.option.$$WRAPPER': 'internal; the wrapper registers itself', - 'com.bugsee.option.$$ENDPOINT': 'reached through the `endpoint` accessor', - endpoint: 'reached through the `endpoint` accessor', -}; +export const RN_OPTION_KEYS: readonly string[] = []; export function keysFor(platform: 'ios' | 'android'): ReadonlySet { return new Set([ + ...RN_OPTION_KEYS, ...SHARED_KEYS, ...(platform === 'ios' ? IOS_ONLY_KEYS : ANDROID_ONLY_KEYS), ...UNDECLARED_KEYS[platform], diff --git a/packages/react-native/src/options/noAccessor.ts b/packages/react-native/src/options/noAccessor.ts new file mode 100644 index 00000000..e0e03be8 --- /dev/null +++ b/packages/react-native/src/options/noAccessor.ts @@ -0,0 +1,16 @@ +/** + * Keys an SDK registers that have NO first-class accessor on purpose. The + * coverage test requires every known key to have an accessor or an entry here + * with a reason, so a new SDK option cannot be silently left unreachable. + * + * Keys whose accessor has a different shape than "one setter, one key" (the + * endpoint override) are covered by {@link UNDECLARED_KEYS}. + */ +export const NO_ACCESSOR: Readonly> = { + 'com.bugsee.option.config.data-encryption': + 'declared in the iOS SDK\'s private header (BGSOptionsPrivate.h), not its public API', + 'com.bugsee.option.$$DEBUG': 'internal', + 'com.bugsee.option.$$WRAPPER': 'internal; the wrapper registers itself', + 'com.bugsee.option.$$ENDPOINT': 'reached through the `endpoint` accessor', + endpoint: 'reached through the `endpoint` accessor', +}; diff --git a/scripts/__tests__/launch-options-doc.test.ts b/scripts/__tests__/launch-options-doc.test.ts new file mode 100644 index 00000000..e8e3e607 --- /dev/null +++ b/scripts/__tests__/launch-options-doc.test.ts @@ -0,0 +1,166 @@ +import { defaultCell, formatDefault, readHead, renderDoc, REFERENCE_MARKER } from '../launch-options-doc'; +import type { AccessorInfo } from '../option-accessors'; +import type { PublishedManifest, PublishedOption } from '../published-manifest'; + +const P = 'com.bugsee.option.'; +const option = (key: string, extra: Partial = {}): PublishedOption => ({ + key: P + key, + type: 'boolean', + default: false, + ...extra, +}); +const manifest = (sdk: string, options: PublishedOption[]): PublishedManifest => ({ + manifestVersion: 1, + sdk, + sdkVersion: '1', + options, +}); +const accessor = (name: string, key: string, doc = 'Does it.', extra: Partial = {}): AccessorInfo => ({ + name, + key: P + key, + type: 'boolean', + doc, + hasSetter: true, + owner: 'base', + ...extra, +}); + +const HEAD = `# Launch options\n\n${REFERENCE_MARKER}\n\nIntro.`; + +describe('formatDefault', () => { + it.each([ + [{ type: 'boolean', default: true }, '`true`'], + [{ type: 'int', default: 20480 }, '`20480`'], + [{ type: 'float', default: 0.01 }, '`0.01`'], + [{ type: 'string', default: 'batched' }, '`"batched"`'], + [{ type: 'string', default: '' }, '`""`'], + [{ type: 'enum', default: 'Verbose' }, '`Verbose`'], + [{ type: 'string', default: null }, 'unset'], + [{ type: 'string' }, 'unset'], + ])('writes %j as %s', (partial, expected) => { + expect(formatDefault({ key: 'k', ...partial })).toBe(expected); + }); +}); + +describe('defaultCell', () => { + it('writes one value when the platforms agree', () => { + expect(defaultCell(option('a', { default: 1, type: 'int' }), option('a', { default: 1, type: 'int' }))).toBe('`1`'); + }); + + it('labels both when they differ', () => { + expect(defaultCell(option('a', { default: false }), option('a', { default: true }))).toBe('Android `false` · iOS `true`'); + }); + + it('writes the one platform\'s value when only one has the option', () => { + expect(defaultCell(option('a', { default: 7, type: 'int' }), undefined)).toBe('`7`'); + expect(defaultCell(undefined, option('a', { default: 9, type: 'int' }))).toBe('`9`'); + }); +}); + +describe('readHead', () => { + it('keeps everything before the first generated group', () => { + expect(readHead(`${HEAD}\n\n### Capture\n\n| x |\n`)).toBe(`${HEAD}\n`); + }); + + it('refuses a document with no Reference heading', () => { + expect(() => readHead('# nothing\n### Capture')).toThrow(/no "## Reference" heading/); + }); + + it('refuses a document with no group after the heading', () => { + expect(() => readHead(`${HEAD}\n`)).toThrow(/no "###" group/); + }); +}); + +describe('renderDoc', () => { + const render = (over: Partial[0]> = {}): string => + renderDoc({ + head: HEAD, + android: manifest('android', [option('capture.logs', { default: true }), option('detect.hang')]), + ios: manifest('ios', [option('capture.logs', { default: true }), option('capture.avplayer')]), + accessors: [ + accessor('captureLogs', 'capture.logs', 'Capture logs.'), + accessor('detectAndReportHang', 'detect.hang', 'Detect hangs.', { owner: 'android' }), + accessor('captureAVPlayer', 'capture.avplayer', 'Capture AVPlayer.', { owner: 'ios' }), + ], + noAccessor: { 'com.bugsee.option.$$X': 'internal' }, + ...over, + }); + + it('keeps the hand-written head and groups the options in order', () => { + const doc = render(); + expect(doc.startsWith(`${HEAD}\n\n### Capture`)).toBe(true); + expect(doc.indexOf('### Capture')).toBeLessThan(doc.indexOf('### Detection')); + expect(doc.indexOf('### Detection')).toBeLessThan(doc.indexOf('### Not exposed on purpose')); + }); + + it('writes a row with the accessor, key, type, platforms, default and notes', () => { + expect(render()).toContain( + '| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | `true` | Capture logs. |', + ); + }); + + it('says which platform has an option that only one does', () => { + const doc = render(); + expect(doc).toContain('| `detectAndReportHang` | `com.bugsee.option.detect.hang` | `boolean` | Android | `false` | Detect hangs. |'); + expect(doc).toContain('| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | `false` | Capture AVPlayer. |'); + }); + + it('sorts the rows of a group by key', () => { + const doc = render(); + expect(doc.indexOf('`captureAVPlayer`')).toBeLessThan(doc.indexOf('`captureLogs`')); + }); + + it('shows an enum by its SDK name, and a default that differs by platform', () => { + const doc = render({ + android: manifest('android', [option('capture.logs.level', { type: 'enum', default: 'Verbose', enum: { name: 'LogLevel', values: {} } })]), + ios: manifest('ios', [option('capture.logs.level', { type: 'enum', default: 'Info', enum: { name: 'BugseeLogLevel', values: {} } })]), + accessors: [accessor('captureLogsLevel', 'capture.logs.level')], + }); + expect(doc).toContain('`enum LogLevel`'); + expect(doc).toContain('Android `Verbose` · iOS `Info`'); + }); + + it('documents an option of the package\'s own, which no SDK manifest has, instead of failing on it', () => { + const doc = render({ + accessors: [accessor('rnOnly', 'capture.rn-only', 'Acted on in React Native.', { type: 'string' })], + android: manifest('android', []), + ios: manifest('ios', []), + }); + expect(doc).toContain( + '| `rnOnly` | `com.bugsee.option.capture.rn-only` | `string` | React Native only | unset | Acted on in React Native. |', + ); + }); + + it('flags a deprecated accessor in its notes', () => { + const doc = render({ + accessors: [accessor('captureLogs', 'capture.logs', 'Capture logs.', { deprecated: 'Gone.' })], + android: manifest('android', [option('capture.logs')]), + ios: manifest('ios', []), + }); + expect(doc).toContain('Capture logs. **Deprecated** — Gone. |'); + }); + + it('escapes a pipe in a note so it cannot split the cell', () => { + expect(render({ accessors: [accessor('captureLogs', 'capture.logs', 'a | b')] })).toContain('a \\| b'); + }); + + it('lists what is not exposed, with the reason', () => { + expect(render()).toContain('- `com.bugsee.option.$$X`: internal.'); + }); + + it('skips a group with no accessors', () => { + expect(render()).not.toContain('### Performance'); + }); + + it('refuses an accessor whose key belongs to no documented group, rather than dropping it', () => { + expect(() => + render({ accessors: [accessor('mystery', 'mystery.thing')], android: manifest('android', [option('mystery.thing')]) }), + ).toThrow(/outside every documented group: com\.bugsee\.option\.mystery\.thing/); + }); + + it('ends with a newline and is stable when rendered twice from its own head', () => { + const once = render(); + expect(once.endsWith('\n')).toBe(true); + expect(render({ head: readHead(once) })).toBe(once); + }); +}); diff --git a/scripts/__tests__/option-accessors.test.ts b/scripts/__tests__/option-accessors.test.ts new file mode 100644 index 00000000..cca6a71c --- /dev/null +++ b/scripts/__tests__/option-accessors.test.ts @@ -0,0 +1,110 @@ +import { parseAccessors, readDoc } from '../option-accessors'; + +const accessor = (name: string, type: string, key: string, doc = ''): string => ` + ${doc} + get ${name}(): ${type} | undefined { + return this.$get('${key}'); + } + set ${name}(value: ${type} | undefined) { + this.$set('${key}', value); + } +`; + +describe('readDoc', () => { + it('has no doc and no deprecation when there is no comment', () => { + expect(readDoc(undefined)).toEqual({ doc: '' }); + }); + + it('joins a multi-line comment into one line without the stars', () => { + expect(readDoc('\n * First line\n * second line.\n ')).toEqual({ doc: 'First line second line.' }); + }); + + it('turns {@link X} into backticked X', () => { + expect(readDoc(' see {@link LogLevel} and {@link FrameRate}. ')).toEqual({ doc: 'see `LogLevel` and `FrameRate`.' }); + }); + + it('splits the @deprecated text from the summary', () => { + expect(readDoc('\n * Has no effect.\n *\n * @deprecated The SDK ignores it.\n ')).toEqual({ + doc: 'Has no effect.', + deprecated: 'The SDK ignores it.', + }); + }); + + it('collapses runs of whitespace', () => { + expect(readDoc('a b\n\n * c')).toEqual({ doc: 'a b c' }); + }); +}); + +describe('parseAccessors', () => { + it('reads name, key, declared type, doc and owner', () => { + const [found] = parseAccessors( + accessor('captureLogs', 'boolean', 'com.bugsee.option.capture.logs', '/**\n * Capture logs.\n */'), + 'base', + ); + expect(found).toEqual({ + name: 'captureLogs', + key: 'com.bugsee.option.capture.logs', + type: 'boolean', + doc: 'Capture logs.', + hasSetter: true, + owner: 'base', + }); + }); + + it('keeps a union type without the trailing undefined', () => { + expect(parseAccessors(accessor('level', 'LogLevel | number', 'k'), 'android')[0]?.type).toBe('LogLevel | number'); + }); + + it('reads an accessor with no doc comment', () => { + expect(parseAccessors(accessor('x', 'string', 'k'), 'ios')[0]?.doc).toBe(''); + }); + + it('carries a deprecation', () => { + const source = accessor('old', 'boolean', 'k', '/**\n * Does nothing.\n *\n * @deprecated Gone.\n */'); + expect(parseAccessors(source, 'base')[0]).toMatchObject({ doc: 'Does nothing.', deprecated: 'Gone.' }); + }); + + it('does not attach one accessor\'s comment to the next', () => { + const found = parseAccessors( + accessor('a', 'boolean', 'ka', '/**\n * First.\n */') + accessor('b', 'boolean', 'kb'), + 'base', + ); + expect(found.map((f) => [f.name, f.doc])).toEqual([['a', 'First.'], ['b', '']]); + }); + + it('finds a getter with no setter, which a check then reports', () => { + const source = ` + get lonely(): boolean | undefined { + return this.$get('k'); + } +`; + expect(parseAccessors(source, 'base')[0]?.hasSetter).toBe(false); + }); + + it('does not take another key\'s setter for this getter\'s', () => { + const source = ` + get a(): boolean | undefined { + return this.$get('ka'); + } + set a(value: boolean | undefined) { + this.$set('other', value); + } +`; + expect(parseAccessors(source, 'base')[0]?.hasSetter).toBe(false); + }); + + it('matches a key containing dots and $ literally', () => { + const key = 'com.bugsee.option.$$ENDPOINT'; + expect(parseAccessors(accessor('endpoint', 'string', key), 'base')[0]?.hasSetter).toBe(true); + const wrongDot = accessor('e', 'string', 'a.b').replace("this.$set('a.b'", "this.$set('aXb'"); + expect(parseAccessors(wrongDot, 'base')[0]?.hasSetter).toBe(false); + }); + + it('ignores a getter that does not read through $get with a literal key', () => { + expect(parseAccessors("get e(): string | undefined {\n return this.$get(SOME_CONSTANT);\n }", 'base')).toEqual([]); + }); + + it('finds every accessor in a file', () => { + expect(parseAccessors(accessor('a', 'boolean', 'ka') + accessor('b', 'number', 'kb'), 'base').map((f) => f.name)).toEqual(['a', 'b']); + }); +}); diff --git a/scripts/__tests__/option-keys.test.ts b/scripts/__tests__/option-keys.test.ts index 432d87eb..f2554c83 100644 --- a/scripts/__tests__/option-keys.test.ts +++ b/scripts/__tests__/option-keys.test.ts @@ -269,6 +269,10 @@ describe('parseAndroidDescriptors', () => { // Android declares `$$WRAPPER` as HashMap.class and publishes it as a map; reading it as a string // is what the published-manifest check caught. ['HashMap', 'HashMap.class', 'null', 'map', null], + // The SDK writes the network body limit as `1024 * 20`; its manifest says 20480. + ['product of integers', 'Integer.class', '1024 * 20', 'int', 20480], + ['product without spaces', 'Integer.class', '2*3*4', 'int', 24], + ['negative factor', 'Integer.class', '-2 * 5', 'int', -10], ['List', 'List.class', 'null', 'list', null], // Each of these pins one literal-parsing regex to the exact text it is // meant to match, not merely a substring of it -- the literal is left as diff --git a/scripts/__tests__/published-manifest.test.ts b/scripts/__tests__/published-manifest.test.ts index 6771ffae..cccc6ee3 100644 --- a/scripts/__tests__/published-manifest.test.ts +++ b/scripts/__tests__/published-manifest.test.ts @@ -1,8 +1,12 @@ import { + ENUM_TS_NAMES, MANIFEST_BASE, + checkAccessors, checkPublished, manifestUrl, parseManifest, + type Accessor, + type AccessorCheckInput, type CheckInput, type PublishedManifest, type PublishedOption, @@ -88,18 +92,16 @@ describe('checkPublished', () => { expect(problems[0]).toContain('option-keys.json'); }); - it('reports a key the package lists and the SDK does not register', () => { - const problems = checkPublished(input({ knownKeys: ['a', 'b', 'gone'] })); - expect(problems).toHaveLength(1); - expect(problems[0]).toContain('lists gone for android'); - expect(problems[0]).toContain('silently ignored'); + it('does not complain about a key this package lists and the SDK does not register', () => { + // The package can have options of its own that the SDK ignores and only the wrapper acts on. + expect(checkPublished(input({ knownKeys: ['a', 'b', 'wrapper-only'] }))).toEqual([]); }); it('lists several problems in key order', () => { const problems = checkPublished( input({ published: manifest([option('z'), option('y')]), knownKeys: ['b', 'a'] }), ); - expect(problems.map((p) => p.match(/\b(registers|lists) (\w+)/)?.[2])).toEqual(['y', 'z', 'a', 'b']); + expect(problems.map((p) => p.match(/\bregisters (\w+)/)?.[1])).toEqual(['y', 'z']); }); it('leaves hidden internals out of the key comparison, in both directions', () => { @@ -129,9 +131,26 @@ describe('checkPublished', () => { ]); }); - it('reports an option the published manifest lacks', () => { - expect(checkPublished(committed([option('a'), option('b'), option('x')]))).toEqual([ - 'android-options-manifest.json has x, which the published manifest does not', + it('does not complain about an option the committed manifest has and the SDK does not', () => { + expect(checkPublished(committed([option('a'), option('b'), option('x')]))).toEqual([]); + }); + + it('reports a default that differs', () => { + const published = manifest([option('a'), option('b', { default: 20480 })]); + const problems = checkPublished({ ...input({ published }), committed: [option('a'), option('b', { default: '1024 * 20' })] }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('differs from the published manifest for b'); + expect(problems[0]).toContain('20480'); + }); + + it('reads an absent default as null, as the SDK manifests write it', () => { + const published = manifest([option('a'), option('b', { default: null })]); + expect(checkPublished({ ...input({ published }), committed: [option('a'), option('b')] })).toEqual([]); + }); + + it('names the committed file in its messages', () => { + expect(checkPublished({ ...input(), committed: [option('a')], committedName: 'ios-options-manifest.json' })).toEqual([ + 'ios-options-manifest.json is missing b', ]); }); @@ -196,3 +215,210 @@ describe('checkPublished', () => { }); }); }); + +describe('checkAccessors', () => { + const accessor = (key: string, type: string, extra: Partial = {}): Accessor => ({ + name: `${key}Accessor`, + key, + type, + hasSetter: true, + owner: 'base', + ...extra, + }); + const check = (extra: Partial = {}): string[] => + checkAccessors({ + platform: 'android', + pinnedVersion: '7.4.2', + published: manifest([option('flag'), option('count', { type: 'int', default: 3 })]), + accessors: [accessor('flag', 'boolean'), accessor('count', 'number')], + noAccessor: {}, + enums: {}, + withheld: {}, + ...extra, + }); + + it('is empty when every published option has a fitting accessor with a setter', () => { + expect(check()).toEqual([]); + }); + + it('names a missing option with its type and default, and where to add it', () => { + const problems = check({ accessors: [accessor('flag', 'boolean')] }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('MISSING OPTION count (int, default 3)'); + expect(problems[0]).toContain('the android SDK 7.4.2 manifest'); + expect(problems[0]).toContain('AndroidLaunchOptions (or BugseeLaunchOptions)'); + expect(problems[0]).toContain('noAccessor.ts'); + }); + + it('names the iOS class for an iOS manifest', () => { + expect(check({ platform: 'ios', accessors: [] })[0]).toContain('IOSLaunchOptions'); + }); + + it('shows a missing enum option as its enum and constant default', () => { + const published = manifest([option('mode', { type: 'enum', default: 'V2', enum: { name: 'VideoMode', values: { V2: 2 } } })]); + expect(check({ published, accessors: [] })[0]).toContain('MISSING OPTION mode (enum VideoMode, default "V2")'); + }); + + it('shows a missing option with no default as null', () => { + expect(check({ published: manifest([option('flag')]), accessors: [] })[0]).toContain('default null'); + }); + + it('reports every missing option, in key order', () => { + const problems = check({ accessors: [] }); + expect(problems.map((p) => p.match(/MISSING OPTION (\w+)/)?.[1])).toEqual(['count', 'flag']); + }); + + it('skips an option that deliberately has no accessor', () => { + expect(check({ accessors: [accessor('flag', 'boolean')], noAccessor: { count: 'internal' } })).toEqual([]); + }); + + it('ignores a hidden option', () => { + const published = manifest([option('flag'), option('$$X', { hidden: true })]); + expect(check({ published, accessors: [accessor('flag', 'boolean')] })).toEqual([]); + }); + + it('does not complain about an accessor for an option the SDK does not register', () => { + // An option of the wrapper's own: sent, ignored by the SDK, acted on in React Native. + expect(check({ accessors: [accessor('flag', 'boolean'), accessor('count', 'number'), accessor('rn-only', 'string')] })).toEqual([]); + }); + + it('reports a getter with no setter', () => { + const problems = check({ accessors: [accessor('flag', 'boolean', { hasSetter: false }), accessor('count', 'number')] }); + expect(problems).toEqual(['flag' + 'Accessor (flag) has a getter but no setter, so the option cannot be set']); + }); + + it.each([ + ['boolean', 'number'], + ['int', 'string'], + ['float', 'boolean'], + ['string', 'number'], + ])('reports a %s option declared %s', (sdkType, declared) => { + const published = manifest([option('x', { type: sdkType })]); + const problems = check({ published, accessors: [accessor('x', declared)] }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain(`is declared ${declared}, but the SDK type is ${sdkType}`); + }); + + it.each([ + ['int', 'number'], + ['float', 'number'], + ['string', 'string'], + ['boolean', 'boolean'], + ])('accepts a %s option declared %s', (sdkType, declared) => { + expect(check({ published: manifest([option('x', { type: sdkType })]), accessors: [accessor('x', declared)] })).toEqual([]); + }); + + it('accepts a union that includes the SDK type', () => { + expect(check({ published: manifest([option('x', { type: 'int' })]), accessors: [accessor('x', 'number | undefined')] })).toEqual([]); + expect(check({ published: manifest([option('x', { type: 'int' })]), accessors: [accessor('x', 'Level | number')] })).toEqual([]); + }); + + it('reports an option type this package cannot represent', () => { + const problems = check({ published: manifest([option('x', { type: 'map' })]), accessors: [accessor('x', 'object')] }); + expect(problems[0]).toContain('is a map option, which this package cannot represent'); + }); + + describe('enums', () => { + const published = (name: string, values: Record) => + manifest([option('level', { type: 'enum', enum: { name, values } })]); + + it('accepts an enum whose constants match, by value', () => { + expect( + check({ + published: published('LogLevel', { Error: 1, Warning: 2 }), + accessors: [accessor('level', 'LogLevel')], + enums: { LogLevel: { Error: 1, Warning: 2 } }, + }), + ).toEqual([]); + }); + + it('compares numeric enums by value, since the SDKs name members differently', () => { + expect( + check({ + platform: 'ios', + published: published('BugseeSeverityLevel', { Low: 1, Blocker: 5 }), + accessors: [accessor('level', 'IssueSeverity')], + enums: { IssueSeverity: { VeryLow: 1, Blocker: 5 } }, + }), + ).toEqual([]); + }); + + it('accepts a union with a plain number, the shape two older accessors keep', () => { + expect( + check({ + published: published('LogLevel', { Error: 1 }), + accessors: [accessor('level', 'LogLevel | number')], + enums: { LogLevel: { Error: 1 } }, + }), + ).toEqual([]); + }); + + it('reports a constant the SDK has and the package lacks', () => { + const problems = check({ + published: published('LogLevel', { Error: 1, Warning: 2, Verbose: 5 }), + accessors: [accessor('level', 'LogLevel')], + enums: { LogLevel: { Error: 1, Warning: 2 } }, + }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain('LogLevel has the constants [1, 2] but LogLevel in the SDK has [1, 2, 5]'); + }); + + it('reports a constant the package has and the SDK lacks', () => { + expect( + check({ + published: published('LogLevel', { Error: 1 }), + accessors: [accessor('level', 'LogLevel')], + enums: { LogLevel: { Error: 1, Extra: 9 } }, + }), + ).toHaveLength(1); + }); + + it('does not count a member the package withholds on purpose', () => { + expect( + check({ + published: published('FrameRate', { Low: 1, Raw: 4 }), + accessors: [accessor('level', 'FrameRate')], + enums: { FrameRate: { Low: 1 } }, + withheld: { FrameRate: { Raw: 4 } }, + }), + ).toEqual([]); + }); + + it('compares a string-valued enum by constant name, which is what crosses the bridge', () => { + const leak = published('MemoryLeakMode', { FAST: 'Fast', DEEP: 'Deep' }); + expect( + check({ published: leak, accessors: [accessor('level', 'MemoryLeakMode')], enums: { MemoryLeakMode: { Fast: 'FAST', Deep: 'DEEP' } } }), + ).toEqual([]); + expect( + check({ published: leak, accessors: [accessor('level', 'MemoryLeakMode')], enums: { MemoryLeakMode: { Fast: 'FAST' } } }), + ).toHaveLength(1); + }); + + it('reports an accessor not declared as the enum', () => { + const problems = check({ + published: published('LogLevel', { Error: 1 }), + accessors: [accessor('level', 'number')], + enums: { LogLevel: { Error: 1 } }, + }); + expect(problems[0]).toContain('is declared number, but the SDK type is the enum LogLevel (LogLevel)'); + }); + + it('reports an SDK enum this package has no TypeScript name for', () => { + expect(check({ published: published('BugseeNew', { A: 1 }), accessors: [accessor('level', 'number')] })[0]).toContain( + 'the SDK enum BugseeNew, which has no TypeScript enum here (add it to ENUM_TS_NAMES)', + ); + }); + + it('reports a TypeScript enum that enums.ts does not export', () => { + expect( + check({ published: published('LogLevel', { Error: 1 }), accessors: [accessor('level', 'LogLevel')], enums: {} })[0], + ).toContain('uses LogLevel, which is not exported from enums.ts'); + }); + + it('maps each SDK enum name to one TypeScript enum', () => { + expect(ENUM_TS_NAMES.BugseeSeverityLevel).toBe('IssueSeverity'); + expect(ENUM_TS_NAMES.BugseeStyle).toBe('ReportingUIStyle'); + expect(ENUM_TS_NAMES.IssueSeverity).toBe('IssueSeverity'); + }); + }); +}); diff --git a/scripts/cli-check-published-manifests.ts b/scripts/cli-check-published-manifests.ts index 88a46db9..c383592b 100644 --- a/scripts/cli-check-published-manifests.ts +++ b/scripts/cli-check-published-manifests.ts @@ -1,41 +1,59 @@ /** - * Fails when the option manifest each native SDK published for the PINNED version disagrees with the - * option fixtures this package ships. Run in CI and before a publish. + * Fails when the option manifest each native SDK published for the PINNED version disagrees with this + * package. Run in CI and before a publish. * - * Usage: cli-check-published-manifests.ts [--dir ] + * It complains about what an SDK PUBLISHES that this package does not match, and about nothing else. For + * Android and iOS it checks that + * - every option the SDK registers is a key this package lists (a new SDK option is named); + * - the committed copy of each manifest has every published option with the same type, default, hidden + * flag, deprecation and enum constants; + * - every published option has an accessor on the options classes, with a setter and a type that can + * hold the SDK's, and the package's enums have the SDK's constants. A missing option is reported by + * name; + * - docs/launch-options.md is what the generator renders from these, so its type and default of every + * option are the SDK's. + * + * It is deliberately one-directional. An option this package has and the SDK does not publish is fine: + * the package can have options of its own, sent to the SDK (which ignores them) and acted on only in + * React Native. + * + * Usage: cli-check-published-manifests.ts [--dir ] [--update] * * By default the manifests are fetched from download.bugsee.com (override the base with * BUGSEE_OPTIONS_MANIFEST_BASE). `--dir` reads `//.json` instead, for - * working offline. An unreachable manifest FAILS the check: a gate that passes when it cannot look is - * not a gate. The fetch is retried, since the file is immutable and only the network can be flaky. + * working offline. `--update` writes the published iOS manifest over ios-options-manifest.json (the + * Android copy is generated by cli-extract-option-keys.ts). An unreachable manifest FAILS the check: a + * gate that passes when it cannot look is not a gate. The fetch is retried, since the file is immutable + * and only the network can be flaky. */ -import { readFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { MANIFEST_BASE, + checkAccessors, checkPublished, manifestUrl, parseManifest, type Platform, - type PublishedOption, + type PublishedManifest, } from './published-manifest.ts'; - -const root = join(import.meta.dirname, '..'); -const options = join(root, 'packages', 'react-native', 'src', 'options'); -const readJson = (path: string): T => JSON.parse(readFileSync(path, 'utf8')) as T; - -const pinned = readJson<{ android: { sdk: string }; ios: { sdk: string } }>( - join(root, 'native-versions.json'), -); -const keys = readJson<{ shared: string[]; ios: string[]; android: string[] }>( - join(options, 'option-keys.json'), -); -const androidManifest = readJson<{ options: PublishedOption[] }>( - join(options, 'android-options-manifest.json'), -); +import { readHead, renderDoc } from './launch-options-doc.ts'; +import { + accessorsFor, + docPath, + fixtureName, + fixtureOptions, + keys, + optionsDir, + pinned, + readAccessors, + readEnums, + readNoAccessor, +} from './cli-options-sources.ts'; const dirFlag = process.argv.indexOf('--dir'); const dir = dirFlag === -1 ? undefined : process.argv[dirFlag + 1]; +const update = process.argv.includes('--update'); const base = process.env.BUGSEE_OPTIONS_MANIFEST_BASE ?? MANIFEST_BASE; async function load(platform: Platform, version: string): Promise { @@ -64,30 +82,80 @@ async function load(platform: Platform, version: string): Promise { throw new Error(`could not fetch ${url}: ${failure}`); } +const accessors = readAccessors(); +const { enums, withheld } = await readEnums(); +const noAccessor = await readNoAccessor(); +const manifests: Partial> = {}; let failed = false; + +function report(label: string, problems: string[]): void { + if (problems.length === 0) { + return; + } + failed = true; + console.error(`${label}: ${problems.length} misalignment(s)`); + for (const problem of problems) { + console.error(` - ${problem}`); + } +} + for (const platform of ['android', 'ios'] as const) { const version = pinned[platform].sdk; + const label = `${platform} ${version}`; try { - const published = parseManifest(await load(platform, version), `${platform} ${version} manifest`); - const problems = checkPublished({ - platform, - pinnedVersion: version, - published, - knownKeys: [...keys.shared, ...keys[platform]], - committed: platform === 'android' ? androidManifest.options : undefined, - }); + const text = await load(platform, version); + const published = parseManifest(text, `${label} manifest`); + manifests[platform] = published; + if (update && platform === 'ios') { + writeFileSync(join(optionsDir, fixtureName('ios')), `${JSON.stringify(published, null, 2)}\n`); + console.log(`wrote ${fixtureName('ios')}`); + } + const problems = [ + ...checkPublished({ + platform, + pinnedVersion: version, + published, + knownKeys: [...keys.shared, ...keys[platform]], + committed: update && platform === 'ios' ? published.options : fixtureOptions(platform), + committedName: fixtureName(platform), + }), + ...checkAccessors({ + platform, + pinnedVersion: version, + published, + accessors: accessorsFor(accessors, platform), + noAccessor, + enums, + withheld, + }), + ]; + report(label, problems); if (problems.length === 0) { - console.log(`${platform} ${version}: aligned (${published.options.length} published options)`); - } else { - failed = true; - console.error(`${platform} ${version}: ${problems.length} misalignment(s)`); - for (const problem of problems) { - console.error(` - ${problem}`); - } + console.log(`${label}: aligned (${published.options.length} published options)`); } } catch (error) { failed = true; - console.error(`${platform} ${version}: ${(error as Error).message}`); + console.error(`${label}: ${(error as Error).message}`); + } +} + +if (manifests.android && manifests.ios) { + const committed = readFileSync(docPath, 'utf8'); + const rendered = renderDoc({ + head: readHead(committed), + android: manifests.android, + ios: manifests.ios, + accessors, + noAccessor, + }); + if (rendered !== committed) { + failed = true; + console.error( + 'docs/launch-options.md is out of date: its types, platforms or defaults differ from the published ' + + 'manifests and the accessors. Run `node scripts/cli-generate-launch-options-doc.ts`.', + ); + } else { + console.log('docs/launch-options.md: matches the published manifests'); } } process.exit(failed ? 1 : 0); diff --git a/scripts/cli-generate-launch-options-doc.ts b/scripts/cli-generate-launch-options-doc.ts new file mode 100644 index 00000000..54c681b6 --- /dev/null +++ b/scripts/cli-generate-launch-options-doc.ts @@ -0,0 +1,20 @@ +/** + * Regenerates the reference tables of docs/launch-options.md from the accessor classes and the + * committed copies of the SDKs' published manifests. Run it after changing an accessor or + * regenerating a fixture; `yarn check:options-manifests` fails when the file is out of date. + * + * Usage: cli-generate-launch-options-doc.ts + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import { renderDoc, readHead } from './launch-options-doc.ts'; +import { docPath, readAccessors, readFixture, readNoAccessor } from './cli-options-sources.ts'; + +const document = renderDoc({ + head: readHead(readFileSync(docPath, 'utf8')), + android: readFixture('android'), + ios: readFixture('ios'), + accessors: readAccessors(), + noAccessor: await readNoAccessor(), +}); +writeFileSync(docPath, document); +console.log(`wrote ${docPath}`); diff --git a/scripts/cli-options-sources.ts b/scripts/cli-options-sources.ts new file mode 100644 index 00000000..d332307c --- /dev/null +++ b/scripts/cli-options-sources.ts @@ -0,0 +1,64 @@ +/** What the option checks and the doc generator read from this repository. */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { parseAccessors, type AccessorInfo } from './option-accessors.ts'; +import type { PublishedManifest, PublishedOption } from './published-manifest.ts'; + +export const root = join(import.meta.dirname, '..'); +export const optionsDir = join(root, 'packages', 'react-native', 'src', 'options'); +export const docPath = join(root, 'docs', 'launch-options.md'); + +const readJson = (path: string): T => JSON.parse(readFileSync(path, 'utf8')) as T; + +export const pinned = readJson<{ android: { sdk: string }; ios: { sdk: string } }>( + join(root, 'native-versions.json'), +); +export const keys = readJson<{ shared: string[]; ios: string[]; android: string[] }>( + join(optionsDir, 'option-keys.json'), +); + +export const fixtureName = (platform: 'android' | 'ios'): string => `${platform}-options-manifest.json`; + +export function readFixture(platform: 'android' | 'ios'): PublishedManifest { + return readJson(join(optionsDir, fixtureName(platform))); +} + +export function fixtureOptions(platform: 'android' | 'ios'): PublishedOption[] { + return readFixture(platform).options; +} + +/** Every accessor, with the class that declares it. */ +export function readAccessors(): AccessorInfo[] { + const file = (name: string, owner: 'base' | 'android' | 'ios'): AccessorInfo[] => + parseAccessors(readFileSync(join(optionsDir, `${name}.ts`), 'utf8'), owner); + return [ + ...file('BugseeLaunchOptions', 'base'), + ...file('AndroidLaunchOptions', 'android'), + ...file('IOSLaunchOptions', 'ios'), + ]; +} + +/** The accessors reachable on one platform's options class. */ +export function accessorsFor(all: readonly AccessorInfo[], platform: 'android' | 'ios'): AccessorInfo[] { + return all.filter((accessor) => accessor.owner === 'base' || accessor.owner === platform); +} + +export async function readEnums(): Promise<{ + enums: Record>; + withheld: Record>; +}> { + const module = (await import(pathToFileURL(join(optionsDir, 'enums.ts')).href)) as Record; + const withheld = module.WITHHELD_FROM_JS as Record>; + const enums = Object.fromEntries( + Object.entries(module).filter(([name]) => name !== 'WITHHELD_FROM_JS'), + ) as Record>; + return { enums, withheld }; +} + +export async function readNoAccessor(): Promise> { + const module = (await import(pathToFileURL(join(optionsDir, 'noAccessor.ts')).href)) as { + NO_ACCESSOR: Record; + }; + return module.NO_ACCESSOR; +} diff --git a/scripts/launch-options-doc.ts b/scripts/launch-options-doc.ts new file mode 100644 index 00000000..c1f04d13 --- /dev/null +++ b/scripts/launch-options-doc.ts @@ -0,0 +1,122 @@ +/** + * Renders the launch-option reference (docs/launch-options.md) from the accessor classes and the SDKs' + * published manifests, so the type, platform and default of every option in the docs is the SDK's own + * and cannot be written from memory. The build fails when the committed file differs from this output. + */ +import type { PublishedManifest, PublishedOption } from './published-manifest.ts'; +import type { AccessorInfo } from './option-accessors.ts'; + +export const REFERENCE_MARKER = '## Reference'; + +/** A manifest default as it reads in a table cell. */ +export function formatDefault(option: PublishedOption): string { + const value = option.default; + if (value === null || value === undefined) { + return 'unset'; + } + if (option.type === 'enum') { + return `\`${String(value)}\``; + } + return `\`${JSON.stringify(value)}\``; +} + +function typeLabel(option: PublishedOption): string { + return option.type === 'enum' ? `enum ${option.enum?.name ?? ''}` : option.type; +} + +const GROUPS: readonly [title: string, prefixes: readonly string[]][] = [ + ['Reporting triggers and dialog', ['reporting.']], + ['Capture', ['capture.']], + ['Detection', ['detect.', 'crash-ndk.']], + ['Configuration', ['config.']], + ['Performance', ['performance.']], +]; + +const PREFIX = 'com.bugsee.option.'; + +export interface DocInput { + /** The committed text up to and including the Reference marker line; kept as written. */ + head: string; + android: PublishedManifest; + ios: PublishedManifest; + accessors: readonly AccessorInfo[]; + noAccessor: Readonly>; +} + +function cell(text: string): string { + return text.replace(/\|/g, '\\|'); +} + +/** The default cell: one value when the platforms agree, both labelled when they differ. */ +export function defaultCell(android: PublishedOption | undefined, ios: PublishedOption | undefined): string { + if (android && ios) { + const a = formatDefault(android); + const i = formatDefault(ios); + return a === i ? a : `Android ${a} · iOS ${i}`; + } + return formatDefault((android ?? ios) as PublishedOption); +} + +export function renderDoc(input: DocInput): string { + const { head, android, ios, accessors, noAccessor } = input; + const a = new Map(android.options.map((option) => [option.key, option])); + const i = new Map(ios.options.map((option) => [option.key, option])); + const out: string[] = [head.trimEnd(), '']; + const placed = new Set(); + + for (const [title, prefixes] of GROUPS) { + const rows = accessors + .filter((accessor) => prefixes.some((prefix) => accessor.key.startsWith(PREFIX + prefix))) + .sort((x, y) => x.key.localeCompare(y.key)); + if (rows.length === 0) { + continue; + } + out.push(`### ${title}`, '', '| Accessor | Option key | Type | Platforms | Default | Notes |', '|---|---|---|---|---|---|'); + for (const accessor of rows) { + placed.add(accessor.key); + const onAndroid = a.get(accessor.key); + const onIos = i.get(accessor.key); + const option = onAndroid ?? onIos; + // An option of this package's own is in no SDK manifest: its type is the accessor's, it names no + // platform's SDK, and it has no SDK default to quote. + const type = option === undefined ? accessor.type : typeLabel(option); + const platforms = + option === undefined ? 'React Native only' : onAndroid && onIos ? 'iOS, Android' : onAndroid ? 'Android' : 'iOS'; + const notes = [accessor.doc, accessor.deprecated ? `**Deprecated** — ${accessor.deprecated}` : ''] + .filter(Boolean) + .join(' '); + out.push( + `| \`${accessor.name}\` | \`${accessor.key}\` | \`${type}\` | ${platforms} | ${option === undefined ? 'unset' : defaultCell(onAndroid, onIos)} | ${cell(notes)} |`, + ); + } + out.push(''); + } + + const stray = accessors.filter((accessor) => !placed.has(accessor.key)).map((accessor) => accessor.key); + if (stray.length > 0) { + throw new Error(`accessors with a key outside every documented group: ${stray.join(', ')}`); + } + + out.push('### Not exposed on purpose', ''); + for (const [key, reason] of Object.entries(noAccessor)) { + out.push(`- \`${key}\`: ${reason}.`); + } + out.push(''); + return out.join('\n'); +} + +/** + * The hand-written part of the committed document: everything before the first generated group, so + * the heading and the sentence under it stay as written. An error when there is no marker or no group. + */ +export function readHead(document: string): string { + const marker = document.indexOf(REFERENCE_MARKER); + if (marker === -1) { + throw new Error(`the launch-options document has no "${REFERENCE_MARKER}" heading to regenerate from`); + } + const firstGroup = document.indexOf('\n### ', marker); + if (firstGroup === -1) { + throw new Error('the launch-options document has no "###" group after its Reference heading'); + } + return `${document.slice(0, firstGroup).trimEnd()}\n`; +} diff --git a/scripts/option-accessors.ts b/scripts/option-accessors.ts new file mode 100644 index 00000000..2f46c35e --- /dev/null +++ b/scripts/option-accessors.ts @@ -0,0 +1,67 @@ +/** + * Reads the launch-option accessors out of the TypeScript sources of `BugseeLaunchOptions` and its + * platform subclasses, so a check can compare what this package declares with what the SDKs publish. + * + * It reads the source, not the compiled classes, because the declared TYPE of an accessor exists only + * there. The accessors are uniform (`get x(): T | undefined { return this.$get('key'); }` and the + * matching setter), which is what makes this a reading and not a TypeScript parser: an accessor that + * deviates from the shape is not found, and the check then reports its option as missing rather than + * passing it unseen. + */ + +export type Owner = 'base' | 'android' | 'ios'; + +export interface AccessorInfo { + name: string; + /** The `com.bugsee.option.*` key it reads and writes. */ + key: string; + /** The declared type without `| undefined`, e.g. `LogLevel | number`. */ + type: string; + /** The JSDoc summary, as one line. */ + doc: string; + /** The `@deprecated` text, when the accessor is deprecated. */ + deprecated?: string; + hasSetter: boolean; + owner: Owner; +} + +/** A JSDoc body as one line: the leading stars go, `{@link X}` becomes `X`, `@deprecated` is split off. */ +export function readDoc(raw: string | undefined): { doc: string; deprecated?: string } { + if (raw === undefined) { + return { doc: '' }; + } + const text = raw + .split('\n') + .map((line) => line.replace(/^\s*\*+ ?/, '').trim()) + .join(' ') + .replace(/\{@link ([^}]+)\}/g, '`$1`') + .replace(/\s+/g, ' ') + .trim(); + const at = text.indexOf('@deprecated'); + if (at === -1) { + return { doc: text }; + } + return { doc: text.slice(0, at).trim(), deprecated: text.slice(at + '@deprecated'.length).trim() }; +} + +const GETTER = + /(?:\/\*\*([\s\S]*?)\*\/\s*)?get (\w+)\(\): ([^{]*?) \| undefined \{\s*return this\.\$get\('([^']+)'\);\s*\}/g; + +export function parseAccessors(source: string, owner: Owner): AccessorInfo[] { + const accessors: AccessorInfo[] = []; + for (const match of source.matchAll(GETTER)) { + const [, rawDoc, name, type, key] = match as unknown as [string, string | undefined, string, string, string]; + const setter = new RegExp( + `set ${name}\\(value: [^)]*\\) \\{\\s*this\\.\\$set\\('${key.replace(/[$.]/g, '\\$&')}', value\\);`, + ); + accessors.push({ + name, + key, + type: type.trim(), + ...readDoc(rawDoc), + hasSetter: setter.test(source), + owner, + }); + } + return accessors; +} diff --git a/scripts/option-keys.ts b/scripts/option-keys.ts index 0edc193e..904723d7 100644 --- a/scripts/option-keys.ts +++ b/scripts/option-keys.ts @@ -204,6 +204,12 @@ function parseJavaLiteral(raw: string): unknown { if (raw === 'true') return true; if (raw === 'false') return false; if (/^-?\d+$/.test(raw)) return Number(raw); + // `1024 * 20`: the SDK writes some sizes as a product of integer literals. Left as text it published + // as the string "1024 * 20" where the SDK's own manifest says 20480. + const product = /^(-?\d+(?:\s*\*\s*-?\d+)+)$/.exec(raw); + if (product) { + return (product[1] as string).split('*').reduce((total, factor) => total * Number(factor.trim()), 1); + } if (/^-?\d*\.\d+f?$/.test(raw)) return Number(raw.replace(/f$/, '')); const quoted = /^"(.*)"$/.exec(raw); if (quoted) return quoted[1]; diff --git a/scripts/published-manifest.ts b/scripts/published-manifest.ts index d3a9a7e5..3bfb1589 100644 --- a/scripts/published-manifest.ts +++ b/scripts/published-manifest.ts @@ -4,15 +4,21 @@ * * Every SDK release publishes an immutable option manifest at * `download.bugsee.com/sdk/options//.json`. The fixtures this package ships - * (`option-keys.json`, `android-options-manifest.json`) are extracted from SDK sources and could + * (`option-keys.json`, the `*-options-manifest.json` copies) are extracted from SDK sources and could * drift from what a release really registers; this is the check against the release itself, run at * build and publish time so a misalignment fails the build instead of reaching a customer as an * option that is silently ignored. + * + * The comparison is one-directional. It complains about what the SDK PUBLISHES that this package does + * not match: an option it lacks, or one whose type or default differs. It never complains about an + * option this package has and the SDK does not, because the package can have options of its own that + * the SDK ignores and only the wrapper acts on. */ export interface PublishedOption { key: string; type: string; + default?: unknown; hidden?: boolean; deprecated?: unknown; enum?: { name: string; values: unknown }; @@ -58,6 +64,7 @@ export function parseManifest(text: string, source: string): PublishedManifest { function describe(option: PublishedOption): string { return JSON.stringify({ type: option.type, + default: option.default === undefined ? null : option.default, hidden: option.hidden === true, deprecated: option.deprecated !== undefined, enum: option.enum === undefined ? null : { name: option.enum.name, values: sorted(option.enum.values) }, @@ -80,19 +87,22 @@ export interface CheckInput { published: PublishedManifest; /** Every user-facing key the package lists for the platform: the shared keys plus its own. */ knownKeys: readonly string[]; - /** The committed Android manifest, compared option by option. iOS has none. */ + /** The committed copy of this platform's manifest, compared option by option. */ committed?: readonly PublishedOption[]; + /** Its file name, for the messages. */ + committedName?: string; } /** * Every way the published manifest and the committed fixtures disagree; empty means aligned. * * Hidden options are internals (`$$ENDPOINT`, `$$WRAPPER`): they are not part of the user-facing - * key lists, so they are left out of the key comparison. The committed Android manifest does - * include them, and is compared in full. + * key lists, so they are left out of the key comparison. The committed manifests do include + * them, and are compared in full: type, default, hidden flag, deprecation and enum constants. */ export function checkPublished(input: CheckInput): string[] { const { platform, pinnedVersion, published, knownKeys, committed } = input; + const file = input.committedName ?? 'android-options-manifest.json'; const problems: string[] = []; if (published.sdk !== platform) { @@ -116,14 +126,6 @@ export function checkPublished(input: CheckInput): string[] { ); } } - for (const key of [...known].sort()) { - if (!publishedKeys.has(key)) { - problems.push( - `this package lists ${key} for ${platform}, which the ${pinnedVersion} SDK does not register, ` + - 'so setting it would be silently ignored', - ); - } - } if (committed !== undefined) { const have = new Map(committed.map((option) => [option.key, option])); @@ -131,20 +133,166 @@ export function checkPublished(input: CheckInput): string[] { for (const [key, option] of [...want].sort(([a], [b]) => a.localeCompare(b))) { const ours = have.get(key); if (ours === undefined) { - problems.push(`android-options-manifest.json is missing ${key}`); + problems.push(`${file} is missing ${key}`); } else if (describe(ours) !== describe(option)) { problems.push( - `android-options-manifest.json differs from the published manifest for ${key}: ` + + `${file} differs from the published manifest for ${key}: ` + `committed ${describe(ours)}, published ${describe(option)}`, ); } } - for (const key of [...have.keys()].sort()) { - if (!want.has(key)) { - problems.push(`android-options-manifest.json has ${key}, which the published manifest does not`); - } - } } return problems; } + +// --------------------------------------------------------------------------- +// The accessor classes against the published manifest +// --------------------------------------------------------------------------- + +/** + * The TypeScript enum each SDK's published enum name stands for. The SDKs name them differently + * (`BugseeSeverityLevel` on iOS, `IssueSeverity` on Android), and this package has one enum each. + */ +export const ENUM_TS_NAMES: Readonly> = { + LogLevel: 'LogLevel', + VideoMode: 'VideoMode', + VideoQuality: 'VideoQuality', + FrameRate: 'FrameRate', + IssueSeverity: 'IssueSeverity', + MemoryLeakMode: 'MemoryLeakMode', + BugseeLogLevel: 'LogLevel', + BugseeVideoQuality: 'VideoQuality', + BugseeFrameRate: 'FrameRate', + BugseeSeverityLevel: 'IssueSeverity', + BugseeStyle: 'ReportingUIStyle', + BugseeCrashHandlerType: 'CrashHandlerType', +}; + +export interface Accessor { + name: string; + key: string; + type: string; + hasSetter: boolean; + owner: 'base' | 'android' | 'ios'; +} + +export interface AccessorCheckInput { + platform: Platform; + pinnedVersion: string; + published: PublishedManifest; + /** Every accessor reachable on this platform's options class: the base class's plus its own. */ + accessors: readonly Accessor[]; + /** Keys that deliberately have no accessor, with the reason. */ + noAccessor: Readonly>; + /** The package's enums, `{ LogLevel: { Error: 1, ... } }`. */ + enums: Readonly>>>; + /** Native members the package withholds, `{ FrameRate: { Raw: 4 } }` (see enums.ts). */ + withheld: Readonly>>>; +} + +const SDK_CLASS: Record = { + android: 'AndroidLaunchOptions', + ios: 'IOSLaunchOptions', +}; + +function expectedTsType(option: PublishedOption): string | undefined { + switch (option.type) { + case 'boolean': + return 'boolean'; + case 'int': + case 'float': + return 'number'; + case 'string': + return 'string'; + default: + return undefined; + } +} + +function sortedValues(values: unknown): string[] { + return Object.values((values ?? {}) as Record).map(String).sort(); +} + +/** + * Every way the accessor classes fall short of the published manifest. Each problem names the option, + * so a failing build says exactly which one is missing or wrong and where to add it: + * + * - an option the SDK registers that has no accessor (and no reason in `noAccessor`); + * - an accessor with no setter, or whose declared type cannot hold the option's type; + * - an enum option whose TypeScript enum has other constants than the SDK's. + * + * It is one-directional on purpose: an accessor for an option the SDK does NOT register is fine. This + * package can have options of its own that the SDK ignores and only the wrapper acts on. + */ +export function checkAccessors(input: AccessorCheckInput): string[] { + const { platform, pinnedVersion, published, accessors, noAccessor, enums, withheld } = input; + const where = `${SDK_CLASS[platform]} (or BugseeLaunchOptions)`; + const sdk = `the ${platform} SDK ${pinnedVersion} manifest`; + const problems: string[] = []; + + const byKey = new Map(accessors.map((accessor) => [accessor.key, accessor])); + const options = published.options.filter((option) => option.hidden !== true); + + for (const option of [...options].sort((a, b) => a.key.localeCompare(b.key))) { + if (option.key in noAccessor) { + continue; + } + const accessor = byKey.get(option.key); + const shape = `${option.type === 'enum' ? `enum ${option.enum?.name}` : option.type}, default ${JSON.stringify(option.default ?? null)}`; + if (accessor === undefined) { + problems.push( + `MISSING OPTION ${option.key} (${shape}) is in ${sdk} but ${where} has no accessor for it. ` + + 'Add a getter and setter, or list it in noAccessor.ts with the reason.', + ); + continue; + } + if (!accessor.hasSetter) { + problems.push(`${accessor.name} (${option.key}) has a getter but no setter, so the option cannot be set`); + } + problems.push(...checkType(option, accessor, enums, withheld)); + } + return problems; +} + +function checkType( + option: PublishedOption, + accessor: Accessor, + enums: AccessorCheckInput['enums'], + withheld: AccessorCheckInput['withheld'], +): string[] { + const members = accessor.type.split('|').map((member) => member.trim()); + if (option.type !== 'enum') { + const expected = expectedTsType(option); + if (expected === undefined) { + return [`${accessor.name} (${option.key}) is a ${option.type} option, which this package cannot represent`]; + } + return members.includes(expected) + ? [] + : [`${accessor.name} (${option.key}) is declared ${accessor.type}, but the SDK type is ${option.type} (${expected})`]; + } + + const name = option.enum?.name ?? ''; + const tsName = ENUM_TS_NAMES[name]; + if (tsName === undefined) { + return [`${accessor.name} (${option.key}) is the SDK enum ${name}, which has no TypeScript enum here (add it to ENUM_TS_NAMES)`]; + } + if (!members.includes(tsName)) { + return [`${accessor.name} (${option.key}) is declared ${accessor.type}, but the SDK type is the enum ${name} (${tsName})`]; + } + const ours = enums[tsName]; + if (ours === undefined) { + return [`${accessor.name} (${option.key}) uses ${tsName}, which is not exported from enums.ts`]; + } + const published = (option.enum?.values ?? {}) as Record; + const left = withheld[tsName] ?? {}; + const kept = Object.fromEntries(Object.entries(published).filter(([member]) => !(member in left))); + const isNumeric = Object.values(published).every((value) => typeof value === 'number'); + // A numeric enum is compared by VALUE (the SDKs name members differently); a string-valued one + // (MemoryLeakMode) by constant NAME, which is what crosses the bridge. + const want = isNumeric ? sortedValues(kept) : Object.keys(kept).sort(); + const have = sortedValues(ours); + return want.join() === have.join() + ? [] + : [`${tsName} has the constants [${have.join(', ')}] but ${name} in the SDK has [${want.join(', ')}] (${option.key})`]; +} From 25a086ab4d53fbd05a15d46c76259904fcba2c28 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 13:46:33 +0500 Subject: [PATCH 11/16] Address CodeQL: escape backslashes in table cells and regex keys Two "incomplete string escaping" alerts in the new scripts: - the doc generator escaped `|` in a table cell but not a backslash, so a written `\|` would read as an escaped pipe; - the accessor parser built a regular expression from an option key escaping only `$` and `.`. Both now escape fully (backslash first in the cell; a standard escapeRegExp for the pattern), with tests that a metacharacter matches only itself. Human guided, AI implemented --- scripts/__tests__/launch-options-doc.test.ts | 17 ++++++++++++++++- scripts/__tests__/option-accessors.test.ts | 14 +++++++++++++- scripts/launch-options-doc.ts | 5 +++-- scripts/option-accessors.ts | 7 ++++++- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/scripts/__tests__/launch-options-doc.test.ts b/scripts/__tests__/launch-options-doc.test.ts index e8e3e607..c336f0ad 100644 --- a/scripts/__tests__/launch-options-doc.test.ts +++ b/scripts/__tests__/launch-options-doc.test.ts @@ -1,4 +1,4 @@ -import { defaultCell, formatDefault, readHead, renderDoc, REFERENCE_MARKER } from '../launch-options-doc'; +import { cell, defaultCell, formatDefault, readHead, renderDoc, REFERENCE_MARKER } from '../launch-options-doc'; import type { AccessorInfo } from '../option-accessors'; import type { PublishedManifest, PublishedOption } from '../published-manifest'; @@ -42,6 +42,21 @@ describe('formatDefault', () => { }); }); +describe('cell', () => { + it('escapes a pipe so it cannot split the cell', () => { + expect(cell('a | b')).toBe('a \\| b'); + }); + + it('escapes a backslash first, so a written \\| is not read as an escaped pipe', () => { + expect(cell('a\\b')).toBe('a\\\\b'); + expect(cell('a\\|b')).toBe('a\\\\\\|b'); + }); + + it('leaves plain text alone', () => { + expect(cell('plain text')).toBe('plain text'); + }); +}); + describe('defaultCell', () => { it('writes one value when the platforms agree', () => { expect(defaultCell(option('a', { default: 1, type: 'int' }), option('a', { default: 1, type: 'int' }))).toBe('`1`'); diff --git a/scripts/__tests__/option-accessors.test.ts b/scripts/__tests__/option-accessors.test.ts index cca6a71c..26e4d4ae 100644 --- a/scripts/__tests__/option-accessors.test.ts +++ b/scripts/__tests__/option-accessors.test.ts @@ -1,4 +1,4 @@ -import { parseAccessors, readDoc } from '../option-accessors'; +import { escapeRegExp, parseAccessors, readDoc } from '../option-accessors'; const accessor = (name: string, type: string, key: string, doc = ''): string => ` ${doc} @@ -10,6 +10,18 @@ const accessor = (name: string, type: string, key: string, doc = ''): string => } `; +describe('escapeRegExp', () => { + it.each(['a.b', 'a+b', 'a*b', 'a?b', '^a$', 'a|b', '(a)', '[a]', '{a}', 'a\\b', '$$X'])('matches %s literally', (text) => { + expect(new RegExp(`^${escapeRegExp(text)}$`).test(text)).toBe(true); + }); + + it('does not let a metacharacter match something else', () => { + expect(new RegExp(`^${escapeRegExp('a.b')}$`).test('aXb')).toBe(false); + expect(new RegExp(`^${escapeRegExp('a|b')}$`).test('a')).toBe(false); + expect(new RegExp(`^${escapeRegExp('a\\b')}$`).test('a\b')).toBe(false); + }); +}); + describe('readDoc', () => { it('has no doc and no deprecation when there is no comment', () => { expect(readDoc(undefined)).toEqual({ doc: '' }); diff --git a/scripts/launch-options-doc.ts b/scripts/launch-options-doc.ts index c1f04d13..65d8dbca 100644 --- a/scripts/launch-options-doc.ts +++ b/scripts/launch-options-doc.ts @@ -43,8 +43,9 @@ export interface DocInput { noAccessor: Readonly>; } -function cell(text: string): string { - return text.replace(/\|/g, '\\|'); +/** Text for a table cell: the backslash first, so an escape written in the text is not undone by ours. */ +export function cell(text: string): string { + return text.replace(/\\/g, '\\\\').replace(/\|/g, '\\|'); } /** The default cell: one value when the platforms agree, both labelled when they differ. */ diff --git a/scripts/option-accessors.ts b/scripts/option-accessors.ts index 2f46c35e..a59e888a 100644 --- a/scripts/option-accessors.ts +++ b/scripts/option-accessors.ts @@ -44,6 +44,11 @@ export function readDoc(raw: string | undefined): { doc: string; deprecated?: st return { doc: text.slice(0, at).trim(), deprecated: text.slice(at + '@deprecated'.length).trim() }; } +/** The text as a regular expression that matches it literally. */ +export function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + const GETTER = /(?:\/\*\*([\s\S]*?)\*\/\s*)?get (\w+)\(\): ([^{]*?) \| undefined \{\s*return this\.\$get\('([^']+)'\);\s*\}/g; @@ -52,7 +57,7 @@ export function parseAccessors(source: string, owner: Owner): AccessorInfo[] { for (const match of source.matchAll(GETTER)) { const [, rawDoc, name, type, key] = match as unknown as [string, string | undefined, string, string, string]; const setter = new RegExp( - `set ${name}\\(value: [^)]*\\) \\{\\s*this\\.\\$set\\('${key.replace(/[$.]/g, '\\$&')}', value\\);`, + `set ${escapeRegExp(name)}\\(value: [^)]*\\) \\{\\s*this\\.\\$set\\('${escapeRegExp(key)}', value\\);`, ); accessors.push({ name, From 744fa4955e5a31231909837e632493888f292f19 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 14:09:29 +0500 Subject: [PATCH 12/16] Address review: strict manifest parsing, accessor docs that stay in their comment - parseManifest now requires manifestVersion 1 (a later format may rename hidden/deprecated/enum, and comparing it as v1 would pass differences it cannot see) and validates every option row; the committed copies are read through the same parser, so a `{}` or malformed fixture fails the check instead of turning the comparison against it into a no-op. - The accessor parser's doc group could run past a comment end, so the first accessor of each class file swallowed the class comment and every non-accessor member: three Notes cells of docs/launch-options.md held source code, and the gate passed on it because it compares the doc with the same parser's output. The group can no longer cross `*/`; the doc is regenerated (26 KB -> 22.7 KB) and tests assert an accessor's doc is only its own comment. Human guided, AI implemented --- docs/launch-options.md | 6 +- scripts/__tests__/option-accessors.test.ts | 27 +++++++++ scripts/__tests__/published-manifest.test.ts | 46 +++++++++++++-- scripts/cli-options-sources.ts | 9 ++- scripts/option-accessors.ts | 6 +- scripts/published-manifest.ts | 60 +++++++++++++++++--- 6 files changed, 135 insertions(+), 19 deletions(-) diff --git a/docs/launch-options.md b/docs/launch-options.md index be79c010..c6ebaf5e 100644 --- a/docs/launch-options.md +++ b/docs/launch-options.md @@ -64,7 +64,7 @@ iOS, does nothing on Android, and reports nothing on either. `launch()` and `rel | Accessor | Option key | Type | Platforms | Default | Notes | |---|---|---|---|---|---| -| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | `false` | Launch options for iOS, adding the keys only that SDK accepts. */ export class IOSLaunchOptions extends BugseeLaunchOptions { /** The API endpoint override. Reads back what the SDK will actually receive rather than what was assigned, because the two differ on iOS. / get endpoint(): string \| undefined { return this.$get(IOS_ENDPOINT_KEY); } set endpoint(value: string \| undefined) { const payload = endpointFor('ios', value); this.$set(IOS_ENDPOINT_KEY, payload[IOS_ENDPOINT_KEY]); } /** Capture `AVPlayer` content. | +| `captureAVPlayer` | `com.bugsee.option.capture.avplayer` | `boolean` | iOS | `false` | Capture `AVPlayer` content. | | `captureBluetoothStatus` | `com.bugsee.option.capture.bluetooth-status` | `boolean` | iOS | `false` | Record the Bluetooth status. | | `captureBreadcrumbs` | `com.bugsee.option.capture.breadcrumbs` | `boolean` | iOS, Android | `false` | Capture breadcrumbs (user and system events). | | `captureBreadcrumbsExtras` | `com.bugsee.option.capture.breadcrumbs.extras` | `boolean` | iOS, Android | `false` | Attach the extra detail of automatically collected device-event breadcrumbs. | @@ -73,8 +73,8 @@ iOS, does nothing on Android, and reports nothing on either. `launch()` and `rel | `crashSignals` | `com.bugsee.option.capture.crash-signals` | `int` | iOS | `128` | The fatal signals the crash reporter intercepts, as the iOS SDK's `BugseeCrashSignals` bit set: ABRT 1, SEGV 2, BUS 4, ILL 8, FPE 16, TRAP 32. Unset leaves the SDK default (every signal). Added in 7.0.0-beta7. | | `captureDeviceAndNetworkNames` | `com.bugsee.option.capture.device-network-names` | `boolean` | iOS | `false` | Record the device and network names. | | `captureDiskSpace` | `com.bugsee.option.capture.disk-space` | `boolean` | iOS | `false` | Record free disk space. | -| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | `true` | Launch options, keyed by the SDKs' real 7.x option keys. Both platforms accept the same `com.bugsee.option.*` namespace in 7.x, so there is no translation layer here and no per-platform key mapping — the map IS the payload. That is what makes `BugseeLaunchOptions.setCustomOption` genuinely useful: a custom key and a first-class accessor write to the same namespace, so an option the wrapper has not surfaced yet, including one added in a future 7.x patch, is reachable with no wrapper release. Subclasses add the accessors for their platform; see `AndroidLaunchOptions` and `IOSLaunchOptions`. / export abstract class BugseeLaunchOptions { /** Sent to the native SDK verbatim. */ private readonly nativeOptions = new Map(); /** JS-only settings for the wrapper's own components, kept in a separate map so they cannot reach the native payload. The native SDK never agreed to these keys; one arriving there is at best ignored and at worst rejects the launch. / private readonly localOptions = new Map(); /** What the SDK last said is in effect. Read by getters, never serialised: sending these back would hand the SDK its own defaults as if the app had chosen them. / private reportedOptions = new Map(); /** Writes a native option. `undefined` **deletes** the key rather than storing an empty value: the payload must not carry a key the caller meant to leave alone, or the native side takes it as an explicit override of the SDK's own default. / protected $set(key: string, value: unknown): void { if (value === undefined) { this.nativeOptions.delete(key); return; } this.nativeOptions.set(key, value); } /** What the app set, or failing that what the SDK last reported. The wrapper hardcodes no defaults. The 6.x implementation did, and drifted: it shipped `videoMode = V3` after 7.x removed that value. The SDKs know their own defaults; Android reports them even before launch. / protected $get(key: string): T \| undefined { if (this.nativeOptions.has(key)) { return this.nativeOptions.get(key) as T; } return this.reportedOptions.get(key) as T \| undefined; } /** Writes a JS-only option. `undefined` deletes, as with `$set`. */ protected $setLocal(key: string, value: unknown): void { if (value === undefined) { this.localOptions.delete(key); return; } this.localOptions.set(key, value); } protected $getLocal(key: string): T \| undefined { return this.localOptions.get(key) as T \| undefined; } // Accessors for options BOTH platforms accept. Platform-specific ones // live on the subclasses, so an iOS-only key is not reachable from an // Android options object. /** Capture logs. Lines sent with `Bugsee.log()` are always recorded. | -| `logsUseAllSources` | `com.bugsee.option.capture.logs.allsources` | `boolean` | Android | `false` | Launch options for Android, adding the keys only that SDK accepts. */ export class AndroidLaunchOptions extends BugseeLaunchOptions { /** The API endpoint override. Reads back what the SDK will actually receive rather than what was assigned, because the two differ on iOS. / get endpoint(): string \| undefined { return this.$get(ANDROID_ENDPOINT_KEY); } set endpoint(value: string \| undefined) { const payload = endpointFor('android', value); this.$set(ANDROID_ENDPOINT_KEY, payload[ANDROID_ENDPOINT_KEY]); } /** Query every logging source (system, radio, ...) rather than only the default ones. | +| `captureLogs` | `com.bugsee.option.capture.logs` | `boolean` | iOS, Android | `true` | Capture logs. Lines sent with `Bugsee.log()` are always recorded. | +| `logsUseAllSources` | `com.bugsee.option.capture.logs.allsources` | `boolean` | Android | `false` | Query every logging source (system, radio, ...) rather than only the default ones. | | `captureLogsLevel` | `com.bugsee.option.capture.logs.level` | `enum LogLevel` | iOS, Android | `Verbose` | Least severe level captured; see `LogLevel`. Also accepts a plain `number`, which this accessor always took, so a level read from config still compiles. | | `captureOSLogs` | `com.bugsee.option.capture.logs.oslog` | `boolean` | iOS | `false` | Has no effect: the iOS SDK accepts the key and ignores it. **Deprecated** — The iOS SDK permanently disables OSLog capture. | | `captureNetwork` | `com.bugsee.option.capture.network` | `boolean` | iOS, Android | `true` | Capture network events. | diff --git a/scripts/__tests__/option-accessors.test.ts b/scripts/__tests__/option-accessors.test.ts index 26e4d4ae..eea22fc3 100644 --- a/scripts/__tests__/option-accessors.test.ts +++ b/scripts/__tests__/option-accessors.test.ts @@ -84,6 +84,33 @@ describe('parseAccessors', () => { expect(found.map((f) => [f.name, f.doc])).toEqual([['a', 'First.'], ['b', '']]); }); + it('takes only the comment directly above an accessor, not the class comment and members before it', () => { + const source = ` +/** Launch options for Android. */ +export class AndroidLaunchOptions { + /** The endpoint override. */ + get endpoint(): string | undefined { + return this.$get(ANDROID_ENDPOINT_KEY); + } + private readonly nativeOptions = new Map(); +${accessor('first', 'boolean', 'k1', '/**\n * First one.\n */')} +}`; + const [found] = parseAccessors(source, 'android'); + expect(found?.name).toBe('first'); + expect(found?.doc).toBe('First one.'); + }); + + it('does not take a @deprecated from a comment it must not reach', () => { + const source = ` +/** @deprecated Class-level, not an accessor's. */ +export class X { + private x = 1; +${accessor('a', 'boolean', 'ka')} +}`; + expect(parseAccessors(source, 'base')[0]).toMatchObject({ name: 'a', doc: '' }); + expect(parseAccessors(source, 'base')[0]?.deprecated).toBeUndefined(); + }); + it('finds a getter with no setter, which a check then reports', () => { const source = ` get lonely(): boolean | undefined { diff --git a/scripts/__tests__/published-manifest.test.ts b/scripts/__tests__/published-manifest.test.ts index cccc6ee3..85be0baf 100644 --- a/scripts/__tests__/published-manifest.test.ts +++ b/scripts/__tests__/published-manifest.test.ts @@ -59,13 +59,51 @@ describe('parseManifest', () => { ['not JSON', '{ nope'], ['null', 'null'], ['a number', '3'], - ['no sdk', JSON.stringify({ sdkVersion: '1', options: [] })], - ['no version', JSON.stringify({ sdk: 'ios', options: [] })], - ['no options', JSON.stringify({ sdk: 'ios', sdkVersion: '1' })], - ['options that are not a list', JSON.stringify({ sdk: 'ios', sdkVersion: '1', options: {} })], + ['a list', '[]'], + ['no sdk', JSON.stringify({ manifestVersion: 1, sdkVersion: '1', options: [] })], + ['no version', JSON.stringify({ manifestVersion: 1, sdk: 'ios', options: [] })], + ['no options', JSON.stringify({ manifestVersion: 1, sdk: 'ios', sdkVersion: '1' })], + ['options that are not a list', JSON.stringify({ manifestVersion: 1, sdk: 'ios', sdkVersion: '1', options: {} })], ])('refuses %s, naming the source', (_name, text) => { expect(() => parseManifest(text, 'the-source')).toThrow(/the-source/); }); + + it.each([ + ['a later version', 2], + ['no version', undefined], + ['a version that is a string', '1'], + ])('refuses %s, saying which version it found', (_name, version) => { + const text = JSON.stringify({ manifestVersion: version, sdk: 'ios', sdkVersion: '1', options: [] }); + expect(() => parseManifest(text, 'the-source')).toThrow(/manifestVersion .*this check reads version 1/); + }); + + it('names the version it found', () => { + expect(() => parseManifest(JSON.stringify({ manifestVersion: 2, sdk: 'a', sdkVersion: '1', options: [] }), 's')).toThrow( + 's is manifestVersion 2; this check reads version 1', + ); + }); + + const withRow = (row: unknown): string => + JSON.stringify({ manifestVersion: 1, sdk: 'ios', sdkVersion: '1', options: [{ key: 'a', type: 'boolean' }, row] }); + + it.each([ + ['a row that is not an object', 'x', /option #1 is not an object/], + ['a row that is a list', [], /option #1 is not an object/], + ['a row with no key', { type: 'boolean' }, /option #1 has no key/], + ['a row with an empty key', { key: '', type: 'boolean' }, /option #1 has no key/], + ['a row with no type', { key: 'b' }, /option #1 \(b\) has no type/], + ['a hidden flag that is not a boolean', { key: 'b', type: 'boolean', hidden: 'yes' }, /\(b\) has a hidden flag that is not a boolean/], + ['an enum with no name', { key: 'b', type: 'enum', enum: { values: {} } }, /\(b\) has an enum without a name and values/], + ['an enum with no values', { key: 'b', type: 'enum', enum: { name: 'E' } }, /\(b\) has an enum without a name and values/], + ['an enum that is not an object', { key: 'b', type: 'enum', enum: 'E' }, /\(b\) has an enum without a name and values/], + ])('refuses %s, naming the row', (_name, row, message) => { + expect(() => parseManifest(withRow(row), 'the-source')).toThrow(message); + }); + + it('accepts a row with a hidden flag, a deprecation and an enum', () => { + const text = withRow({ key: 'b', type: 'enum', hidden: false, deprecated: { since: '1' }, enum: { name: 'E', values: { A: 1 } } }); + expect(parseManifest(text, 's').options).toHaveLength(2); + }); }); describe('checkPublished', () => { diff --git a/scripts/cli-options-sources.ts b/scripts/cli-options-sources.ts index d332307c..e4c2a127 100644 --- a/scripts/cli-options-sources.ts +++ b/scripts/cli-options-sources.ts @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { parseAccessors, type AccessorInfo } from './option-accessors.ts'; -import type { PublishedManifest, PublishedOption } from './published-manifest.ts'; +import { parseManifest, type PublishedManifest, type PublishedOption } from './published-manifest.ts'; export const root = join(import.meta.dirname, '..'); export const optionsDir = join(root, 'packages', 'react-native', 'src', 'options'); @@ -20,8 +20,13 @@ export const keys = readJson<{ shared: string[]; ios: string[]; android: string[ export const fixtureName = (platform: 'android' | 'ios'): string => `${platform}-options-manifest.json`; +/** + * A committed copy of a manifest, read as strictly as the published one: a file that is `{}` or has + * malformed rows must fail the check, not turn the comparison against it into a no-op. + */ export function readFixture(platform: 'android' | 'ios'): PublishedManifest { - return readJson(join(optionsDir, fixtureName(platform))); + const name = fixtureName(platform); + return parseManifest(readFileSync(join(optionsDir, name), 'utf8'), name); } export function fixtureOptions(platform: 'android' | 'ios'): PublishedOption[] { diff --git a/scripts/option-accessors.ts b/scripts/option-accessors.ts index a59e888a..c2a25d8b 100644 --- a/scripts/option-accessors.ts +++ b/scripts/option-accessors.ts @@ -3,7 +3,9 @@ * platform subclasses, so a check can compare what this package declares with what the SDKs publish. * * It reads the source, not the compiled classes, because the declared TYPE of an accessor exists only - * there. The accessors are uniform (`get x(): T | undefined { return this.$get('key'); }` and the + * there. A doc comment is the one directly above its getter: the pattern for it cannot run past a + * comment end, or the first accessor of a file would swallow the class comment and every member that is + * not an accessor. The accessors are uniform (`get x(): T | undefined { return this.$get('key'); }` and the * matching setter), which is what makes this a reading and not a TypeScript parser: an accessor that * deviates from the shape is not found, and the check then reports its option as missing rather than * passing it unseen. @@ -50,7 +52,7 @@ export function escapeRegExp(text: string): string { } const GETTER = - /(?:\/\*\*([\s\S]*?)\*\/\s*)?get (\w+)\(\): ([^{]*?) \| undefined \{\s*return this\.\$get\('([^']+)'\);\s*\}/g; + /(?:\/\*\*((?:(?!\*\/)[\s\S])*?)\*\/\s*)?get (\w+)\(\): ([^{]*?) \| undefined \{\s*return this\.\$get\('([^']+)'\);\s*\}/g; export function parseAccessors(source: string, owner: Owner): AccessorInfo[] { const accessors: AccessorInfo[] = []; diff --git a/scripts/published-manifest.ts b/scripts/published-manifest.ts index 3bfb1589..ab753c0f 100644 --- a/scripts/published-manifest.ts +++ b/scripts/published-manifest.ts @@ -39,7 +39,41 @@ export function manifestUrl(base: string, platform: Platform, version: string): return `${base.replace(/\/+$/, '')}/${platform}/${version}.json`; } -/** Rejects anything that is not a version-1 manifest, rather than comparing against a half-read one. */ +/** What this check reads: the only manifest format it understands. */ +export const SUPPORTED_MANIFEST_VERSION = 1; + +function isObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** The reason an option row is unusable, or undefined when it is a version-1 row. */ +function rowProblem(row: unknown): string | undefined { + if (!isObject(row)) { + return 'is not an object'; + } + if (typeof row.key !== 'string' || row.key === '') { + return 'has no key'; + } + if (typeof row.type !== 'string') { + return `(${row.key}) has no type`; + } + if (row.hidden !== undefined && typeof row.hidden !== 'boolean') { + return `(${row.key}) has a hidden flag that is not a boolean`; + } + if (row.enum !== undefined) { + const named = isObject(row.enum) && typeof row.enum.name === 'string' && isObject(row.enum.values); + if (!named) { + return `(${row.key}) has an enum without a name and values`; + } + } + return undefined; +} + +/** + * Rejects anything that is not a manifest this check can read, rather than comparing against a + * half-understood one. Version 1 is the only format: a later one may rename `hidden`, `deprecated` or + * `enum`, and comparing it as version 1 would pass differences it cannot see. + */ export function parseManifest(text: string, source: string): PublishedManifest { let parsed: unknown; try { @@ -47,17 +81,27 @@ export function parseManifest(text: string, source: string): PublishedManifest { } catch { throw new Error(`${source} is not valid JSON`); } - const manifest = parsed as Partial | null; if ( - manifest === null || - typeof manifest !== 'object' || - typeof manifest.sdk !== 'string' || - typeof manifest.sdkVersion !== 'string' || - !Array.isArray(manifest.options) + !isObject(parsed) || + typeof parsed.sdk !== 'string' || + typeof parsed.sdkVersion !== 'string' || + !Array.isArray(parsed.options) ) { throw new Error(`${source} is not an option manifest (needs sdk, sdkVersion and options)`); } - return manifest as PublishedManifest; + if (parsed.manifestVersion !== SUPPORTED_MANIFEST_VERSION) { + throw new Error( + `${source} is manifestVersion ${JSON.stringify(parsed.manifestVersion)}; ` + + `this check reads version ${SUPPORTED_MANIFEST_VERSION}`, + ); + } + for (const [index, row] of parsed.options.entries()) { + const problem = rowProblem(row); + if (problem !== undefined) { + throw new Error(`${source}: option #${index} ${problem}`); + } + } + return parsed as unknown as PublishedManifest; } /** The fields the committed manifest and the published one must agree on, in a comparable form. */ From c74fa3f7ced6052f7d63c74cedfac488d3d24691 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 14:10:37 +0500 Subject: [PATCH 13/16] Do not expose showVideoCapturePreview / hideVideoCapturePreview Removed from the native module spec, both bridges, the mock, the JS facade, the tests and the docs, as requested in review. The parity map now exempts both iOS methods with a reason (an SDK debug overlay, deliberately not exposed), so the guard still accounts for them. Human guided, AI implemented --- docs/native-api-parity.md | 5 ++--- packages/react-native/README.md | 4 ++-- .../java/com/bugsee/reactnative/BugseeModule.java | 10 ---------- packages/react-native/ios/BugseeModule.mm | 12 ------------ packages/react-native/src/NativeBugsee.ts | 3 --- packages/react-native/src/__mocks__/native.ts | 2 -- .../react-native/src/__tests__/native-api.test.ts | 7 ------- packages/react-native/src/index.ts | 13 ------------- scripts/sdk-api-map.ts | 5 +++-- 9 files changed, 7 insertions(+), 54 deletions(-) diff --git a/docs/native-api-parity.md b/docs/native-api-parity.md index 60c71b6a..262e1cd4 100644 --- a/docs/native-api-parity.md +++ b/docs/native-api-parity.md @@ -9,15 +9,13 @@ versions in `native-versions.json`. ## Platform-specific calls -These exist in only one SDK. They are no-ops on the other platform, like `startBlackout` before launch is a no-op where -the SDK cannot honour it. +These exist in only one SDK, and are no-ops on the other platform. | Method | Android | iOS | |---|---|---| | `resetVideoCapturePermission()` | forgets the stored fullscreen-capture consent | no-op | | `addSecureActivity(className)`, `removeSecureActivity(className)` | hides the activity from capture | no-op | | `isSecureActivity(className)` | whether the activity is secure | `false` | -| `showVideoCapturePreview()`, `hideVideoCapturePreview()` | no-op | debug overlay of what video capture records | ## Not exposed, and why @@ -29,6 +27,7 @@ the SDK cannot honour it. | `getDefaultNetworkSanitizer`, `getExchangeFactory` | used inside the wrapper's own filter and event bridges. | | `getVideoFrameConsumer` | SPI for wrappers that feed their own video frames; this one records natively. | | `setWrapper`, `onUncaughtException`, `delegate`, `sharedInstance` | the wrapper's own plumbing. | +| `showVideoCapturePreview`, `hideVideoCapturePreview` (iOS) | an SDK debug overlay for checking video capture; deliberately not exposed. | | `getLaunched`, `launched` | `await getStatus()` against `Status.Launched`. | | `addSecureViews`, `setLogFilter` (Android) | deprecated in the SDK. | diff --git a/packages/react-native/README.md b/packages/react-native/README.md index b6d3ea9a..81200ecb 100644 --- a/packages/react-native/README.md +++ b/packages/react-native/README.md @@ -123,8 +123,8 @@ The full list, with keys, types and platforms, is in ### Methods that exist on one platform `getHostLaunchOptions()` returns only what your app supplied to `launch`. Android-only: `resetVideoCapturePermission()`, -`addSecureActivity(className)`, `removeSecureActivity(className)`, `isSecureActivity(className)`. iOS-only: -`showVideoCapturePreview()`, `hideVideoCapturePreview()`. The other platform treats these as no-ops. Which native methods +`addSecureActivity(className)`, `removeSecureActivity(className)`, `isSecureActivity(className)`. iOS treats +these as no-ops. Which native methods this package does not expose, and why, is in [`docs/native-api-parity.md`](https://github.com/bugsee/bugsee-react-native/blob/main/docs/native-api-parity.md). diff --git a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java index 2a3e03cf..1f2cb2a0 100644 --- a/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +++ b/packages/react-native/android/src/main/java/com/bugsee/reactnative/BugseeModule.java @@ -524,16 +524,6 @@ public void isSecureActivity(final String className, final Promise promise) { promise.resolve(Bugsee.isSecureActivity(className)); } - @Override - public void showVideoCapturePreview() { - // iOS-only debug overlay. - } - - @Override - public void hideVideoCapturePreview() { - // iOS-only debug overlay. - } - /** * A handled JS exception. Posted onto {@link ExceptionExecutors#HANDLED}: * the SDK must not run on the native-modules thread. diff --git a/packages/react-native/ios/BugseeModule.mm b/packages/react-native/ios/BugseeModule.mm index 00d90f9a..c168210c 100644 --- a/packages/react-native/ios/BugseeModule.mm +++ b/packages/react-native/ios/BugseeModule.mm @@ -1466,18 +1466,6 @@ - (void)isSecureActivity:(NSString *)className resolve(@NO); } -- (void)showVideoCapturePreview { - BGSRNRunOnMain(^{ - [Bugsee showVideoCapturePreview]; - }); -} - -- (void)hideVideoCapturePreview { - BGSRNRunOnMain(^{ - [Bugsee hideVideoCapturePreview]; - }); -} - /// A handled JS exception. `payloadJson` is the Task 7.1a payload, forwarded /// verbatim as the reason; `optionsJson` is `{domain?}` or null. Unparseable /// options are logged and the exception is still sent, without a domain — a diff --git a/packages/react-native/src/NativeBugsee.ts b/packages/react-native/src/NativeBugsee.ts index 7610d9e8..6a7eeffd 100644 --- a/packages/react-native/src/NativeBugsee.ts +++ b/packages/react-native/src/NativeBugsee.ts @@ -171,9 +171,6 @@ export interface Spec extends TurboModule { removeSecureActivity(className: string): void; /** Whether the activity is currently secure. Always `false` on iOS. */ isSecureActivity(className: string): Promise; - /** iOS: shows the debug overlay of what video capture is recording. No-op on Android. */ - showVideoCapturePreview(): void; - hideVideoCapturePreview(): void; /** * Creates and uploads a bug report immediately, without showing any UI. diff --git a/packages/react-native/src/__mocks__/native.ts b/packages/react-native/src/__mocks__/native.ts index 90b66828..e2089a3f 100644 --- a/packages/react-native/src/__mocks__/native.ts +++ b/packages/react-native/src/__mocks__/native.ts @@ -274,8 +274,6 @@ export const native = { addSecureActivity: jest.fn(), removeSecureActivity: jest.fn(), isSecureActivity: jest.fn, [string]>(), - showVideoCapturePreview: jest.fn(), - hideVideoCapturePreview: jest.fn(), testCrash: jest.fn(), upload: jest.fn(), showReportDialog: diff --git a/packages/react-native/src/__tests__/native-api.test.ts b/packages/react-native/src/__tests__/native-api.test.ts index 8cf640c4..f675ec9b 100644 --- a/packages/react-native/src/__tests__/native-api.test.ts +++ b/packages/react-native/src/__tests__/native-api.test.ts @@ -81,11 +81,4 @@ describe('platform-specific calls forward to native', () => { await expect(Bugsee.isSecureActivity('com.example.A')).resolves.toBe(true); expect(native.isSecureActivity).toHaveBeenCalledWith('com.example.A'); }); - - it('showVideoCapturePreview and hideVideoCapturePreview', () => { - Bugsee.showVideoCapturePreview(); - Bugsee.hideVideoCapturePreview(); - expect(native.showVideoCapturePreview).toHaveBeenCalledTimes(1); - expect(native.hideVideoCapturePreview).toHaveBeenCalledTimes(1); - }); }); diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index 90941435..46850792 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -827,19 +827,6 @@ class Bugsee { return NativeBugsee.isSecureActivity(className); } - /** - * iOS: shows a debug overlay of what video capture is recording, to check that - * secure regions are covered. No-op on Android. - */ - showVideoCapturePreview(): void { - NativeBugsee.showVideoCapturePreview(); - } - - /** iOS: hides the overlay {@link showVideoCapturePreview} showed. No-op on Android. */ - hideVideoCapturePreview(): void { - NativeBugsee.hideVideoCapturePreview(); - } - /** * The SDK's own test crash: a Java `RuntimeException` on Android, an * `NSException` on iOS. For a real native (signal) crash, see the bare diff --git a/scripts/sdk-api-map.ts b/scripts/sdk-api-map.ts index 50350d25..6f5280a0 100644 --- a/scripts/sdk-api-map.ts +++ b/scripts/sdk-api-map.ts @@ -23,6 +23,7 @@ const NOT_READ_BACK = skip('the wrapper owns the rectangles it publishes; the SD const EXT = skip('native extension lookup and registration; extension SPIs are not callable from JavaScript'); const SANITIZER = skip('used inside the wrapper\'s own network-filter bridge, not callable from JavaScript'); const EXCHANGE = skip('internal: builds the events addNetworkEvent and addBreadcrumb take'); +const DEBUG_OVERLAY = skip('an iOS SDK debug overlay for checking video capture; deliberately not exposed'); const STATUS = skip('derivable: `await getStatus()` against `Status.Launched`'); export const ANDROID: Readonly> = { @@ -115,7 +116,7 @@ export const IOS: Readonly> = { getHostLaunchOptions: rn('getHostLaunchOptions'), getLaunchOptions: rn('getLaunchOptions'), getUserIdentifier: rn('getUserIdentifier'), - hideVideoCapturePreview: rn('hideVideoCapturePreview'), + hideVideoCapturePreview: DEBUG_OVERLAY, isBlackout: rn('isBlackout'), launchWithToken: rn('launch'), launched: STATUS, @@ -139,7 +140,7 @@ export const IOS: Readonly> = { sharedInstance: skip('singleton accessor; the wrapper calls the class methods directly'), showReportDialog: rn('showReportDialog'), showReportDialogWithSummary: rn('showReportDialog'), - showVideoCapturePreview: rn('showVideoCapturePreview'), + showVideoCapturePreview: DEBUG_OVERLAY, startBlackout: rn('startBlackout'), startSpanWithOperation: rn('startSpan'), startTransactionWithName: rn('startTransaction'), From 7bd6a0b1cc4277a9a9340c4169f4e49b3440402e Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 16:08:15 +0500 Subject: [PATCH 14/16] Address review: read Android method declarations across lines The extractor matched `public static ...` one line at a time, so a declaration split across lines (`public static` / `void added() {}`) was omitted, and an inventory missing a method lets the parity test pass without a mapping for it. It now reads the whole source, with the modifiers, return type and name allowed on separate lines, and still ignores fields, nested classes and comments. A regression fixture covers single-line and split declarations, a split generic signature, a split @Deprecated one, and the non-declarations. Regenerating from the pinned checkouts gives the same 61 methods, so none was being missed there. Human guided, AI implemented --- .../src/__tests__/sdk-api-parity.test.ts | 29 +++++++++++++++++++ scripts/sdk-api.ts | 28 +++++++++++------- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/packages/react-native/src/__tests__/sdk-api-parity.test.ts b/packages/react-native/src/__tests__/sdk-api-parity.test.ts index bb61fb08..dc03090b 100644 --- a/packages/react-native/src/__tests__/sdk-api-parity.test.ts +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -84,6 +84,35 @@ describe('the extractors', () => { ]); }); + it('read a declaration split across lines, which a line-by-line reading missed', () => { + const source = ` + public final class Bugsee { + public static void single() {} + public static + void modifiersSplit() {} + public static void + nameOnNextLine() {} + public static + T genericSplit(Class type) { return null; } + @Deprecated + public static + void deprecatedSplit() {} + public static final int FIELD = compute(1); + public static class Nested { + void notAMethod() {} + } + // public static void inAComment() {} + /* public static void inABlockComment() {} */ + }`; + expect(parseAndroidApi(source)).toEqual([ + { name: 'deprecatedSplit', deprecated: true }, + { name: 'genericSplit', deprecated: false }, + { name: 'modifiersSplit', deprecated: false }, + { name: 'nameOnNextLine', deprecated: false }, + { name: 'single', deprecated: false }, + ]); + }); + it('read the class methods and properties of the iOS Bugsee interface only', () => { const header = ` @interface Other : NSObject diff --git a/scripts/sdk-api.ts b/scripts/sdk-api.ts index c3f1709c..b09a3416 100644 --- a/scripts/sdk-api.ts +++ b/scripts/sdk-api.ts @@ -10,32 +10,38 @@ export interface SdkMethod { deprecated: boolean; } +/** + * A public static method declaration, read across line breaks: the modifiers, the return type and the + * name may each sit on their own line. Reading line by line missed `public static` followed by + * `void added() {}`, and an extraction that misses a method writes an incomplete inventory the parity + * test then passes. Anchored at a line start, so a mention inside a comment (` * public static ...`) is + * not a declaration; `{`, `;` and `=` are outside the type pattern, so a field or a nested class is not + * one either. + */ +const ANDROID_DECLARATION = /^[ \t]*public\s+static\s+(?:<[^>]+>\s+)?[\w<>[\],.?\s]+?\s+(\w+)\s*\(/gm; + /** Public static methods of the Android `Bugsee` class, deduplicated across overloads. */ export function parseAndroidApi(source: string): SdkMethod[] { - const lines = source.split('\n'); const methods = new Map(); - lines.forEach((line, index) => { - const match = /^\s*public\s+static\s+(?:<[^>]+>\s+)?[\w<>[\],.? ]+?\s+(\w+)\s*\(/.exec(line); - if (!match) { - return; - } + for (const match of source.matchAll(ANDROID_DECLARATION)) { const name = match[1] as string; // Only the annotations and comments directly above this method: a wider window reads // the previous method's @Deprecated as this one's. + const above = source.slice(0, match.index).split('\n'); let deprecated = false; - for (let up = index - 1; up >= 0; up--) { - const above = (lines[up] as string).trim(); - if (/^@Deprecated\b/.test(above)) { + for (let up = above.length - 1; up >= 0; up--) { + const line = (above[up] as string).trim(); + if (/^@Deprecated\b/.test(line)) { deprecated = true; } - if (above !== '' && !/^(?:@|\/\*|\*|\/\/)/.test(above)) { + if (line !== '' && !/^(?:@|\/\*|\*|\/\/)/.test(line)) { break; } } const previous = methods.get(name); // A name is deprecated only when every overload is. methods.set(name, { name, deprecated: previous ? previous.deprecated && deprecated : deprecated }); - }); + } if (methods.size === 0) { throw new Error('no public static methods found; the parser missed the source'); } From c9a87be3f30ca7d871bac74ae4714ea48a27ca4d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 16:45:47 +0500 Subject: [PATCH 15/16] Address review: read annotated Android method declarations The declaration pattern still missed two legal forms: an annotation on the same line as `public` (`@Deprecated public static void old()`) and one inside the signature (`public static @Nullable String name()`). Both are now read, with or without annotation arguments, and `synchronized`/`final` and generic returns too. A same-line @Deprecated marks that method deprecated; the upward scan now treats only annotation-only lines as belonging to the method below, so a one-line annotated declaration is not mistaken for the next method's annotation. Regenerating from the pinned v7.4.2 checkout gives the same 61 methods, so the pinned SDK uses neither form today; the fixture covers both for a later release. Human guided, AI implemented --- .../src/__tests__/sdk-api-parity.test.ts | 12 +++++++ scripts/sdk-api.ts | 31 +++++++++++++------ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/packages/react-native/src/__tests__/sdk-api-parity.test.ts b/packages/react-native/src/__tests__/sdk-api-parity.test.ts index dc03090b..3f38ed3d 100644 --- a/packages/react-native/src/__tests__/sdk-api-parity.test.ts +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -97,6 +97,12 @@ describe('the extractors', () => { @Deprecated public static void deprecatedSplit() {} + @Deprecated public static void oldSameLine() {} + @Deprecated @Nullable public static void twoAnnotations() {} + public static @Nullable String annotated() { return null; } + public static @Size(max = 3) String annotatedWithArgument() { return null; } + public static final synchronized void withModifiers() {} + public static Map genericReturn() { return null; } public static final int FIELD = compute(1); public static class Nested { void notAMethod() {} @@ -105,11 +111,17 @@ describe('the extractors', () => { /* public static void inABlockComment() {} */ }`; expect(parseAndroidApi(source)).toEqual([ + { name: 'annotated', deprecated: false }, + { name: 'annotatedWithArgument', deprecated: false }, { name: 'deprecatedSplit', deprecated: true }, + { name: 'genericReturn', deprecated: false }, { name: 'genericSplit', deprecated: false }, { name: 'modifiersSplit', deprecated: false }, { name: 'nameOnNextLine', deprecated: false }, + { name: 'oldSameLine', deprecated: true }, { name: 'single', deprecated: false }, + { name: 'twoAnnotations', deprecated: true }, + { name: 'withModifiers', deprecated: false }, ]); }); diff --git a/scripts/sdk-api.ts b/scripts/sdk-api.ts index b09a3416..3a88cb9d 100644 --- a/scripts/sdk-api.ts +++ b/scripts/sdk-api.ts @@ -14,27 +14,38 @@ export interface SdkMethod { * A public static method declaration, read across line breaks: the modifiers, the return type and the * name may each sit on their own line. Reading line by line missed `public static` followed by * `void added() {}`, and an extraction that misses a method writes an incomplete inventory the parity - * test then passes. Anchored at a line start, so a mention inside a comment (` * public static ...`) is - * not a declaration; `{`, `;` and `=` are outside the type pattern, so a field or a nested class is not - * one either. + * test then passes. + * + * Annotations are allowed in front of `public` (`@Deprecated public static void old()`) and among the + * signature's words (`public static @Nullable String name()`), with or without arguments. Everything + * between `static` and the name is a run of words or annotations each followed by whitespace, so `=`, + * `;` and `{` end it: a field or a nested class is not a declaration. It is anchored at a line start, so + * a mention inside a comment (` * public static ...`) is not one either. */ -const ANDROID_DECLARATION = /^[ \t]*public\s+static\s+(?:<[^>]+>\s+)?[\w<>[\],.?\s]+?\s+(\w+)\s*\(/gm; +const ANDROID_DECLARATION = + /^[ \t]*((?:@\w+(?:\([^)]*\))?\s+)*)public\s+static\s+(?:(?:@\w+(?:\([^)]*\))?|[\w<>[\],.?]+)\s+)+(\w+)\s*\(/gm; + +const ANNOTATIONS_ONLY = /^(?:@\w+(?:\([^)]*\))?\s*)+$/; /** Public static methods of the Android `Bugsee` class, deduplicated across overloads. */ export function parseAndroidApi(source: string): SdkMethod[] { const methods = new Map(); for (const match of source.matchAll(ANDROID_DECLARATION)) { - const name = match[1] as string; - // Only the annotations and comments directly above this method: a wider window reads - // the previous method's @Deprecated as this one's. + const name = match[2] as string; + // Deprecated when annotated on the same line as `public`, or by the annotations and comments directly + // above: a wider window reads the previous method's @Deprecated as this one's. const above = source.slice(0, match.index).split('\n'); - let deprecated = false; + let deprecated = /@Deprecated\b/.test(match[1] as string); for (let up = above.length - 1; up >= 0; up--) { const line = (above[up] as string).trim(); - if (/^@Deprecated\b/.test(line)) { + // A line that only carries annotations belongs to the declaration below it. A line that starts + // with one but goes on to declare a method (`@Deprecated public static void old() {}`) is that + // method's own, and ends the search. + const annotationsOnly = ANNOTATIONS_ONLY.test(line); + if (annotationsOnly && /@Deprecated\b/.test(line)) { deprecated = true; } - if (line !== '' && !/^(?:@|\/\*|\*|\/\/)/.test(line)) { + if (line !== '' && !annotationsOnly && !/^(?:\/\*|\*|\/\/)/.test(line)) { break; } } From 628381373ea9db9d96eeeec4d4da3a77f7400c01 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 16 Nov 2026 17:05:48 +0500 Subject: [PATCH 16/16] Address review: accept modifiers between `public` and `static` Java does not fix the order of modifiers, so `public final static void x()` is a public static method, but the pattern required `public static` adjacent and omitted it. `final`, `synchronized`, `native` and `strictfp` are now accepted between the two as well as after. The fixture gains each form beside matching methods, and a `public final static` field, which must still not be read as a method. The pinned SDK has no such declaration, so sdk-api.json is unchanged. Human guided, AI implemented --- .../react-native/src/__tests__/sdk-api-parity.test.ts | 9 +++++++++ scripts/sdk-api.ts | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/react-native/src/__tests__/sdk-api-parity.test.ts b/packages/react-native/src/__tests__/sdk-api-parity.test.ts index 3f38ed3d..578fd2a8 100644 --- a/packages/react-native/src/__tests__/sdk-api-parity.test.ts +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -102,6 +102,11 @@ describe('the extractors', () => { public static @Nullable String annotated() { return null; } public static @Size(max = 3) String annotatedWithArgument() { return null; } public static final synchronized void withModifiers() {} + public final static void modifierBeforeStatic() {} + public synchronized static void synchronizedBeforeStatic() {} + public final synchronized static void twoBeforeStatic() {} + public native static void nativeBeforeStatic(); + public final static int NOT_A_METHOD = 3; public static Map genericReturn() { return null; } public static final int FIELD = compute(1); public static class Nested { @@ -116,11 +121,15 @@ describe('the extractors', () => { { name: 'deprecatedSplit', deprecated: true }, { name: 'genericReturn', deprecated: false }, { name: 'genericSplit', deprecated: false }, + { name: 'modifierBeforeStatic', deprecated: false }, { name: 'modifiersSplit', deprecated: false }, { name: 'nameOnNextLine', deprecated: false }, + { name: 'nativeBeforeStatic', deprecated: false }, { name: 'oldSameLine', deprecated: true }, { name: 'single', deprecated: false }, + { name: 'synchronizedBeforeStatic', deprecated: false }, { name: 'twoAnnotations', deprecated: true }, + { name: 'twoBeforeStatic', deprecated: false }, { name: 'withModifiers', deprecated: false }, ]); }); diff --git a/scripts/sdk-api.ts b/scripts/sdk-api.ts index 3a88cb9d..fcb483bd 100644 --- a/scripts/sdk-api.ts +++ b/scripts/sdk-api.ts @@ -16,6 +16,9 @@ export interface SdkMethod { * `void added() {}`, and an extraction that misses a method writes an incomplete inventory the parity * test then passes. * + * Java does not fix the order of modifiers, so `final`, `synchronized`, `native` and `strictfp` may sit + * between `public` and `static` as well as after it (`public final static void x()`). + * * Annotations are allowed in front of `public` (`@Deprecated public static void old()`) and among the * signature's words (`public static @Nullable String name()`), with or without arguments. Everything * between `static` and the name is a run of words or annotations each followed by whitespace, so `=`, @@ -23,7 +26,7 @@ export interface SdkMethod { * a mention inside a comment (` * public static ...`) is not one either. */ const ANDROID_DECLARATION = - /^[ \t]*((?:@\w+(?:\([^)]*\))?\s+)*)public\s+static\s+(?:(?:@\w+(?:\([^)]*\))?|[\w<>[\],.?]+)\s+)+(\w+)\s*\(/gm; + /^[ \t]*((?:@\w+(?:\([^)]*\))?\s+)*)public\s+(?:(?:final|synchronized|native|strictfp)\s+)*static\s+(?:(?:@\w+(?:\([^)]*\))?|[\w<>[\],.?]+)\s+)+(\w+)\s*\(/gm; const ANNOTATIONS_ONLY = /^(?:@\w+(?:\([^)]*\))?\s*)+$/;