diff --git a/docs/launch-options.md b/docs/launch-options.md index c6ebaf5e..2d0b0642 100644 --- a/docs/launch-options.md +++ b/docs/launch-options.md @@ -34,8 +34,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..262e1cd4 --- /dev/null +++ b/docs/native-api-parity.md @@ -0,0 +1,35 @@ +# 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, 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` | + +## 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. | +| `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. | + +`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..81200ecb 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 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..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 @@ -493,11 +493,37 @@ 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)); + } + /** * 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..c168210c 100644 --- a/packages/react-native/ios/BugseeModule.mm +++ b/packages/react-native/ios/BugseeModule.mm @@ -1432,12 +1432,40 @@ - (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); +} + /// 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..6a7eeffd 100644 --- a/packages/react-native/src/NativeBugsee.ts +++ b/packages/react-native/src/NativeBugsee.ts @@ -150,8 +150,28 @@ 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; + /** * 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..e2089a3f 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,11 @@ 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]>(), 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..f675ec9b --- /dev/null +++ b/packages/react-native/src/__tests__/native-api.test.ts @@ -0,0 +1,84 @@ +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'); + }); +}); 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..578fd2a8 --- /dev/null +++ b/packages/react-native/src/__tests__/sdk-api-parity.test.ts @@ -0,0 +1,156 @@ +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 nativeVersions from '../../../../native-versions.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('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); + + 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 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() {} + @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 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 { + void notAMethod() {} + } + // public static void inAComment() {} + /* 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: '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 }, + ]); + }); + + 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..46850792 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,42 @@ 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); + } + /** * 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..4a62290f --- /dev/null +++ b/scripts/cli-extract-sdk-api.ts @@ -0,0 +1,34 @@ +/** + * 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'; +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')); + +const out = join(import.meta.dirname, 'sdk-api.json'); +writeFileSync( + out, + `${JSON.stringify({ sdk: { android: readSdkVersion(androidRoot), ios: readSdkVersion(iosRoot) }, 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..6f5280a0 --- /dev/null +++ b/scripts/sdk-api-map.ts @@ -0,0 +1,153 @@ +/** + * 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 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> = { + 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: DEBUG_OVERLAY, + 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: DEBUG_OVERLAY, + 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..46a4e2a4 --- /dev/null +++ b/scripts/sdk-api.json @@ -0,0 +1,490 @@ +{ + "sdk": { + "android": "7.4.2", + "ios": "7.0.0" + }, + "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..fcb483bd --- /dev/null +++ b/scripts/sdk-api.ts @@ -0,0 +1,84 @@ +/** + * 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; +} + +/** + * 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. + * + * 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 `=`, + * `;` 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]*((?:@\w+(?:\([^)]*\))?\s+)*)public\s+(?:(?:final|synchronized|native|strictfp)\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[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 = /@Deprecated\b/.test(match[1] as string); + for (let up = above.length - 1; up >= 0; up--) { + const line = (above[up] as string).trim(); + // 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 !== '' && !annotationsOnly && !/^(?:\/\*|\*|\/\/)/.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'); + } + 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)); +}