@ledgerhq/device-transport-kit-react-native-ble 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +32 -0
  2. package/lib/cjs/api/index.js +1 -1
  3. package/lib/cjs/api/index.js.map +3 -3
  4. package/lib/cjs/api/model/Errors.js +1 -1
  5. package/lib/cjs/api/model/Errors.js.map +3 -3
  6. package/lib/cjs/api/permissions/AndroidPermissionsService.js +2 -0
  7. package/lib/cjs/api/permissions/AndroidPermissionsService.js.map +7 -0
  8. package/lib/cjs/api/permissions/AndroidPermissionsService.test.js +2 -0
  9. package/lib/cjs/api/permissions/AndroidPermissionsService.test.js.map +7 -0
  10. package/lib/cjs/api/permissions/DefaultPermissionsService.js +2 -0
  11. package/lib/cjs/api/permissions/DefaultPermissionsService.js.map +7 -0
  12. package/lib/cjs/api/permissions/IOSPermissionsService.test.js +2 -0
  13. package/lib/cjs/api/permissions/IOSPermissionsService.test.js.map +7 -0
  14. package/lib/cjs/api/permissions/PermissionsAndroidNarrowedType.js +2 -0
  15. package/lib/cjs/api/permissions/PermissionsAndroidNarrowedType.js.map +7 -0
  16. package/lib/cjs/api/permissions/PermissionsService.js +2 -0
  17. package/lib/cjs/api/permissions/PermissionsService.js.map +7 -0
  18. package/lib/cjs/api/transport/RNBleApduSender.js +1 -1
  19. package/lib/cjs/api/transport/RNBleApduSender.js.map +2 -2
  20. package/lib/cjs/api/transport/RNBleTransport.js +1 -1
  21. package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
  22. package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
  23. package/lib/cjs/api/transport/RNBleTransport.test.js.map +3 -3
  24. package/lib/cjs/api/transport/RNBleTransportFactory.js +2 -0
  25. package/lib/cjs/api/transport/RNBleTransportFactory.js.map +7 -0
  26. package/lib/cjs/package.json +1 -1
  27. package/lib/esm/api/index.js +1 -1
  28. package/lib/esm/api/index.js.map +3 -3
  29. package/lib/esm/api/model/Errors.js +1 -1
  30. package/lib/esm/api/model/Errors.js.map +3 -3
  31. package/lib/esm/api/permissions/AndroidPermissionsService.js +2 -0
  32. package/lib/esm/api/permissions/AndroidPermissionsService.js.map +7 -0
  33. package/lib/esm/api/permissions/AndroidPermissionsService.test.js +2 -0
  34. package/lib/esm/api/permissions/AndroidPermissionsService.test.js.map +7 -0
  35. package/lib/esm/api/permissions/DefaultPermissionsService.js +2 -0
  36. package/lib/esm/api/permissions/DefaultPermissionsService.js.map +7 -0
  37. package/lib/esm/api/permissions/IOSPermissionsService.test.js +2 -0
  38. package/lib/esm/api/permissions/IOSPermissionsService.test.js.map +7 -0
  39. package/lib/esm/api/permissions/PermissionsAndroidNarrowedType.js +1 -0
  40. package/lib/esm/api/permissions/PermissionsAndroidNarrowedType.js.map +7 -0
  41. package/lib/esm/api/permissions/PermissionsService.js +1 -0
  42. package/lib/esm/api/permissions/PermissionsService.js.map +7 -0
  43. package/lib/esm/api/transport/RNBleApduSender.js +1 -1
  44. package/lib/esm/api/transport/RNBleApduSender.js.map +2 -2
  45. package/lib/esm/api/transport/RNBleTransport.js +1 -1
  46. package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
  47. package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
  48. package/lib/esm/api/transport/RNBleTransport.test.js.map +3 -3
  49. package/lib/esm/api/transport/RNBleTransportFactory.js +2 -0
  50. package/lib/esm/api/transport/RNBleTransportFactory.js.map +7 -0
  51. package/lib/esm/package.json +1 -1
  52. package/lib/types/api/index.d.ts +2 -1
  53. package/lib/types/api/index.d.ts.map +1 -1
  54. package/lib/types/api/model/Errors.d.ts +10 -0
  55. package/lib/types/api/model/Errors.d.ts.map +1 -1
  56. package/lib/types/api/permissions/AndroidPermissionsService.d.ts +12 -0
  57. package/lib/types/api/permissions/AndroidPermissionsService.d.ts.map +1 -0
  58. package/lib/types/api/permissions/AndroidPermissionsService.test.d.ts +2 -0
  59. package/lib/types/api/permissions/AndroidPermissionsService.test.d.ts.map +1 -0
  60. package/lib/types/api/permissions/DefaultPermissionsService.d.ts +6 -0
  61. package/lib/types/api/permissions/DefaultPermissionsService.d.ts.map +1 -0
  62. package/lib/types/api/permissions/IOSPermissionsService.test.d.ts +2 -0
  63. package/lib/types/api/permissions/IOSPermissionsService.test.d.ts.map +1 -0
  64. package/lib/types/api/permissions/PermissionsAndroidNarrowedType.d.ts +20 -0
  65. package/lib/types/api/permissions/PermissionsAndroidNarrowedType.d.ts.map +1 -0
  66. package/lib/types/api/permissions/PermissionsService.d.ts +5 -0
  67. package/lib/types/api/permissions/PermissionsService.d.ts.map +1 -0
  68. package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
  69. package/lib/types/api/transport/RNBleTransport.d.ts +22 -15
  70. package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
  71. package/lib/types/api/transport/RNBleTransportFactory.d.ts +3 -0
  72. package/lib/types/api/transport/RNBleTransportFactory.d.ts.map +1 -0
  73. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  74. package/package.json +10 -10
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleTransport.ts"],
4
- "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { BleError, BleManager, type Device, State } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n filter,\n finalize,\n from,\n map,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n throttleTime,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._isSupported = Maybe.zero();\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._bleStateSubject.next(state);\n }, true);\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _maybeScanningSubject: Maybe<\n BehaviorSubject<InternalScannedDevice[]>\n > = Nothing;\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._startedScanningSubscriber = from(this._bleStateSubject)\n .pipe(\n filter((state) => state === \"PoweredOn\"),\n switchMap(() => this.requestPermission()),\n switchMap((isSupported) => {\n if (!isSupported) {\n return throwError(() => new BleNotSupported(\"BLE not supported\"));\n }\n\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n this._maybeScanningSubject = Maybe.of(subject);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[RNBleTransport][startScanning] startDeviceScan\");\n this._manager.startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error || !rnDevice) {\n subject.error(error || new Error(\"scan error\"));\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n );\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.asObservable().pipe(\n finalize(() => {\n this._logger.debug(\"[RNBleTransport][startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._maybeScanningSubject = Nothing;\n this._manager.stopDeviceScan();\n }),\n );\n }),\n throttleTime(1000),\n )\n .subscribe({\n next: (devices) => {\n this._logger.debug(\n \"[RNBleTransport][startScanning] onNext called with devices\",\n { data: { devices } },\n );\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._maybeScanningSubject.map((subject) => {\n subject.complete();\n this._maybeScanningSubject = Nothing;\n });\n\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n this._startScanning();\n\n return this._scannedDevicesSubject.asObservable().pipe(\n map((internalScannedDevices) => {\n const eitherConnectedDevices = Array.from(\n this._deviceConnectionsById.values(),\n ).map((connection) =>\n this._mapDeviceToTransportDiscoveredDevice(\n connection.getDependencies().device,\n [\n connection.getDependencies().internalDevice.bleDeviceInfos\n .serviceUuid,\n ],\n ),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n device.id,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n },\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => {\n this.tryToReconnect(params.deviceId);\n },\n onTerminated: () => {\n try {\n this._safeCancel(params.deviceId);\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n disconnectionSubscription.remove();\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) =>\n sub.unsubscribe(),\n );\n this._reconnectionSubscription = Maybe.zero();\n }\n } catch (e) {\n this._logger.error(\n \"Error in termination of device connection\",\n { data: { e } },\n );\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[RNBLE][_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private tryToReconnect(deviceId: DeviceId) {\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._stopScanning();\n await this._safeCancel(deviceId);\n }),\n switchMap(async () => {\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnecting to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n \"[_handleDeviceDisconnected] reconnected to device\",\n { data: { id: deviceId } },\n );\n const reconnectedDeviceUsable =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n \"[_handleDeviceDisconnected] discovered all services and characteristics\",\n { data: { reconnectedDeviceUsable } },\n );\n await this._handleDeviceReconnected(reconnectedDeviceUsable);\n return reconnectedDeviceUsable;\n }),\n retry(5),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n await this._manager.cancelDeviceConnection(deviceId);\n }\n }\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n new BleManager(),\n );\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAyD,gCACzDC,EAoBO,2CACPC,EAAiE,qBACjEC,EAYO,gBAEPC,EAKO,4BACPC,EAKO,6BACPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMF,CAAoC,CAa/C,YACmBY,EACAC,EAGAC,EACAC,EACAC,EACAC,EAAsB,WACtBC,EAA0C,qBAC1CC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUR,EAAsB,yBAAyB,EAC9D,KAAK,aAAe,QAAM,KAAK,EAC/B,KAAK,uBAAyB,IAAI,IAClC,KAAK,0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EAAO,GACX,eAAgBM,CAClB,GAEF,KAAOlB,IACL,KAAK,QAAQ,MACX,2DACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEOuB,EAAOvB,CAAK,EAEvB,CAAC,EAED6B,EAA6B,gBAAgB,CAC3C,OAAAjB,EACA,QAAS,KAAK,SACd,eAAAc,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOE,GAAM,CAChE,WAAK,YAAYnB,EAAO,EAAE,EACpBmB,CACR,CAAC,EAEDF,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYG,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMzB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWK,KAAUL,EACfK,EAAO,KAAOoB,GAChB,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CAGzD,CACF,CACF,CAEO,MAAM1D,EAA0C,CAAC,CACtD,sBAAAqE,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIzE,EACFsE,EACAC,EACAC,EACAC,EACA,IAAI,YACN",
6
- "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "RNBleTransportFactory", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsAndroid", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "isSupported", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherConnectedDevices", "connection", "connectedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "servicesUUIDs", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "e", "deviceId", "deviceConnection", "granted", "result", "reconnect$", "reconnectedDevice", "reconnectedDeviceUsable", "sm", "errorOrDeviceConnection", "liftEither", "s", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAOO,gCACPC,EAmBO,2CACPC,EAAwD,qBACxDC,EAYO,gBAEPC,EAKO,4BACPC,EAOO,6BAEPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMD,CAAoC,CAY/C,YACmBW,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EAAsB,yBAAyB,EAC9D,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4B,QAAM,KAAK,EAE5C,IAAIW,EAAwB,GAC5B,KAAK,SAAS,cAAeC,GAAU,CACrC,KAAK,QAAQ,MAAM,8CAA8CA,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,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
6
+ "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "deviceModel", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("react-native-ble-plx"),f=require("@ledgerhq/device-management-kit"),R=require("purify-ts"),w=require("rxjs"),i=require("vitest"),E=require("../model/Errors"),r=require("./RNBleTransport");const u={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const h=async(v,O)=>{const b={OS:"android",Version:v.version},T={request:vi.fn().mockImplementation(o=>Promise.resolve({ACCESS_FINE_LOCATION:v.accessFineLocationResult}[o])),PERMISSIONS:v.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(v.requestPermissionResult))},m=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},new t.BleManager,b,T);await m.requestPermission();const C=m.isSupported();O.callRequestPermission&&(0,i.expect)(T.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),(0,i.expect)(C).toBe(O.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const O=(0,r.RNBleTransportFactory)({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>u,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});(0,i.expect)(O).toBeInstanceOf(r.RNBleTransport)})});describe("RNBleTransport",()=>{const v={OS:"ios"},O=new f.TransportDeviceModel({id:f.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),b=vi.fn(()=>["ledgerId"]),T=vi.fn(()=>({ledgerId:new f.BleDeviceInfos(O,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),m={getBluetoothServices:b,getBluetoothServicesInfos:T};let C;(0,i.beforeEach)(()=>{vi.clearAllMocks()}),afterEach(()=>{C&&C.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const o=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},o).getIdentifier();(0,i.expect)(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const o={OS:"ios"},n=new t.BleManager,e=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},n,o);await e.requestPermission();const s=e.isSupported();(0,i.expect)(s).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await h({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await h({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const o=new t.BleManager,n=new r.RNBleTransport("DeviceModelDataSource",()=>u,()=>{},()=>{},o,{OS:"windows"});await n.requestPermission();const e=n.isSupported();(0,i.expect)(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const o={OS:"windows"},n=new t.BleManager,e=new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,o);try{e.startDiscovering()}catch(s){(0,i.expect)(s).toBeInstanceOf(E.BleNotSupported)}}),it("should emit an empty array",()=>new Promise(o=>{const n=new t.BleManager;C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{}).startDiscovering().subscribe({next:a=>{(0,i.expect)(a).toStrictEqual([]),o(void 0)},error:a=>{throw a},complete:()=>{o(void 0)}})})),it.skip("should emit discovered new device",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s=vi.fn().mockImplementation((c,k,d)=>(n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),a=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(e,"startDeviceScan").mockImplementation(s),vi.spyOn(e,"stopDeviceScan").mockImplementation(a),C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).startDiscovering().subscribe({next:c=>{(0,i.expect)(c).toStrictEqual([]),o(void 0)},error:c=>{throw c},complete:()=>{throw new Error("complete should not be called")}})})),it.skip("should emit both known and new device",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((d,I,D)=>(n=setInterval(()=>{D(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),D(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),p=vi.fn().mockImplementation(()=>(n&&(clearInterval(n),n=null),Promise.resolve()));vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn());const c=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).startDiscovering(),k={};C=c.subscribe({next:d=>{k[d.id]=d,Object.values(k).length===2&&((0,i.expect)(Object.values(k)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:O,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:O,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const o=new t.BleManager,n=vi.fn();vi.spyOn(o,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(o,"stopDeviceScan").mockImplementation(n),new r.RNBleTransport(m,()=>u,()=>{},()=>{},o,v,{}).stopDiscovering(),(0,i.expect)(n).toHaveBeenCalled()}),it.skip("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let o=null;const n=new t.BleManager,e=vi.fn().mockImplementation((p,S,c)=>(o=setInterval(()=>{c(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),c(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43}),Promise.resolve())),s=vi.fn().mockImplementation(()=>(o&&(clearInterval(o),o=null),Promise.resolve()));vi.spyOn(n,"connectedDevices").mockResolvedValueOnce([]),vi.spyOn(n,"startDeviceScan").mockImplementation(e),vi.spyOn(n,"stopDeviceScan").mockImplementation(s),vi.spyOn(n,"onDeviceDisconnected").mockImplementation(vi.fn()),new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{}).startDiscovering().subscribe().unsubscribe(),(0,i.expect)(e).toHaveBeenCalled(),(0,i.expect)(s).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(o=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})},a=vi.fn().mockImplementation((c,k,d)=>{n=setInterval(()=>{d(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},10),d(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockResolvedValueOnce([s]),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(c=>(c(t.State.PoweredOn),{remove:vi.fn()})),C=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{}).listenToAvailableDevices().subscribe({next:c=>{c.length===1&&((0,i.expect)(c).toEqual([{id:"id",name:"name",deviceModel:O,transport:"RN_BLE",rssi:42}]),o(void 0))}})}))}),describe("connect",()=>{let o;(0,i.beforeEach)(()=>{o=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const n=new t.BleManager;vi.spyOn(n,"connectedDevices").mockImplementation(o),vi.spyOn(n,"discoverAllServicesAndCharacteristicsForDevice").mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"));const e=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),a=await new r.RNBleTransport(m,()=>u,()=>{},()=>{},n,v,{},vi.fn(),e).connect({deviceId:null,onDisconnect:vi.fn()});(0,i.expect)(a).toEqual((0,R.Left)(new f.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let n=null;const e=new t.BleManager,s={readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((A,y,g)=>{n=setInterval(()=>{g(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),g(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(A=>(A(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn().mockResolvedValue(void 0),c=vi.fn().mockReturnValue({sendApdu:vi.fn()}),k=vi.fn().mockReturnValue({setupConnection:S}),d=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});(0,i.expect)(D.isRight()).toBe(!0),(0,i.expect)(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,i.expect)(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,i.expect)(S).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((y,g,l)=>{n=setInterval(()=>{l(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)});vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(y=>(y(t.State.PoweredOn),{remove:vi.fn()}));const S=vi.fn(),c=vi.fn().mockReturnValue({sendApdu:S}),k=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),d=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},c,k),[I]=await(0,w.lastValueFrom)(d.listenToAvailableDevices().pipe((0,w.take)(3))),D=await d.connect({deviceId:I.id,onDisconnect:vi.fn()});D.extract().sendApdu(Uint8Array.from([67,50])),(0,i.expect)(D).toEqual((0,R.Right)(new f.TransportConnectedDevice({id:"deviceId",deviceModel:O,type:"BLE",transport:"RN_BLE",sendApdu:i.expect.any(Function)}))),(0,i.expect)(S).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let o;(0,i.beforeEach)(()=>{o=vi.fn().mockResolvedValue([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((l,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((l,N)=>(N(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(l=>(l(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=l=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:l.deviceApduSender,timeoutDuration:1e3,onTerminated:l.onTerminated,tryToReconnect:l.tryToReconnect}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,i.expect)(g).toEqual((0,R.Right)(void 0)),(0,i.expect)(D).toHaveBeenCalled(),(0,i.expect)(c).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let n=null;const e=new t.BleManager,s={id:"deviceId",readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})}),services:vi.fn().mockResolvedValueOnce([{uuid:"ledgerId"}])},a=vi.fn().mockImplementation((l,N,P)=>{n=setInterval(()=>{P(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),p=vi.fn().mockImplementation(()=>{n&&(clearInterval(n),n=null)}),S=vi.fn().mockImplementation((l,N)=>(N(new Error("yolo"),null),{remove:vi.fn()})),c=vi.fn();vi.spyOn(e,"connectedDevices").mockImplementation(o),vi.spyOn(e,"startDeviceScan").mockImplementation(a),vi.spyOn(e,"stopDeviceScan").mockImplementation(p),vi.spyOn(e,"connectToDevice").mockResolvedValueOnce(s),vi.spyOn(e,"discoverAllServicesAndCharacteristicsForDevice").mockResolvedValueOnce(s),vi.spyOn(e,"monitorCharacteristicForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"writeCharacteristicWithoutResponseForDevice").mockImplementation(vi.fn()),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(vi.fn()),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn()),vi.spyOn(e,"onStateChange").mockImplementation(l=>(l(t.State.PoweredOn),{remove:vi.fn()})),vi.spyOn(e,"onDeviceDisconnected").mockImplementation(S),vi.spyOn(e,"isDeviceConnected").mockImplementation(vi.fn());const k=l=>new f.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:l.deviceApduSender,timeoutDuration:1e3,onTerminated:l.onTerminated,tryToReconnect:l.tryToReconnect}),d=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:c}),I=new r.RNBleTransport(m,()=>u,()=>{},()=>{},e,v,{},k,d),D=vi.fn(),[A]=await(0,w.lastValueFrom)(I.listenToAvailableDevices().pipe((0,w.take)(3))),y=await I.connect({deviceId:A.id,onDisconnect:D}),g=await I.disconnect({connectedDevice:y.extract()});(0,i.expect)(g).toEqual((0,R.Right)(void 0)),(0,i.expect)(D).toHaveBeenCalled()})})});
1
+ "use strict";var d=require("react-native-ble-plx"),S=require("@ledgerhq/device-management-kit"),P=require("purify-ts"),l=require("rxjs"),t=require("vitest"),k=require("../model/Errors"),T=require("../permissions/DefaultPermissionsService"),F=require("./RNBleTransport"),O=require("./RNBleTransportFactory");const E={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},V={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const C=new S.TransportDeviceModel({id:S.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},U={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=g();loggerServiceFactory=()=>E;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new d.BleManager;platform=h;permissionsService=new T.DefaultPermissionsService;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=V){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new F.RNBleTransport(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function g(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new S.BleDeviceInfos(C,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function A(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function f(p={},e=d.State.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:g(),loggerServiceFactory:()=>E,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=(0,O.RNBleTransportFactory)(p);(0,t.expect)(e).toBeInstanceOf(F.RNBleTransport)})});describe("RNBleTransport",()=>{let p;(0,t.beforeEach)(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(f({onStateChange:e})).build(),(0,t.expect)(e).toHaveBeenCalledWith(t.expect.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.State.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(f({onStateChange:e})).build().observeBleState(),c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new l.Subject,o=new s().withBleManager(f({onStateChange:r=>(r(d.State.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff);const c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOff),e.next(d.State.Resetting);const i=await(0,l.firstValueFrom)(o);(0,t.expect)(i).toBe(d.State.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new l.Subject,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.State.PoweredOn)},10)})),c=new s().withBleManager(f({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff),(0,t.expect)(n).not.toHaveBeenCalled(),e.next(d.State.Unknown);const i=await(0,l.firstValueFrom)(c);(0,t.expect)(i).toBe(d.State.Unknown),(0,t.expect)(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await(0,l.firstValueFrom)(c);(0,t.expect)(r).toBe(d.State.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();(0,t.expect)(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(U).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();(0,t.expect)(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(g()).build().startDiscovering().subscribe({next:i=>{try{(0,t.expect)(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=f({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(g()).build().stopDiscovering(),(0,t.expect)(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(f()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{(0,t.expect)(c).toBeInstanceOf(k.BleNotSupported)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(f({},d.State.PoweredOff)).build().listenToAvailableDevices();let o;await(0,l.firstValueFrom)(n).catch(c=>{o=c}),(0,t.expect)(o).toBeInstanceOf(k.BlePoweredOff)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=f({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.State.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(()=>{}),(0,t.expect)(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await(0,l.firstValueFrom)(r.observeBleState()),await(0,l.firstValueFrom)(a),(0,t.expect)(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,u)=>{a.subscribe({error:m=>{try{(0,t.expect)(m).toBeInstanceOf(k.BlePermissionsNotGranted)}catch(w){u(w)}v(void 0)},complete:()=>{u(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=A({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(m,w,b)=>{o=setInterval(()=>{b(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),b(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=f({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:m=>(m(d.State.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(g()).withScanThrottleDelayMs(1).build(),u=[];p=v.listenToAvailableDevices().subscribe({next:m=>{if(u.push(m),u.length===2)try{(0,t.expect)(u).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(w){n(w)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(f({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{(0,t.expect)(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(f({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await(0,l.firstValueFrom)(c).catch(v=>{i=v}),(0,t.expect)(i).toBe(e),n.mockImplementation(async(v,u,m)=>{m(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await(0,l.firstValueFrom)(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});(0,t.expect)(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=f({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(g()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});(0,t.expect)(c).toEqual((0,P.Left)(new S.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(y,M,B)=>{B(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:y=>(y(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),u=v.listenToAvailableDevices(),m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});(0,t.expect)(b.isRight()).toBe(!0),(0,t.expect)(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,t.expect)(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,t.expect)(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(M,B,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:M=>(M(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),u=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});b.extract().sendApdu(Uint8Array.from([67,50])),(0,t.expect)(b).toEqual((0,P.Right)(new S.TransportConnectedDevice({id:"deviceId",deviceModel:C,type:"BLE",transport:"RN_BLE",sendApdu:t.expect.any(Function)}))),(0,t.expect)(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled(),(0,t.expect)(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()})}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled()})})});
2
2
  //# sourceMappingURL=RNBleTransport.test.js.map