@ledgerhq/device-transport-kit-react-native-ble 0.0.0-wip-20250214170223 → 1.1.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.
- package/README.md +89 -0
- package/lib/cjs/api/model/Const.js +1 -1
- package/lib/cjs/api/model/Const.js.map +3 -3
- package/lib/cjs/api/model/Errors.js +1 -1
- package/lib/cjs/api/model/Errors.js.map +3 -3
- package/lib/cjs/api/transport/RNBleApduSender.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.js.map +3 -3
- package/lib/cjs/api/transport/RNBleApduSender.test.js +2 -0
- package/lib/cjs/api/transport/RNBleApduSender.test.js.map +7 -0
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +2 -0
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +7 -0
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/package.json +22 -20
- package/lib/esm/api/model/Const.js +1 -1
- package/lib/esm/api/model/Const.js.map +3 -3
- package/lib/esm/api/model/Errors.js +1 -1
- package/lib/esm/api/model/Errors.js.map +3 -3
- package/lib/esm/api/transport/RNBleApduSender.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.js.map +3 -3
- package/lib/esm/api/transport/RNBleApduSender.test.js +2 -0
- package/lib/esm/api/transport/RNBleApduSender.test.js.map +7 -0
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +2 -0
- package/lib/esm/api/transport/RNBleTransport.test.js.map +7 -0
- package/lib/esm/package.json +22 -20
- package/lib/types/api/model/Const.d.ts +3 -2
- package/lib/types/api/model/Const.d.ts.map +1 -1
- package/lib/types/api/model/Errors.d.ts +26 -1
- package/lib/types/api/model/Errors.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.d.ts +7 -9
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.test.d.ts +2 -0
- package/lib/types/api/transport/RNBleApduSender.test.d.ts.map +1 -0
- package/lib/types/api/transport/RNBleTransport.d.ts +33 -64
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransport.test.d.ts +2 -0
- package/lib/types/api/transport/RNBleTransport.test.d.ts.map +1 -0
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +23 -21
package/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Transport Device Kit React Native BLE
|
|
2
|
+
|
|
3
|
+
- [Transport Device Kit React Native BLE Documentation](#transport-device-kit-react-native-ble)
|
|
4
|
+
- [Description](#description)
|
|
5
|
+
- [Installation](#installation)
|
|
6
|
+
- [Usage](#usage)
|
|
7
|
+
- [Compatibility](#compatibility)
|
|
8
|
+
- [Pre-requisites](#pre-requisites)
|
|
9
|
+
- [Main Features](#main-features)
|
|
10
|
+
- [How To](#how-to)
|
|
11
|
+
|
|
12
|
+
## Description
|
|
13
|
+
|
|
14
|
+
This transport is used to interact with a Ledger device through [react-native-ble-plx](https://github.com/dotintent/react-native-ble-plx) implementation by the Device Management Kit.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
To install the core package, run the following command:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install @ledgerhq/device-transport-kit-react-native-ble
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### Compatibility
|
|
27
|
+
|
|
28
|
+
- iOS (11+)
|
|
29
|
+
- Android (6.0+)
|
|
30
|
+
|
|
31
|
+
| React Native | React Native BLE PLX | 0.1.1 |
|
|
32
|
+
| :----------: | :------------------: | :---: |
|
|
33
|
+
| \>0.74.1 | 0.3.4 | ✅ |
|
|
34
|
+
|
|
35
|
+
### Pre-requisites
|
|
36
|
+
|
|
37
|
+
To use this transport, ensure you have the Device Management Kit installed in your project.
|
|
38
|
+
|
|
39
|
+
### Main Features
|
|
40
|
+
|
|
41
|
+
- Exposing a transport factory to be injected into the DeviceManagementKit
|
|
42
|
+
- Exposing the transport directly for a custom configuration
|
|
43
|
+
|
|
44
|
+
### How To
|
|
45
|
+
|
|
46
|
+
To use the transport, you need to inject it in the DeviceManagementKitBuilder before the build. This will allow the Device Management Kit to find and interact with devices on the iOS or Android BLE protocol.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit";
|
|
50
|
+
import {
|
|
51
|
+
RNBleTransportFactory,
|
|
52
|
+
RNBleTransport,
|
|
53
|
+
} from "@ledgerhq/device-transport-kit-react-native-ble";
|
|
54
|
+
|
|
55
|
+
// Easy setup with the factory
|
|
56
|
+
const dmk = new DeviceManagementKitBuilder()
|
|
57
|
+
.addTransport(RNBleTransportFactory)
|
|
58
|
+
.build();
|
|
59
|
+
|
|
60
|
+
// With custom config
|
|
61
|
+
const dmk = new DeviceManagementKitBuilder()
|
|
62
|
+
.addTransport(
|
|
63
|
+
({
|
|
64
|
+
deviceModelDataSource,
|
|
65
|
+
loggerServiceFactory,
|
|
66
|
+
config,
|
|
67
|
+
apduSenderServiceFactory,
|
|
68
|
+
apduReceiverServiceFactory,
|
|
69
|
+
}: {
|
|
70
|
+
deviceModelDataSource: DeviceModelDataSource;
|
|
71
|
+
loggerServiceFactory: (tag: string) => LoggerPublisherService;
|
|
72
|
+
config: DmkConfig;
|
|
73
|
+
apduSenderServiceFactory: ApduSenderServiceFactory;
|
|
74
|
+
apduReceiverServiceFactory: ApduReceiverServiceFactory;
|
|
75
|
+
}) => {
|
|
76
|
+
// custom code
|
|
77
|
+
return new RNBleTransport(
|
|
78
|
+
deviceModelDataSource,
|
|
79
|
+
loggerServiceFactory,
|
|
80
|
+
config,
|
|
81
|
+
apduSenderServiceFactory,
|
|
82
|
+
apduReceiverServiceFactory,
|
|
83
|
+
);
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
.build();
|
|
87
|
+
|
|
88
|
+
// You can then make use of the Device Management Kit
|
|
89
|
+
```
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var e=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var C=(E,T)=>{for(var _ in T)o(E,_,{get:T[_],enumerable:!0})},D=(E,T,_,t)=>{if(T&&typeof T=="object"||typeof T=="function")for(let O of e(T))!I.call(E,O)&&O!==_&&o(E,O,{get:()=>T[O],enumerable:!(t=N(T,O))||t.enumerable});return E};var L=E=>D(o({},"__esModule",{value:!0}),E);var s={};C(s,{BLE_DISCONNECT_TIMEOUT_ANDROID:()=>p,BLE_DISCONNECT_TIMEOUT_IOS:()=>r,CONNECTION_LOST_DELAY:()=>n,DEFAULT_MTU:()=>c});module.exports=L(s);const c=156,n=2e3,p=15e3,r=1e4;0&&(module.exports={BLE_DISCONNECT_TIMEOUT_ANDROID,BLE_DISCONNECT_TIMEOUT_IOS,CONNECTION_LOST_DELAY,DEFAULT_MTU});
|
|
2
2
|
//# sourceMappingURL=Const.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/model/Const.ts"],
|
|
4
|
-
"sourcesContent": ["export const DEFAULT_MTU = 156;\nexport const CONNECTION_LOST_DELAY =
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,
|
|
6
|
-
"names": ["Const_exports", "__export", "
|
|
4
|
+
"sourcesContent": ["export const DEFAULT_MTU = 156;\nexport const CONNECTION_LOST_DELAY = 2e3; // 2s;\nexport const BLE_DISCONNECT_TIMEOUT_ANDROID = 15e3; // 15s;\nexport const BLE_DISCONNECT_TIMEOUT_IOS = 10e3; // 10s;\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oCAAAE,EAAA,+BAAAC,EAAA,0BAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAN,GAAO,MAAMK,EAAc,IACdD,EAAwB,IACxBF,EAAiC,KACjCC,EAA6B",
|
|
6
|
+
"names": ["Const_exports", "__export", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "__toCommonJS"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var d=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var c=(o,e)=>{for(var r in e)d(o,r,{get:e[r],enumerable:!0})},i=(o,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of l(e))!u.call(o,t)&&t!==r&&d(o,t,{get:()=>e[t],enumerable:!(s=a(e,t))||s.enumerable});return o};var p=o=>i(d({},"__esModule",{value:!0}),o);var _={};c(_,{BleDeviceGattServerError:()=>x,BleNotSupported:()=>E,BleTransportNotSupportedError:()=>v,DeviceConnectionNotFound:()=>y,InternalDeviceNotFound:()=>g,NoDeviceModelFoundError:()=>k,PairingRefusedError:()=>w,PeerRemovedPairingError:()=>D,UnknownBleError:()=>N});module.exports=p(_);var n=require("@ledgerhq/device-management-kit");class v extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleTransportNotSupportedError"}class x extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleDeviceGattServerError"}class y extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="DeviceConnectionNotFound"}class g extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="InternalDeviceNotFound"}class E extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleNotSupported"}class k extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="NoDeviceModelFoundError"}class w extends n.OpeningConnectionError{constructor(r){super(r);this.err=r}_tag="PairingRefusedError"}class N extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="UnknownBleError"}class D extends n.OpeningConnectionError{constructor(r){super(r);this.err=r}_tag="PeerRemovedPairingError"}0&&(module.exports={BleDeviceGattServerError,BleNotSupported,BleTransportNotSupportedError,DeviceConnectionNotFound,InternalDeviceNotFound,NoDeviceModelFoundError,PairingRefusedError,PeerRemovedPairingError,UnknownBleError});
|
|
2
2
|
//# sourceMappingURL=Errors.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/model/Errors.ts"],
|
|
4
|
-
"sourcesContent": ["import {
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,IAAA,eAAAC,
|
|
6
|
-
"names": ["Errors_exports", "__export", "BleDeviceGattServerError", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "__toCommonJS", "import_device_management_kit", "err"]
|
|
4
|
+
"sourcesContent": ["import {\n GeneralDmkError,\n OpeningConnectionError,\n} from \"@ledgerhq/device-management-kit\";\n\nexport class BleTransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"BleTransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class BleDeviceGattServerError extends GeneralDmkError {\n override readonly _tag = \"BleDeviceGattServerError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class DeviceConnectionNotFound extends GeneralDmkError {\n override readonly _tag = \"DeviceConnectionNotFound\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class InternalDeviceNotFound extends GeneralDmkError {\n override readonly _tag = \"InternalDeviceNotFound\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class BleNotSupported extends GeneralDmkError {\n override readonly _tag = \"BleNotSupported\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class NoDeviceModelFoundError extends GeneralDmkError {\n override readonly _tag = \"NoDeviceModelFoundError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class PairingRefusedError extends OpeningConnectionError {\n override readonly _tag = \"PairingRefusedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class UnknownBleError extends GeneralDmkError {\n override readonly _tag = \"UnknownBleError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class PeerRemovedPairingError extends OpeningConnectionError {\n override readonly _tag = \"PeerRemovedPairingError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,EAAA,oBAAAC,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAX,GAAA,IAAAY,EAGO,2CAEA,MAAMR,UAAsC,iBAAgB,CAEjE,YAAqBS,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,+BAI3B,CACO,MAAMX,UAAiC,iBAAgB,CAE5D,YAAqBW,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAMR,UAAiC,iBAAgB,CAE5D,YAAqBQ,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAMP,UAA+B,iBAAgB,CAE1D,YAAqBO,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,wBAI3B,CAEO,MAAMV,UAAwB,iBAAgB,CAEnD,YAAqBU,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,iBAI3B,CAEO,MAAMN,UAAgC,iBAAgB,CAE3D,YAAqBM,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B,CAEO,MAAML,UAA4B,wBAAuB,CAE9D,YAAqBK,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,qBAI3B,CAEO,MAAMH,UAAwB,iBAAgB,CAEnD,YAAqBG,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,iBAI3B,CAEO,MAAMJ,UAAgC,wBAAuB,CAElE,YAAqBI,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,yBAI3B",
|
|
6
|
+
"names": ["Errors_exports", "__export", "BleDeviceGattServerError", "BleNotSupported", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "NoDeviceModelFoundError", "PairingRefusedError", "PeerRemovedPairingError", "UnknownBleError", "__toCommonJS", "import_device_management_kit", "err"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var y=(d,e)=>{for(var t in e)v(d,t,{get:e[t],enumerable:!0})},g=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!f.call(d,i)&&i!==t&&v(d,i,{get:()=>e[i],enumerable:!(n=m(e,i))||n.enumerable});return d};var A=d=>g(v({},"__esModule",{value:!0}),d);var D={};y(D,{RNBleApduSender:()=>S});module.exports=A(D);var u=require("@ledgerhq/device-management-kit"),p=require("js-base64"),s=require("purify-ts"),l=require("rxjs"),a=require("../model/Errors");const R=3;class S{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;_writeCharacteristic;_characteristicSubscription=void 0;constructor({apduSenderFactory:e,apduReceiverFactory:t,dependencies:n},i){this._dependencies=n,this._isDeviceReady=new l.BehaviorSubject(!1),this._logger=i("RNBleApduSender"),this._apduSenderFactory=e,this._apduSender=s.Nothing,this._apduReceiver=t(),this._sendApduPromiseResolver=s.Nothing}onReceiveSetupApduResponse(e){const t=new Uint8Array(e),{device:n}=this._dependencies,[i]=t.slice(5);let r=n.mtu-R;i&&i!==r&&(r=i),this._apduSender=s.Maybe.of(this._apduSenderFactory({frameSize:r})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(n=>{n.map(i=>{this._logger.debug("Received APDU Response",{data:{response:i}}),this._sendApduPromiseResolver.map(r=>r((0,s.Right)(i)))})}).mapLeft(n=>{this._sendApduPromiseResolver.map(i=>i((0,s.Left)(n)))})}onMonitor(e){if(!e.value)return;const t=p.Base64.toUint8Array(e.value);this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(e){return this._writeCharacteristic.isWritableWithoutResponse?this._writeCharacteristic.writeWithoutResponse(e):this._writeCharacteristic.writeWithResponse(e)}getDependencies(){return this._dependencies}setDependencies(e){this._dependencies=e,this._isDeviceReady=new l.BehaviorSubject(!1),this._characteristicSubscription&&(this._characteristicSubscription.remove(),this._characteristicSubscription=void 0)}async setupConnection(){this._characteristicSubscription=this._dependencies.device.monitorCharacteristicForService(this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,o)=>{if(r?.message.includes("notify change failed")){this._isDeviceReady.error(new a.PairingRefusedError(r)),this._logger.error("Pairing failed",{data:{error:r}});return}else r&&(this._isDeviceReady.error(new a.UnknownBleError(r)),this._logger.error("Error monitoring characteristic",{data:{error:r}}));!r&&o&&this.onMonitor(o)});const e=await this._dependencies.manager.characteristicsForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid);let t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid);if(t)this._writeCharacteristic=t;else if(t=e.find(r=>r.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeUuid),t)this._writeCharacteristic=t;else throw this._logger.error("No write characteristic found"),new Error("No write characteristic found");const n=Uint8Array.from([8,0,0,0,0]);await this.write(p.Base64.fromUint8Array(n)).catch(r=>{throw this._logger.error("Pairing failed",{data:{error:r}}),new a.PairingRefusedError(r)});let i;await new Promise((r,o)=>{i&&i.unsubscribe(),i=this._isDeviceReady.subscribe({next:c=>{c&&r()},error:c=>{o(c)}})})}async sendApdu(e,t,n){if(this._logger.debug("[sendApdu]",{data:{apdu:e,abortTimeout:n}}),!this._isDeviceReady.value)return Promise.resolve((0,s.Left)(new u.DeviceNotInitializedError("Unknown MTU")));let i;const r=new Promise(c=>{this._sendApduPromiseResolver=s.Maybe.of((...h)=>(i&&clearTimeout(i),c(...h)))}),o=this._apduSender.caseOf({Just:c=>c.getFrames(e),Nothing:()=>[]});for(const c of o)try{await this.write(p.Base64.fromUint8Array(c.getRawData()))}catch(h){this._logger.info("Error sending frame",{data:{error:h}})}return n&&(i=setTimeout(()=>{this._logger.debug("[sendApdu] Abort timeout triggered"),this._sendApduPromiseResolver.map(c=>c((0,s.Left)(new u.SendApduTimeoutError("Abort timeout"))))},n)),r}closeConnection(){this._dependencies.device.cancelConnection()}}0&&(module.exports={RNBleApduSender});
|
|
2
2
|
//# sourceMappingURL=RNBleApduSender.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleApduSender.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD,
|
|
6
|
-
"names": ["RNBleApduSender_exports", "__export", "RNBleApduSender", "__toCommonJS", "import_device_management_kit", "import_js_base64", "import_purify_ts", "import_rxjs", "FRAME_HEADER_SIZE", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "
|
|
4
|
+
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as BleCharacteristicSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nimport { PairingRefusedError, UnknownBleError } from \"@api/model/Errors\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n};\n\nexport type RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n private _writeCharacteristic!: Characteristic;\n private _characteristicSubscription:\n | BleCharacteristicSubscription\n | undefined = undefined;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n if (this._writeCharacteristic.isWritableWithoutResponse) {\n return this._writeCharacteristic.writeWithoutResponse(value);\n }\n\n return this._writeCharacteristic.writeWithResponse(value);\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n\n //Set dependencies mean we are reconnecting to a new device\n // So we need to reset the state of the sender\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n if (this._characteristicSubscription) {\n this._characteristicSubscription.remove();\n this._characteristicSubscription = undefined;\n }\n }\n\n public async setupConnection() {\n this._characteristicSubscription =\n this._dependencies.device.monitorCharacteristicForService(\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (error?.message.includes(\"notify change failed\")) {\n // iOS pairing refused error\n this._isDeviceReady.error(new PairingRefusedError(error));\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n return;\n } else if (error) {\n this._isDeviceReady.error(new UnknownBleError(error));\n this._logger.error(\"Error monitoring characteristic\", {\n data: { error },\n });\n }\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n\n // Setup Write characteristic\n const characteristics =\n await this._dependencies.manager.characteristicsForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n );\n\n let tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n );\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n tmpWriteCharacteristic = characteristics.find(\n (characteristic) =>\n characteristic.uuid ===\n this._dependencies.internalDevice.bleDeviceInfos.writeUuid,\n );\n\n //This should never happen\n if (tmpWriteCharacteristic) {\n this._writeCharacteristic = tmpWriteCharacteristic;\n } else {\n this._logger.error(\"No write characteristic found\");\n throw new Error(\"No write characteristic found\");\n }\n }\n\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame)).catch((error) => {\n // Android pairing refused error\n this._logger.error(\"Pairing failed\", {\n data: { error },\n });\n throw new PairingRefusedError(error);\n });\n let sub: Subscription | undefined;\n await new Promise<void>((resolve, reject) => {\n if (sub) {\n sub.unsubscribe();\n }\n\n sub = this._isDeviceReady.subscribe({\n next: (isReady) => {\n if (isReady) {\n resolve(); // FIXME: we should instead return a Right\n }\n },\n error: (error) => {\n reject(error); // FIXME: we should instead return a Left so it's properly typed\n },\n });\n });\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(\"[sendApdu]\", {\n data: { apdu, abortTimeout },\n });\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n if (abortTimeout) {\n timeout = setTimeout(() => {\n this._logger.debug(\"[sendApdu] Abort timeout triggered\");\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2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GF,OAAIS,IACFC,EAAU,WAAW,IAAM,CACzB,KAAK,QAAQ,MAAM,oCAAoC,EACvD,KAAK,yBAAyB,IAAKX,GACjCA,KAAQ,QAAK,IAAI,uBAAqB,eAAe,CAAC,CAAC,CACzD,CACF,EAAGU,CAAY,GAGVE,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
|
|
6
|
+
"names": ["RNBleApduSender_exports", "__export", "RNBleApduSender", "__toCommonJS", "import_device_management_kit", "import_js_base64", "import_purify_ts", "import_rxjs", "import_Errors", "FRAME_HEADER_SIZE", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "response", "apduResponse", "resolve", "error", "characteristic", "characteristics", "tmpWriteCharacteristic", "requestMtuFrame", "sub", "reject", "isReady", "_triggersDisconnection", "abortTimeout", "timeout", "resultPromise", "args", "frames", "apduSender", "frame"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var s=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),w=require("./RNBleApduSender");vi.mock("react-native-ble-plx",()=>({BleManager:vi.fn()}));const f=3,C=156;class U{subscribers=[];tag;constructor(t,r){this.subscribers=t,this.tag=r}error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}let l,v,h,e,n;const p=vi.fn();describe.skip("RNBleApduSender",()=>{beforeEach(()=>{l=i=>new U([],i),v=vi.fn(()=>(0,s.defaultApduSenderServiceStubBuilder)(void 0,l)),h=vi.fn(()=>(0,s.defaultApduReceiverServiceStubBuilder)(void 0,l)),e=new w.RNBleApduSender({dependencies:{device:{mtu:156,cancelConnection:p},internalDevice:{},manager:{}},apduReceiverFactory:h,apduSenderFactory:v},l)}),afterEach(()=>{vi.clearAllMocks()}),describe("constructor",()=>{it("should create an instance of RNBleApduSender",()=>{expect(e).toBeDefined()})}),describe("getDependencies",()=>{it("should return the dependencies",()=>{const i=e.getDependencies();expect(i).toStrictEqual({device:{mtu:156,cancelConnection:p},internalDevice:{},manager:{}})})}),describe("setDependencies",()=>{it("should set the dependencies",()=>{const i={device:{mtu:156,id:"deviceId",cancelConnection:p},internalDevice:{id:"deviceId",bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:{}};e.setDependencies(i);const t=e.getDependencies();expect(t).toStrictEqual(i)})}),describe("setupConnection",()=>{beforeEach(()=>{n={monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn()};const i={device:{mtu:156,id:"deviceId"},internalDevice:{bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:n};e.setDependencies(i)}),it("should setup the connection and resolve when the device is ready",async()=>{vi.spyOn(n,"monitorCharacteristicForDevice").mockImplementation((i,t,r,c)=>(c(null,{value:"BQAAAA8BBUJPTE9TBTEuMi4ykAA="}),{remove:vi.fn()})),vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((i,t,r,c)=>(e.onMonitor({value:c}),Promise.resolve({value:c}))),await e.setupConnection(),expect(n.monitorCharacteristicForDevice).toHaveBeenCalled(),expect(n.writeCharacteristicWithoutResponseForDevice).toHaveBeenCalled()})}),describe("closeConnection",()=>{it("should close the connection",()=>{e.closeConnection(),expect(p).toHaveBeenCalled()})}),describe("sendApdu",()=>{beforeEach(async()=>{n={monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn()};const i={device:{mtu:156,id:"deviceId"},internalDevice:{bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:n};vi.spyOn(n,"monitorCharacteristicForDevice").mockImplementationOnce((t,r,c,o)=>(o(null,{value:"BQAAAA8BBUJPTE9TBTEuMi4ykAA="}),{remove:vi.fn()})),vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((t,r,c,o)=>(e.onMonitor({value:o}),Promise.resolve({value:o}))),e.setDependencies(i),await e.setupConnection()}),describe("when the device is not ready",()=>{it("should return a DeviceNotInitializedError",async()=>{const i=new Uint8Array([8,0,0,0]);e._isDeviceReady.next(!1);const t=await e.sendApdu(i);expect(t).toStrictEqual((0,a.Left)(new s.DeviceNotInitializedError("Unknown MTU")))})}),describe("when the device is ready",()=>{it("should send the apdu",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new Uint8Array([5,0,0,0,15,1,5,66,79,76,79,83,5,49,46,50,46,50,144,0]),r=new Uint8Array([144,0]),c={data:t,statusCode:r};vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((u,d,y,m)=>(e.onMonitor({value:m}),Promise.resolve({value:m}))),vi.spyOn(e._apduReceiver,"handleFrame").mockImplementation(()=>(0,a.Right)(a.Maybe.of(c)));const o=await e.sendApdu(i);expect(v).toHaveBeenCalledTimes(2),expect(v).toHaveBeenNthCalledWith(1,{frameSize:1}),expect(v).toHaveBeenNthCalledWith(2,{frameSize:C-f}),expect(o).toStrictEqual((0,a.Right)(c))}),it("should return an error if the frame cannot be handled",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.GeneralDmkError("could not handle frame");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({value:d}),Promise.resolve({value:d}))),vi.spyOn(e._apduReceiver,"handleFrame").mockImplementation(()=>(0,a.Left)(t));const r=await e.sendApdu(i);expect(r).toStrictEqual((0,a.Left)(t))}),it("should return a SendApduTimeoutError if something takes too long",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new Uint8Array([5,0,0,0,15,1,5,66,79,76,79,83,5,49,46,50,46,50,144,0]),r=new Uint8Array([144,0]),c={data:t,statusCode:r},o=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((d,y,m,x)=>(e.onMonitor({value:x}),Promise.resolve({value:x}))),vi.spyOn(e,"onMonitor").mockImplementation(()=>{setTimeout(()=>(0,a.Right)(a.Maybe.of(c)),2e3)});const u=await e.sendApdu(i,!1,100);expect(u).toStrictEqual((0,a.Left)(o))}),it("should and and log an error if the this.write fails",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({value:d}),Promise.resolve({value:d}))),vi.spyOn(e,"write").mockImplementation(()=>Promise.reject(new Error("test")));const r=await e.sendApdu(i,!1,100);expect(r).toStrictEqual((0,a.Left)(t))}),it("should timeout if there are no characteristic.value",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({}),Promise.resolve({}))),vi.spyOn(e,"write").mockImplementation(()=>Promise.reject(new Error("test")));const r=await e.sendApdu(i,!1,100);expect(r).toStrictEqual((0,a.Left)(t))})})})});
|
|
2
|
+
//# sourceMappingURL=RNBleApduSender.test.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/api/transport/RNBleApduSender.test.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n GeneralDmkError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Maybe, Right } from \"purify-ts\";\n\nimport { RNBleApduSender, type RNBleInternalDevice } from \"./RNBleApduSender\";\n\nvi.mock(\"react-native-ble-plx\", () => ({\n BleManager: vi.fn(),\n}));\n\nconst FRAME_HEADER_SIZE = 3;\nconst LEDGER_MTU = 156;\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\nlet logger: (tag: string) => LoggerPublisherService;\nlet apduSenderFactory: ApduSenderServiceFactory;\nlet apduReceiverFactory: ApduReceiverServiceFactory;\nlet apduSender: RNBleApduSender;\nlet manager: BleManager;\nconst cancelConnection = vi.fn();\n\n// TODO: fix these tests, sorry they are completely broken now\ndescribe.skip(\"RNBleApduSender\", () => {\n beforeEach(() => {\n logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n apduSenderFactory = vi.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = vi.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n apduSender = new RNBleApduSender(\n {\n dependencies: {\n device: {\n mtu: 156,\n cancelConnection,\n } as unknown as Device,\n internalDevice: {} as RNBleInternalDevice,\n manager: {} as BleManager,\n },\n apduReceiverFactory: apduReceiverFactory,\n apduSenderFactory: apduSenderFactory,\n },\n logger,\n );\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n });\n\n describe(\"constructor\", () => {\n it(\"should create an instance of RNBleApduSender\", () => {\n expect(apduSender).toBeDefined();\n });\n });\n\n describe(\"getDependencies\", () => {\n it(\"should return the dependencies\", () => {\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual({\n device: {\n mtu: 156,\n cancelConnection,\n },\n internalDevice: {},\n manager: {},\n });\n });\n });\n\n describe(\"setDependencies\", () => {\n it(\"should set the dependencies\", () => {\n const newDependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n cancelConnection,\n } as unknown as Device,\n internalDevice: {\n id: \"deviceId\",\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager: {} as BleManager,\n };\n apduSender.setDependencies(newDependencies);\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual(newDependencies);\n });\n });\n\n describe(\"setupConnection\", () => {\n beforeEach(() => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n apduSender.setDependencies(dependencies);\n });\n\n it(\"should setup the connection and resolve when the device is ready\", async () => {\n vi.spyOn(manager, \"monitorCharacteristicForDevice\").mockImplementation(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n await apduSender.setupConnection();\n\n expect(manager.monitorCharacteristicForDevice).toHaveBeenCalled();\n expect(\n manager.writeCharacteristicWithoutResponseForDevice,\n ).toHaveBeenCalled();\n });\n });\n\n describe(\"closeConnection\", () => {\n it(\"should close the connection\", () => {\n apduSender.closeConnection();\n expect(cancelConnection).toHaveBeenCalled();\n });\n });\n\n describe(\"sendApdu\", () => {\n beforeEach(async () => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n vi.spyOn(\n manager,\n \"monitorCharacteristicForDevice\",\n ).mockImplementationOnce(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n apduSender.setDependencies(dependencies);\n await apduSender.setupConnection();\n });\n\n describe(\"when the device is not ready\", () => {\n it(\"should return a DeviceNotInitializedError\", async () => {\n const apdu = new Uint8Array([0x08, 0x00, 0x00, 0x00]);\n // @ts-expect-error private access for tests\n apduSender._isDeviceReady.next(false);\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n });\n\n describe(\"when the device is ready\", () => {\n it(\"should send the apdu\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Right(Maybe.of(response));\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(apduSenderFactory).toHaveBeenCalledTimes(2);\n\n // first call is for the setup\n expect(apduSenderFactory).toHaveBeenNthCalledWith(1, {\n frameSize: 1,\n });\n\n // second call is for the apdu\n expect(apduSenderFactory).toHaveBeenNthCalledWith(2, {\n frameSize: LEDGER_MTU - FRAME_HEADER_SIZE,\n });\n\n expect(result).toStrictEqual(Right(response));\n });\n\n it(\"should return an error if the frame cannot be handled\", async () => {\n // {\"error\": {\"_tag\": \"DeviceLockedError\", \"errorCode\": \"5515\", \"message\": \"Device is locked.\", \"originalError\": undefined}, \"status\": \"ERROR\"}\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedError = new GeneralDmkError(\"could not handle frame\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Left(expectedError);\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should return a SendApduTimeoutError if something takes too long\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"onMonitor\").mockImplementation(() => {\n setTimeout(() => {\n return Right(Maybe.of(response));\n }, 2000);\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should and and log an error if the this.write fails\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should timeout if there are no characteristic.value\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, _value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({} as Characteristic);\n\n return Promise.resolve({} as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "aAKA,IAAAA,EAUO,2CACPC,EAAmC,qBAEnCC,EAA0D,6BAE1D,GAAG,KAAK,uBAAwB,KAAO,CACrC,WAAY,GAAG,GAAG,CACpB,EAAE,EAEF,MAAMC,EAAoB,EACpBC,EAAa,IAEnB,MAAMC,CAA6D,CACjE,YAAyC,CAAC,EAC1C,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,MAAQ,GAAG,GAAG,EACd,KAAO,GAAG,GAAG,EACb,KAAO,GAAG,GAAG,EACb,MAAQ,GAAG,GAAG,CAChB,CAEA,IAAIC,EACAC,EACAC,EACAC,EACAC,EACJ,MAAMC,EAAmB,GAAG,GAAG,EAG/B,SAAS,KAAK,kBAAmB,IAAM,CACrC,WAAW,IAAM,CACfL,EAAUD,GAAgB,IAAIF,EAA2B,CAAC,EAAGE,CAAG,EAChEE,EAAoB,GAAG,GAAG,OACxB,uCAAoC,OAAWD,CAAM,CACvD,EACAE,EAAsB,GAAG,GAAG,OAC1B,yCAAsC,OAAWF,CAAM,CACzD,EACAG,EAAa,IAAI,kBACf,CACE,aAAc,CACZ,OAAQ,CACN,IAAK,IACL,iBAAAE,CACF,EACA,eAAgB,CAAC,EACjB,QAAS,CAAC,CACZ,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O,IAAI,WAAW,CAAC,IAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EACpDK,EAAgB,IAAI,uBAAqB,eAAe,EAE9D,GAAG,MACDf,EACA,6CACF,EAAE,mBACA,CAACI,EAAWC,EAAcG,EAAeC,KAEvCV,EAAW,UAAU,CACnB,MAAOU,CACT,CAAmB,EAEZ,QAAQ,QAAQ,CACrB,MAAOA,CACT,CAAmB,EAEvB,EAGA,GAAG,MAAMV,EAAY,OAAO,EAAE,mBAAmB,IACxC,QAAQ,OAAO,IAAI,MAAM,MAAM,CAAC,CACxC,EAED,MAAMY,EAAS,MAAMZ,EAAW,SAASW,EAAM,GAAO,GAAG,EACzD,OAAOC,CAAM,EAAE,iBAAc,QAAKI,CAAa,CAAC,CAClD,CAAC,EAED,GAAG,sDAAuD,SAAY,CAEpE,MAAML,EAAO,IAAI,WAAW,CAAC,IAAM,EAAM,EAAM,EAAM,CAAI,CAAC,EACpDK,EAAgB,IAAI,uBAAqB,eAAe,EAE9D,GAAG,MACDf,EACA,6CACF,EAAE,mBACA,CAACI,EAAWC,EAAcG,EAAeQ,KAEvCjB,EAAW,UAAU,CAAC,CAAmB,EAElC,QAAQ,QAAQ,CAAC,CAAmB,EAE/C,EAGA,GAAG,MAAMA,EAAY,OAAO,EAAE,mBAAmB,IACxC,QAAQ,OAAO,IAAI,MAAM,MAAM,CAAC,CACxC,EAED,MAAMY,EAAS,MAAMZ,EAAW,SAASW,EAAM,GAAO,GAAG,EACzD,OAAOC,CAAM,EAAE,iBAAc,QAAKI,CAAa,CAAC,CAClD,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["import_device_management_kit", "import_purify_ts", "import_RNBleApduSender", "FRAME_HEADER_SIZE", "LEDGER_MTU", "LoggerPublisherServiceStub", "subscribers", "tag", "logger", "apduSenderFactory", "apduReceiverFactory", "apduSender", "manager", "cancelConnection", "dependencies", "newDependencies", "_deviceId", "_serviceUuid", "_notifyUuid", "callback", "_writeCmdUuid", "value", "apdu", "result", "expectedResponse", "statusCode", "response", "expectedError", "_value"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var h=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var T=(v,e)=>{for(var i in e)h(v,i,{get:e[i],enumerable:!0})},f=(v,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of y(e))!g.call(v,t)&&t!==i&&h(v,t,{get:()=>e[t],enumerable:!(r=I(e,t))||r.enumerable});return v};var N=v=>f(h({},"__esModule",{value:!0}),v);var B={};T(B,{RNBleTransport:()=>m,RNBleTransportFactory:()=>C,rnBleTransportIdentifier:()=>E});module.exports=N(B);var c=require("react-native"),S=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),s=require("rxjs"),l=require("../model/Const"),D=require("../model/Errors"),_=require("../transport/RNBleApduSender");const E="RN_BLE";class m{constructor(e,i,r,t){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=r;this._apduReceiverFactory=t;this._logger=i("ReactNativeBleTransport"),this._manager=new S.BleManager,this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return this._internalDevicesById.clear(),(0,s.from)(this.requestPermission()).pipe((0,s.switchMap)(i=>{if(!i)throw new Error("BLE not supported");return(0,s.merge)(this._discoverKnownDevices(e),this._discoverNewDevices(e))}))}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return(0,n.EitherAsync)(async({liftEither:i,throwE:r})=>{const t=await i(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new p.UnknownDeviceError(`Unknown device ${e.deviceId}`)));let o;try{o=await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(d){return r(new p.OpeningConnectionError(d))}const a=new _.RNBleApduSender({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:t,manager:this._manager}},this._loggerServiceFactory),u=new p.DeviceConnectionStateMachine({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:l.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const d=this._internalDevicesById.get(e.deviceId);d&&d.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await a.setupConnection(),this._deviceConnectionsById.set(t.id,u),t.disconnectionSubscription=this._manager.onDeviceDisconnected(t.id,(...d)=>{this._handleDeviceDisconnected(...d)}),t.lastDiscoveredTimeStamp=n.Maybe.zero(),new p.TransportConnectedDevice({id:t.id,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...d)=>u.sendApdu(...d),transport:this.identifier})}).run()}async disconnect(e){return n.Maybe.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(r=>{r.closeConnection()}),Promise.resolve((0,n.Right)(void 0))}_isDiscoveredDeviceLost(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+l.CONNECTION_LOST_DELAY,Nothing:()=>(e.lastDiscoveredTimeStamp=n.Maybe.of(Date.now()),!0)})}listenToKnownDevices(){return(0,s.from)([])}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(c.Platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(c.Platform.OS==="android"&&c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(c.Platform.Version.toString(),10)<31){const i=await c.PermissionsAndroid.request(c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===c.PermissionsAndroid.RESULTS.GRANTED)}if(c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await c.PermissionsAndroid.requestMultiple([c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===c.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===c.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===c.PermissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const r=n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o)));return n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).isJust()?n.Nothing:r.mapOrDefault(o=>{const a=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(a[o]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier},bleDeviceInfos:d}))},n.Nothing)}_handleLostDiscoveredDevices(e){this._internalDevicesById.forEach(i=>{this._isDiscoveredDeviceLost(i)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,available:!1}))})}_emitDiscoveredDevice(e,i,r){e.next(r);const t={id:r.id,bleDeviceInfos:i,discoveredDevice:r,available:!0,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(r.id,{...t,disconnectionSubscription:this._manager.onDeviceDisconnected(r.id,()=>{e.next({...r,available:!1})})})}_discoverNewDevices(e){return new s.Observable(i=>{this._manager.startDeviceScan(null,null,(r,t)=>{if(this._handleLostDiscoveredDevices(i),r||!t){i.error(r);return}this._getDiscoveredDeviceFrom(t,e).map(({discoveredDevice:o,bleDeviceInfos:a})=>{this._emitDiscoveredDevice(i,a,o)})})})}_discoverKnownDevices(e){return(0,s.from)(this._manager.connectedDevices(e)).pipe((0,s.switchMap)(i=>new s.Observable(r=>{i.forEach(t=>{this._getDiscoveredDeviceFrom(t,e).map(({bleDeviceInfos:o,discoveredDevice:a})=>{this._emitDiscoveredDevice(r,o,a)})})})))}_handleDeviceDisconnected(e,i){if(e&&this._logger.error("device disconnected error",{data:{error:e,device:i}}),!i){this._logger.info("disconnected handler didn't found device");return}n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id)).map(o=>{o.eventDeviceDetached()});let t;(0,s.from)([0]).pipe((0,s.switchMap)(async()=>{try{t=await i.connect({requestMTU:l.DEFAULT_MTU}),t=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(t)}catch(o){throw this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:o}}),n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id)).map(a=>{a.closeConnection()}),o}return i}),(0,s.retry)({count:5,delay:l.BLE_DISCONNECT_TIMEOUT/5})).subscribe({next:o=>this._logger.info("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:o}}),error:o=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:o}})}})}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new D.DeviceConnectionNotFound),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new D.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:t})=>{const o=await t(i),a=await t(r);o.setDependencies({device:e,manager:this._manager,internalDevice:a}),await o.setupConnection(),o.eventDeviceAttached()}).run()}}const C=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:r})=>new m(v,e,i,r);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
|
|
1
|
+
"use strict";var m=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var A=(v,e)=>{for(var i in e)m(v,i,{get:e[i],enumerable:!0})},B=(v,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of E(e))!N.call(v,t)&&t!==i&&m(v,t,{get:()=>e[t],enumerable:!(n=C(e,t))||n.enumerable});return v};var M=v=>B(m({},"__esModule",{value:!0}),v);var R={};A(R,{RNBleTransport:()=>I,RNBleTransportFactory:()=>O,rnBleTransportIdentifier:()=>w});module.exports=M(R);var _=require("react-native"),D=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),r=require("purify-ts"),o=require("rxjs"),l=require("../model/Const"),h=require("../model/Errors"),y=require("../transport/RNBleApduSender");const w="RN_BLE";class I{constructor(e,i,n,t,a,c=_.Platform,S=_.PermissionsAndroid,d=u=>new p.DeviceConnectionStateMachine(u),f=(u,g)=>new y.RNBleApduSender(u,g)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=n;this._apduReceiverFactory=t;this._manager=a;this._platform=c;this._permissionsAndroid=S;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=f;this._logger=i("ReactNativeBleTransport"),this._isSupported=r.Maybe.zero(),this._deviceConnectionsById=new Map,this._reconnectionSubscription=r.Maybe.zero(),this._manager.onStateChange(u=>{this._bleStateSubject.next(u)},!0)}_logger;_isSupported;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new o.BehaviorSubject(D.State.Unknown);startDiscovering(){return(0,o.from)([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=r.Nothing;_scannedDevicesSubject=new o.BehaviorSubject([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=(0,o.from)(this._bleStateSubject).pipe((0,o.filter)(e=>e==="PoweredOn"),(0,o.switchMap)(()=>this.requestPermission()),(0,o.switchMap)(e=>{if(!e)return(0,o.throwError)(()=>new h.BleNotSupported("BLE not supported"));const i=new o.BehaviorSubject([]);this._maybeScanningSubject=r.Maybe.of(i);const n=new Map;this._logger.info("[RNBleTransport][startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(a,c)=>{if(a||!c){i.error(a||new Error("scan error"));return}n.set(c.id,{device:c,timestamp:Date.now()}),i.next(Array.from(n.values()))});const t=setInterval(()=>{i.next(Array.from(n.values()))},1e3);return i.asObservable().pipe((0,o.finalize)(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),i.complete(),clearInterval(t),this._maybeScanningSubject=r.Nothing,this._manager.stopDeviceScan()}))}),(0,o.throttleTime)(1e3)).subscribe({next:e=>{this._logger.debug("[RNBleTransport][startScanning] onNext called with devices",{data:{devices:e}}),this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}})}}))}async _stopScanning(){this._maybeScanningSubject.map(e=>{e.complete(),this._maybeScanningSubject=r.Nothing}),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0}listenToAvailableDevices(){return this._startScanning(),this._scannedDevicesSubject.asObservable().pipe((0,o.map)(e=>{const i=Array.from(this._deviceConnectionsById.values()).map(c=>this._mapDeviceToTransportDiscoveredDevice(c.getDependencies().device,[c.getDependencies().internalDevice.bleDeviceInfos.serviceUuid])),n=r.Either.rights(i),t=e.filter(({timestamp:c})=>c>Date.now()-l.CONNECTION_LOST_DELAY).sort((c,S)=>(S.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),a=r.Either.rights(t);return[...n,...a]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const i of e||[]){const n=this._deviceModelDataSource.getBluetoothServicesInfos()[i];if(n)return(0,r.Right)(n)}return(0,r.Left)(new h.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(n=>n.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,i){return this._mapServicesUUIDsToDeviceModel(i).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const n=i.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return(0,r.Right)(new p.TransportConnectedDevice({id:e.deviceId,deviceModel:n,type:"BLE",sendApdu:(...t)=>i.sendApdu(...t),transport:this.identifier}))}return await this._stopScanning(),await this._safeCancel(e.deviceId),(0,r.EitherAsync)(async({throwE:n})=>{let t,a=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),a=(await t.services()).map(s=>s.uuid)}catch(s){return s instanceof D.BleError&&s.iosErrorCode===14?n(new h.PeerRemovedPairingError(s)):n(new p.OpeningConnectionError(s))}const c=this._manager.onDeviceDisconnected(t.id,(s,T)=>{this._handleDeviceDisconnected(s,T)}),S=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>s,Left:s=>n(new p.OpeningConnectionError(s))}),d=S.deviceModel,f={id:t.id,bleDeviceInfos:S},u=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),g=_.Platform.OS==="ios"?l.BLE_DISCONNECT_TIMEOUT_IOS:l.BLE_DISCONNECT_TIMEOUT_ANDROID,b=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:u,timeoutDuration:g,tryToReconnect:()=>{this.tryToReconnect(e.deviceId)},onTerminated:()=>{try{this._safeCancel(e.deviceId),e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),c.remove(),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(s=>s.unsubscribe()),this._reconnectionSubscription=r.Maybe.zero())}catch(s){this._logger.error("Error in termination of device connection",{data:{e:s}})}}});return await u.setupConnection().catch(s=>{throw this._safeCancel(e.deviceId),c.remove(),s}),this._deviceConnectionsById.set(e.deviceId,b),new p.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...s)=>b.sendApdu(...s),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id,n=this._deviceConnectionsById.get(i);if(!n)throw new p.UnknownDeviceError(`No connected device found with id ${i}`);return n.closeConnection(),Promise.resolve((0,r.Right)(void 0))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=r.Maybe.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=r.Maybe.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=r.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=r.Maybe.of(!1),!1}_handleDeviceDisconnected(e,i){if(this._logger.debug("[RNBLE][_handleDeviceDisconnected]",{data:{error:e,device:i}}),!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const n=i.id;this._reconnectionSubscription.isJust()||r.Maybe.fromNullable(this._deviceConnectionsById.get(n)).map(t=>t.eventDeviceDisconnected())}tryToReconnect(e){const i=(0,o.from)([0]).pipe((0,o.switchMap)(async()=>{await this._stopScanning(),await this._safeCancel(e)}),(0,o.switchMap)(async()=>{this._logger.debug("[_handleDeviceDisconnected] reconnecting to device",{data:{id:e}});const n=await this._manager.connectToDevice(e,{requestMTU:l.DEFAULT_MTU,timeout:2e3});this._logger.debug("[_handleDeviceDisconnected] reconnected to device",{data:{id:e}});const t=await n.discoverAllServicesAndCharacteristics();return this._logger.debug("[_handleDeviceDisconnected] discovered all services and characteristics",{data:{reconnectedDeviceUsable:t}}),await this._handleDeviceReconnected(t),t}),(0,o.retry)(5));this._reconnectionSubscription=r.Maybe.of(i.subscribe({next:n=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:n.id}}),complete:()=>{this._reconnectionSubscription=r.Maybe.zero()},error:n=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:n}}),r.Maybe.fromNullable(this._deviceConnectionsById.get(e)).map(t=>t.closeConnection()),this._reconnectionSubscription=r.Maybe.zero()}}))}async _handleDeviceReconnected(e){const i=r.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new h.DeviceConnectionNotFound);return(0,r.EitherAsync)(async({liftEither:n,throwE:t})=>{const a=await n(i),c=(await e.services()).map(d=>d.uuid),S=this._mapServicesUUIDsToBluetoothDeviceInfo(c).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});a.setDependencies({device:e,manager:this._manager,internalDevice:S}),await a.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),a.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const i=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const n of i)n.id===e&&await this._manager.cancelDeviceConnection(e)}}}const O=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:n})=>new I(v,e,i,n,new D.BleManager);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -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 { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n merge,\n Observable,\n retry,\n type Subscriber,\n switchMap,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\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 ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n this._internalDevicesById.clear();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return merge(\n this._discoverKnownDevices(ledgerUuids),\n this._discoverNewDevices(ledgerUuids),\n );\n }),\n );\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._manager.stopDeviceScan();\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 return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.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 deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n private _isDiscoveredDeviceLost(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n internalDevice.lastDiscoveredTimeStamp = Maybe.of(Date.now());\n return true;\n },\n });\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 listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\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 (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n 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() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return Nothing;\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n this._internalDevicesById.forEach((internalDevice) => {\n if (this._isDiscoveredDeviceLost(internalDevice)) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n available: false,\n });\n }\n });\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} Does*/\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n available: true,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n // this._internalDevicesById.delete(discoveredDevice.id);\n subscriber.next({ ...discoveredDevice, available: false });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n this._handleLostDiscoveredDevices(subscriber);\n\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n devices.forEach((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }),\n ),\n );\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 * @param {DisconnectHandler} onDisconnect - A callback function to be called if the reconnection attempts fail completely.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n }\n\n if (!device) {\n this._logger.info(\"disconnected handler didn't found device\");\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n Maybe.fromNullable(this._deviceConnectionsById.get(device.id)).map(\n (deviceConnection) => {\n deviceConnection.closeConnection();\n },\n );\n\n throw e;\n }\n\n return device;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.info(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\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 device 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 const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\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 );\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,
|
|
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", "
|
|
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,0BAA4B,QAAM,KAAK,EAC5C,KAAK,SAAS,cAAeU,GAAU,CACrC,KAAK,iBAAiB,KAAKA,CAAK,CAClC,EAAG,EAAI,CACT,CAvCQ,QACA,aACA,uBAKS,WAAkC,SAC3C,0BACS,iBACf,IAAI,kBAAuB,QAAM,OAAO,EAmC1C,kBAA0D,CACxD,SAAO,QAAK,CAAC,CAAC,CAChB,CAOA,MAAM,iBAAiC,CACrC,MAAM,KAAK,cA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K,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"]
|
|
7
7
|
}
|