@ledgerhq/device-transport-kit-react-native-ble 0.0.0-rnhid-transport-20250411151739 → 0.0.0-try-to-fix-20250429171448

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.
@@ -1,2 +1,2 @@
1
- "use strict";var _=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var C=(d,e)=>{for(var i in e)_(d,i,{get:e[i],enumerable:!0})},A=(d,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of T(e))!N.call(d,r)&&r!==i&&_(d,r,{get:()=>e[r],enumerable:!(t=I(e,r))||t.enumerable});return d};var E=d=>A(_({},"__esModule",{value:!0}),d);var O={};C(O,{RNBleTransport:()=>y,RNBleTransportFactory:()=>B,rnBleTransportIdentifier:()=>b});module.exports=E(O);var u=require("react-native"),S=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),s=require("rxjs"),v=require("../model/Const"),D=require("../model/Errors"),m=require("../transport/RNBleApduSender");const b="RN_BLE";class y{constructor(e,i,t,r,o=u.Platform,a=u.PermissionsAndroid,l=()=>new S.BleManager,c=h=>new p.DeviceConnectionStateMachine(h),g=(h,f)=>new m.RNBleApduSender(h,f)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._platform=o;this._permissionsAndroid=a;this._deviceConnectionStateMachineFactory=c;this._deviceApduSenderFactory=g;this._logger=i("ReactNativeBleTransport"),this._manager=l(),this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=n.Maybe.zero(),this._lastScanTimestamp=n.Maybe.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_lastScanTimestamp;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return(0,s.from)(this.requestPermission()).pipe((0,s.switchMap)(i=>{if(!i)throw new D.BleNotSupported("BLE not supported");return this._discoverKnownDevices(e)}),(0,s.mergeWith)(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return(0,n.EitherAsync)(async({liftEither:i,throwE:t})=>{const r=await i(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new p.UnknownDeviceError(`Unknown device ${e.deviceId}`)));let o;try{o=await this._manager.connectToDevice(e.deviceId,{requestMTU:v.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(c){return t(new p.OpeningConnectionError(c))}const a=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:r,manager:this._manager}},this._loggerServiceFactory),l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:v.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const c=this._internalDevicesById.get(e.deviceId);c&&c.disconnectionSubscription.remove()}});return await a.setupConnection(),this._deviceConnectionsById.set(r.id,l),r.disconnectionSubscription=this._manager.onDeviceDisconnected(r.id,(...c)=>{this._handleDeviceDisconnected(...c)}),r.lastDiscoveredTimeStamp=n.Maybe.zero(),new p.TransportConnectedDevice({id:r.id,deviceModel:r.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier})}).run()}async disconnect(e){return n.Maybe.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(t=>{const r=t.getDeviceId();this._manager.onDeviceDisconnected(r,()=>null),t.closeConnection()}),Promise.resolve((0,n.Right)(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe((0,s.map)(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=n.Maybe.fromNullable(n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o))).orDefaultLazy(()=>n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).mapOrDefault(o=>o.bleDeviceInfos.serviceUuid,""))),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id));return r.isJust()?r.map(o=>({bleDeviceInfos:o.bleDeviceInfos,discoveredDevice:{...o.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(o=>{const a=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(a[o]).map(c=>({discoveredDevice:{id:e.id,name:e.localName||c.deviceModel.productName,deviceModel:c.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:c}))},n.Nothing)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+v.CONNECTION_LOST_DELAY,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const r={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(t.id,{...r,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return this._lastScanTimestamp.mapOrDefault(i=>Date.now()-i<5e3,!1)?(0,s.from)([...this._internalDevicesById.values()].map(i=>i.discoveredDevice)):new s.Observable(i=>(this._lastScanTimestamp=n.Maybe.of(Date.now()),this._manager.startDeviceScan(null,{allowDuplicates:!0},(t,r)=>{if(t||!r){i.error(t);return}this._getDiscoveredDeviceFrom(r,e).map(({discoveredDevice:o,bleDeviceInfos:a})=>{this._emitDiscoveredDevice(i,a,o)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return(0,s.from)(this._manager.connectedDevices(e)).pipe((0,s.switchMap)(i=>new s.Observable(t=>{for(const r of i)r.readRSSI().then(o=>{o.discoverAllServicesAndCharacteristics().then(a=>{a.services().then(()=>{this._getDiscoveredDeviceFrom(a,e).map(({bleDeviceInfos:l,discoveredDevice:c})=>{this._emitDiscoveredDevice(t,l,c)})})})})})),(0,s.repeat)({delay:v.BLE_DISCONNECT_TIMEOUT/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const t=n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id));t.map(o=>{o.eventDeviceDetached()});let r;this._reconnectionSubscription=n.Maybe.of((0,s.from)([0]).pipe((0,s.switchMap)(async()=>{try{r=await i.connect({requestMTU:v.DEFAULT_MTU}),r=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(r)}catch(o){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:o}}),(0,s.throwError)(()=>o);return}return r}),(0,s.retry)({count:5,delay:v.BLE_DISCONNECT_TIMEOUT/5})).subscribe({next:o=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:o}}),complete:()=>{this._reconnectionSubscription=n.Maybe.zero()},error:o=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:o}}),this._reconnectionSubscription=n.Maybe.zero(),t.map(a=>{a.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new D.DeviceConnectionNotFound),t=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new D.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:r})=>{const o=await r(i),a=await r(t);o.setDependencies({device:e,manager:this._manager,internalDevice:a}),await o.setupConnection(),o.eventDeviceAttached()}).run()}}const B=({deviceModelDataSource:d,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new y(d,e,i,t);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
1
+ "use strict";var S=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var B=(v,e)=>{for(var i in e)S(v,i,{get:e[i],enumerable:!0})},N=(v,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of T(e))!C.call(v,r)&&r!==i&&S(v,r,{get:()=>e[r],enumerable:!(t=g(e,r))||t.enumerable});return v};var b=v=>N(S({},"__esModule",{value:!0}),v);var w={};B(w,{RNBleTransport:()=>I,RNBleTransportFactory:()=>E,rnBleTransportIdentifier:()=>A});module.exports=b(w);var u=require("react-native"),m=require("react-native-ble-plx"),d=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),s=require("rxjs"),D=require("../model/Const"),h=require("../model/Errors"),y=require("../transport/RNBleApduSender");const A="RN_BLE";class I{constructor(e,i,t,r,o=u.Platform,c=u.PermissionsAndroid,a=()=>new m.BleManager,p=_=>new d.DeviceConnectionStateMachine(_),l=(_,f)=>new y.RNBleApduSender(_,f)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._platform=o;this._permissionsAndroid=c;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=l;this._logger=i("ReactNativeBleTransport"),this._manager=a(),this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=n.Maybe.zero(),this._lastScanTimestamp=n.Maybe.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_lastScanTimestamp;_disconnectHandlersById=new Map;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return(0,s.from)(this.requestPermission()).pipe((0,s.switchMap)(i=>{if(!i)throw new h.BleNotSupported("BLE not supported");return this._discoverKnownDevices(e)}),(0,s.mergeWith)(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const t=this._internalDevicesById.get(e.deviceId);return(0,n.Right)(new d.TransportConnectedDevice({id:e.deviceId,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...r)=>i.sendApdu(...r),transport:this.identifier}))}return await this._safeCancel(e.deviceId),await this._manager.stopDeviceScan(),(0,n.EitherAsync)(async({liftEither:t,throwE:r})=>{const o=await t(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new d.UnknownDeviceError(`Unknown device ${e.deviceId}`)));this._disconnectHandlersById.set(o.id,e.onDisconnect);let c;try{c=await this._manager.connectToDevice(e.deviceId,{requestMTU:D.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(l){return r(new d.OpeningConnectionError(l))}const a=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:c,internalDevice:o,manager:this._manager}},this._loggerServiceFactory),p=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:D.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{const l=this._disconnectHandlersById.get(e.deviceId);l&&l(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),this._internalDevicesById.get(e.deviceId)?.disconnectionSubscription.remove()}});return await a.setupConnection(),this._deviceConnectionsById.set(e.deviceId,p),o.disconnectionSubscription=this._manager.onDeviceDisconnected(e.deviceId,(...l)=>this._handleDeviceDisconnected(...l)),o.lastDiscoveredTimeStamp=n.Maybe.zero(),new d.TransportConnectedDevice({id:o.id,deviceModel:o.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...l)=>p.sendApdu(...l),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id;n.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(c=>c.closeConnection()),this._deviceConnectionsById.delete(i);const r=this._internalDevicesById.get(i);r&&(r.disconnectionSubscription.remove(),this._internalDevicesById.delete(i)),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(c=>c.unsubscribe()),this._reconnectionSubscription=n.Maybe.zero()),await this._safeCancel(i);const o=this._disconnectHandlersById.get(i);return o&&(o(i),this._disconnectHandlersById.delete(i)),Promise.resolve((0,n.Right)(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe((0,s.map)(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=n.Maybe.fromNullable(n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o))).orDefaultLazy(()=>n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).mapOrDefault(o=>o.bleDeviceInfos.serviceUuid,""))),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id));return r.isJust()?r.map(o=>({bleDeviceInfos:o.bleDeviceInfos,discoveredDevice:{...o.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(o=>{const c=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(c[o]).map(p=>({discoveredDevice:{id:e.id,name:e.localName||p.deviceModel.productName,deviceModel:p.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:p}))},n.Nothing)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+D.CONNECTION_LOST_DELAY,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const r={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(t.id,{...r,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return this._lastScanTimestamp.mapOrDefault(i=>Date.now()-i<5e3,!1)?(0,s.from)([...this._internalDevicesById.values()].map(i=>i.discoveredDevice)):new s.Observable(i=>(this._lastScanTimestamp=n.Maybe.of(Date.now()),this._manager.startDeviceScan(null,{allowDuplicates:!0},(t,r)=>{if(t||!r){i.error(t);return}this._getDiscoveredDeviceFrom(r,e).map(({discoveredDevice:o,bleDeviceInfos:c})=>{this._emitDiscoveredDevice(i,c,o)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return(0,s.from)(this._manager.connectedDevices(e)).pipe((0,s.switchMap)(i=>new s.Observable(t=>{for(const r of i)r.readRSSI().then(o=>{o.discoverAllServicesAndCharacteristics().then(c=>{c.services().then(()=>{this._getDiscoveredDeviceFrom(c,e).map(({bleDeviceInfos:a,discoveredDevice:p})=>{this._emitDiscoveredDevice(t,a,p)})})})})})),(0,s.repeat)({delay:D.BLE_DISCONNECT_TIMEOUT/5}))}_handleDeviceDisconnected(e,i){if(!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const t=i.id;if(this._reconnectionSubscription.isJust())return;n.Maybe.fromNullable(this._deviceConnectionsById.get(t)).map(c=>c.eventDeviceDetached());const r=this._internalDevicesById.get(t);r&&r.disconnectionSubscription.remove();const o=(0,s.from)([0]).pipe((0,s.switchMap)(async()=>{await this._safeCancel(t)}),(0,s.delay)(2e3),(0,s.switchMap)(async()=>{await this._manager.stopDeviceScan();const c=await this._manager.connectToDevice(t,{requestMTU:D.DEFAULT_MTU}).then(async a=>await a.discoverAllServicesAndCharacteristics());return await this._handleDeviceReconnected(c),c}),(0,s.retry)({delay:(c,a)=>c?(0,s.throwError)(()=>new d.ReconnectionFailedError(c)):a===5?s.EMPTY:(0,s.timer)(0)}));this._reconnectionSubscription=n.Maybe.of(o.subscribe({next:c=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:c.id}}),complete:()=>{this._reconnectionSubscription=n.Maybe.zero()},error:c=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:c}}),n.Maybe.fromNullable(this._deviceConnectionsById.get(t)).map(a=>a.closeConnection()),this._reconnectionSubscription=n.Maybe.zero()}}))}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new h.DeviceConnectionNotFound),t=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new h.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:r})=>{const o=await r(i),c=await r(t);o.setDependencies({device:e,manager:this._manager,internalDevice:c}),await o.setupConnection(),o.eventDeviceAttached()}).run()}async _safeCancel(e){typeof this._manager.cancelDeviceConnection=="function"&&await this._manager.cancelDeviceConnection(e).catch(i=>this._logger.error("[_safeCancel] cancelDeviceConnection failed",{data:{e:i}}))}}const E=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new I(v,e,i,t);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
2
2
  //# sourceMappingURL=RNBleTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleTransport.ts"],
4
- "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type 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 TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private _lastScanTimestamp: Maybe<number>;\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 _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n _bleManagerFactory: () => BleManager = () => new BleManager(),\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._manager = _bleManagerFactory();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n this._lastScanTimestamp = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n const deviceId = d.getDeviceId();\n this._manager.onDeviceDisconnected(deviceId, () => null);\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\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 const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n ).orDefaultLazy(() =>\n Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n ).mapOrDefault((iDevice) => iDevice.bleDeviceInfos.serviceUuid, \"\"),\n ),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) => {\n return Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY;\n },\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n if (\n this._lastScanTimestamp.mapOrDefault(\n (lastScanTimestamp) => Date.now() - lastScanTimestamp < 5000,\n false,\n )\n ) {\n return from(\n [...this._internalDevicesById.values()].map(\n (iDevice) => iDevice.discoveredDevice,\n ),\n );\n }\n\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._lastScanTimestamp = Maybe.of(Date.now());\n this._manager.startDeviceScan(\n null,\n { allowDuplicates: true },\n (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n\n this._handleLostDiscoveredDevices(subscriber);\n },\n );\n\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((deviceWithRssi) => {\n deviceWithRssi\n .discoverAllServicesAndCharacteristics()\n .then((device) => {\n device.services().then(() => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAuD,gCACvDC,EAmBO,2CACPC,EAAgE,qBAChEC,EAWO,gBAEPC,EAIO,4BACPC,EAIO,6BACPC,EAKO,0CAEA,MAAMT,EAA2B,SAEjC,MAAMF,CAAoC,CAa/C,YACmBY,EACAC,EAGAC,EACAC,EACAC,EAAsB,WACtBC,EAA0C,qBAC3DC,EAAuC,IAAM,IAAI,aAChCC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,eAAAC,EACA,yBAAAC,EAEA,0CAAAE,EAIA,8BAAAE,EAMjB,KAAK,QAAUR,EAAsB,yBAAyB,EAC9D,KAAK,SAAWK,EAAmB,EACnC,KAAK,aAAe,QAAM,KAAK,EAC/B,KAAK,qBAAuB,IAAI,IAChC,KAAK,uBAAyB,IAAI,IAClC,KAAK,kBAAkB,EACvB,KAAK,0BAA4B,QAAM,KAAK,EAC5C,KAAK,mBAAqB,QAAM,KAAK,CACvC,CAxCQ,QACA,aACA,qBACA,uBAIS,SACA,WAAkC,SAC3C,0BACA,mBAgCA,mBAAoB,CAC1B,MAAMK,EAAc,KAAK,uBAAuB,qBAAqB,EACrE,SAAO,QAAK,KAAK,kBAAkB,CAAC,EAAE,QACpC,aAAWC,GAAgB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EAEMxB,EAAiB,MAAMF,EAAW+B,CAAqB,EAE7DzB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAM/B,EAA0C,CAAC,CACtD,sBAAAyD,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI7D,EACF0D,EACAC,EACAC,EACAC,CACF",
6
- "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "RNBleTransportFactory", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_platform", "_permissionsAndroid", "_bleManagerFactory", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "d", "deviceId", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "lastScanTimestamp", "devices", "fromDevice", "deviceWithRssi", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n ReconnectionFailedError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n delay,\n EMPTY,\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n timer,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private _lastScanTimestamp: Maybe<number>;\n private _disconnectHandlersById: Map<DeviceId, DisconnectHandler> = new Map();\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 _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n _bleManagerFactory: () => BleManager = () => new BleManager(),\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._manager = _bleManagerFactory();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n this._lastScanTimestamp = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const cachedDevice = this._internalDevicesById.get(params.deviceId)!;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: cachedDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._safeCancel(params.deviceId);\n\n await this._manager.stopDeviceScan();\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n this._disconnectHandlersById.set(\n internalDevice.id,\n params.onDisconnect,\n );\n\n let device: Device;\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\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 deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n const handler = this._disconnectHandlersById.get(params.deviceId);\n if (handler) handler(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n this._internalDevicesById\n .get(params.deviceId)\n ?.disconnectionSubscription.remove();\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(params.deviceId, (...args) =>\n this._handleDeviceDisconnected(...args),\n );\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const machineM = Maybe.fromNullable(\n this._deviceConnectionsById.get(deviceId),\n );\n machineM.map((sm) => sm.closeConnection());\n this._deviceConnectionsById.delete(deviceId);\n\n const internal = this._internalDevicesById.get(deviceId);\n if (internal) {\n internal.disconnectionSubscription.remove();\n this._internalDevicesById.delete(deviceId);\n }\n\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) => sub.unsubscribe());\n this._reconnectionSubscription = Maybe.zero();\n }\n\n await this._safeCancel(deviceId);\n\n const handler = this._disconnectHandlersById.get(deviceId);\n if (handler) {\n handler(deviceId);\n this._disconnectHandlersById.delete(deviceId);\n }\n\n return Promise.resolve(Right(undefined));\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 const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n ).orDefaultLazy(() =>\n Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n ).mapOrDefault((iDevice) => iDevice.bleDeviceInfos.serviceUuid, \"\"),\n ),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) => {\n return Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY;\n },\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n if (\n this._lastScanTimestamp.mapOrDefault(\n (lastScanTimestamp) => Date.now() - lastScanTimestamp < 5000,\n false,\n )\n ) {\n return from(\n [...this._internalDevicesById.values()].map(\n (iDevice) => iDevice.discoveredDevice,\n ),\n );\n }\n\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._lastScanTimestamp = Maybe.of(Date.now());\n this._manager.startDeviceScan(\n null,\n { allowDuplicates: true },\n (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n\n this._handleLostDiscoveredDevices(subscriber);\n },\n );\n\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((deviceWithRssi) => {\n deviceWithRssi\n .discoverAllServicesAndCharacteristics()\n .then((device) => {\n device.services().then(() => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map((sm) =>\n sm.eventDeviceDetached(),\n );\n\n const cachedDevice = this._internalDevicesById.get(deviceId);\n if (cachedDevice) {\n cachedDevice.disconnectionSubscription.remove();\n }\n\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._safeCancel(deviceId);\n }),\n delay(2000),\n switchMap(async () => {\n await this._manager.stopDeviceScan();\n const reconnected = await this._manager\n .connectToDevice(deviceId, { requestMTU: DEFAULT_MTU })\n .then(\n async (connectedDevice) =>\n await connectedDevice.discoverAllServicesAndCharacteristics(),\n );\n await this._handleDeviceReconnected(reconnected);\n return reconnected;\n }),\n retry({\n delay: (err, retryCount) => {\n if (err) {\n return throwError(() => new ReconnectionFailedError(err));\n }\n if (retryCount === 5) {\n return EMPTY;\n }\n return timer(0);\n },\n }),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n await this._manager.cancelDeviceConnection(deviceId).catch((e) =>\n this._logger.error(\"[_safeCancel] cancelDeviceConnection failed\", {\n data: { e },\n }),\n );\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAuD,gCACvDC,EAoBO,2CACPC,EAAgE,qBAChEC,EAcO,gBAEPC,EAIO,4BACPC,EAIO,6BACPC,EAKO,0CAEA,MAAMT,EAA2B,SAEjC,MAAMF,CAAoC,CAc/C,YACmBY,EACAC,EAGAC,EACAC,EACAC,EAAsB,WACtBC,EAA0C,qBAC3DC,EAAuC,IAAM,IAAI,aAChCC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,eAAAC,EACA,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BN,EAAgB,CACrD,MAAMiC,EAA0B,QAAM,aACpC,KAAK,uBAAuB,IAAIjC,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAI,0BAA0B,EAEnCkC,EAAwB,QAAM,aAClC,KAAK,qBAAqB,IAAIlC,EAAO,EAAE,CACzC,EAAE,SAAS,IAAI,wBAAwB,EAEvC,SAAO,eAAY,MAAO,CAAE,WAAAH,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCoC,CACF,EAEMlC,EAAiB,MAAMF,EAAWqC,CAAqB,EAE7D/B,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAExC,OAAO,KAAK,SAAS,wBAA2B,YAClD,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,EAAE,MAAO2B,GAC1D,KAAK,QAAQ,MAAM,8CAA+C,CAChE,KAAM,CAAE,EAAAA,CAAE,CACZ,CAAC,CACH,CAEJ,CACF,CAEO,MAAM/D,EAA0C,CAAC,CACtD,sBAAAkE,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAItE,EACFmE,EACAC,EACAC,EACAC,CACF",
6
+ "names": ["RNBleTransport_exports", "__export", "RNBleTransport", "RNBleTransportFactory", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_platform", "_permissionsAndroid", "_bleManagerFactory", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "ledgerUuids", "isSupported", "params", "existing", "cachedDevice", "a", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "handler", "deviceId", "sm", "internal", "sub", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "iDevice", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "lastScanTimestamp", "devices", "fromDevice", "deviceWithRssi", "reconnect$", "reconnected", "connectedDevice", "err", "retryCount", "d", "e", "errorOrDeviceConnection", "errorOrInternalDevice", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{PermissionsAndroid as y,Platform as g}from"react-native";import{BleManager as f}from"react-native-ble-plx";import{DeviceConnectionStateMachine as I,OpeningConnectionError as T,TransportConnectedDevice as N,UnknownDeviceError as C}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Maybe as o,Nothing as A,Right as E}from"purify-ts";import{from as d,map as b,mergeWith as B,Observable as h,repeat as O,retry as w,switchMap as p,throwError as M}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as l,CONNECTION_LOST_DELAY as R,DEFAULT_MTU as _}from"../model/Const";import{BleNotSupported as L,DeviceConnectionNotFound as F,InternalDeviceNotFound as P}from"../model/Errors";import{RNBleApduSender as U}from"../transport/RNBleApduSender";const V="RN_BLE";class x{constructor(e,i,t,n,r=g,c=y,a=()=>new f,s=v=>new I(v),S=(v,m)=>new U(v,m)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=n;this._platform=r;this._permissionsAndroid=c;this._deviceConnectionStateMachineFactory=s;this._deviceApduSenderFactory=S;this._logger=i("ReactNativeBleTransport"),this._manager=a(),this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=o.zero(),this._lastScanTimestamp=o.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_lastScanTimestamp;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return d(this.requestPermission()).pipe(p(i=>{if(!i)throw new L("BLE not supported");return this._discoverKnownDevices(e)}),B(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return u(async({liftEither:i,throwE:t})=>{const n=await i(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new C(`Unknown device ${e.deviceId}`)));let r;try{r=await this._manager.connectToDevice(e.deviceId,{requestMTU:_}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(s){return t(new T(s))}const c=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:r,internalDevice:n,manager:this._manager}},this._loggerServiceFactory),a=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:c,timeoutDuration:l,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const s=this._internalDevicesById.get(e.deviceId);s&&s.disconnectionSubscription.remove()}});return await c.setupConnection(),this._deviceConnectionsById.set(n.id,a),n.disconnectionSubscription=this._manager.onDeviceDisconnected(n.id,(...s)=>{this._handleDeviceDisconnected(...s)}),n.lastDiscoveredTimeStamp=o.zero(),new N({id:n.id,deviceModel:n.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...s)=>a.sendApdu(...s),transport:this.identifier})}).run()}async disconnect(e){return o.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(t=>{const n=t.getDeviceId();this._manager.onDeviceDisconnected(n,()=>null),t.closeConnection()}),Promise.resolve(E(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe(b(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=o.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=o.fromNullable(o.fromNullable(e?.serviceUUIDs?.find(r=>i.includes(r))).orDefaultLazy(()=>o.fromNullable(this._internalDevicesById.get(e.id)).mapOrDefault(r=>r.bleDeviceInfos.serviceUuid,""))),n=o.fromNullable(this._internalDevicesById.get(e.id));return n.isJust()?n.map(r=>({bleDeviceInfos:r.bleDeviceInfos,discoveredDevice:{...r.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(r=>{const c=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(c[r]).map(s=>({discoveredDevice:{id:e.id,name:e.localName||s.deviceModel.productName,deviceModel:s.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:s}))},A)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+R,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const n={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(t.id,{...n,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return this._lastScanTimestamp.mapOrDefault(i=>Date.now()-i<5e3,!1)?d([...this._internalDevicesById.values()].map(i=>i.discoveredDevice)):new h(i=>(this._lastScanTimestamp=o.of(Date.now()),this._manager.startDeviceScan(null,{allowDuplicates:!0},(t,n)=>{if(t||!n){i.error(t);return}this._getDiscoveredDeviceFrom(n,e).map(({discoveredDevice:r,bleDeviceInfos:c})=>{this._emitDiscoveredDevice(i,c,r)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return d(this._manager.connectedDevices(e)).pipe(p(i=>new h(t=>{for(const n of i)n.readRSSI().then(r=>{r.discoverAllServicesAndCharacteristics().then(c=>{c.services().then(()=>{this._getDiscoveredDeviceFrom(c,e).map(({bleDeviceInfos:a,discoveredDevice:s})=>{this._emitDiscoveredDevice(t,a,s)})})})})})),O({delay:l/5}))}_handleDeviceDisconnected(e,i){if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}if(!i){this._logger.debug("disconnected handler didn't found device");return}if(this._reconnectionSubscription.isJust())return;const t=o.fromNullable(this._deviceConnectionsById.get(i.id));t.map(r=>{r.eventDeviceDetached()});let n;this._reconnectionSubscription=o.of(d([0]).pipe(p(async()=>{try{n=await i.connect({requestMTU:_}),n=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(n)}catch(r){this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:r}}),M(()=>r);return}return n}),w({count:5,delay:l/5})).subscribe({next:r=>this._logger.debug("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:r}}),complete:()=>{this._reconnectionSubscription=o.zero()},error:r=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:r}}),this._reconnectionSubscription=o.zero(),t.map(c=>{c.closeConnection()})}}))}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new F),t=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new P);return u(async({liftEither:n})=>{const r=await n(i),c=await n(t);r.setDependencies({device:e,manager:this._manager,internalDevice:c}),await r.setupConnection(),r.eventDeviceAttached()}).run()}}const W=({deviceModelDataSource:D,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new x(D,e,i,t);export{x as RNBleTransport,W as RNBleTransportFactory,V as rnBleTransportIdentifier};
1
+ import{PermissionsAndroid as f,Platform as g}from"react-native";import{BleManager as T}from"react-native-ble-plx";import{DeviceConnectionStateMachine as C,OpeningConnectionError as B,ReconnectionFailedError as N,TransportConnectedDevice as h,UnknownDeviceError as b}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Maybe as o,Nothing as A,Right as _}from"purify-ts";import{delay as E,EMPTY as w,from as v,map as O,mergeWith as M,Observable as S,repeat as R,retry as L,switchMap as l,throwError as F,timer as P}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as m,CONNECTION_LOST_DELAY as U,DEFAULT_MTU as y}from"../model/Const";import{BleNotSupported as H,DeviceConnectionNotFound as x,InternalDeviceNotFound as z}from"../model/Errors";import{RNBleApduSender as q}from"../transport/RNBleApduSender";const Q="RN_BLE";class J{constructor(e,i,t,s,n=g,r=f,c=()=>new T,d=p=>new C(p),a=(p,I)=>new q(p,I)){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=s;this._platform=n;this._permissionsAndroid=r;this._deviceConnectionStateMachineFactory=d;this._deviceApduSenderFactory=a;this._logger=i("ReactNativeBleTransport"),this._manager=c(),this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission(),this._reconnectionSubscription=o.zero(),this._lastScanTimestamp=o.zero()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";_reconnectionSubscription;_lastScanTimestamp;_disconnectHandlersById=new Map;_startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return v(this.requestPermission()).pipe(l(i=>{if(!i)throw new H("BLE not supported");return this._discoverKnownDevices(e)}),M(this._discoverNewDevices(e)))}startDiscovering(){return this._startDiscovering()}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){const i=this._deviceConnectionsById.get(e.deviceId);if(i){const t=this._internalDevicesById.get(e.deviceId);return _(new h({id:e.deviceId,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...s)=>i.sendApdu(...s),transport:this.identifier}))}return await this._safeCancel(e.deviceId),await this._manager.stopDeviceScan(),u(async({liftEither:t,throwE:s})=>{const n=await t(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new b(`Unknown device ${e.deviceId}`)));this._disconnectHandlersById.set(n.id,e.onDisconnect);let r;try{r=await this._manager.connectToDevice(e.deviceId,{requestMTU:y}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(a){return s(new B(a))}const c=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:r,internalDevice:n,manager:this._manager}},this._loggerServiceFactory),d=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:c,timeoutDuration:m,onTerminated:()=>{const a=this._disconnectHandlersById.get(e.deviceId);a&&a(e.deviceId),this._deviceConnectionsById.delete(e.deviceId),this._internalDevicesById.get(e.deviceId)?.disconnectionSubscription.remove()}});return await c.setupConnection(),this._deviceConnectionsById.set(e.deviceId,d),n.disconnectionSubscription=this._manager.onDeviceDisconnected(e.deviceId,(...a)=>this._handleDeviceDisconnected(...a)),n.lastDiscoveredTimeStamp=o.zero(),new h({id:n.id,deviceModel:n.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...a)=>d.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){const i=e.connectedDevice.id;o.fromNullable(this._deviceConnectionsById.get(i)).map(r=>r.closeConnection()),this._deviceConnectionsById.delete(i);const s=this._internalDevicesById.get(i);s&&(s.disconnectionSubscription.remove(),this._internalDevicesById.delete(i)),this._reconnectionSubscription.isJust()&&(this._reconnectionSubscription.map(r=>r.unsubscribe()),this._reconnectionSubscription=o.zero()),await this._safeCancel(i);const n=this._disconnectHandlersById.get(i);return n&&(n(i),this._disconnectHandlersById.delete(i)),Promise.resolve(_(void 0))}listenToAvailableDevices(){const e={};return this._startDiscovering().pipe(O(i=>(e[i.id]=i,Object.values(e).filter(t=>t.rssi!==null))))}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(this._platform.OS==="ios")return this._isSupported=o.of(!0),!0;if(this._platform.OS==="android"&&this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(this._platform.Version.toString(),10)<31){const i=await this._permissionsAndroid.request(this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===this._permissionsAndroid.RESULTS.GRANTED)}if(this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await this._permissionsAndroid.requestMultiple([this._permissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,this._permissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,this._permissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===this._permissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===this._permissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this._isSupported.extract()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=o.fromNullable(o.fromNullable(e?.serviceUUIDs?.find(n=>i.includes(n))).orDefaultLazy(()=>o.fromNullable(this._internalDevicesById.get(e.id)).mapOrDefault(n=>n.bleDeviceInfos.serviceUuid,""))),s=o.fromNullable(this._internalDevicesById.get(e.id));return s.isJust()?s.map(n=>({bleDeviceInfos:n.bleDeviceInfos,discoveredDevice:{...n.discoveredDevice,rssi:e.rssi||void 0}})):t.mapOrDefault(n=>{const r=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(r[n]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier,rssi:e.rssi||void 0},bleDeviceInfos:d}))},A)}_isDiscoveredDeviceDelayOver(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+U,Nothing:()=>!1})}async _handleLostDiscoveredDevices(e){for(const i of this._internalDevicesById.values())this._isDiscoveredDeviceDelayOver(i)&&!await this._manager.isDeviceConnected(i.id)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,rssi:null}))}_emitDiscoveredDevice(e,i,t){e.next(t);const s={id:t.id,bleDeviceInfos:i,discoveredDevice:t,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(t.id,{...s,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,rssi:null})})})}_discoverNewDevices(e){return this._lastScanTimestamp.mapOrDefault(i=>Date.now()-i<5e3,!1)?v([...this._internalDevicesById.values()].map(i=>i.discoveredDevice)):new S(i=>(this._lastScanTimestamp=o.of(Date.now()),this._manager.startDeviceScan(null,{allowDuplicates:!0},(t,s)=>{if(t||!s){i.error(t);return}this._getDiscoveredDeviceFrom(s,e).map(({discoveredDevice:n,bleDeviceInfos:r})=>{this._emitDiscoveredDevice(i,r,n)}),this._handleLostDiscoveredDevices(i)}),{unsubscribe:async()=>{await this._manager.stopDeviceScan(),i.unsubscribe()}}))}_discoverKnownDevices(e){return v(this._manager.connectedDevices(e)).pipe(l(i=>new S(t=>{for(const s of i)s.readRSSI().then(n=>{n.discoverAllServicesAndCharacteristics().then(r=>{r.services().then(()=>{this._getDiscoveredDeviceFrom(r,e).map(({bleDeviceInfos:c,discoveredDevice:d})=>{this._emitDiscoveredDevice(t,c,d)})})})})})),R({delay:m/5}))}_handleDeviceDisconnected(e,i){if(!i){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!i?.id||!this._deviceConnectionsById.has(i?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:i}});return}const t=i.id;if(this._reconnectionSubscription.isJust())return;o.fromNullable(this._deviceConnectionsById.get(t)).map(r=>r.eventDeviceDetached());const s=this._internalDevicesById.get(t);s&&s.disconnectionSubscription.remove();const n=v([0]).pipe(l(async()=>{await this._safeCancel(t)}),E(2e3),l(async()=>{await this._manager.stopDeviceScan();const r=await this._manager.connectToDevice(t,{requestMTU:y}).then(async c=>await c.discoverAllServicesAndCharacteristics());return await this._handleDeviceReconnected(r),r}),L({delay:(r,c)=>r?F(()=>new N(r)):c===5?w:P(0)}));this._reconnectionSubscription=o.of(n.subscribe({next:r=>this._logger.debug("[_handleDeviceDisconnected] Reconnected to device",{data:{id:r.id}}),complete:()=>{this._reconnectionSubscription=o.zero()},error:r=>{this._logger.error("[_handleDeviceDisconnected] All reconnection attempts failed",{data:{e:r}}),o.fromNullable(this._deviceConnectionsById.get(t)).map(c=>c.closeConnection()),this._reconnectionSubscription=o.zero()}}))}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new x),t=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new z);return u(async({liftEither:s})=>{const n=await s(i),r=await s(t);n.setDependencies({device:e,manager:this._manager,internalDevice:r}),await n.setupConnection(),n.eventDeviceAttached()}).run()}async _safeCancel(e){typeof this._manager.cancelDeviceConnection=="function"&&await this._manager.cancelDeviceConnection(e).catch(i=>this._logger.error("[_safeCancel] cancelDeviceConnection failed",{data:{e:i}}))}}const X=({deviceModelDataSource:D,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new J(D,e,i,t);export{J as RNBleTransport,X as RNBleTransportFactory,Q as rnBleTransportIdentifier};
2
2
  //# sourceMappingURL=RNBleTransport.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/RNBleTransport.ts"],
4
- "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type 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 TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private _lastScanTimestamp: Maybe<number>;\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 _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n _bleManagerFactory: () => BleManager = () => new BleManager(),\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._manager = _bleManagerFactory();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n this._lastScanTimestamp = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n const deviceId = d.getDeviceId();\n this._manager.onDeviceDisconnected(deviceId, () => null);\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\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 const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n ).orDefaultLazy(() =>\n Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n ).mapOrDefault((iDevice) => iDevice.bleDeviceInfos.serviceUuid, \"\"),\n ),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) => {\n return Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY;\n },\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n if (\n this._lastScanTimestamp.mapOrDefault(\n (lastScanTimestamp) => Date.now() - lastScanTimestamp < 5000,\n false,\n )\n ) {\n return from(\n [...this._internalDevicesById.values()].map(\n (iDevice) => iDevice.discoveredDevice,\n ),\n );\n }\n\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._lastScanTimestamp = Maybe.of(Date.now());\n this._manager.startDeviceScan(\n null,\n { allowDuplicates: true },\n (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n\n this._handleLostDiscoveredDevices(subscriber);\n },\n );\n\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((deviceWithRssi) => {\n deviceWithRssi\n .discoverAllServicesAndCharacteristics()\n .then((device) => {\n device.services().then(() => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n\n if (!device) {\n this._logger.debug(\"disconnected handler didn't found device\");\n return;\n }\n\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n this._reconnectionSubscription = Maybe.of(\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n throwError(() => e);\n return;\n }\n return reconnectedDevice;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n this._reconnectionSubscription = Maybe.zero();\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.closeConnection();\n });\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
- "mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAwB,cAAAC,MAA+B,uBACvD,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YAChE,OACE,QAAAC,EACA,OAAAC,EACA,aAAAC,EACA,cAAAC,EACA,UAAAC,EACA,SAAAC,EAGA,aAAAC,EACA,cAAAC,MACK,OAEP,OACE,0BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,0BAAAC,MACK,oBACP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,EAA2B,SAEjC,MAAMC,CAAoC,CAa/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EAAsB/B,EACtBgC,EAA0CjC,EAC3DkC,EAAuC,IAAM,IAAIhC,EAChCiC,EAEiDC,GAChE,IAAIjC,EAA6BiC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAIb,EAAgBW,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,eAAAC,EACA,yBAAAC,EAEA,0CAAAE,EAIA,8BAAAE,EAMjB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,CAC9C,EACA,MAAQ+D,GAAM,CACZ,KAAK,QAAQ,MACX,oEACA,CAAE,KAAM,CAAE,EAAAA,CAAE,CAAE,CAChB,EACA,KAAK,0BAA4B/D,EAAM,KAAK,EAC5C4D,EAAwB,IAAKC,GAAqB,CAChDA,EAAiB,gBAAgB,CACnC,CAAC,CACH,CACF,CAAC,CACL,CACF,CAaA,MAAc,yBAAyBxB,EAAgB,CACrD,MAAMuB,EAA0B5D,EAAM,aACpC,KAAK,uBAAuB,IAAIqC,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAItB,CAA0B,EAEnCkD,EAAwBjE,EAAM,aAClC,KAAK,qBAAqB,IAAIqC,EAAO,EAAE,CACzC,EAAE,SAAS,IAAIrB,CAAwB,EAEvC,OAAOjB,EAAY,MAAO,CAAE,WAAAmC,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzC0B,CACF,EAEMxB,EAAiB,MAAMF,EAAW+B,CAAqB,EAE7DzB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAM0B,EAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAInD,EACFgD,EACAC,EACAC,EACAC,CACF",
6
- "names": ["PermissionsAndroid", "Platform", "BleManager", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Maybe", "Nothing", "Right", "from", "map", "mergeWith", "Observable", "repeat", "retry", "switchMap", "throwError", "BLE_DISCONNECT_TIMEOUT", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "DeviceConnectionNotFound", "InternalDeviceNotFound", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_platform", "_permissionsAndroid", "_bleManagerFactory", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "d", "deviceId", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "lastScanTimestamp", "devices", "fromDevice", "deviceWithRssi", "errorOrDeviceConnection", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrInternalDevice", "RNBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
4
+ "sourcesContent": ["import { PermissionsAndroid, Platform } from \"react-native\";\nimport { type BleError, BleManager, type Device } from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n ReconnectionFailedError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n delay,\n EMPTY,\n from,\n map,\n mergeWith,\n Observable,\n repeat,\n retry,\n type Subscriber,\n type Subscription,\n switchMap,\n throwError,\n timer,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private _lastScanTimestamp: Maybe<number>;\n private _disconnectHandlersById: Map<DeviceId, DisconnectHandler> = new Map();\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 _platform: Platform = Platform,\n private readonly _permissionsAndroid: PermissionsAndroid = PermissionsAndroid,\n _bleManagerFactory: () => BleManager = () => new BleManager(),\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._manager = _bleManagerFactory();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n this._reconnectionSubscription = Maybe.zero();\n this._lastScanTimestamp = Maybe.zero();\n }\n\n private _startDiscovering() {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n return this._discoverKnownDevices(ledgerUuids);\n }),\n mergeWith(this._discoverNewDevices(ledgerUuids)),\n );\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return this._startDiscovering();\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n const cachedDevice = this._internalDevicesById.get(params.deviceId)!;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: cachedDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n }),\n );\n }\n\n await this._safeCancel(params.deviceId);\n\n await this._manager.stopDeviceScan();\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n this._disconnectHandlersById.set(\n internalDevice.id,\n params.onDisconnect,\n );\n\n let device: Device;\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\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 deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n const handler = this._disconnectHandlersById.get(params.deviceId);\n if (handler) handler(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n this._internalDevicesById\n .get(params.deviceId)\n ?.disconnectionSubscription.remove();\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(params.deviceId, (...args) =>\n this._handleDeviceDisconnected(...args),\n );\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const machineM = Maybe.fromNullable(\n this._deviceConnectionsById.get(deviceId),\n );\n machineM.map((sm) => sm.closeConnection());\n this._deviceConnectionsById.delete(deviceId);\n\n const internal = this._internalDevicesById.get(deviceId);\n if (internal) {\n internal.disconnectionSubscription.remove();\n this._internalDevicesById.delete(deviceId);\n }\n\n if (this._reconnectionSubscription.isJust()) {\n this._reconnectionSubscription.map((sub) => sub.unsubscribe());\n this._reconnectionSubscription = Maybe.zero();\n }\n\n await this._safeCancel(deviceId);\n\n const handler = this._disconnectHandlersById.get(deviceId);\n if (handler) {\n handler(deviceId);\n this._disconnectHandlersById.delete(deviceId);\n }\n\n return Promise.resolve(Right(undefined));\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 const scannedDeviceMap: Record<DeviceId, TransportDiscoveredDevice> = {};\n return this._startDiscovering().pipe(\n map((discoveredDevice) => {\n scannedDeviceMap[discoveredDevice.id] = discoveredDevice;\n return Object.values(scannedDeviceMap).filter(\n (device) => device.rssi !== null,\n );\n }),\n );\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (this._platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n this._platform.OS === \"android\" &&\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(this._platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await this._permissionsAndroid.request(\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await this._permissionsAndroid.requestMultiple([\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n this._permissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n this._permissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n this._permissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this._isSupported.extract() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n ).orDefaultLazy(() =>\n Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n ).mapOrDefault((iDevice) => iDevice.bleDeviceInfos.serviceUuid, \"\"),\n ),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return existingInternalDevice.map((internalDevice) => ({\n bleDeviceInfos: internalDevice.bleDeviceInfos,\n discoveredDevice: {\n ...internalDevice.discoveredDevice,\n rssi: rnDevice.rssi || undefined,\n },\n }));\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n rssi: rnDevice.rssi || undefined,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Determines whether the delay since the device was last discovered has exceeded a predefined threshold.\n *\n * @param {RNBleInternalDevice} internalDevice - The internal device object containing the last discovered timestamp.\n * @return {boolean} - Returns true if the delay is over, otherwise false.\n */\n private _isDiscoveredDeviceDelayOver(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) => {\n return Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY;\n },\n Nothing: () => {\n return false;\n },\n });\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private async _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n for (const internalDevice of this._internalDevicesById.values()) {\n if (\n this._isDiscoveredDeviceDelayOver(internalDevice) &&\n !(await this._manager.isDeviceConnected(internalDevice.id))\n ) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n rssi: null,\n });\n }\n }\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} */\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n subscriber.next({\n ...discoveredDevice,\n rssi: null,\n });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n if (\n this._lastScanTimestamp.mapOrDefault(\n (lastScanTimestamp) => Date.now() - lastScanTimestamp < 5000,\n false,\n )\n ) {\n return from(\n [...this._internalDevicesById.values()].map(\n (iDevice) => iDevice.discoveredDevice,\n ),\n );\n }\n\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._lastScanTimestamp = Maybe.of(Date.now());\n this._manager.startDeviceScan(\n null,\n { allowDuplicates: true },\n (error, device) => {\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n\n this._handleLostDiscoveredDevices(subscriber);\n },\n );\n\n return {\n unsubscribe: async () => {\n await this._manager.stopDeviceScan();\n subscriber.unsubscribe();\n },\n };\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n for (const fromDevice of devices) {\n fromDevice.readRSSI().then((deviceWithRssi) => {\n deviceWithRssi\n .discoverAllServicesAndCharacteristics()\n .then((device) => {\n device.services().then(() => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n });\n }\n }),\n ),\n repeat({ delay: BLE_DISCONNECT_TIMEOUT / 5 }),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n if (this._reconnectionSubscription.isJust()) {\n return;\n }\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map((sm) =>\n sm.eventDeviceDetached(),\n );\n\n const cachedDevice = this._internalDevicesById.get(deviceId);\n if (cachedDevice) {\n cachedDevice.disconnectionSubscription.remove();\n }\n\n const reconnect$ = from([0]).pipe(\n switchMap(async () => {\n await this._safeCancel(deviceId);\n }),\n delay(2000),\n switchMap(async () => {\n await this._manager.stopDeviceScan();\n const reconnected = await this._manager\n .connectToDevice(deviceId, { requestMTU: DEFAULT_MTU })\n .then(\n async (connectedDevice) =>\n await connectedDevice.discoverAllServicesAndCharacteristics(),\n );\n await this._handleDeviceReconnected(reconnected);\n return reconnected;\n }),\n retry({\n delay: (err, retryCount) => {\n if (err) {\n return throwError(() => new ReconnectionFailedError(err));\n }\n if (retryCount === 5) {\n return EMPTY;\n }\n return timer(0);\n },\n }),\n );\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n \"[_handleDeviceDisconnected] Reconnected to device\",\n { data: { id: d.id } },\n ),\n complete: () => {\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] All reconnection attempts failed\",\n { data: { e } },\n );\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (sm) => sm.closeConnection(),\n );\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n await this._manager.cancelDeviceConnection(deviceId).catch((e) =>\n this._logger.error(\"[_safeCancel] cancelDeviceConnection failed\", {\n data: { e },\n }),\n );\n }\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "AAAA,OAAS,sBAAAA,EAAoB,YAAAC,MAAgB,eAC7C,OAAwB,cAAAC,MAA+B,uBACvD,OAKE,gCAAAC,EAOA,0BAAAC,EACA,2BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YAChE,OACE,SAAAC,EACA,SAAAC,EACA,QAAAC,EACA,OAAAC,EACA,aAAAC,EACA,cAAAC,EACA,UAAAC,EACA,SAAAC,EAGA,aAAAC,EACA,cAAAC,EACA,SAAAC,MACK,OAEP,OACE,0BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,0BAAAC,MACK,oBACP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,EAA2B,SAEjC,MAAMC,CAAoC,CAc/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EAAsBnC,EACtBoC,EAA0CrC,EAC3DsC,EAAuC,IAAM,IAAIpC,EAChCqC,EAEiDC,GAChE,IAAIrC,EAA6BqC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAIb,EAAgBW,EAAME,CAAa,EACzC,CAlBiB,4BAAAV,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,eAAAC,EACA,yBAAAC,EAEA,0CAAAE,EAIA,8BAAAE,EAMjB,KAAK,QAAUR,EAAsB,yBAAyB,EAC9D,KAAK,SAAWK,EAAmB,EACnC,KAAK,aAAe7B,EAAM,KAAK,EAC/B,KAAK,qBAAuB,IAAI,IAChC,KAAK,uBAAyB,IAAI,IAClC,KAAK,kBAAkB,EACvB,KAAK,0BAA4BA,EAAM,K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,EAAE,SAAS,IAAIzB,CAA0B,EAEnC2D,EAAwB7E,EAAM,aAClC,KAAK,qBAAqB,IAAI2C,EAAO,EAAE,CACzC,EAAE,SAAS,IAAIxB,CAAwB,EAEvC,OAAOpB,EAAY,MAAO,CAAE,WAAAyC,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCoC,CACF,EAEMlC,EAAiB,MAAMF,EAAWqC,CAAqB,EAE7D/B,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAExC,OAAO,KAAK,SAAS,wBAA2B,YAClD,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,EAAE,MAAO2B,GAC1D,KAAK,QAAQ,MAAM,8CAA+C,CAChE,KAAM,CAAE,EAAAA,CAAE,CACZ,CAAC,CACH,CAEJ,CACF,CAEO,MAAMG,EAA0C,CAAC,CACtD,sBAAAC,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAI5D,EACFyD,EACAC,EACAC,EACAC,CACF",
6
+ "names": ["PermissionsAndroid", "Platform", "BleManager", "DeviceConnectionStateMachine", "OpeningConnectionError", "ReconnectionFailedError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Maybe", "Nothing", "Right", "delay", "EMPTY", "from", "map", "mergeWith", "Observable", "repeat", "retry", "switchMap", "throwError", "timer", "BLE_DISCONNECT_TIMEOUT", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "DeviceConnectionNotFound", "InternalDeviceNotFound", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_platform", "_permissionsAndroid", "_bleManagerFactory", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "ledgerUuids", "isSupported", "params", "existing", "cachedDevice", "a", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "handler", "deviceId", "sm", "internal", "sub", "scannedDeviceMap", "discoveredDevice", "granted", "result", "rnDevice", "maybeUuid", "uuid", "iDevice", "existingInternalDevice", "serviceToBleInfos", "bleDeviceInfos", "lastDiscoveredTimeStamp", "subscriber", "lastScanTimestamp", "devices", "fromDevice", "deviceWithRssi", "reconnect$", "reconnected", "connectedDevice", "err", "retryCount", "d", "e", "errorOrDeviceConnection", "errorOrInternalDevice", "RNBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
7
  }
@@ -22,6 +22,7 @@ export declare class RNBleTransport implements Transport {
22
22
  private readonly identifier;
23
23
  private _reconnectionSubscription;
24
24
  private _lastScanTimestamp;
25
+ private _disconnectHandlersById;
25
26
  constructor(_deviceModelDataSource: DeviceModelDataSource, _loggerServiceFactory: (tag: string) => LoggerPublisherService, _apduSenderFactory: ApduSenderServiceFactory, _apduReceiverFactory: ApduReceiverServiceFactory, _platform?: Platform, _permissionsAndroid?: PermissionsAndroid, _bleManagerFactory?: () => BleManager, _deviceConnectionStateMachineFactory?: (args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>) => DeviceConnectionStateMachine<RNBleApduSenderDependencies>, _deviceApduSenderFactory?: (args: RNBleApduSenderConstructorArgs, loggerFactory: (tag: string) => LoggerPublisherService) => RNBleApduSender);
26
27
  private _startDiscovering;
27
28
  /**
@@ -164,6 +165,7 @@ export declare class RNBleTransport implements Transport {
164
165
  * the reconnection process.
165
166
  */
166
167
  private _handleDeviceReconnected;
168
+ private _safeCancel;
167
169
  }
168
170
  export declare const RNBleTransportFactory: TransportFactory;
169
171
  //# sourceMappingURL=RNBleTransport.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"RNBleTransport.d.ts","sourceRoot":"","sources":["../../../../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