@ledgerhq/device-transport-kit-react-native-ble 1.1.1 → 1.3.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/lib/cjs/api/model/Errors.js +1 -1
- package/lib/cjs/api/model/Errors.js.map +3 -3
- package/lib/cjs/api/permissions/AndroidPermissionsService.js +1 -1
- package/lib/cjs/api/permissions/AndroidPermissionsService.js.map +3 -3
- package/lib/cjs/api/transport/RNBleApduSender.js +1 -1
- package/lib/cjs/api/transport/RNBleApduSender.js.map +2 -2
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/api/transport/RNBleTransport.test.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/cjs/package.json +2 -2
- package/lib/esm/api/model/Errors.js +1 -1
- package/lib/esm/api/model/Errors.js.map +3 -3
- package/lib/esm/api/permissions/AndroidPermissionsService.js +1 -1
- package/lib/esm/api/permissions/AndroidPermissionsService.js.map +3 -3
- package/lib/esm/api/transport/RNBleApduSender.js +1 -1
- package/lib/esm/api/transport/RNBleApduSender.js.map +2 -2
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/api/transport/RNBleTransport.test.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.test.js.map +3 -3
- package/lib/esm/package.json +2 -2
- package/lib/types/api/model/Errors.d.ts +5 -0
- package/lib/types/api/model/Errors.d.ts.map +1 -1
- package/lib/types/api/permissions/AndroidPermissionsService.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -1
- package/lib/types/api/transport/RNBleTransport.d.ts +15 -3
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +6 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var s=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var c=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},i=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of l(e))!u.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=a(e,t))||d.enumerable});return o};var p=o=>i(s({},"__esModule",{value:!0}),o);var D={};c(D,{BleDeviceGattServerError:()=>x,BleNotSupported:()=>
|
|
1
|
+
"use strict";var s=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var c=(o,e)=>{for(var r in e)s(o,r,{get:e[r],enumerable:!0})},i=(o,e,r,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of l(e))!u.call(o,t)&&t!==r&&s(o,t,{get:()=>e[t],enumerable:!(d=a(e,t))||d.enumerable});return o};var p=o=>i(s({},"__esModule",{value:!0}),o);var D={};c(D,{BleDeviceGattServerError:()=>x,BleNotSupported:()=>k,BlePermissionsNotGranted:()=>E,BlePoweredOff:()=>w,BleTransportNotSupportedError:()=>v,DeviceConnectionNotFound:()=>y,InternalDeviceNotFound:()=>g,NoDeviceModelFoundError:()=>B,PairingRefusedError:()=>N,PeerRemovedPairingError:()=>P,UnknownBleError:()=>_});module.exports=p(D);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 w extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BlePoweredOff"}class k extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleNotSupported"}class E extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BlePermissionsNotGranted"}class B extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="NoDeviceModelFoundError"}class N extends n.OpeningConnectionError{constructor(r){super(r);this.err=r}_tag="PairingRefusedError"}class _ extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="UnknownBleError"}class P extends n.OpeningConnectionError{constructor(r){super(r);this.err=r}_tag="PeerRemovedPairingError"}0&&(module.exports={BleDeviceGattServerError,BleNotSupported,BlePermissionsNotGranted,BlePoweredOff,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 {\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 BlePermissionsNotGranted extends GeneralDmkError {\n override readonly _tag = \"BlePermissionsNotGranted\";\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,6BAAAC,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,oBAAAC,IAAA,eAAAC,
|
|
6
|
-
"names": ["Errors_exports", "__export", "BleDeviceGattServerError", "BleNotSupported", "BlePermissionsNotGranted", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "NoDeviceModelFoundError", "PairingRefusedError", "PeerRemovedPairingError", "UnknownBleError", "__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 BlePoweredOff extends GeneralDmkError {\n override readonly _tag = \"BlePoweredOff\";\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 BlePermissionsNotGranted extends GeneralDmkError {\n override readonly _tag = \"BlePermissionsNotGranted\";\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,6BAAAC,EAAA,kBAAAC,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAb,GAAA,IAAAc,EAGO,2CAEA,MAAMR,UAAsC,iBAAgB,CAEjE,YAAqBS,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,+BAI3B,CACO,MAAMb,UAAiC,iBAAgB,CAE5D,YAAqBa,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,UAAsB,iBAAgB,CAEjD,YAAqBU,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,eAI3B,CAEO,MAAMZ,UAAwB,iBAAgB,CAEnD,YAAqBY,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,iBAI3B,CAEO,MAAMX,UAAiC,iBAAgB,CAE5D,YAAqBW,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,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", "BlePermissionsNotGranted", "BlePoweredOff", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "NoDeviceModelFoundError", "PairingRefusedError", "PeerRemovedPairingError", "UnknownBleError", "__toCommonJS", "import_device_management_kit", "err"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var n=Object.defineProperty;var t=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var n=Object.defineProperty;var t=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var a=(i,s)=>{for(var r in s)n(i,r,{get:s[r],enumerable:!0})},l=(i,s,r,o)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of m(s))!d.call(i,e)&&e!==r&&n(i,e,{get:()=>s[e],enumerable:!(o=t(s,e))||o.enumerable});return i};var P=i=>l(n({},"__esModule",{value:!0}),i);var S={};a(S,{AndroidPermissionsService:()=>p});module.exports=P(S);class p{constructor(s,r){this._permissionsAndroid=s;this._apiLevel=r}getRequiredPermissions(){return this._apiLevel<=28?[this._permissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION]:this._apiLevel<=30?[this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]:[this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT]}async checkRequiredPermissions(){const s=this.getRequiredPermissions();return(await Promise.all(s.map(e=>this._permissionsAndroid.check(e)))).every(e=>e)}async requestRequiredPermissions(){const s=this.getRequiredPermissions(),r=await this._permissionsAndroid.requestMultiple(s);return Object.values(r).every(e=>e===this._permissionsAndroid.RESULTS.GRANTED)}}0&&(module.exports={AndroidPermissionsService});
|
|
2
2
|
//# sourceMappingURL=AndroidPermissionsService.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/permissions/AndroidPermissionsService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Permission } from \"react-native\";\n\nimport type { PermissionsAndroidNarrowedType } from \"./PermissionsAndroidNarrowedType\";\nimport { type PermissionsService } from \"./PermissionsService\";\n\nexport class AndroidPermissionsService implements PermissionsService {\n constructor(\n private readonly _permissionsAndroid: PermissionsAndroidNarrowedType,\n private readonly _apiLevel: number,\n ) {}\n\n getRequiredPermissions(): Permission[] {\n if (this._apiLevel <= 28) {\n return [this._permissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION];\n }\n\n if (this._apiLevel <= 30) {\n return [this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION];\n }\n\n return [\n this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,\n this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,\n ];\n }\n\n async checkRequiredPermissions(): Promise<boolean> {\n const allPermissions = this.getRequiredPermissions();\n\n
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,EAAAH,GAKO,MAAME,CAAwD,CACnE,YACmBE,EACAC,EACjB,CAFiB,yBAAAD,EACA,eAAAC,CAChB,CAEH,wBAAuC,CACrC,OAAI,KAAK,WAAa,GACb,CAAC,KAAK,oBAAoB,YAAY,sBAAsB,EAGjE,KAAK,WAAa,GACb,CAAC,KAAK,oBAAoB,YAAY,oBAAoB,EAG5D,CACL,KAAK,oBAAoB,YAAY,eACrC,KAAK,oBAAoB,YAAY,iBACvC,CACF,CAEA,MAAM,0BAA6C,CACjD,MAAMC,EAAiB,KAAK,uBAAuB,
|
|
6
|
-
"names": ["AndroidPermissionsService_exports", "__export", "AndroidPermissionsService", "__toCommonJS", "_permissionsAndroid", "_apiLevel", "allPermissions", "
|
|
4
|
+
"sourcesContent": ["import type { Permission } from \"react-native\";\n\nimport type { PermissionsAndroidNarrowedType } from \"./PermissionsAndroidNarrowedType\";\nimport { type PermissionsService } from \"./PermissionsService\";\n\nexport class AndroidPermissionsService implements PermissionsService {\n constructor(\n private readonly _permissionsAndroid: PermissionsAndroidNarrowedType,\n private readonly _apiLevel: number,\n ) {}\n\n getRequiredPermissions(): Permission[] {\n if (this._apiLevel <= 28) {\n return [this._permissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION];\n }\n\n if (this._apiLevel <= 30) {\n return [this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION];\n }\n\n return [\n this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,\n this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,\n ];\n }\n\n async checkRequiredPermissions(): Promise<boolean> {\n const allPermissions = this.getRequiredPermissions();\n\n const allPermissionsCheckResults = await Promise.all(\n allPermissions.map((permission) =>\n this._permissionsAndroid.check(permission),\n ),\n );\n\n const allPermissionsGranted = allPermissionsCheckResults.every(\n (granted) => granted,\n );\n\n return allPermissionsGranted;\n }\n\n async requestRequiredPermissions(): Promise<boolean> {\n const allPermissions = this.getRequiredPermissions();\n\n const allPermissionsRequestResults =\n await this._permissionsAndroid.requestMultiple(allPermissions);\n\n const allPermissionsGrantedAfterRequest = Object.values(\n allPermissionsRequestResults,\n ).every(\n (requested) => requested === this._permissionsAndroid.RESULTS.GRANTED,\n );\n\n return allPermissionsGrantedAfterRequest;\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,EAAAH,GAKO,MAAME,CAAwD,CACnE,YACmBE,EACAC,EACjB,CAFiB,yBAAAD,EACA,eAAAC,CAChB,CAEH,wBAAuC,CACrC,OAAI,KAAK,WAAa,GACb,CAAC,KAAK,oBAAoB,YAAY,sBAAsB,EAGjE,KAAK,WAAa,GACb,CAAC,KAAK,oBAAoB,YAAY,oBAAoB,EAG5D,CACL,KAAK,oBAAoB,YAAY,eACrC,KAAK,oBAAoB,YAAY,iBACvC,CACF,CAEA,MAAM,0BAA6C,CACjD,MAAMC,EAAiB,KAAK,uBAAuB,EAYnD,OAVmC,MAAM,QAAQ,IAC/CA,EAAe,IAAKC,GAClB,KAAK,oBAAoB,MAAMA,CAAU,CAC3C,CACF,GAEyD,MACtDC,GAAYA,CACf,CAGF,CAEA,MAAM,4BAA+C,CACnD,MAAMF,EAAiB,KAAK,uBAAuB,EAE7CG,EACJ,MAAM,KAAK,oBAAoB,gBAAgBH,CAAc,EAQ/D,OAN0C,OAAO,OAC/CG,CACF,EAAE,MACCC,GAAcA,IAAc,KAAK,oBAAoB,QAAQ,OAChE,CAGF,CACF",
|
|
6
|
+
"names": ["AndroidPermissionsService_exports", "__export", "AndroidPermissionsService", "__toCommonJS", "_permissionsAndroid", "_apiLevel", "allPermissions", "permission", "granted", "allPermissionsRequestResults", "requested"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var y=(o,e)=>{for(var t in e)v(o,t,{get:e[t],enumerable:!0})},R=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!_.call(o,r)&&r!==t&&v(o,r,{get:()=>e[r],enumerable:!(n=m(e,r))||n.enumerable});return o};var S=o=>R(v({},"__esModule",{value:!0}),o);var D={};y(D,{RNBleApduSender:()=>g});module.exports=S(D);var u=require("@ledgerhq/device-management-kit"),p=require("js-base64"),s=require("purify-ts"),l=require("rxjs"),d=require("../model/Errors");const A=3;class g{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;_writeCharacteristic;_characteristicSubscription=void 0;constructor({apduSenderFactory:e,apduReceiverFactory:t,dependencies:n},r){this._dependencies=n,this._isDeviceReady=new l.BehaviorSubject(!1),this._logger=r("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,[r]=t.slice(5);let i=n.mtu-A;r&&r!==i&&(i=r),this._apduSender=s.Maybe.of(this._apduSenderFactory({frameSize:i})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(n=>{n.map(r=>{this._sendApduPromiseResolver.map(i=>i((0,s.Right)(r)))})}).mapLeft(n=>{this._sendApduPromiseResolver.map(r=>r((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,(i,a)=>{if(i?.message.includes("notify change failed")){this._isDeviceReady.error(new d.PairingRefusedError(i)),this._logger.error("Pairing failed",{data:{error:i}});return}else i&&(this._isDeviceReady.error(new d.UnknownBleError(i)),this._logger.error("Error monitoring characteristic",{data:{error:i}}));!i&&a&&this.onMonitor(a)});const e=await this._dependencies.manager.characteristicsForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid);let t=e.find(i=>i.uuid===this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid);if(t)this._writeCharacteristic=t;else if(t=e.find(i=>i.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(i=>{throw this._logger.error("Pairing failed",{data:{error:i}}),new d.PairingRefusedError(i)});let r;await new Promise((i,a)=>{r&&r.unsubscribe(),r=this._isDeviceReady.subscribe({next:c=>{c&&i()},error:c=>{a(c)}})})}async sendApdu(e,t,n){if(!this._isDeviceReady.value)return Promise.resolve((0,s.Left)(new u.DeviceNotInitializedError("Unknown MTU")));let r;const i=new Promise(c=>{this._sendApduPromiseResolver=s.Maybe.of((...h)=>(r&&clearTimeout(r),c(...h)))}),a=this._apduSender.caseOf({Just:c=>c.getFrames(e),Nothing:()=>[]});for(const c of a)try{await this.write(p.Base64.fromUint8Array(c.getRawData()))}catch(h){this._logger.info("Error sending frame",{data:{error:h}})}return n&&(r=setTimeout(()=>{this._logger.debug("[sendApdu] Abort timeout triggered"),this._sendApduPromiseResolver.map(c=>c((0,s.Left)(new u.SendApduTimeoutError("Abort timeout"))))},n)),i}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 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.
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD,gBAEnDC,EAAqD,6BAErD,MAAMC,EAAoB,EAmBnB,MAAMP,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAQ,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,KAAK,QAAUC,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAc,UACnB,KAAK,cAAgBC,EAAoB,EACzC,KAAK,yBAA2B,SAClC,CAEQ,2BAA2BG,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMP,EACzBQ,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAc,QAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAC,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACV,KAAK,cAAc,YAAYA,CAAI,EAG1D,IAAKC,GAAa,CACjBA,EAAS,IAAKC,GAAiB,CAC7B,KAAK,
|
|
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._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 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,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD,gBAEnDC,EAAqD,6BAErD,MAAMC,EAAoB,EAmBnB,MAAMP,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIA,qBACA,4BAEQ,OAEhB,YACE,CACE,kBAAAQ,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,KAAK,QAAUC,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAc,UACnB,KAAK,cAAgBC,EAAoB,EACzC,KAAK,yBAA2B,SAClC,CAEQ,2BAA2BG,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,I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I,4BAA0B,aAAa,CAAC,CACnD,EAGF,IAAIC,EAEJ,MAAMC,EAAgB,IAAI,QACvBZ,GAAY,CACX,KAAK,yBAA2B,QAAM,GAAG,IAAIa,KACvCF,GACF,aAAaA,CAAO,EAEfX,EAAQ,GAAGa,CAAI,EACvB,CACH,CACF,EAEMC,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUlB,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWmB,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM,SAAO,eAAeE,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASf,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,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
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
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var y=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var w=(g,e)=>{for(var n in e)y(g,n,{get:e[n],enumerable:!0})},B=(g,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of T(e))!C.call(g,t)&&t!==n&&y(g,t,{get:()=>e[t],enumerable:!(i=I(e,t))||i.enumerable});return g};var R=g=>B(y({},"__esModule",{value:!0}),g);var A={};w(A,{RNBleTransport:()=>E,rnBleTransportIdentifier:()=>M});module.exports=R(A);var m=require("react-native"),S=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),r=require("purify-ts"),c=require("rxjs"),h=require("../model/Const"),u=require("../model/Errors"),f=require("../transport/RNBleApduSender");const M="RN_BLE";class E{constructor(e,n,i,t,a,v,o,d=l=>new p.DeviceConnectionStateMachine(l),D=(l,_)=>new f.RNBleApduSender(l,_)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=a;this._platform=v;this._permissionsService=o;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=D;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=r.Maybe.zero(),this._manager.onStateChange(l=>{this._logger.debug("[manager.onStateChange]",{data:{state:l}}),this._bleStateSubject.next(l)},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new c.BehaviorSubject(S.State.Unknown);startDiscovering(){return(0,c.from)([])}async stopDiscovering(){await this._stopScanning()}_maybeScanningSubject=r.Nothing;_scannedDevicesSubject=new c.BehaviorSubject([]);_startedScanningSubscriber=void 0;_startScanning(){this._startedScanningSubscriber==null&&(this._scannedDevicesSubject.next([]),this._startedScanningSubscriber=(0,c.from)(this._bleStateSubject).pipe((0,c.tap)(()=>{if(!this.isSupported())throw new u.BleNotSupported("BLE not supported")}),(0,c.filter)(e=>e==="PoweredOn"),(0,c.switchMap)(async()=>this.checkAndRequestPermissions()),(0,c.switchMap)(e=>{if(!e)return(0,c.throwError)(()=>new u.BlePermissionsNotGranted("Permissions not granted"));const n=new c.BehaviorSubject([]);this._maybeScanningSubject=r.Maybe.of(n);const i=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(a,v)=>{if(a||!v){n.error(a||new Error("scan error"));return}i.set(v.id,{device:v,timestamp:Date.now()}),n.next(Array.from(i.values()))}),this._logger.debug("[startScanning] after startDeviceScan");const t=setInterval(()=>{n.next(Array.from(i.values()))},1e3);return n.asObservable().pipe((0,c.finalize)(()=>{this._logger.debug("[RNBleTransport][startScanning] finalize"),n.complete(),clearInterval(t),this._maybeScanningSubject=r.Nothing,this._manager.stopDeviceScan()}))}),(0,c.throttleTime)(1e3)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.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,c.switchMap)(async e=>{const n=e.filter(({timestamp:o})=>o>Date.now()-h.CONNECTION_LOST_DELAY).sort((o,d)=>(d.device.rssi??-1/0)-(o.device.rssi??-1/0)).map(({device:o})=>this._mapDeviceToTransportDiscoveredDevice(o,o.serviceUUIDs)).filter(o=>!!o),i=r.Either.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()),a=await Promise.all(t.map(async o=>{try{const D=(await o.services()).map(l=>l.uuid);return this._mapDeviceToTransportDiscoveredDevice(o,D)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,r.Left)(new u.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=r.Either.rights(a);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(o=>o.name),connectedDevices:v.map(o=>o.name),scannedDevices:i.map(o=>o.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return(0,r.Right)(i)}return(0,r.Left)(new u.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies().internalDevice.bleDeviceInfos.deviceModel;return(0,r.Right)(new p.TransportConnectedDevice({id:e.deviceId,deviceModel:i,type:"BLE",sendApdu:(...t)=>n.sendApdu(...t),transport:this.identifier}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,r.EitherAsync)(async({throwE:i})=>{let t,a=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:h.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),a=(await t.services()).map(s=>s.uuid)}catch(s){return s instanceof S.BleError&&s.iosErrorCode===14?i(new u.PeerRemovedPairingError(s)):i(new p.OpeningConnectionError(s))}const v=this._listenToDeviceDisconnected(e.deviceId),o=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>s,Left:s=>i(new p.OpeningConnectionError(s))}),d=o.deviceModel,D={id:t.id,bleDeviceInfos:o},l=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:D,manager:this._manager}},this._loggerServiceFactory),_=m.Platform.OS==="ios"?h.BLE_DISCONNECT_TIMEOUT_IOS:h.BLE_DISCONNECT_TIMEOUT_ANDROID,b=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:l,timeoutDuration:_,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(s){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:s}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(s=>{s.unsubscribe(),this._reconnectionSubscription=r.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await l.setupConnection().catch(s=>{throw this._safeCancel(e.deviceId),v.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 n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new p.UnknownDeviceError(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve((0,r.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;r.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,c.defer)(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const a=await this._manager.connectToDevice(e,{requestMTU:h.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const v=await a.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(a){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:a}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),a}}).pipe((0,c.retry)(5));this._reconnectionSubscription=r.Maybe.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=r.Maybe.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=r.Maybe.zero()}}))}async _handleDeviceReconnected(e){const n=r.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new u.DeviceConnectionNotFound);return(0,r.EitherAsync)(async({liftEither:i,throwE:t})=>{const a=await i(n),v=(await e.services()).map(d=>d.uuid),o=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});a.setDependencies({device:e,manager:this._manager,internalDevice:o}),await a.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),a.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}0&&(module.exports={RNBleTransport,rnBleTransportIdentifier});
|
|
1
|
+
"use strict";var b=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var T=(D,e)=>{for(var n in e)b(D,n,{get:e[n],enumerable:!0})},B=(D,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of w(e))!C.call(D,t)&&t!==n&&b(D,t,{get:()=>e[t],enumerable:!(i=I(e,t))||i.enumerable});return D};var R=D=>B(b({},"__esModule",{value:!0}),D);var N={};T(N,{RNBleTransport:()=>E,rnBleTransportIdentifier:()=>M});module.exports=R(N);var m=require("react-native"),u=require("react-native-ble-plx"),g=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),r=require("rxjs"),p=require("../model/Const"),l=require("../model/Errors"),y=require("../transport/RNBleApduSender");const M="RN_BLE";class E{constructor(e,n,i,t,s,v,c,d=1e3,f=h=>new g.DeviceConnectionStateMachine(h),_=(h,S)=>new y.RNBleApduSender(h,S)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=s;this._platform=v;this._permissionsService=c;this._scanThrottleDelayMs=d;this._deviceConnectionStateMachineFactory=f;this._deviceApduSenderFactory=_;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=a.Maybe.zero();let h=!1;this._manager.onStateChange(S=>{this._logger.debug(`[manager.onStateChange] called with state: ${S}`),this._bleStateSubject.next(S),h=S===u.State.Unknown,h&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(o=>{h&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${o}"`),this._bleStateSubject.next(o))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new r.BehaviorSubject(u.State.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return(0,r.from)([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new r.BehaviorSubject([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return(0,r.from)([!0]).pipe((0,r.tap)(()=>{if(!this.isSupported())throw new l.BleNotSupported("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),(0,r.switchMap)(async()=>this.checkAndRequestPermissions()),(0,r.tap)(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new l.BlePermissionsNotGranted("Permissions not granted")}),(0,r.switchMap)(()=>this.observeBleState()),(0,r.first)(e=>{const n=e===u.State.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.State.PoweredOff)throw new l.BlePoweredOff;if(e===u.State.Unauthorized)throw new l.BlePermissionsNotGranted('Ble State is "Unauthorized"');if(e===u.State.Unsupported)throw new l.BleNotSupported;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=(0,r.from)([!0]).pipe((0,r.switchMap)(()=>{const e=new r.BehaviorSubject([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,s)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:s}}),e.error(t);return}if(!s){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:s}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(s.id,{device:s,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe((0,r.finalize)(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),(0,r.throttleTime)(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new r.BehaviorSubject([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe((0,r.tap)(()=>this._startScanning()),(0,r.switchMap)(()=>this._scannedDevicesSubject),(0,r.switchMap)(async e=>{const n=e.filter(({timestamp:c})=>c>Date.now()-p.CONNECTION_LOST_DELAY).sort((c,d)=>(d.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),i=a.Either.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(c=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:c}}),c}),s=await Promise.all(t.map(async c=>{try{const f=(await c.services()).map(_=>_.uuid);return this._mapDeviceToTransportDiscoveredDevice(c,f)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,a.Left)(new l.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=a.Either.rights(s);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(c=>c.name),connectedDevices:v.map(c=>c.name),scannedDevices:i.map(c=>c.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return(0,a.Right)(i)}return(0,a.Left)(new l.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,s=i.device.localName||i.device.name||void 0;return(0,a.Right)(new g.TransportConnectedDevice({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...v)=>n.sendApdu(...v),transport:this.identifier,name:s}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,a.EitherAsync)(async({throwE:i})=>{let t,s=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),s=(await t.services()).map(o=>o.uuid)}catch(o){return o instanceof u.BleError&&o.iosErrorCode===14?i(new l.PeerRemovedPairingError(o)):o instanceof u.BleError&&o.errorCode===u.BleErrorCode.OperationCancelled&&m.Platform.OS==="android"?i(new l.PeerRemovedPairingError(o)):i(new g.OpeningConnectionError(o))}const v=this._listenToDeviceDisconnected(e.deviceId),c=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:o=>o,Left:o=>i(new g.OpeningConnectionError(o))}),d=c.deviceModel,f={id:t.id,bleDeviceInfos:c},_=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),h=m.Platform.OS==="ios"?p.BLE_DISCONNECT_TIMEOUT_IOS:p.BLE_DISCONNECT_TIMEOUT_ANDROID,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:_,timeoutDuration:h,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=a.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await _.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),v.remove(),o}),this._deviceConnectionsById.set(e.deviceId,S),new g.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...o)=>S.sendApdu(...o),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new g.UnknownDeviceError(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve((0,a.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;a.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,r.defer)(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const s=await this._manager.connectToDevice(e,{requestMTU:p.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const v=await s.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(s){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:s}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),s}}).pipe((0,r.retry)(5));this._reconnectionSubscription=a.Maybe.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=a.Maybe.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=a.Maybe.zero()}}))}async _handleDeviceReconnected(e){const n=a.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new l.DeviceConnectionNotFound);return(0,a.EitherAsync)(async({liftEither:i,throwE:t})=>{const s=await i(n),v=(await e.services()).map(d=>d.uuid),c=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});s.setDependencies({device:e,manager:this._manager,internalDevice:c}),await s.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),s.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}0&&(module.exports={RNBleTransport,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 { Platform } from \"react-native\";\nimport {\n BleError,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n filter,\n finalize,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\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 BlePermissionsNotGranted,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n this._manager.onStateChange((state) => {\n this._logger.debug(\"[manager.onStateChange]\", { data: { 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 tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n }),\n filter((state) => state === \"PoweredOn\"),\n switchMap(async () => this.checkAndRequestPermissions()),\n switchMap((hasPermissions) => {\n if (!hasPermissions) {\n return throwError(\n () => new BlePermissionsNotGranted(\"Permissions not granted\"),\n );\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(\"[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 this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.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._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"Error while scanning\", { data: { error } });\n this._scannedDevicesSubject.error(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 switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const deviceModel =\n existing.getDependencies().internalDevice.bleDeviceInfos.deviceModel;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAMO,gCACPC,EAmBO,2CACPC,EAAiE,qBACjEC,EAaO,gBAEPC,EAKO,4BACPC,EAMO,6BAEPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMD,CAAoC,CAY/C,YACmBW,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,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,uBAAyB,IAAI,IAClC,KAAK,0BAA4B,QAAM,KAAK,EAC5C,KAAK,SAAS,cAAeU,GAAU,CACrC,KAAK,QAAQ,MAAM,0BAA2B,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,EACjE,KAAK,iBAAiB,KAAKA,CAAK,CAClC,EAAG,EAAI,CACT,CAtCQ,QACA,uBAKS,WAAkC,SAC3C,0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yBAAyBxB,EAAgB,CACrD,MAAM8B,EAA0B,QAAM,aACpC,KAAK,uBAAuB,IAAI9B,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAI,0BAA0B,EAEzC,SAAO,eAAY,MAAO,CAAE,WAAA+B,EAAY,OAAAf,CAAO,IAAM,CACnD,MAAMM,EAA+B,MAAMS,EACzCD,CACF,EAEMzB,GAAiB,MAAML,EAAO,SAAS,GAAG,IAAKM,GAAMA,EAAE,IAAI,EAE3Da,EAAiB,KAAK,uCAC1Bd,CACF,EAAE,OAAO,CACP,MAAQM,IACC,CACL,GAAIX,EAAO,GACX,eAAgBW,CAClB,GAEF,KAAOpB,IACL,KAAK,QAAQ,MACX,sFACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEOyB,EAAOzB,CAAK,EAEvB,CAAC,EAED+B,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAOf,GAAM,CAChE,WAAK,YAAYP,EAAO,EAAE,EACpBO,CACR,CAAC,EAEDe,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMhB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWR,KAAUQ,EACnB,GAAIR,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAASjB,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
-
"names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "state", "hasPermissions", "subject", "devicesById", "error", "rnDevice", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "
|
|
4
|
+
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\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 name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n name: device.localName || device.name || undefined,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAOO,gCACPC,EAmBO,2CACPC,EAAwD,qBACxDC,EAYO,gBAEPC,EAKO,4BACPC,EAOO,6BAEPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMD,CAAoC,CAY/C,YACmBW,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EAAsB,yBAAyB,EAC9D,KAA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,SAAS,wBAA2B,WAAY,CAC9D,MAAMlB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAShC,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
+
"names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "dependencies", "deviceModel", "deviceName", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var M=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),b=require("purify-ts"),w=require("rxjs"),i=require("vitest"),P=require("../model/Errors"),B=require("../permissions/DefaultPermissionsService"),R=require("./RNBleTransport"),T=require("./RNBleTransportFactory");const N={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const I=new p.TransportDeviceModel({id:p.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),D={OS:"ios"},O={OS:"android"},F={OS:"windows"};class l{deviceModelDataSource=h();loggerServiceFactory=()=>N;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new M.BleManager;platform=D;permissionsService=new B.DefaultPermissionsService;deviceConnectionStateMachineFactory;deviceApduSenderFactory;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}build(){return new R.RNBleTransport(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function h(){const f=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new p.BleDeviceInfos(I,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:f,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function y(f={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...f}}function k(f={}){return{onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),...f}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const f={deviceModelDataSource:h(),loggerServiceFactory:()=>N,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=(0,T.RNBleTransportFactory)(f);(0,i.expect)(e).toBeInstanceOf(R.RNBleTransport)})});describe("RNBleTransport",()=>{let f;(0,i.beforeEach)(()=>{vi.clearAllMocks()}),afterEach(()=>{f&&f.unsubscribe()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new l().build().getIdentifier();(0,i.expect)(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new l().withPlatform(D).build().isSupported();(0,i.expect)(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new l().withPlatform(O).build().isSupported();(0,i.expect)(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new l().withPlatform(F).build().isSupported();(0,i.expect)(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{f=new l().withPlatform(D).withDeviceModelDataSource(h()).build().startDiscovering().subscribe({next:r=>{try{(0,i.expect)(r).toStrictEqual([])}catch(a){n(a)}},error:r=>{throw n(r),r},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=k({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new l().withBleManager(n).withPlatform(D).withDeviceModelDataSource(h()).build().stopDiscovering(),(0,i.expect)(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new l().withBleManager(k()).withPlatform(F).build();return new Promise((n,c)=>{e.listenToAvailableDevices().subscribe({next:()=>{c(new Error("Should not emit any value"))},error:v=>{try{(0,i.expect)(v).toBeInstanceOf(P.BleNotSupported)}catch(r){c(r)}n(void 0)},complete:()=>{c(new Error("Should not complete"))}})})}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),c={checkRequiredPermissions:e,requestRequiredPermissions:n},v=vi.fn(),r=k({startDeviceScan:v,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:a=>(a(M.State.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,o)=>{d.subscribe({next:()=>{try{(0,i.expect)(e).toHaveBeenCalled()}catch(t){o(t)}s(void 0)},error:t=>{o(t)}})})}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,o)=>{d.subscribe({next:()=>{try{(0,i.expect)(v).toHaveBeenCalled()}catch(t){o(t)}s(void 0)},error:t=>{o(t)}})})}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,o)=>{d.subscribe({next:()=>{try{(0,i.expect)(n).toHaveBeenCalled()}catch(t){o(t)}s(void 0)},complete:()=>{o(new Error("Should not complete"))},error:t=>{o(t)}})})}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();let s=0;return new Promise((o,t)=>{d.subscribe({next:()=>{if(s++,s>1){try{(0,i.expect)(v).toHaveBeenCalled()}catch(u){t(u)}o(void 0)}}})})}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const d=new l().withBleManager(r).withPlatform(D).withPermissionsService(c).build().listenToAvailableDevices();return new Promise((s,o)=>{d.subscribe({error:t=>{try{(0,i.expect)(t).toBeInstanceOf(P.BlePermissionsNotGranted)}catch(u){o(u)}s(void 0)},complete:()=>{o(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let c=null;const v=y({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),r=vi.fn().mockImplementation((t,u,S)=>{c=setInterval(()=>{S(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),S(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),a=vi.fn().mockImplementation(()=>{c&&(clearInterval(c),c=null)}),d=k({connectedDevices:vi.fn().mockResolvedValue([v]),startDeviceScan:r,stopDeviceScan:a,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:t=>(t(M.State.PoweredOn),{remove:vi.fn()})}),s=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(h()).build(),o=[];f=s.listenToAvailableDevices().subscribe({next:t=>{if(o.push(t),o.length===2)try{(0,i.expect)(o).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:I,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(u){n(u)}}})}))}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=k({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=await new l().withBleManager(e).withPlatform(D).withDeviceModelDataSource(h()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});(0,i.expect)(v).toEqual((0,b.Left)(new p.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{let e=null;const n=y({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((S,g,C)=>{e=setInterval(()=>{C(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),C(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=k({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:S=>(S(M.State.PoweredOn),{remove:vi.fn()})}),a=vi.fn().mockResolvedValue(void 0),d=vi.fn().mockReturnValue({sendApdu:vi.fn()}),s=vi.fn().mockReturnValue({setupConnection:a}),o=new l().withBleManager(r).withPlatform(D).withDeviceModelDataSource(h()).withDeviceConnectionStateMachineFactory(d).withDeviceApduSenderFactory(s).build(),[t]=await(0,w.lastValueFrom)(o.listenToAvailableDevices().pipe((0,w.take)(3))),u=await o.connect({deviceId:t.id,onDisconnect:vi.fn()});(0,i.expect)(u.isRight()).toBe(!0),(0,i.expect)(r.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,i.expect)(r.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,i.expect)(a).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{let e=null;const n=y({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((g,C,m)=>{e=setInterval(()=>{m(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=k({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:g=>(g(M.State.PoweredOn),{remove:vi.fn()})}),a=vi.fn(),d=vi.fn().mockReturnValue({sendApdu:a}),s=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),o=new l().withBleManager(r).withPlatform(D).withDeviceModelDataSource(h()).withDeviceConnectionStateMachineFactory(d).withDeviceApduSenderFactory(s).build(),[t]=await(0,w.lastValueFrom)(o.listenToAvailableDevices().pipe((0,w.take)(3))),u=await o.connect({deviceId:t.id,onDisconnect:vi.fn()});u.extract().sendApdu(Uint8Array.from([67,50])),(0,i.expect)(u).toEqual((0,b.Right)(new p.TransportConnectedDevice({id:"deviceId",deviceModel:I,type:"BLE",transport:"RN_BLE",sendApdu:i.expect.any(Function)}))),(0,i.expect)(a).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{let e=null;const n=y({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((m,V,A)=>{e=setInterval(()=>{A(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=vi.fn().mockImplementation(()=>({remove:vi.fn()})),a=vi.fn(),d=k({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:m=>(m(M.State.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:r,isDeviceConnected:vi.fn()}),s=m=>new p.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated,tryToReconnect:m.tryToReconnect}),o=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:a}),t=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(h()).withDeviceConnectionStateMachineFactory(s).withDeviceApduSenderFactory(o).build(),u=vi.fn(),[S]=await(0,w.lastValueFrom)(t.listenToAvailableDevices().pipe((0,w.take)(3))),g=await t.connect({deviceId:S.id,onDisconnect:u}),C=await t.disconnect({connectedDevice:g.extract()});(0,i.expect)(C).toEqual((0,b.Right)(void 0)),(0,i.expect)(u).toHaveBeenCalled(),(0,i.expect)(a).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{let e=null;const n=y({id:"deviceId",localName:"name"}),c=vi.fn().mockImplementation((m,V,A)=>{e=setInterval(()=>{A(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},100)}),v=vi.fn().mockImplementation(()=>{e&&(clearInterval(e),e=null)}),r=vi.fn().mockImplementation(()=>({remove:vi.fn()})),a=vi.fn(),d=k({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:c,stopDeviceScan:v,connectToDevice:vi.fn().mockResolvedValueOnce(n),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(n),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:r,isDeviceConnected:vi.fn(),onStateChange:m=>(m(M.State.PoweredOn),{remove:vi.fn()})}),s=m=>new p.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:m.deviceApduSender,timeoutDuration:1e3,onTerminated:m.onTerminated,tryToReconnect:m.tryToReconnect}),o=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:a}),t=new l().withBleManager(d).withPlatform(D).withDeviceModelDataSource(h()).withDeviceConnectionStateMachineFactory(s).withDeviceApduSenderFactory(o).build(),u=vi.fn(),[S]=await(0,w.lastValueFrom)(t.listenToAvailableDevices().pipe((0,w.take)(3))),g=await t.connect({deviceId:S.id,onDisconnect:u}),C=await t.disconnect({connectedDevice:g.extract()});(0,i.expect)(C).toEqual((0,b.Right)(void 0)),(0,i.expect)(u).toHaveBeenCalled()})})});
|
|
1
|
+
"use strict";var d=require("react-native-ble-plx"),S=require("@ledgerhq/device-management-kit"),P=require("purify-ts"),l=require("rxjs"),t=require("vitest"),k=require("../model/Errors"),T=require("../permissions/DefaultPermissionsService"),F=require("./RNBleTransport"),O=require("./RNBleTransportFactory");const E={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn(),subscribers:[]},V={error:console.error,info:console.info,warn:console.warn,debug:console.debug,subscribers:[]};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({Device:vi.fn(),State:{PoweredOn:"PoweredOn",Unknown:"Unknown",PoweredOff:"PoweredOff",Resetting:"Resetting",Unsupported:"Unsupported",Unauthorized:"Unauthorized"},BleError:vi.fn(),BleManager:vi.fn().mockReturnValue({onStateChange:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()})}));const C=new S.TransportDeviceModel({id:S.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744]}),h={OS:"ios"},U={OS:"android"},I={OS:"windows"};class s{deviceModelDataSource=g();loggerServiceFactory=()=>E;apduSenderServiceFactory=()=>{};apduReceiverServiceFactory=()=>{};bleManager=new d.BleManager;platform=h;permissionsService=new T.DefaultPermissionsService;deviceConnectionStateMachineFactory;deviceApduSenderFactory;scanThrottleDelayMs=1e3;withDeviceModelDataSource(e){return this.deviceModelDataSource=e,this}withPlatform(e){return this.platform=e,this}withPermissionsService(e){return this.permissionsService=e,this}withBleManager(e){return this.bleManager=e,this}withDeviceConnectionStateMachineFactory(e){return this.deviceConnectionStateMachineFactory=e,this}withDeviceApduSenderFactory(e){return this.deviceApduSenderFactory=e,this}withLogger(e=V){return this.loggerServiceFactory=()=>e,this}withScanThrottleDelayMs(e){return this.scanThrottleDelayMs=e,this}build(){return new F.RNBleTransport(this.deviceModelDataSource,this.loggerServiceFactory,this.apduSenderServiceFactory,this.apduReceiverServiceFactory,this.bleManager,this.platform,this.permissionsService,this.scanThrottleDelayMs,this.deviceConnectionStateMachineFactory,this.deviceApduSenderFactory)}}function g(){const p=vi.fn(()=>["ledgerId"]),e=vi.fn(()=>({ledgerId:new S.BleDeviceInfos(C,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")}));return{getBluetoothServices:p,getBluetoothServicesInfos:e,getAllDeviceModels:vi.fn(),getDeviceModel:vi.fn(),filterDeviceModels:vi.fn()}}function A(p={}){return{id:"deviceId",localName:"deviceName",serviceUUIDs:["ledgerId"],services:vi.fn().mockResolvedValue([{uuid:"ledgerId"}]),...p}}function f(p={},e=d.State.PoweredOn){return{onStateChange:vi.fn().mockImplementation((o,c)=>(c&&o(e),{remove:vi.fn()})),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),connectToDevice:vi.fn(),disconnectFromDevice:vi.fn(),cancelDeviceConnection:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),discoverAllServicesAndCharacteristicsForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),state:vi.fn(),...p}}describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const p={deviceModelDataSource:g(),loggerServiceFactory:()=>E,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}},e=(0,O.RNBleTransportFactory)(p);(0,t.expect)(e).toBeInstanceOf(F.RNBleTransport)})});describe("RNBleTransport",()=>{let p;(0,t.beforeEach)(()=>{vi.clearAllMocks(),vi.useRealTimers()}),afterEach(()=>{p&&p.unsubscribe()}),describe("BLE state monitoring",()=>{test("the constructor should call BleManager.onStateChange with a parameter requesting the initial state",()=>{const e=vi.fn();new s().withBleManager(f({onStateChange:e})).build(),(0,t.expect)(e).toHaveBeenCalledWith(t.expect.any(Function),!0)}),describe("observeBleState",()=>{it("should emit the initial BLE state",async()=>{const e=vi.fn().mockImplementation((i,r)=>(r&&i(d.State.PoweredOn),{remove:vi.fn()})),o=new s().withBleManager(f({onStateChange:e})).build().observeBleState(),c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOn)}),it("should emit the new BLE state values",async()=>{const e=new l.Subject,o=new s().withBleManager(f({onStateChange:r=>(r(d.State.PoweredOn),e.subscribe(a=>r(a)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff);const c=await(0,l.firstValueFrom)(o);(0,t.expect)(c).toBe(d.State.PoweredOff),e.next(d.State.Resetting);const i=await(0,l.firstValueFrom)(o);(0,t.expect)(i).toBe(d.State.Resetting)}),it("should recover from an Unknown state by calling BleManager.state() method and emitting the new state",async()=>{vi.useFakeTimers();const e=new l.Subject,n=vi.fn().mockImplementation(()=>new Promise(a=>{setTimeout(()=>{a(d.State.PoweredOn)},10)})),c=new s().withBleManager(f({state:n,onStateChange:a=>(e.subscribe(v=>a(v)),{remove:vi.fn()})})).build().observeBleState();e.next(d.State.PoweredOff),(0,t.expect)(n).not.toHaveBeenCalled(),e.next(d.State.Unknown);const i=await(0,l.firstValueFrom)(c);(0,t.expect)(i).toBe(d.State.Unknown),(0,t.expect)(n).toHaveBeenCalled(),vi.advanceTimersByTime(11),await Promise.resolve();const r=await(0,l.firstValueFrom)(c);(0,t.expect)(r).toBe(d.State.PoweredOn)})})}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const n=new s().build().getIdentifier();(0,t.expect)(n).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",()=>{const n=new s().withPlatform(h).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return true if platform is android",()=>{const n=new s().withPlatform(U).build().isSupported();(0,t.expect)(n).toBe(!0)}),it("should return false if platform is not android nor ios",()=>{const n=new s().withPlatform(I).build().isSupported();(0,t.expect)(n).toBe(!1)})}),describe("startDiscovering",()=>{it("should emit an empty array",()=>new Promise((e,n)=>{p=new s().withPlatform(h).withDeviceModelDataSource(g()).build().startDiscovering().subscribe({next:i=>{try{(0,t.expect)(i).toStrictEqual([])}catch(r){n(r)}},error:i=>{throw n(i),i},complete:()=>{e(void 0)}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const e=vi.fn(),n=f({stopDeviceScan:e,connectedDevices:vi.fn().mockResolvedValueOnce([])});new s().withBleManager(n).withPlatform(h).withDeviceModelDataSource(g()).build().stopDiscovering(),(0,t.expect)(e).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should emit an error if platform is not android nor ios",async()=>{const e=new s().withBleManager(f()).withPlatform(I).build();return new Promise((n,o)=>{e.listenToAvailableDevices().subscribe({error:c=>{try{(0,t.expect)(c).toBeInstanceOf(k.BleNotSupported)}catch(i){o(i)}n(void 0)},complete:()=>{o(new Error("Should not complete"))}})})}),it("should emit an error if BLE state is PoweredOff",async()=>{const n=new s().withBleManager(f({},d.State.PoweredOff)).build().listenToAvailableDevices();let o;await(0,l.firstValueFrom)(n).catch(c=>{o=c}),(0,t.expect)(o).toBeInstanceOf(k.BlePoweredOff)}),describe("permissions check",()=>{const e=vi.fn(),n=vi.fn(),o={checkRequiredPermissions:e,requestRequiredPermissions:n},c=vi.fn().mockImplementation(async()=>{}),i=f({startDeviceScan:c,stopDeviceScan:vi.fn(),connectedDevices:vi.fn().mockResolvedValue([]),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:r=>(r(d.State.PoweredOn),{remove:vi.fn()})});it("should call checkPermissions",async()=>{const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(e).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if checkPermissions resolves to true",async()=>{e.mockResolvedValue(!0);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(v=>{(0,t.expect)(v).toBeInstanceOf(k.BlePermissionsNotGranted)}),(0,t.expect)(c).toHaveBeenCalled()}),it("should call requestPermissions if checkPermissions resolves to false",async()=>{e.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();await(0,l.firstValueFrom)(a).catch(()=>{}),(0,t.expect)(n).toHaveBeenCalled()}),it("should call BleManager.startDeviceScan if requestPermissions resolves to true",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!0);const r=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build(),a=r.listenToAvailableDevices();await(0,l.firstValueFrom)(r.observeBleState()),await(0,l.firstValueFrom)(a),(0,t.expect)(c).toHaveBeenCalled()}),it("should emit an error if checkPermissions and requestPermissions resolve to false",async()=>{e.mockResolvedValue(!1),n.mockResolvedValue(!1);const a=new s().withBleManager(i).withPlatform(h).withPermissionsService(o).build().listenToAvailableDevices();return new Promise((v,u)=>{a.subscribe({error:m=>{try{(0,t.expect)(m).toBeInstanceOf(k.BlePermissionsNotGranted)}catch(w){u(w)}v(void 0)},complete:()=>{u(new Error("Should not complete"))}})})})}),it("should return already connected devices and scanned devices",()=>new Promise((e,n)=>{let o=null;const c=A({id:"aConnectedDeviceId",localName:"aConnectedDeviceName"}),i=vi.fn().mockImplementation(async(m,w,b)=>{o=setInterval(()=>{b(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})},10),b(null,{id:"aNonLedgerScannedDeviceId",localName:"aNonLedgerScannedDeviceName",serviceUUIDs:["notLedgerId"],rssi:2})}),r=vi.fn().mockImplementation(()=>{o&&(clearInterval(o),o=null)}),a=f({connectedDevices:vi.fn().mockResolvedValue([c]),startDeviceScan:i,stopDeviceScan:r,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:m=>(m(d.State.PoweredOn),{remove:vi.fn()})}),v=new s().withBleManager(a).withPlatform(h).withDeviceModelDataSource(g()).withScanThrottleDelayMs(1).build(),u=[];p=v.listenToAvailableDevices().subscribe({next:m=>{if(u.push(m),u.length===2)try{(0,t.expect)(u).toEqual([[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0}],[{id:"aConnectedDeviceId",name:"aConnectedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:void 0},{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}]]),e(void 0)}catch(w){n(w)}}})})),it("should propagate the error if startDeviceScan throws an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockRejectedValueOnce(e),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate the error if startDeviceScan emits an error",()=>{const e=new Error("startDeviceScan error"),n=vi.fn().mockImplementation(async(i,r,a)=>{a(e,{})}),c=new s().withBleManager(f({startDeviceScan:n})).build().listenToAvailableDevices();return new Promise((i,r)=>{c.subscribe({error:a=>{try{(0,t.expect)(a).toBe(e),i(void 0)}catch(v){r(v)}i(void 0)},complete:()=>r(new Error("Should not complete"))})})}),it("should propagate an error if startDeviceScan emits a null device",()=>{const e=vi.fn().mockImplementation(async(c,i,r)=>{r(null,null)}),o=new s().withBleManager(f({startDeviceScan:e})).build().listenToAvailableDevices();return new Promise((c,i)=>{o.subscribe({error:r=>{try{(0,t.expect)(r).toEqual(new Error("Null device in startDeviceScan callback")),c(void 0)}catch(a){i(a)}}})})}),it("should recover from a scanning error, allowing next calls of listenToAvailableDevices to succeed and emit the devices",async()=>{vi.useFakeTimers();const e=new Error("A Scan Error"),n=vi.fn().mockRejectedValueOnce(e),o=new s().withBleManager(f({startDeviceScan:n})).build(),c=o.listenToAvailableDevices();let i;await(0,l.firstValueFrom)(c).catch(v=>{i=v}),(0,t.expect)(i).toBe(e),n.mockImplementation(async(v,u,m)=>{m(null,{id:"aScannedDeviceId",localName:"aScannedDeviceName",serviceUUIDs:["ledgerId"],rssi:1})});const r=o.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const a=await(0,l.firstValueFrom)(r).catch(()=>{throw new Error("Caught error in second observable, this should not happen if listenToAvailableDevices recovers from the scanning error")});(0,t.expect)(a).toEqual([{id:"aScannedDeviceId",name:"aScannedDeviceName",deviceModel:C,transport:"RN_BLE",rssi:1}])})}),describe("connect",()=>{it("should throw an error if device id is unknown",async()=>{const e=f({connectedDevices:vi.fn().mockResolvedValue([]),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockRejectedValueOnce(new Error("discoverAllServicesAndCharacteristicsForDevice error"))}),n=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),c=await new s().withBleManager(e).withPlatform(h).withDeviceModelDataSource(g()).withDeviceApduSenderFactory(n).build().connect({deviceId:null,onDisconnect:vi.fn()});(0,t.expect)(c).toEqual((0,P.Left)(new S.OpeningConnectionError("discoverAllServicesAndCharacteristicsForDevice error")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(y,M,B)=>{B(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:y=>(y(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn().mockResolvedValue(void 0),r=vi.fn().mockReturnValue({sendApdu:vi.fn()}),a=vi.fn().mockReturnValue({setupConnection:i}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).withScanThrottleDelayMs(1).build(),u=v.listenToAvailableDevices(),m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});(0,t.expect)(b.isRight()).toBe(!0),(0,t.expect)(c.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,t.expect)(c.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,t.expect)(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(M,B,D)=>{D(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),onStateChange:M=>(M(d.State.PoweredOn),{remove:vi.fn()})}),i=vi.fn(),r=vi.fn().mockReturnValue({sendApdu:i}),a=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0)}),v=new s().withBleManager(c).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(r).withDeviceApduSenderFactory(a).build(),u=v.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const m=await(0,l.firstValueFrom)(u),[w]=m,b=await v.connect({deviceId:w.id,onDisconnect:vi.fn()});b.extract().sendApdu(Uint8Array.from([67,50])),(0,t.expect)(b).toEqual((0,P.Right)(new S.TransportConnectedDevice({id:"deviceId",deviceModel:C,type:"BLE",transport:"RN_BLE",sendApdu:t.expect.any(Function),name:"name"}))),(0,t.expect)(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{it("should disconnect gracefully",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()}),onDeviceDisconnected:c,isDeviceConnected:vi.fn()}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled(),(0,t.expect)(i).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{vi.useFakeTimers();const e=A({id:"deviceId",localName:"name"}),n=vi.fn().mockImplementation(async(D,N,R)=>{R(null,{id:"deviceId",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})}),o=vi.fn(),c=vi.fn().mockImplementation(()=>({remove:vi.fn()})),i=vi.fn(),r=f({connectedDevices:vi.fn().mockResolvedValue([]),startDeviceScan:n,stopDeviceScan:o,connectToDevice:vi.fn().mockResolvedValueOnce(e),discoverAllServicesAndCharacteristicsForDevice:vi.fn().mockResolvedValueOnce(e),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),onDeviceDisconnected:c,isDeviceConnected:vi.fn(),onStateChange:D=>(D(d.State.PoweredOn),{remove:vi.fn()})}),a=D=>new S.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:D.deviceApduSender,timeoutDuration:1e3,onTerminated:D.onTerminated,tryToReconnect:D.tryToReconnect}),v=vi.fn().mockReturnValue({setupConnection:vi.fn().mockResolvedValue(void 0),closeConnection:i}),u=new s().withBleManager(r).withPlatform(h).withDeviceModelDataSource(g()).withDeviceConnectionStateMachineFactory(a).withDeviceApduSenderFactory(v).build(),m=vi.fn(),w=u.listenToAvailableDevices();vi.advanceTimersByTime(2e3);const b=await(0,l.firstValueFrom)(w),[y]=b,M=await u.connect({deviceId:y.id,onDisconnect:m}),B=await u.disconnect({connectedDevice:M.extract()});(0,t.expect)(B).toEqual((0,P.Right)(void 0)),(0,t.expect)(m).toHaveBeenCalled()})})});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.test.js.map
|