@ledgerhq/device-transport-kit-react-native-ble 0.0.0-wrong-error-when-in-experimental-provider-20251021162636 → 0.0.0-zzz-solana-20251204140055
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/cjs/package.json +44 -40
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +2 -2
- package/lib/esm/package.json +44 -40
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +35 -31
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.test.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport { type Platform } from \"react-native\";\nimport { BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n BleDeviceInfos,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceModelDataSource,\n DeviceModelId,\n type DmkConfig,\n type LoggerPublisherService,\n OpeningConnectionError,\n TransportConnectedDevice,\n TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { firstValueFrom, Subject, Subscription } from \"rxjs\";\nimport { beforeEach, expect } from \"vitest\";\n\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n} from \"@api/model/Errors\";\nimport { DefaultPermissionsService } from \"@api/permissions/DefaultPermissionsService\";\nimport { PermissionsService } from \"@api/permissions/PermissionsService\";\n\nimport { type RNBleApduSenderDependencies } from \"./RNBleApduSender\";\nimport { RNBleTransport } from \"./RNBleTransport\";\nimport { RNBleTransportFactory } from \"./RNBleTransportFactory\";\n\n// ===== MOCKS =====\nconst fakeLogger: LoggerPublisherService = {\n error: vi.fn(),\n info: vi.fn(),\n warn: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n};\n\nconst consoleLogger: LoggerPublisherService = {\n error: console.error,\n info: console.info,\n warn: console.warn,\n debug: console.debug,\n subscribers: [],\n};\n\nvi.mock(\"react-native\", () => ({\n Platform: {},\n PermissionsAndroid: {},\n}));\n\nvi.mock(\"react-native-ble-plx\", () => ({\n Device: vi.fn(),\n State: {\n PoweredOn: \"PoweredOn\",\n Unknown: \"Unknown\",\n PoweredOff: \"PoweredOff\",\n Resetting: \"Resetting\",\n Unsupported: \"Unsupported\",\n Unauthorized: \"Unauthorized\",\n },\n BleError: vi.fn(),\n BleManager: vi.fn().mockReturnValue({\n onStateChange: vi.fn(),\n startDeviceScan: vi.fn(),\n stopDeviceScan: vi.fn(),\n connectToDevice: vi.fn(),\n disconnectFromDevice: vi.fn(),\n cancelDeviceConnection: vi.fn(),\n connectedDevices: vi.fn(),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n discoverAllServicesAndCharacteristicsForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n }),\n}));\n\n// ===== TEST DATA =====\nconst FAKE_DEVICE_MODEL = new TransportDeviceModel({\n id: DeviceModelId.FLEX,\n productName: \"Ledger Flex\",\n usbProductId: 0x70,\n bootloaderUsbProductId: 0x0007,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33300000],\n});\n\nconst IOS_PLATFORM = { OS: \"ios\" as const } as Platform;\nconst ANDROID_PLATFORM = { OS: \"android\" as const } as Platform;\nconst WINDOWS_PLATFORM = { OS: \"windows\" as const } as Platform;\n\n// ===== TEST HELPERS =====\nclass TestTransportBuilder {\n private deviceModelDataSource: DeviceModelDataSource = createFakeDataSource();\n private loggerServiceFactory = () =>\n fakeLogger as unknown as LoggerPublisherService;\n private apduSenderServiceFactory =\n (() => {}) as unknown as ApduSenderServiceFactory;\n private apduReceiverServiceFactory =\n (() => {}) as unknown as ApduReceiverServiceFactory;\n private bleManager = new BleManager();\n private platform: Platform = IOS_PLATFORM;\n private permissionsService: PermissionsService =\n new DefaultPermissionsService();\n private deviceConnectionStateMachineFactory?: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private deviceApduSenderFactory?: (args: any, loggerFactory: any) => any;\n private scanThrottleDelayMs: number = 1000;\n\n withDeviceModelDataSource(dataSource: DeviceModelDataSource) {\n this.deviceModelDataSource = dataSource;\n return this;\n }\n\n withPlatform(platform: Platform) {\n this.platform = platform;\n return this;\n }\n\n withPermissionsService(permissions: PermissionsService) {\n this.permissionsService = permissions;\n return this;\n }\n\n withBleManager(bleManager: BleManager) {\n this.bleManager = bleManager;\n return this;\n }\n\n withDeviceConnectionStateMachineFactory(\n factory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies>,\n ) {\n this.deviceConnectionStateMachineFactory = factory;\n return this;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withDeviceApduSenderFactory(factory: (args: any, loggerFactory: any) => any) {\n this.deviceApduSenderFactory = factory;\n return this;\n }\n\n withLogger(logger: LoggerPublisherService = consoleLogger) {\n this.loggerServiceFactory = () => logger;\n return this;\n }\n\n withScanThrottleDelayMs(delayMs: number) {\n this.scanThrottleDelayMs = delayMs;\n return this;\n }\n\n build(): RNBleTransport {\n return new RNBleTransport(\n this.deviceModelDataSource,\n this.loggerServiceFactory,\n this.apduSenderServiceFactory,\n this.apduReceiverServiceFactory,\n this.bleManager,\n this.platform,\n this.permissionsService,\n this.scanThrottleDelayMs,\n this.deviceConnectionStateMachineFactory,\n this.deviceApduSenderFactory,\n );\n }\n}\n\nfunction createFakeDataSource() {\n const getBluetoothServicesMock = vi.fn(() => [\"ledgerId\"]);\n const getBluetoothServicesInfosMock = vi.fn(() => ({\n ledgerId: new BleDeviceInfos(\n FAKE_DEVICE_MODEL,\n \"serviceUuid\",\n \"notifyUuid\",\n \"writeCmdUuid\",\n \"readCmdUuid\",\n ),\n }));\n\n return {\n getBluetoothServices: getBluetoothServicesMock,\n getBluetoothServicesInfos: getBluetoothServicesInfosMock,\n getAllDeviceModels: vi.fn(),\n getDeviceModel: vi.fn(),\n filterDeviceModels: vi.fn(),\n } as unknown as DeviceModelDataSource;\n}\n\nfunction createMockDevice(overrides: Partial<Device> = {}): Device {\n return {\n id: \"deviceId\",\n localName: \"deviceName\",\n serviceUUIDs: [\"ledgerId\"],\n services: vi.fn().mockResolvedValue([{ uuid: \"ledgerId\" }]),\n ...overrides,\n } as unknown as Device;\n}\n\nfunction createMockBleManager(\n overrides: Partial<BleManager> = {},\n initialState: State = State.PoweredOn,\n): BleManager {\n const mockBleManager = {\n onStateChange: vi\n .fn()\n .mockImplementation(\n (listener: (state: State) => void, emitInitialState: boolean) => {\n if (emitInitialState) listener(initialState);\n return { remove: vi.fn() };\n },\n ),\n startDeviceScan: vi.fn(),\n stopDeviceScan: vi.fn(),\n connectToDevice: vi.fn(),\n disconnectFromDevice: vi.fn(),\n cancelDeviceConnection: vi.fn(),\n connectedDevices: vi.fn().mockResolvedValue([]),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n discoverAllServicesAndCharacteristicsForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n state: vi.fn(),\n ...overrides,\n } as unknown as BleManager;\n\n return mockBleManager;\n}\n\n// ===== TEST SUITES =====\ndescribe(\"RNBleTransportFactory\", () => {\n it(\"should return a RNBleTransport\", () => {\n const fakeArgs = {\n deviceModelDataSource:\n createFakeDataSource() as unknown as DeviceModelDataSource,\n loggerServiceFactory: () =>\n fakeLogger as unknown as LoggerPublisherService,\n apduSenderServiceFactory:\n (() => {}) as unknown as ApduSenderServiceFactory,\n apduReceiverServiceFactory:\n (() => {}) as unknown as ApduReceiverServiceFactory,\n config: {} as DmkConfig,\n };\n\n const transport = RNBleTransportFactory(fakeArgs);\n\n expect(transport).toBeInstanceOf(RNBleTransport);\n });\n});\n\ndescribe(\"RNBleTransport\", () => {\n let subscription: Subscription | undefined;\n\n beforeEach(() => {\n vi.clearAllMocks();\n vi.useRealTimers();\n });\n\n afterEach(() => {\n if (subscription) {\n subscription.unsubscribe();\n }\n });\n\n describe(\"BLE state monitoring\", () => {\n test(\"the constructor should call BleManager.onStateChange with a parameter requesting the initial state\", () => {\n const mockedOnStateChange = vi.fn();\n\n new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: mockedOnStateChange,\n }),\n )\n .build();\n\n expect(mockedOnStateChange).toHaveBeenCalledWith(\n expect.any(Function),\n true,\n );\n });\n\n describe(\"observeBleState\", () => {\n it(\"should emit the initial BLE state\", async () => {\n const mockedOnStateChange = vi\n .fn()\n .mockImplementation(\n (listener: (state: State) => void, emitInitialState: boolean) => {\n if (emitInitialState) listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n );\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: mockedOnStateChange,\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n\n const initialState = await firstValueFrom(observable);\n\n expect(initialState).toBe(State.PoweredOn);\n });\n\n it(\"should emit the new BLE state values\", async () => {\n const statesSubject = new Subject<State>();\n\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n statesSubject.subscribe((newState) => listener(newState));\n return { remove: vi.fn() };\n },\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n\n // When a new state is emitted\n statesSubject.next(State.PoweredOff);\n\n // Then observeBleState should emit the new state\n const newState = await firstValueFrom(observable);\n expect(newState).toBe(State.PoweredOff);\n\n // When a new state is emitted\n statesSubject.next(State.Resetting);\n\n // Then observeBleState should emit the new state\n const newState2 = await firstValueFrom(observable);\n expect(newState2).toBe(State.Resetting);\n });\n\n it(\"should recover from an Unknown state by calling BleManager.state() method and emitting the new state\", async () => {\n vi.useFakeTimers();\n const statesSubject = new Subject<State>();\n\n const mockedStateFunction = vi.fn().mockImplementation(() => {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(State.PoweredOn);\n }, 10);\n });\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n state: mockedStateFunction,\n onStateChange: (listener: (state: State) => void) => {\n statesSubject.subscribe((newState) => listener(newState));\n return { remove: vi.fn() };\n },\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n statesSubject.next(State.PoweredOff);\n\n expect(mockedStateFunction).not.toHaveBeenCalled();\n\n // Emit new state Unknown\n statesSubject.next(State.Unknown);\n\n // The value Unknown should be emitted\n const newState = await firstValueFrom(observable);\n expect(newState).toBe(State.Unknown);\n\n // BleManager.state() should be called\n expect(mockedStateFunction).toHaveBeenCalled();\n\n vi.advanceTimersByTime(11);\n\n await Promise.resolve();\n\n // And the value returned by BleManager.state() should be emitted\n const newState2 = await firstValueFrom(observable);\n expect(newState2).toBe(State.PoweredOn);\n });\n });\n });\n\n describe(\"getIdentifier\", () => {\n it(\"should return rnBleTransportIdentifier\", () => {\n const transport = new TestTransportBuilder().build();\n const identifier = transport.getIdentifier();\n expect(identifier).toStrictEqual(\"RN_BLE\");\n });\n });\n\n describe(\"isSupported\", () => {\n it(\"should return true if platform is ios\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(IOS_PLATFORM)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(true);\n });\n\n it(\"should return true if platform is android\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(ANDROID_PLATFORM as Platform)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(true);\n });\n\n it(\"should return false if platform is not android nor ios\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(WINDOWS_PLATFORM)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(false);\n });\n });\n\n describe(\"startDiscovering\", () => {\n it(\"should emit an empty array\", () =>\n new Promise((done, reject) => {\n const transport = new TestTransportBuilder()\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .build();\n\n const observable = transport.startDiscovering();\n\n subscription = observable.subscribe({\n next: (discoveredDevice) => {\n try {\n expect(discoveredDevice).toStrictEqual([]);\n } catch (e) {\n reject(e);\n }\n },\n error: (e) => {\n reject(e);\n throw e;\n },\n complete: () => {\n done(undefined);\n },\n });\n }));\n });\n\n describe(\"stopDiscovering\", () => {\n it(\"should call ble manager stop scan on stop discovering\", () => {\n const stopDeviceScan = vi.fn();\n const bleManager = createMockBleManager({\n stopDeviceScan,\n connectedDevices: vi.fn().mockResolvedValueOnce([]),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .build();\n\n transport.stopDiscovering();\n\n expect(stopDeviceScan).toHaveBeenCalled();\n });\n });\n\n describe(\"listenToAvailableDevices\", () => {\n it(\"should emit an error if platform is not android nor ios\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager())\n .withPlatform(WINDOWS_PLATFORM)\n .build();\n\n return new Promise((done, reject) => {\n transport.listenToAvailableDevices().subscribe({\n error: (e) => {\n try {\n expect(e).toBeInstanceOf(BleNotSupported);\n } catch (innerError) {\n reject(innerError);\n }\n done(undefined);\n },\n complete: () => {\n reject(new Error(\"Should not complete\"));\n },\n });\n });\n });\n\n it(\"should emit an error if BLE state is PoweredOff\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({}, State.PoweredOff))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n let caughtError: unknown;\n await firstValueFrom(observable).catch((e) => {\n caughtError = e;\n });\n\n expect(caughtError).toBeInstanceOf(BlePoweredOff);\n });\n\n describe(\"permissions check\", () => {\n const checkPermissions = vi.fn();\n const requestPermissions = vi.fn();\n\n const mockedPermissionsService = {\n checkRequiredPermissions: checkPermissions,\n requestRequiredPermissions: requestPermissions,\n };\n\n const startDeviceScan = vi.fn().mockImplementation(async () => {});\n const bleManager = createMockBleManager({\n startDeviceScan: startDeviceScan,\n stopDeviceScan: vi.fn(),\n connectedDevices: vi.fn().mockResolvedValue([]),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n it(\"should call checkPermissions\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch((e) => {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n });\n\n expect(checkPermissions).toHaveBeenCalled();\n });\n\n it(\"should call BleManager.startDeviceScan if checkPermissions resolves to true\", async () => {\n checkPermissions.mockResolvedValue(true);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch((e) => {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n });\n\n expect(startDeviceScan).toHaveBeenCalled();\n });\n\n it(\"should call requestPermissions if checkPermissions resolves to false\", async () => {\n checkPermissions.mockResolvedValue(false);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch(() => {});\n\n expect(requestPermissions).toHaveBeenCalled();\n });\n\n it(\"should call BleManager.startDeviceScan if requestPermissions resolves to true\", async () => {\n checkPermissions.mockResolvedValue(false);\n requestPermissions.mockResolvedValue(true);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n await firstValueFrom(transport.observeBleState());\n await firstValueFrom(observable);\n\n expect(startDeviceScan).toHaveBeenCalled();\n });\n\n it(\"should emit an error if checkPermissions and requestPermissions resolve to false\", async () => {\n checkPermissions.mockResolvedValue(false);\n requestPermissions.mockResolvedValue(false);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (e) => {\n try {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n } catch (innerError) {\n reject(innerError);\n }\n done(undefined);\n },\n complete: () => {\n reject(new Error(\"Should not complete\"));\n },\n });\n });\n });\n });\n\n it(\"should return already connected devices and scanned devices\", () =>\n new Promise((done, reject) => {\n let scanInterval: NodeJS.Timeout | null = null;\n\n const connectedDevice = createMockDevice({\n id: \"aConnectedDeviceId\",\n localName: \"aConnectedDeviceName\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n listener(null, {\n id: \"aScannedDeviceId\",\n localName: \"aScannedDeviceName\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 1,\n });\n }, 10);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n listener(null, {\n id: \"aNonLedgerScannedDeviceId\",\n localName: \"aNonLedgerScannedDeviceName\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 2,\n });\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([connectedDevice]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withScanThrottleDelayMs(1) // Use very fast throttle for tests\n .build();\n\n const availableDevicesEvents: TransportDiscoveredDevice[][] = [];\n\n subscription = transport.listenToAvailableDevices().subscribe({\n next: (devices) => {\n availableDevicesEvents.push(devices);\n if (availableDevicesEvents.length === 2) {\n try {\n expect(availableDevicesEvents).toEqual([\n [\n {\n id: \"aConnectedDeviceId\",\n name: \"aConnectedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: undefined,\n },\n ],\n [\n {\n id: \"aConnectedDeviceId\",\n name: \"aConnectedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: undefined,\n },\n {\n id: \"aScannedDeviceId\",\n name: \"aScannedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: 1,\n },\n ],\n ]);\n done(undefined);\n } catch (e) {\n reject(e);\n }\n }\n },\n });\n }));\n\n it(\"should propagate the error if startDeviceScan throws an error\", () => {\n const scanError = new Error(\"startDeviceScan error\");\n const startScan = vi.fn().mockRejectedValueOnce(scanError);\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toBe(scanError);\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n },\n complete: () => reject(new Error(\"Should not complete\")),\n });\n });\n });\n\n it(\"should propagate the error if startDeviceScan emits an error\", () => {\n const scanError = new Error(\"startDeviceScan error\");\n const startScan = vi\n .fn()\n .mockImplementation(\n async (\n _uuids,\n _options,\n listener: (error: Error | null, device: Device) => void,\n ) => {\n listener(scanError, {} as Device);\n },\n );\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toBe(scanError);\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n done(undefined);\n },\n complete: () => reject(new Error(\"Should not complete\")),\n });\n });\n });\n\n it(\"should propagate an error if startDeviceScan emits a null device\", () => {\n const startScan = vi\n .fn()\n .mockImplementation(\n async (\n _uuids,\n _options,\n listener: (error: Error | null, device: Device | null) => void,\n ) => {\n listener(null, null);\n },\n );\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toEqual(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n },\n });\n });\n });\n\n it(\"should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices\", async () => {\n vi.useFakeTimers();\n const scanError = new Error(\"A Scan Error\");\n const startScan = vi.fn().mockRejectedValueOnce(scanError);\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable1 = transport.listenToAvailableDevices();\n\n let caughtError: unknown;\n await firstValueFrom(observable1).catch((e) => {\n caughtError = e;\n });\n\n expect(caughtError).toBe(scanError);\n\n startScan.mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"aScannedDeviceId\",\n localName: \"aScannedDeviceName\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 1,\n });\n });\n\n const observable2 = transport.listenToAvailableDevices();\n\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable2).catch(() => {\n throw new Error(\n \"Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error\",\n );\n });\n\n expect(devices).toEqual([\n {\n id: \"aScannedDeviceId\",\n name: \"aScannedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: 1,\n },\n ]);\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw an error if device id is unknown\", async () => {\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockRejectedValueOnce(\n new Error(\"discoverAllServicesAndCharacteristicsForDevice error\"),\n ),\n });\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const result = await transport.connect({\n // @ts-expect-error test case\n deviceId: null,\n onDisconnect: vi.fn(),\n });\n\n expect(result).toEqual(\n Left(\n new OpeningConnectionError(\n `discoverAllServicesAndCharacteristicsForDevice error`,\n ),\n ),\n );\n });\n\n it(\"should connect to a discovered device with correct MTU and discover services and setup apdu sender\", async () => {\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n // Immediately emit a device to ensure we have results\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const fakeSetupConnection = vi.fn().mockResolvedValue(undefined);\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: vi.fn(),\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: fakeSetupConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .withScanThrottleDelayMs(1) // Use very fast throttle for tests\n .build();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n expect(result.isRight()).toBe(true);\n expect(bleManager.connectToDevice).toHaveBeenCalledWith(\"deviceId\", {\n requestMTU: 156,\n });\n expect(\n bleManager.discoverAllServicesAndCharacteristicsForDevice,\n ).toHaveBeenCalledWith(\"deviceId\");\n expect(fakeSetupConnection).toHaveBeenCalled();\n });\n\n it(\"should return a connected device which calls state machine sendApdu\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n // Immediately emit a device to ensure we have results\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const fakeSendApdu = vi.fn();\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: fakeSendApdu,\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n const connectedDevice = result.extract() as TransportConnectedDevice;\n connectedDevice.sendApdu(Uint8Array.from([0x43, 0x32]));\n\n expect(result).toEqual(\n Right(\n new TransportConnectedDevice({\n id: \"deviceId\",\n deviceModel: FAKE_DEVICE_MODEL,\n type: \"BLE\",\n transport: \"RN_BLE\",\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n sendApdu: expect.any(Function),\n }),\n ),\n );\n expect(fakeSendApdu).toHaveBeenCalledWith(Uint8Array.from([0x43, 0x32]));\n });\n });\n\n describe(\"disconnect\", () => {\n it(\"should disconnect gracefully\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const onDeviceDisconnected = vi.fn().mockImplementation(() => {\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n onDeviceDisconnected,\n isDeviceConnected: vi.fn(),\n });\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const fakeOnDisconnect = vi.fn();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n expect(res).toEqual(Right(undefined));\n expect(fakeOnDisconnect).toHaveBeenCalled();\n expect(fakeCloseConnection).toHaveBeenCalled();\n });\n\n it(\"should handle error while disconnecting\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const onDeviceDisconnected = vi.fn().mockImplementation(() => {\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected,\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const fakeOnDisconnect = vi.fn();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n expect(res).toEqual(Right(undefined));\n expect(fakeOnDisconnect).toHaveBeenCalled();\n });\n });\n});\n"],
|
|
5
|
-
"mappings": "aAEA,IAAAA,EAA+C,gCAC/CC,EAcO,2CACPC,EAA4B,qBAC5BC,EAAsD,gBACtDC,EAAmC,kBAEnCC,EAIO,6BACPC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AU,EACzD,+CAAgD,GAC7C,GAAG,EACH,sBAAsBA,CAAU,EACnC,+BAAgC,GAAG,GAAG,EACtC,4CAA6C,GAAG,GAAG,EACnD,qBAAAK,EACA,kBAAmB,GAAG,GAAG,EACzB,cAAgB7C,IACdA,EAAS,QAAM,SAAS,EACjB,CAAE,OAAQ,GAAG,GAAG,CAAE,EAE7B,CAAC,EAEK0C,EACJK,GAEO,IAAI,+BAA6B,CACtC,SAAU,WACV,iBAAkBA,EAAM,iBACxB,gBAAiB,IACjB,aAAcA,EAAM,aACpB,eAAgBA,EAAM,cACxB,CAAC,EAGGT,EAA0B,GAAG,GAAG,EAAE,gBAAgB,CACtD,gBAAiB,GAAG,GAAG,EAAE,kBAAkB,MAAS,EACpD,gBAAiBQ,CACnB,CAAC,EAEK3C,EAAY,IAAIlB,EAAqB,EACxC,eAAeK,CAAU,EACzB,aAAaR,CAAY,EACzB,0BACCI,EAAqB,CACvB,EACC,wCACCwD,CACF,EACC,4BAA4BJ,CAAuB,EACnD,MAAM,EAEHU,EAAmB,GAAG,GAAG,EAGzB1C,EAAaH,EAAU,yBAAyB,EAGtD,GAAG,oBAAoB,GAAI,EAE3B,MAAM6B,EAAU,QAAM,kBAAe1B,CAAU,EACzC,CAACqC,CAAM,EAAIX,EACXO,EAAS,MAAMpC,EAAU,QAAQ,CACrC,SAAUwC,EAAQ,GAClB,aAAcK,CAChB,CAAC,EAEKC,EAAM,MAAM9C,EAAU,WAAW,CACrC,gBAAiBoC,EAAO,QAAQ,CAClC,CAAC,KAED,UAAOU,CAAG,EAAE,WAAQ,SAAM,MAAS,CAAC,KACpC,UAAOD,CAAgB,EAAE,iBAAiB,CAC5C,CAAC,CACH,CAAC,CACH,CAAC",
|
|
4
|
+
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport { type Platform } from \"react-native\";\nimport { BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n BleDeviceInfos,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceModelDataSource,\n DeviceModelId,\n type DmkConfig,\n type LoggerPublisherService,\n OpeningConnectionError,\n TransportConnectedDevice,\n TransportDeviceModel,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { firstValueFrom, Subject, Subscription } from \"rxjs\";\nimport { beforeEach, expect } from \"vitest\";\n\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n} from \"@api/model/Errors\";\nimport { DefaultPermissionsService } from \"@api/permissions/DefaultPermissionsService\";\nimport { PermissionsService } from \"@api/permissions/PermissionsService\";\n\nimport { type RNBleApduSenderDependencies } from \"./RNBleApduSender\";\nimport { RNBleTransport } from \"./RNBleTransport\";\nimport { RNBleTransportFactory } from \"./RNBleTransportFactory\";\n\n// ===== MOCKS =====\nconst fakeLogger: LoggerPublisherService = {\n error: vi.fn(),\n info: vi.fn(),\n warn: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n};\n\nconst consoleLogger: LoggerPublisherService = {\n error: console.error,\n info: console.info,\n warn: console.warn,\n debug: console.debug,\n subscribers: [],\n};\n\nvi.mock(\"react-native\", () => ({\n Platform: {},\n PermissionsAndroid: {},\n}));\n\nvi.mock(\"react-native-ble-plx\", () => ({\n Device: vi.fn(),\n State: {\n PoweredOn: \"PoweredOn\",\n Unknown: \"Unknown\",\n PoweredOff: \"PoweredOff\",\n Resetting: \"Resetting\",\n Unsupported: \"Unsupported\",\n Unauthorized: \"Unauthorized\",\n },\n BleError: vi.fn(),\n BleManager: vi.fn().mockReturnValue({\n onStateChange: vi.fn(),\n startDeviceScan: vi.fn(),\n stopDeviceScan: vi.fn(),\n connectToDevice: vi.fn(),\n disconnectFromDevice: vi.fn(),\n cancelDeviceConnection: vi.fn(),\n connectedDevices: vi.fn(),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n discoverAllServicesAndCharacteristicsForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n }),\n}));\n\n// ===== TEST DATA =====\nconst FAKE_DEVICE_MODEL = new TransportDeviceModel({\n id: DeviceModelId.FLEX,\n productName: \"Ledger Flex\",\n usbProductId: 0x70,\n bootloaderUsbProductId: 0x0007,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33300000],\n});\n\nconst IOS_PLATFORM = { OS: \"ios\" as const } as Platform;\nconst ANDROID_PLATFORM = { OS: \"android\" as const } as Platform;\nconst WINDOWS_PLATFORM = { OS: \"windows\" as const } as Platform;\n\n// ===== TEST HELPERS =====\nclass TestTransportBuilder {\n private deviceModelDataSource: DeviceModelDataSource = createFakeDataSource();\n private loggerServiceFactory = () =>\n fakeLogger as unknown as LoggerPublisherService;\n private apduSenderServiceFactory =\n (() => {}) as unknown as ApduSenderServiceFactory;\n private apduReceiverServiceFactory =\n (() => {}) as unknown as ApduReceiverServiceFactory;\n private bleManager = new BleManager();\n private platform: Platform = IOS_PLATFORM;\n private permissionsService: PermissionsService =\n new DefaultPermissionsService();\n private deviceConnectionStateMachineFactory?: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private deviceApduSenderFactory?: (args: any, loggerFactory: any) => any;\n private scanThrottleDelayMs: number = 1000;\n\n withDeviceModelDataSource(dataSource: DeviceModelDataSource) {\n this.deviceModelDataSource = dataSource;\n return this;\n }\n\n withPlatform(platform: Platform) {\n this.platform = platform;\n return this;\n }\n\n withPermissionsService(permissions: PermissionsService) {\n this.permissionsService = permissions;\n return this;\n }\n\n withBleManager(bleManager: BleManager) {\n this.bleManager = bleManager;\n return this;\n }\n\n withDeviceConnectionStateMachineFactory(\n factory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies>,\n ) {\n this.deviceConnectionStateMachineFactory = factory;\n return this;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withDeviceApduSenderFactory(factory: (args: any, loggerFactory: any) => any) {\n this.deviceApduSenderFactory = factory;\n return this;\n }\n\n withLogger(logger: LoggerPublisherService = consoleLogger) {\n this.loggerServiceFactory = () => logger;\n return this;\n }\n\n withScanThrottleDelayMs(delayMs: number) {\n this.scanThrottleDelayMs = delayMs;\n return this;\n }\n\n build(): RNBleTransport {\n return new RNBleTransport(\n this.deviceModelDataSource,\n this.loggerServiceFactory,\n this.apduSenderServiceFactory,\n this.apduReceiverServiceFactory,\n this.bleManager,\n this.platform,\n this.permissionsService,\n this.scanThrottleDelayMs,\n this.deviceConnectionStateMachineFactory,\n this.deviceApduSenderFactory,\n );\n }\n}\n\nfunction createFakeDataSource() {\n const getBluetoothServicesMock = vi.fn(() => [\"ledgerId\"]);\n const getBluetoothServicesInfosMock = vi.fn(() => ({\n ledgerId: new BleDeviceInfos(\n FAKE_DEVICE_MODEL,\n \"serviceUuid\",\n \"notifyUuid\",\n \"writeCmdUuid\",\n \"readCmdUuid\",\n ),\n }));\n\n return {\n getBluetoothServices: getBluetoothServicesMock,\n getBluetoothServicesInfos: getBluetoothServicesInfosMock,\n getAllDeviceModels: vi.fn(),\n getDeviceModel: vi.fn(),\n filterDeviceModels: vi.fn(),\n } as unknown as DeviceModelDataSource;\n}\n\nfunction createMockDevice(overrides: Partial<Device> = {}): Device {\n return {\n id: \"deviceId\",\n localName: \"deviceName\",\n serviceUUIDs: [\"ledgerId\"],\n services: vi.fn().mockResolvedValue([{ uuid: \"ledgerId\" }]),\n ...overrides,\n } as unknown as Device;\n}\n\nfunction createMockBleManager(\n overrides: Partial<BleManager> = {},\n initialState: State = State.PoweredOn,\n): BleManager {\n const mockBleManager = {\n onStateChange: vi\n .fn()\n .mockImplementation(\n (listener: (state: State) => void, emitInitialState: boolean) => {\n if (emitInitialState) listener(initialState);\n return { remove: vi.fn() };\n },\n ),\n startDeviceScan: vi.fn(),\n stopDeviceScan: vi.fn(),\n connectToDevice: vi.fn(),\n disconnectFromDevice: vi.fn(),\n cancelDeviceConnection: vi.fn(),\n connectedDevices: vi.fn().mockResolvedValue([]),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n discoverAllServicesAndCharacteristicsForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n state: vi.fn(),\n ...overrides,\n } as unknown as BleManager;\n\n return mockBleManager;\n}\n\n// ===== TEST SUITES =====\ndescribe(\"RNBleTransportFactory\", () => {\n it(\"should return a RNBleTransport\", () => {\n const fakeArgs = {\n deviceModelDataSource:\n createFakeDataSource() as unknown as DeviceModelDataSource,\n loggerServiceFactory: () =>\n fakeLogger as unknown as LoggerPublisherService,\n apduSenderServiceFactory:\n (() => {}) as unknown as ApduSenderServiceFactory,\n apduReceiverServiceFactory:\n (() => {}) as unknown as ApduReceiverServiceFactory,\n config: {} as DmkConfig,\n };\n\n const transport = RNBleTransportFactory(fakeArgs);\n\n expect(transport).toBeInstanceOf(RNBleTransport);\n });\n});\n\ndescribe(\"RNBleTransport\", () => {\n let subscription: Subscription | undefined;\n\n beforeEach(() => {\n vi.clearAllMocks();\n vi.useRealTimers();\n });\n\n afterEach(() => {\n if (subscription) {\n subscription.unsubscribe();\n }\n });\n\n describe(\"BLE state monitoring\", () => {\n test(\"the constructor should call BleManager.onStateChange with a parameter requesting the initial state\", () => {\n const mockedOnStateChange = vi.fn();\n\n new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: mockedOnStateChange,\n }),\n )\n .build();\n\n expect(mockedOnStateChange).toHaveBeenCalledWith(\n expect.any(Function),\n true,\n );\n });\n\n describe(\"observeBleState\", () => {\n it(\"should emit the initial BLE state\", async () => {\n const mockedOnStateChange = vi\n .fn()\n .mockImplementation(\n (listener: (state: State) => void, emitInitialState: boolean) => {\n if (emitInitialState) listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n );\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: mockedOnStateChange,\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n\n const initialState = await firstValueFrom(observable);\n\n expect(initialState).toBe(State.PoweredOn);\n });\n\n it(\"should emit the new BLE state values\", async () => {\n const statesSubject = new Subject<State>();\n\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n statesSubject.subscribe((newState) => listener(newState));\n return { remove: vi.fn() };\n },\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n\n // When a new state is emitted\n statesSubject.next(State.PoweredOff);\n\n // Then observeBleState should emit the new state\n const newState = await firstValueFrom(observable);\n expect(newState).toBe(State.PoweredOff);\n\n // When a new state is emitted\n statesSubject.next(State.Resetting);\n\n // Then observeBleState should emit the new state\n const newState2 = await firstValueFrom(observable);\n expect(newState2).toBe(State.Resetting);\n });\n\n it(\"should recover from an Unknown state by calling BleManager.state() method and emitting the new state\", async () => {\n vi.useFakeTimers();\n const statesSubject = new Subject<State>();\n\n const mockedStateFunction = vi.fn().mockImplementation(() => {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(State.PoweredOn);\n }, 10);\n });\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(\n createMockBleManager({\n state: mockedStateFunction,\n onStateChange: (listener: (state: State) => void) => {\n statesSubject.subscribe((newState) => listener(newState));\n return { remove: vi.fn() };\n },\n }),\n )\n .build();\n\n const observable = transport.observeBleState();\n statesSubject.next(State.PoweredOff);\n\n expect(mockedStateFunction).not.toHaveBeenCalled();\n\n // Emit new state Unknown\n statesSubject.next(State.Unknown);\n\n // The value Unknown should be emitted\n const newState = await firstValueFrom(observable);\n expect(newState).toBe(State.Unknown);\n\n // BleManager.state() should be called\n expect(mockedStateFunction).toHaveBeenCalled();\n\n vi.advanceTimersByTime(11);\n\n await Promise.resolve();\n\n // And the value returned by BleManager.state() should be emitted\n const newState2 = await firstValueFrom(observable);\n expect(newState2).toBe(State.PoweredOn);\n });\n });\n });\n\n describe(\"getIdentifier\", () => {\n it(\"should return rnBleTransportIdentifier\", () => {\n const transport = new TestTransportBuilder().build();\n const identifier = transport.getIdentifier();\n expect(identifier).toStrictEqual(\"RN_BLE\");\n });\n });\n\n describe(\"isSupported\", () => {\n it(\"should return true if platform is ios\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(IOS_PLATFORM)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(true);\n });\n\n it(\"should return true if platform is android\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(ANDROID_PLATFORM as Platform)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(true);\n });\n\n it(\"should return false if platform is not android nor ios\", () => {\n const transport = new TestTransportBuilder()\n .withPlatform(WINDOWS_PLATFORM)\n .build();\n\n const isSupported = transport.isSupported();\n\n expect(isSupported).toBe(false);\n });\n });\n\n describe(\"startDiscovering\", () => {\n it(\"should emit an empty array\", () =>\n new Promise((done, reject) => {\n const transport = new TestTransportBuilder()\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .build();\n\n const observable = transport.startDiscovering();\n\n subscription = observable.subscribe({\n next: (discoveredDevice) => {\n try {\n expect(discoveredDevice).toStrictEqual([]);\n } catch (e) {\n reject(e);\n }\n },\n error: (e) => {\n reject(e);\n throw e;\n },\n complete: () => {\n done(undefined);\n },\n });\n }));\n });\n\n describe(\"stopDiscovering\", () => {\n it(\"should call ble manager stop scan on stop discovering\", () => {\n const stopDeviceScan = vi.fn();\n const bleManager = createMockBleManager({\n stopDeviceScan,\n connectedDevices: vi.fn().mockResolvedValueOnce([]),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .build();\n\n transport.stopDiscovering();\n\n expect(stopDeviceScan).toHaveBeenCalled();\n });\n });\n\n describe(\"listenToAvailableDevices\", () => {\n it(\"should emit an error if platform is not android nor ios\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager())\n .withPlatform(WINDOWS_PLATFORM)\n .build();\n\n return new Promise((done, reject) => {\n transport.listenToAvailableDevices().subscribe({\n error: (e) => {\n try {\n expect(e).toBeInstanceOf(BleNotSupported);\n } catch (innerError) {\n reject(innerError);\n }\n done(undefined);\n },\n complete: () => {\n reject(new Error(\"Should not complete\"));\n },\n });\n });\n });\n\n it(\"should emit an error if BLE state is PoweredOff\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({}, State.PoweredOff))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n let caughtError: unknown;\n await firstValueFrom(observable).catch((e) => {\n caughtError = e;\n });\n\n expect(caughtError).toBeInstanceOf(BlePoweredOff);\n });\n\n describe(\"permissions check\", () => {\n const checkPermissions = vi.fn();\n const requestPermissions = vi.fn();\n\n const mockedPermissionsService = {\n checkRequiredPermissions: checkPermissions,\n requestRequiredPermissions: requestPermissions,\n };\n\n const startDeviceScan = vi.fn().mockImplementation(async () => {});\n const bleManager = createMockBleManager({\n startDeviceScan: startDeviceScan,\n stopDeviceScan: vi.fn(),\n connectedDevices: vi.fn().mockResolvedValue([]),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n it(\"should call checkPermissions\", async () => {\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch((e) => {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n });\n\n expect(checkPermissions).toHaveBeenCalled();\n });\n\n it(\"should call BleManager.startDeviceScan if checkPermissions resolves to true\", async () => {\n checkPermissions.mockResolvedValue(true);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch((e) => {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n });\n\n expect(startDeviceScan).toHaveBeenCalled();\n });\n\n it(\"should call requestPermissions if checkPermissions resolves to false\", async () => {\n checkPermissions.mockResolvedValue(false);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n await firstValueFrom(observable).catch(() => {});\n\n expect(requestPermissions).toHaveBeenCalled();\n });\n\n it(\"should call BleManager.startDeviceScan if requestPermissions resolves to true\", async () => {\n checkPermissions.mockResolvedValue(false);\n requestPermissions.mockResolvedValue(true);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n await firstValueFrom(transport.observeBleState());\n await firstValueFrom(observable);\n\n expect(startDeviceScan).toHaveBeenCalled();\n });\n\n it(\"should emit an error if checkPermissions and requestPermissions resolve to false\", async () => {\n checkPermissions.mockResolvedValue(false);\n requestPermissions.mockResolvedValue(false);\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withPermissionsService(mockedPermissionsService)\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (e) => {\n try {\n expect(e).toBeInstanceOf(BlePermissionsNotGranted);\n } catch (innerError) {\n reject(innerError);\n }\n done(undefined);\n },\n complete: () => {\n reject(new Error(\"Should not complete\"));\n },\n });\n });\n });\n });\n\n it(\"should return already connected devices and scanned devices\", () =>\n new Promise((done, reject) => {\n let scanInterval: NodeJS.Timeout | null = null;\n\n const connectedDevice = createMockDevice({\n id: \"aConnectedDeviceId\",\n localName: \"aConnectedDeviceName\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n scanInterval = setInterval(() => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n listener(null, {\n id: \"aScannedDeviceId\",\n localName: \"aScannedDeviceName\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 1,\n });\n }, 10);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n listener(null, {\n id: \"aNonLedgerScannedDeviceId\",\n localName: \"aNonLedgerScannedDeviceName\",\n serviceUUIDs: [\"notLedgerId\"],\n rssi: 2,\n });\n });\n\n const stopScan = vi.fn().mockImplementation(() => {\n if (scanInterval) {\n clearInterval(scanInterval);\n scanInterval = null;\n }\n });\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([connectedDevice]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withScanThrottleDelayMs(1) // Use very fast throttle for tests\n .build();\n\n const availableDevicesEvents: TransportDiscoveredDevice[][] = [];\n\n subscription = transport.listenToAvailableDevices().subscribe({\n next: (devices) => {\n availableDevicesEvents.push(devices);\n if (availableDevicesEvents.length === 2) {\n try {\n expect(availableDevicesEvents).toEqual([\n [\n {\n id: \"aConnectedDeviceId\",\n name: \"aConnectedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: undefined,\n },\n ],\n [\n {\n id: \"aConnectedDeviceId\",\n name: \"aConnectedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: undefined,\n },\n {\n id: \"aScannedDeviceId\",\n name: \"aScannedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: 1,\n },\n ],\n ]);\n done(undefined);\n } catch (e) {\n reject(e);\n }\n }\n },\n });\n }));\n\n it(\"should propagate the error if startDeviceScan throws an error\", () => {\n const scanError = new Error(\"startDeviceScan error\");\n const startScan = vi.fn().mockRejectedValueOnce(scanError);\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toBe(scanError);\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n },\n complete: () => reject(new Error(\"Should not complete\")),\n });\n });\n });\n\n it(\"should propagate the error if startDeviceScan emits an error\", () => {\n const scanError = new Error(\"startDeviceScan error\");\n const startScan = vi\n .fn()\n .mockImplementation(\n async (\n _uuids,\n _options,\n listener: (error: Error | null, device: Device) => void,\n ) => {\n listener(scanError, {} as Device);\n },\n );\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toBe(scanError);\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n done(undefined);\n },\n complete: () => reject(new Error(\"Should not complete\")),\n });\n });\n });\n\n it(\"should propagate an error if startDeviceScan emits a null device\", () => {\n const startScan = vi\n .fn()\n .mockImplementation(\n async (\n _uuids,\n _options,\n listener: (error: Error | null, device: Device | null) => void,\n ) => {\n listener(null, null);\n },\n );\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable = transport.listenToAvailableDevices();\n\n return new Promise((done, reject) => {\n observable.subscribe({\n error: (observedError) => {\n try {\n expect(observedError).toEqual(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n done(undefined);\n } catch (expectError) {\n reject(expectError);\n }\n },\n });\n });\n });\n\n it(\"should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices\", async () => {\n vi.useFakeTimers();\n const scanError = new Error(\"A Scan Error\");\n const startScan = vi.fn().mockRejectedValueOnce(scanError);\n\n const transport = new TestTransportBuilder()\n .withBleManager(createMockBleManager({ startDeviceScan: startScan }))\n .build();\n\n const observable1 = transport.listenToAvailableDevices();\n\n let caughtError: unknown;\n await firstValueFrom(observable1).catch((e) => {\n caughtError = e;\n });\n\n expect(caughtError).toBe(scanError);\n\n startScan.mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"aScannedDeviceId\",\n localName: \"aScannedDeviceName\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 1,\n });\n });\n\n const observable2 = transport.listenToAvailableDevices();\n\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable2).catch(() => {\n throw new Error(\n \"Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error\",\n );\n });\n\n expect(devices).toEqual([\n {\n id: \"aScannedDeviceId\",\n name: \"aScannedDeviceName\",\n deviceModel: FAKE_DEVICE_MODEL,\n transport: \"RN_BLE\",\n rssi: 1,\n },\n ]);\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw an error if device id is unknown\", async () => {\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockRejectedValueOnce(\n new Error(\"discoverAllServicesAndCharacteristicsForDevice error\"),\n ),\n });\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const result = await transport.connect({\n // @ts-expect-error test case\n deviceId: null,\n onDisconnect: vi.fn(),\n });\n\n expect(result).toEqual(\n Left(\n new OpeningConnectionError(\n `discoverAllServicesAndCharacteristicsForDevice error`,\n ),\n ),\n );\n });\n\n it(\"should connect to a discovered device with correct MTU and discover services and setup apdu sender\", async () => {\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n // Immediately emit a device to ensure we have results\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const fakeSetupConnection = vi.fn().mockResolvedValue(undefined);\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: vi.fn(),\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: fakeSetupConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .withScanThrottleDelayMs(1) // Use very fast throttle for tests\n .build();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n expect(result.isRight()).toBe(true);\n expect(bleManager.connectToDevice).toHaveBeenCalledWith(\"deviceId\", {\n requestMTU: 156,\n });\n expect(\n bleManager.discoverAllServicesAndCharacteristicsForDevice,\n ).toHaveBeenCalledWith(\"deviceId\");\n expect(fakeSetupConnection).toHaveBeenCalled();\n });\n\n it(\"should return a connected device which calls state machine sendApdu\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n // Immediately emit a device to ensure we have results\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected: vi.fn(),\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const fakeSendApdu = vi.fn();\n const deviceConnectionStateMachineFactory = vi.fn().mockReturnValue({\n sendApdu: fakeSendApdu,\n });\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: vi.fn(),\n });\n\n const connectedDevice = result.extract() as TransportConnectedDevice;\n connectedDevice.sendApdu(Uint8Array.from([0x43, 0x32]));\n\n expect(result).toEqual(\n Right(\n new TransportConnectedDevice({\n id: \"deviceId\",\n deviceModel: FAKE_DEVICE_MODEL,\n type: \"BLE\",\n transport: \"RN_BLE\",\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n sendApdu: expect.any(Function),\n name: \"name\",\n }),\n ),\n );\n expect(fakeSendApdu).toHaveBeenCalledWith(Uint8Array.from([0x43, 0x32]));\n });\n });\n\n describe(\"disconnect\", () => {\n it(\"should disconnect gracefully\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const onDeviceDisconnected = vi.fn().mockImplementation(() => {\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n onDeviceDisconnected,\n isDeviceConnected: vi.fn(),\n });\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const fakeOnDisconnect = vi.fn();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n expect(res).toEqual(Right(undefined));\n expect(fakeOnDisconnect).toHaveBeenCalled();\n expect(fakeCloseConnection).toHaveBeenCalled();\n });\n\n it(\"should handle error while disconnecting\", async () => {\n vi.useFakeTimers();\n\n const mockDevice = createMockDevice({\n id: \"deviceId\",\n localName: \"name\",\n });\n\n const startScan = vi\n .fn()\n .mockImplementation(async (_uuids, _options, listener) => {\n listener(null, {\n id: \"deviceId\",\n localName: \"name\",\n serviceUUIDs: [\"ledgerId\"],\n rssi: 42,\n });\n });\n\n const stopScan = vi.fn();\n\n const onDeviceDisconnected = vi.fn().mockImplementation(() => {\n return { remove: vi.fn() };\n });\n\n const fakeCloseConnection = vi.fn();\n\n const bleManager = createMockBleManager({\n connectedDevices: vi.fn().mockResolvedValue([]),\n startDeviceScan: startScan,\n stopDeviceScan: stopScan,\n connectToDevice: vi.fn().mockResolvedValueOnce(mockDevice),\n discoverAllServicesAndCharacteristicsForDevice: vi\n .fn()\n .mockResolvedValueOnce(mockDevice),\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n onDeviceDisconnected,\n isDeviceConnected: vi.fn(),\n onStateChange: (listener: (state: State) => void) => {\n listener(State.PoweredOn);\n return { remove: vi.fn() };\n },\n });\n\n const deviceConnectionStateMachineFactory = (\n _args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => {\n return new DeviceConnectionStateMachine({\n deviceId: \"deviceId\",\n deviceApduSender: _args.deviceApduSender,\n timeoutDuration: 1000,\n onTerminated: _args.onTerminated,\n tryToReconnect: _args.tryToReconnect,\n });\n };\n\n const deviceApduSenderFactory = vi.fn().mockReturnValue({\n setupConnection: vi.fn().mockResolvedValue(undefined),\n closeConnection: fakeCloseConnection,\n });\n\n const transport = new TestTransportBuilder()\n .withBleManager(bleManager)\n .withPlatform(IOS_PLATFORM)\n .withDeviceModelDataSource(\n createFakeDataSource() as unknown as DeviceModelDataSource,\n )\n .withDeviceConnectionStateMachineFactory(\n deviceConnectionStateMachineFactory,\n )\n .withDeviceApduSenderFactory(deviceApduSenderFactory)\n .build();\n\n const fakeOnDisconnect = vi.fn();\n\n // Start listening to devices\n const observable = transport.listenToAvailableDevices();\n\n // Advance timers to trigger the throttleTime and allow scan results to be emitted\n vi.advanceTimersByTime(2000);\n\n const devices = await firstValueFrom(observable);\n const [device] = devices;\n const result = await transport.connect({\n deviceId: device!.id,\n onDisconnect: fakeOnDisconnect,\n });\n\n const res = await transport.disconnect({\n connectedDevice: result.extract() as TransportConnectedDevice,\n });\n\n expect(res).toEqual(Right(undefined));\n expect(fakeOnDisconnect).toHaveBeenCalled();\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "aAEA,IAAAA,EAA+C,gCAC/CC,EAcO,2CACPC,EAA4B,qBAC5BC,EAAsD,gBACtDC,EAAmC,kBAEnCC,EAIO,6BACPC,EAA0C,sDAI1CC,EAA+B,4BAC/BC,EAAsC,mCAGtC,MAAMC,EAAqC,CACzC,MAAO,GAAG,GAAG,EACb,KAAM,GAAG,GAAG,EACZ,KAAM,GAAG,GAAG,EACZ,MAAO,GAAG,GAAG,EACb,YAAa,CAAC,CAChB,EAEMC,EAAwC,CAC5C,MAAO,QAAQ,MACf,KAAM,QAAQ,KACd,KAAM,QAAQ,KACd,MAAO,QAAQ,MACf,YAAa,CAAC,CAChB,EAEA,GAAG,KAAK,eAAgB,KAAO,CAC7B,SAAU,CAAC,EACX,mBAAoB,CAAC,CACvB,EAAE,EAEF,GAAG,KAAK,uBAAwB,KAAO,CACrC,OAAQ,GAAG,GAAG,EACd,MAAO,CACL,UAAW,YACX,QAAS,UACT,WAAY,aACZ,UAAW,YACX,YAAa,cACb,aAAc,cAChB,EACA,SAAU,GAAG,GAAG,EAChB,WAAY,GAAG,GAAG,EAAE,gBAAgB,CAClC,cAAe,GAAG,GAAG,EACrB,gBAAiB,GAAG,GAAG,EACvB,eAAgB,GAAG,GAAG,EACtB,gBAAiB,GAAG,GAAG,EACvB,qBAAsB,GAAG,GAAG,EAC5B,uBAAwB,GAAG,GAAG,EAC9B,iBAAkB,GAAG,GAAG,EACxB,+BAAgC,GAAG,GAAG,EACtC,4CAA6C,GAAG,GAAG,EACnD,+CAAgD,GAAG,GAAG,EACtD,qBAAsB,GAAG,GAAG,EAC5B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CAAC,EAEKC,EAAM,MAAM9C,EAAU,WAAW,CACrC,gBAAiBoC,EAAO,QAAQ,CAClC,CAAC,KAED,UAAOU,CAAG,EAAE,WAAQ,SAAM,MAAS,CAAC,KACpC,UAAOD,CAAgB,EAAE,iBAAiB,CAC5C,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
6
|
"names": ["import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_vitest", "import_Errors", "import_DefaultPermissionsService", "import_RNBleTransport", "import_RNBleTransportFactory", "fakeLogger", "consoleLogger", "FAKE_DEVICE_MODEL", "IOS_PLATFORM", "ANDROID_PLATFORM", "WINDOWS_PLATFORM", "TestTransportBuilder", "createFakeDataSource", "dataSource", "platform", "permissions", "bleManager", "factory", "logger", "delayMs", "getBluetoothServicesMock", "getBluetoothServicesInfosMock", "createMockDevice", "overrides", "createMockBleManager", "initialState", "listener", "emitInitialState", "fakeArgs", "transport", "subscription", "mockedOnStateChange", "observable", "statesSubject", "newState", "newState2", "mockedStateFunction", "resolve", "identifier", "isSupported", "done", "reject", "discoveredDevice", "e", "stopDeviceScan", "innerError", "caughtError", "checkPermissions", "requestPermissions", "mockedPermissionsService", "startDeviceScan", "scanInterval", "connectedDevice", "startScan", "_uuids", "_options", "stopScan", "availableDevicesEvents", "devices", "scanError", "observedError", "expectError", "observable1", "observable2", "deviceApduSenderFactory", "result", "mockDevice", "fakeSetupConnection", "deviceConnectionStateMachineFactory", "device", "fakeSendApdu", "onDeviceDisconnected", "fakeCloseConnection", "_args", "fakeOnDisconnect", "res"]
|
|
7
7
|
}
|
package/lib/cjs/package.json
CHANGED
|
@@ -1,64 +1,68 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
"dependencies": {
|
|
3
|
+
"@sentry/minimal": "catalog:",
|
|
4
|
+
"js-base64": "catalog:",
|
|
5
|
+
"purify-ts": "catalog:",
|
|
6
|
+
"uuid": "catalog:"
|
|
7
|
+
},
|
|
8
|
+
"devDependencies": {
|
|
9
|
+
"@ledgerhq/device-management-kit": "workspace:^",
|
|
10
|
+
"@ledgerhq/eslint-config-dsdk": "workspace:^",
|
|
11
|
+
"@ledgerhq/ldmk-tool": "workspace:^",
|
|
12
|
+
"@ledgerhq/prettier-config-dsdk": "workspace:^",
|
|
13
|
+
"@ledgerhq/tsconfig-dsdk": "workspace:^",
|
|
14
|
+
"@ledgerhq/vitest-config-dmk": "workspace:^",
|
|
15
|
+
"@types/uuid": "catalog:",
|
|
16
|
+
"@vitejs/plugin-react": "catalog:",
|
|
17
|
+
"react-native": "catalog:",
|
|
18
|
+
"react-native-ble-plx": "catalog:",
|
|
19
|
+
"rxjs": "catalog:",
|
|
20
|
+
"ts-node": "catalog:",
|
|
21
|
+
"vitest-react-native": "catalog:"
|
|
22
|
+
},
|
|
6
23
|
"exports": {
|
|
7
24
|
".": {
|
|
8
|
-
"types": "./lib/types/index.d.ts",
|
|
9
25
|
"import": "./lib/esm/index.js",
|
|
10
|
-
"require": "./lib/cjs/index.js"
|
|
26
|
+
"require": "./lib/cjs/index.js",
|
|
27
|
+
"types": "./lib/types/index.d.ts"
|
|
11
28
|
},
|
|
12
29
|
"./*": {
|
|
13
|
-
"types": "./lib/types/*",
|
|
14
30
|
"import": "./lib/esm/*",
|
|
15
|
-
"require": "./lib/cjs/*"
|
|
31
|
+
"require": "./lib/cjs/*",
|
|
32
|
+
"types": "./lib/types/*"
|
|
16
33
|
}
|
|
17
34
|
},
|
|
18
35
|
"files": [
|
|
19
36
|
"./lib"
|
|
20
37
|
],
|
|
38
|
+
"license": "Apache-2.0",
|
|
39
|
+
"name": "@ledgerhq/device-transport-kit-react-native-ble",
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@ledgerhq/device-management-kit": "workspace:^",
|
|
42
|
+
"react-native": ">0.74.1",
|
|
43
|
+
"react-native-ble-plx": "3.4.0",
|
|
44
|
+
"rxjs": "catalog:"
|
|
45
|
+
},
|
|
46
|
+
"private": false,
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "https://github.com/LedgerHQ/device-sdk-ts.git"
|
|
50
|
+
},
|
|
21
51
|
"scripts": {
|
|
22
|
-
"prebuild": "rimraf lib",
|
|
23
52
|
"build": "pnpm ldmk-tool build --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
24
53
|
"dev": "concurrently \"pnpm watch:builds\" \"pnpm watch:types\"",
|
|
25
|
-
"watch:builds": "pnpm ldmk-tool watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
26
|
-
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\"",
|
|
27
54
|
"lint": "eslint",
|
|
28
55
|
"lint:fix": "pnpm lint --fix",
|
|
29
56
|
"postpack": "find . -name '*.tgz' -exec cp {} ../../../dist/ \\; ",
|
|
57
|
+
"prebuild": "rimraf lib",
|
|
30
58
|
"prettier": "prettier . --check",
|
|
31
59
|
"prettier:fix": "prettier . --write",
|
|
32
|
-
"typecheck": "tsc --noEmit",
|
|
33
60
|
"test": "vitest run",
|
|
61
|
+
"test:coverage": "vitest run --coverage",
|
|
34
62
|
"test:watch": "vitest",
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"@sentry/minimal": "catalog:",
|
|
39
|
-
"js-base64": "catalog:",
|
|
40
|
-
"purify-ts": "catalog:",
|
|
41
|
-
"uuid": "catalog:"
|
|
42
|
-
},
|
|
43
|
-
"devDependencies": {
|
|
44
|
-
"@ledgerhq/device-management-kit": "workspace:*",
|
|
45
|
-
"@ledgerhq/eslint-config-dsdk": "workspace:*",
|
|
46
|
-
"@ledgerhq/ldmk-tool": "workspace:*",
|
|
47
|
-
"@ledgerhq/prettier-config-dsdk": "workspace:*",
|
|
48
|
-
"@ledgerhq/tsconfig-dsdk": "workspace:*",
|
|
49
|
-
"@ledgerhq/vitest-config-dmk": "workspace:*",
|
|
50
|
-
"@types/uuid": "catalog:",
|
|
51
|
-
"@vitejs/plugin-react": "catalog:",
|
|
52
|
-
"react-native": "catalog:",
|
|
53
|
-
"react-native-ble-plx": "catalog:",
|
|
54
|
-
"rxjs": "catalog:",
|
|
55
|
-
"ts-node": "catalog:",
|
|
56
|
-
"vitest-react-native": "catalog:"
|
|
63
|
+
"typecheck": "tsc --noEmit",
|
|
64
|
+
"watch:builds": "pnpm ldmk-tool watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
65
|
+
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\""
|
|
57
66
|
},
|
|
58
|
-
"
|
|
59
|
-
"@ledgerhq/device-management-kit": "workspace:*",
|
|
60
|
-
"react-native": ">0.74.1",
|
|
61
|
-
"react-native-ble-plx": "3.4.0",
|
|
62
|
-
"rxjs": "catalog:"
|
|
63
|
-
}
|
|
67
|
+
"version": "0.0.0-zzz-solana-20251204140055"
|
|
64
68
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Platform as M}from"react-native";import{BleError as E,State as u}from"react-native-ble-plx";import{DeviceConnectionStateMachine as A,OpeningConnectionError as b,TransportConnectedDevice as y,UnknownDeviceError as N}from"@ledgerhq/device-management-kit";import{Either as m,EitherAsync as I,Left as w,Maybe as v,Right as S}from"purify-ts";import{BehaviorSubject as D,defer as P,finalize as U,first as F,from as _,retry as O,switchMap as h,tap as f,throttleTime as q}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as L,BLE_DISCONNECT_TIMEOUT_IOS as k,CONNECTION_LOST_DELAY as j,DEFAULT_MTU as T}from"../model/Const";import{BleNotSupported as C,BlePermissionsNotGranted as B,BlePoweredOff as $,DeviceConnectionNotFound as x,NoDeviceModelFoundError as R,PeerRemovedPairingError as z}from"../model/Errors";import{RNBleApduSender as H}from"../transport/RNBleApduSender";const ee="RN_BLE";class te{constructor(e,t,i,n,o,a,r,s=1e3,p=d=>new A(d),g=(d,l)=>new H(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=t;this._apduSenderFactory=i;this._apduReceiverFactory=n;this._manager=o;this._platform=a;this._permissionsService=r;this._scanThrottleDelayMs=s;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=g;this._logger=t("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero();let d=!1;this._manager.onStateChange(l=>{this._logger.debug(`[manager.onStateChange] called with state: ${l}`),this._bleStateSubject.next(l),d=l===u.Unknown,d&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(c=>{d&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${c}"`),this._bleStateSubject.next(c))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(u.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return _([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return _([!0]).pipe(f(()=>{if(!this.isSupported())throw new C("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),h(async()=>this.checkAndRequestPermissions()),f(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new B("Permissions not granted")}),h(()=>this.observeBleState()),F(e=>{const t=e===u.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${t}`),e===u.PoweredOff)throw new $;if(e===u.Unauthorized)throw new B('Ble State is "Unauthorized"');if(e===u.Unsupported)throw new C;return t}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=_([!0]).pipe(h(()=>{const e=new D([]),t=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(n,o)=>{if(n){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:n,rnDevice:o}}),e.error(n);return}if(!o){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:o}}),e.error(new Error("Null device in startDeviceScan callback"));return}t.set(o.id,{device:o,timestamp:Date.now()}),e.next(Array.from(t.values()))}).catch(n=>{e.error(n),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:n}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(t.values()))},1e3);return e.pipe(U(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),q(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new D([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe(f(()=>this._startScanning()),h(()=>this._scannedDevicesSubject),h(async e=>{const t=e.filter(({timestamp:r})=>r>Date.now()-j).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),i=m.rights(t),n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(r=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:r}}),r}),o=await Promise.all(n.map(async r=>{try{const p=(await r.services()).map(g=>g.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,p)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),w(new R(`Error in mapping device to transport discovered device: ${s}`))}})),a=m.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:n.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:i.map(r=>r.name)}}),[...a,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const t of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[t];if(i)return S(i)}return w(new R(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,t){return this._mapServicesUUIDsToDeviceModel(t).map(n=>({id:e.id,name:e.localName||e.name||"",deviceModel:n,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const t=this._deviceConnectionsById.get(e.deviceId);if(t){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=t.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return S(new y({id:e.deviceId,deviceModel:i,type:"BLE",sendApdu:(...n)=>t.sendApdu(...n),transport:this.identifier}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),I(async({throwE:i})=>{let n,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:T}),n=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await n.services()).map(c=>c.uuid)}catch(c){return c instanceof E&&c.iosErrorCode===14?i(new z(c)):i(new b(c))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>i(new b(c))}),s=r.deviceModel,p={id:n.id,bleDeviceInfos:r},g=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:n,internalDevice:p,manager:this._manager}},this._loggerServiceFactory),d=M.OS==="ios"?k:L,l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:g,timeoutDuration:d,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(c){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:c}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(c=>{c.unsubscribe(),this._reconnectionSubscription=v.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await g.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),a.remove(),c}),this._deviceConnectionsById.set(e.deviceId,l),new y({id:n.id,deviceModel:s,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier})}).run()}async disconnect(e){const t=e.connectedDevice.id,i=this._deviceConnectionsById.get(t);if(!i)throw new N(`No connected device found with id ${t}`);return i.closeConnection(),Promise.resolve(S(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,t){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:t}}),!t){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!t?.id||!this._deviceConnectionsById.has(t?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:t}});return}const i=t.id;v.fromNullable(this._deviceConnectionsById.get(i)).map(n=>n.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const t=this._manager.onDeviceDisconnected(e,(i,n)=>{this._handleDeviceDisconnected(i,n),t.remove()});return t}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let t=0;await this._stopScanning(),await this._safeCancel(e);const i=P(async()=>{let n=null;t++;try{this._logger.debug(`[tryToReconnect](try=${t}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:T,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${t}) Established connection to device`,{data:{id:e}});const a=await o.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${t}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:a}}),n=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(o){throw this._logger.warn(`[tryToReconnect](try=${t}) Reconnecting to device failed`,{data:{e:o}}),n?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(O(5));this._reconnectionSubscription=v.of(i.subscribe({next:n=>this._logger.debug(`[tryToReconnect](try=${t}) Fully reconnected to device (id=${n.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:n=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:n}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const t=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new x);return I(async({liftEither:i,throwE:n})=>{const o=await i(t),a=(await e.services()).map(s=>s.uuid),r=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>({id:e.id,bleDeviceInfos:s}),Left:s=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:s}}),n(s))});o.setDependencies({device:e,manager:this._manager,internalDevice:r}),await o.setupConnection().catch(s=>{throw this._safeCancel(e.id),s}),o.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of t)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(n){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:n}})}}}}export{te as RNBleTransport,ee as rnBleTransportIdentifier};
|
|
1
|
+
import{Platform as b}from"react-native";import{BleError as m,BleErrorCode as A,State as u}from"react-native-ble-plx";import{DeviceConnectionStateMachine as P,OpeningConnectionError as y,TransportConnectedDevice as I,UnknownDeviceError as U}from"@ledgerhq/device-management-kit";import{Either as w,EitherAsync as C,Left as T,Maybe as v,Right as S}from"purify-ts";import{BehaviorSubject as D,defer as F,finalize as O,first as q,from as _,retry as L,switchMap as h,tap as f,throttleTime as k}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as j,BLE_DISCONNECT_TIMEOUT_IOS as $,CONNECTION_LOST_DELAY as x,DEFAULT_MTU as B}from"../model/Const";import{BleNotSupported as R,BlePermissionsNotGranted as M,BlePoweredOff as z,DeviceConnectionNotFound as H,NoDeviceModelFoundError as E,PeerRemovedPairingError as N}from"../model/Errors";import{RNBleApduSender as G}from"../transport/RNBleApduSender";const ne="RN_BLE";class te{constructor(e,n,i,t,o,a,r,s=1e3,p=d=>new P(d),g=(d,l)=>new G(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=o;this._platform=a;this._permissionsService=r;this._scanThrottleDelayMs=s;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=g;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero();let d=!1;this._manager.onStateChange(l=>{this._logger.debug(`[manager.onStateChange] called with state: ${l}`),this._bleStateSubject.next(l),d=l===u.Unknown,d&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(c=>{d&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${c}"`),this._bleStateSubject.next(c))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(u.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return _([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return _([!0]).pipe(f(()=>{if(!this.isSupported())throw new R("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),h(async()=>this.checkAndRequestPermissions()),f(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new M("Permissions not granted")}),h(()=>this.observeBleState()),q(e=>{const n=e===u.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.PoweredOff)throw new z;if(e===u.Unauthorized)throw new M('Ble State is "Unauthorized"');if(e===u.Unsupported)throw new R;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=_([!0]).pipe(h(()=>{const e=new D([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,o)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:o}}),e.error(t);return}if(!o){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:o}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(o.id,{device:o,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe(O(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),k(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new D([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe(f(()=>this._startScanning()),h(()=>this._scannedDevicesSubject),h(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-x).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),i=w.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(r=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:r}}),r}),o=await Promise.all(t.map(async r=>{try{const p=(await r.services()).map(g=>g.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,p)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),T(new E(`Error in mapping device to transport discovered device: ${s}`))}})),a=w.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:i.map(r=>r.name)}}),[...a,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return S(i)}return T(new E(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,o=i.device.localName||i.device.name||void 0;return S(new I({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...a)=>n.sendApdu(...a),transport:this.identifier,name:o}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),C(async({throwE:i})=>{let t,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:B}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await t.services()).map(c=>c.uuid)}catch(c){return c instanceof m&&c.iosErrorCode===14?i(new N(c)):c instanceof m&&c.errorCode===A.OperationCancelled&&b.OS==="android"?i(new N(c)):i(new y(c))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>i(new y(c))}),s=r.deviceModel,p={id:t.id,bleDeviceInfos:r},g=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:p,manager:this._manager}},this._loggerServiceFactory),d=b.OS==="ios"?$:j,l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:g,timeoutDuration:d,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(c){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:c}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(c=>{c.unsubscribe(),this._reconnectionSubscription=v.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await g.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),a.remove(),c}),this._deviceConnectionsById.set(e.deviceId,l),new I({id:t.id,deviceModel:s,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new U(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve(S(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;v.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=F(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:B,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const a=await o.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:a}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(o){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:o}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(L(5));this._reconnectionSubscription=v.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const n=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new H);return C(async({liftEither:i,throwE:t})=>{const o=await i(n),a=(await e.services()).map(s=>s.uuid),r=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>({id:e.id,bleDeviceInfos:s}),Left:s=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:s}}),t(s))});o.setDependencies({device:e,manager:this._manager,internalDevice:r}),await o.setupConnection().catch(s=>{throw this._safeCancel(e.id),s}),o.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}export{te as RNBleTransport,ne as rnBleTransportIdentifier};
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|