@ledgerhq/device-transport-kit-react-native-ble 0.0.0-develop-20250412001122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE.MD +202 -0
  2. package/README.md +92 -0
  3. package/lib/cjs/api/index.js +2 -0
  4. package/lib/cjs/api/index.js.map +7 -0
  5. package/lib/cjs/api/model/Const.js +2 -0
  6. package/lib/cjs/api/model/Const.js.map +7 -0
  7. package/lib/cjs/api/model/Errors.js +2 -0
  8. package/lib/cjs/api/model/Errors.js.map +7 -0
  9. package/lib/cjs/api/transport/RNBleApduSender.js +2 -0
  10. package/lib/cjs/api/transport/RNBleApduSender.js.map +7 -0
  11. package/lib/cjs/api/transport/RNBleApduSender.test.js +2 -0
  12. package/lib/cjs/api/transport/RNBleApduSender.test.js.map +7 -0
  13. package/lib/cjs/api/transport/RNBleTransport.js +2 -0
  14. package/lib/cjs/api/transport/RNBleTransport.js.map +7 -0
  15. package/lib/cjs/api/transport/RNBleTransport.test.js +2 -0
  16. package/lib/cjs/api/transport/RNBleTransport.test.js.map +7 -0
  17. package/lib/cjs/index.js +2 -0
  18. package/lib/cjs/index.js.map +7 -0
  19. package/lib/cjs/package.json +64 -0
  20. package/lib/esm/api/index.js +2 -0
  21. package/lib/esm/api/index.js.map +7 -0
  22. package/lib/esm/api/model/Const.js +2 -0
  23. package/lib/esm/api/model/Const.js.map +7 -0
  24. package/lib/esm/api/model/Errors.js +2 -0
  25. package/lib/esm/api/model/Errors.js.map +7 -0
  26. package/lib/esm/api/transport/RNBleApduSender.js +2 -0
  27. package/lib/esm/api/transport/RNBleApduSender.js.map +7 -0
  28. package/lib/esm/api/transport/RNBleApduSender.test.js +2 -0
  29. package/lib/esm/api/transport/RNBleApduSender.test.js.map +7 -0
  30. package/lib/esm/api/transport/RNBleTransport.js +2 -0
  31. package/lib/esm/api/transport/RNBleTransport.js.map +7 -0
  32. package/lib/esm/api/transport/RNBleTransport.test.js +2 -0
  33. package/lib/esm/api/transport/RNBleTransport.test.js.map +7 -0
  34. package/lib/esm/index.js +2 -0
  35. package/lib/esm/index.js.map +7 -0
  36. package/lib/esm/package.json +64 -0
  37. package/lib/types/api/index.d.ts +3 -0
  38. package/lib/types/api/index.d.ts.map +1 -0
  39. package/lib/types/api/model/Const.d.ts +4 -0
  40. package/lib/types/api/model/Const.d.ts.map +1 -0
  41. package/lib/types/api/model/Errors.d.ts +27 -0
  42. package/lib/types/api/model/Errors.d.ts.map +1 -0
  43. package/lib/types/api/transport/RNBleApduSender.d.ts +40 -0
  44. package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -0
  45. package/lib/types/api/transport/RNBleApduSender.test.d.ts +2 -0
  46. package/lib/types/api/transport/RNBleApduSender.test.d.ts.map +1 -0
  47. package/lib/types/api/transport/RNBleTransport.d.ts +169 -0
  48. package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -0
  49. package/lib/types/api/transport/RNBleTransport.test.d.ts +2 -0
  50. package/lib/types/api/transport/RNBleTransport.test.d.ts.map +1 -0
  51. package/lib/types/index.d.ts +2 -0
  52. package/lib/types/index.d.ts.map +1 -0
  53. package/lib/types/tsconfig.prod.tsbuildinfo +1 -0
  54. package/package.json +63 -0
package/LICENSE.MD ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024-present Ledger
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # Transport Device Kit React Native BLE
2
+
3
+ > [!CAUTION]
4
+ > This is still under development and we are free to make new interfaces which may lead to breaking changes.
5
+
6
+ - [Transport Device Kit React Native BLE Documentation](#transport-device-kit-react-native-ble)
7
+ - [Description](#description)
8
+ - [Installation](#installation)
9
+ - [Usage](#usage)
10
+ - [Compatibility](#compatibility)
11
+ - [Pre-requisites](#pre-requisites)
12
+ - [Main Features](#main-features)
13
+ - [How To](#how-to)
14
+
15
+ ## Description
16
+
17
+ This transport is used to interact with a Ledger device through [react-native-ble-plx](https://github.com/dotintent/react-native-ble-plx) implementation by the Device Management Kit.
18
+
19
+ ## Installation
20
+
21
+ To install the core package, run the following command:
22
+
23
+ ```sh
24
+ npm install @ledgerhq/device-transport-kit-react-native-ble
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Compatibility
30
+
31
+ - iOS (11+)
32
+ - Android (6.0+)
33
+
34
+ | React Native | React Native BLE PLX | 0.1.1 |
35
+ | :----------: | :------------------: | :---: |
36
+ | \>0.74.1 | 0.3.4 | ✅ |
37
+
38
+ ### Pre-requisites
39
+
40
+ To use this transport, ensure you have the Device Management Kit installed in your project.
41
+
42
+ ### Main Features
43
+
44
+ - Exposing a transport factory to be injected into the DeviceManagementKit
45
+ - Exposing the transport directly for a custom configuration
46
+
47
+ ### How To
48
+
49
+ To use the transport, you need to inject it in the DeviceManagementKitBuilder before the build. This will allow the Device Management Kit to find and interact with devices on the iOS or Android BLE protocol.
50
+
51
+ ```typescript
52
+ import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit";
53
+ import {
54
+ rnBleTransportIdentifier,
55
+ RNBleTransport,
56
+ } from "@ledgerhq/device-transport-kit-react-native-ble";
57
+
58
+ // Easy setup with the factory
59
+ const dmk = new DeviceManagementKitBuilder()
60
+ .addTransport(rnBleTransportIdentifier)
61
+ .build();
62
+
63
+ // With custom config
64
+ const dmk = new DeviceManagementKitBuilder()
65
+ .addTransport(
66
+ ({
67
+ deviceModelDataSource,
68
+ loggerServiceFactory,
69
+ config,
70
+ apduSenderServiceFactory,
71
+ apduReceiverServiceFactory,
72
+ }: {
73
+ deviceModelDataSource: DeviceModelDataSource;
74
+ loggerServiceFactory: (tag: string) => LoggerPublisherService;
75
+ config: DmkConfig;
76
+ apduSenderServiceFactory: ApduSenderServiceFactory;
77
+ apduReceiverServiceFactory: ApduReceiverServiceFactory;
78
+ }) => {
79
+ // custom code
80
+ return new RNBleTransport(
81
+ deviceModelDataSource,
82
+ loggerServiceFactory,
83
+ config,
84
+ apduSenderServiceFactory,
85
+ apduReceiverServiceFactory,
86
+ );
87
+ },
88
+ )
89
+ .build();
90
+
91
+ // You can then make use of the Device Management Kit
92
+ ```
@@ -0,0 +1,2 @@
1
+ "use strict";var l=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var m=(o,r)=>{for(var e in r)l(o,e,{get:r[e],enumerable:!0})},f=(o,r,e,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of T(r))!i.call(o,n)&&n!==e&&l(o,n,{get:()=>r[n],enumerable:!(s=B(r,n))||s.enumerable});return o},a=(o,r,e)=>(f(o,r,"default"),e&&f(e,r,"default"));var x=o=>f(l({},"__esModule",{value:!0}),o);var p={};m(p,{RNBleTransport:()=>t.RNBleTransport,RNBleTransportFactory:()=>t.RNBleTransportFactory,rnBleTransportIdentifier:()=>t.rnBleTransportIdentifier});module.exports=x(p);a(p,require("./model/Errors"),module.exports);var t=require("./transport/RNBleTransport");0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier,...require("./model/Errors")});
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/api/index.ts"],
4
+ "sourcesContent": ["export * from \"./model/Errors\";\nexport {\n RNBleTransport,\n RNBleTransportFactory,\n rnBleTransportIdentifier,\n} from \"./transport/RNBleTransport\";\n"],
5
+ "mappings": "2dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gKAAAE,EAAAF,GAAAG,EAAAH,EAAc,0BAAd,gBACA,IAAAI,EAIO",
6
+ "names": ["api_exports", "__export", "__toCommonJS", "__reExport", "import_RNBleTransport"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var e=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var L=(o,T)=>{for(var E in T)e(o,E,{get:T[E],enumerable:!0})},c=(o,T,E,N)=>{if(T&&typeof T=="object"||typeof T=="function")for(let t of _(T))!C.call(o,t)&&t!==E&&e(o,t,{get:()=>T[t],enumerable:!(N=O(T,t))||N.enumerable});return o};var n=o=>c(e({},"__esModule",{value:!0}),o);var x={};L(x,{BLE_DISCONNECT_TIMEOUT:()=>s,CONNECTION_LOST_DELAY:()=>r,DEFAULT_MTU:()=>p});module.exports=n(x);const p=156,r=2e3,s=1e4;0&&(module.exports={BLE_DISCONNECT_TIMEOUT,CONNECTION_LOST_DELAY,DEFAULT_MTU});
2
+ //# sourceMappingURL=Const.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/model/Const.ts"],
4
+ "sourcesContent": ["export const DEFAULT_MTU = 156;\nexport const CONNECTION_LOST_DELAY = 2e3; // 2s;\nexport const BLE_DISCONNECT_TIMEOUT = 10e3; // 10s;\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,4BAAAE,EAAA,0BAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAL,GAAO,MAAMI,EAAc,IACdD,EAAwB,IACxBD,EAAyB",
6
+ "names": ["Const_exports", "__export", "BLE_DISCONNECT_TIMEOUT", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "__toCommonJS"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var d=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var u=(o,e)=>{for(var r in e)d(o,r,{get:e[r],enumerable:!0})},p=(o,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of l(e))!c.call(o,t)&&t!==r&&d(o,t,{get:()=>e[t],enumerable:!(a=s(e,t))||a.enumerable});return o};var i=o=>p(d({},"__esModule",{value:!0}),o);var k={};u(k,{BleDeviceGattServerError:()=>x,BleNotSupported:()=>D,BleTransportNotSupportedError:()=>v,DeviceConnectionNotFound:()=>y,InternalDeviceNotFound:()=>N});module.exports=i(k);var n=require("@ledgerhq/device-management-kit");class v extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleTransportNotSupportedError"}class x extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleDeviceGattServerError"}class y extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="DeviceConnectionNotFound"}class N extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="InternalDeviceNotFound"}class D extends n.GeneralDmkError{constructor(r){super(r);this.err=r}_tag="BleNotSupported"}0&&(module.exports={BleDeviceGattServerError,BleNotSupported,BleTransportNotSupportedError,DeviceConnectionNotFound,InternalDeviceNotFound});
2
+ //# sourceMappingURL=Errors.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/model/Errors.ts"],
4
+ "sourcesContent": ["import { GeneralDmkError } from \"@ledgerhq/device-management-kit\";\n\nexport class BleTransportNotSupportedError extends GeneralDmkError {\n override readonly _tag = \"BleTransportNotSupportedError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class BleDeviceGattServerError extends GeneralDmkError {\n override readonly _tag = \"BleDeviceGattServerError\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class DeviceConnectionNotFound extends GeneralDmkError {\n override readonly _tag = \"DeviceConnectionNotFound\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\nexport class InternalDeviceNotFound extends GeneralDmkError {\n override readonly _tag = \"InternalDeviceNotFound\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n\nexport class BleNotSupported extends GeneralDmkError {\n override readonly _tag = \"BleNotSupported\";\n constructor(readonly err?: unknown) {\n super(err);\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,EAAA,oBAAAC,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAP,GAAA,IAAAQ,EAAgC,2CAEzB,MAAMJ,UAAsC,iBAAgB,CAEjE,YAAqBK,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,+BAI3B,CACO,MAAMP,UAAiC,iBAAgB,CAE5D,YAAqBO,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAMJ,UAAiC,iBAAgB,CAE5D,YAAqBI,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAMH,UAA+B,iBAAgB,CAE1D,YAAqBG,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,wBAI3B,CAEO,MAAMN,UAAwB,iBAAgB,CAEnD,YAAqBM,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,iBAI3B",
6
+ "names": ["Errors_exports", "__export", "BleDeviceGattServerError", "BleNotSupported", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "__toCommonJS", "import_device_management_kit", "err"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var u=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var A=(s,e)=>{for(var r in e)u(s,r,{get:e[r],enumerable:!0})},R=(s,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of y(e))!h.call(s,i)&&i!==r&&u(s,i,{get:()=>e[i],enumerable:!(t=m(e,i))||t.enumerable});return s};var D=s=>R(u({},"__esModule",{value:!0}),s);var f={};A(f,{RNBleApduSender:()=>_});module.exports=D(f);var p=require("@ledgerhq/device-management-kit"),c=require("js-base64"),n=require("purify-ts"),v=require("rxjs");const S=3;class _{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:e,apduReceiverFactory:r,dependencies:t},i){this._dependencies=t,this._isDeviceReady=new v.BehaviorSubject(!1),this._logger=i("RNBleApduSender"),this._apduSenderFactory=e,this._apduSender=n.Nothing,this._apduReceiver=r(),this._sendApduPromiseResolver=n.Nothing}onReceiveSetupApduResponse(e){const r=new Uint8Array(e),{device:t}=this._dependencies,[i]=r.slice(5);let d=t.mtu-S;i&&i!==d&&(d=i),this._apduSender=n.Maybe.of(this._apduSenderFactory({frameSize:d})),this._isDeviceReady.next(!0)}receiveApdu(e){this._apduReceiver.handleFrame(e).map(t=>{t.map(i=>{this._logger.debug("Received APDU Response",{data:{response:i}}),this._sendApduPromiseResolver.map(d=>d((0,n.Right)(i)))})}).mapLeft(t=>{this._sendApduPromiseResolver.map(i=>i((0,n.Left)(t)))})}onMonitor(e){if(!e.value)return;const r=c.Base64.toUint8Array(e.value);this._isDeviceReady.value?this.receiveApdu(r):this.onReceiveSetupApduResponse(r)}write(e){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,e)}getDependencies(){return this._dependencies}setDependencies(e){this._dependencies=e}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(t,i)=>{!t&&i&&this.onMonitor(i)}),this._isDeviceReady.next(!1);const e=Uint8Array.from([8,0,0,0,0]);await this.write(c.Base64.fromUint8Array(e));let r;await new Promise(t=>{r&&r.unsubscribe(),r=this._isDeviceReady.subscribe({next:i=>{i&&t()}})})}async sendApdu(e,r,t){if(!this._isDeviceReady.value)return Promise.resolve((0,n.Left)(new p.DeviceNotInitializedError("Unknown MTU")));let i;const d=new Promise(o=>{this._sendApduPromiseResolver=n.Maybe.of((...a)=>(i&&clearTimeout(i),o(...a)))}),l=this._apduSender.caseOf({Just:o=>o.getFrames(e),Nothing:()=>[]});for(const o of l)try{await this.write(c.Base64.fromUint8Array(o.getRawData()))}catch(a){this._logger.info("Error sending frame",{data:{error:a}})}return t&&(i=setTimeout(()=>{this._sendApduPromiseResolver.map(o=>o((0,n.Left)(new p.SendApduTimeoutError("Abort timeout"))))},t)),d}closeConnection(){this._dependencies.device.cancelConnection()}}0&&(module.exports={RNBleApduSender});
2
+ //# sourceMappingURL=RNBleApduSender.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/RNBleApduSender.ts"],
4
+ "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n type Subscription as RNBleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type DeviceApduSender,\n type DeviceId,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n SendApduTimeoutError,\n type TransportDiscoveredDevice,\n} from \"@ledgerhq/device-management-kit\";\nimport { Base64 } from \"js-base64\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { BehaviorSubject, type Subscription } from \"rxjs\";\n\nconst FRAME_HEADER_SIZE = 3;\n\nexport type RNBleInternalDevice = {\n id: DeviceId;\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n disconnectionSubscription: RNBleSubscription;\n lastDiscoveredTimeStamp: Maybe<number>;\n};\n\nexport type RNBleApduSenderConstructorArgs = {\n dependencies: RNBleApduSenderDependencies;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type RNBleApduSenderDependencies = {\n device: Device;\n internalDevice: RNBleInternalDevice;\n manager: BleManager;\n};\n\nexport class RNBleApduSender\n implements DeviceApduSender<RNBleApduSenderDependencies>\n{\n private _dependencies: RNBleApduSenderDependencies;\n private _isDeviceReady: BehaviorSubject<boolean>;\n private _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduPromiseResolver: Maybe<\n (value: Either<DmkError, ApduResponse>) => void\n >;\n\n constructor(\n {\n apduSenderFactory,\n apduReceiverFactory,\n dependencies,\n }: RNBleApduSenderConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._dependencies = dependencies;\n this._isDeviceReady = new BehaviorSubject<boolean>(false);\n this._logger = loggerServiceFactory(\"RNBleApduSender\");\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._sendApduPromiseResolver = Nothing;\n }\n\n private onReceiveSetupApduResponse(value: Uint8Array) {\n const mtuResponse = new Uint8Array(value);\n const { device } = this._dependencies;\n // ledger mtu is the 5th byte of the response\n const [ledgerMtu] = mtuResponse.slice(5);\n let frameSize = device.mtu - FRAME_HEADER_SIZE;\n if (ledgerMtu && ledgerMtu !== frameSize) {\n // should never happen since ble mtu is negotiated on device connect with 156 bytes and ledger should return mtu size minus header size\n frameSize = ledgerMtu;\n }\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._isDeviceReady.next(true);\n }\n\n private receiveApdu(apdu: Uint8Array) {\n const maybeApduResponse = this._apduReceiver.handleFrame(apdu);\n\n maybeApduResponse\n .map((response) => {\n response.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Right(apduResponse)),\n );\n });\n })\n .mapLeft((error) => {\n this._sendApduPromiseResolver.map((resolve) => resolve(Left(error)));\n });\n }\n\n private onMonitor(characteristic: Characteristic) {\n if (!characteristic.value) {\n return;\n }\n\n const apdu = Base64.toUint8Array(characteristic.value);\n if (!this._isDeviceReady.value) {\n this.onReceiveSetupApduResponse(apdu);\n } else {\n this.receiveApdu(apdu);\n }\n }\n\n private write(value: string) {\n return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,\n value,\n );\n }\n\n public getDependencies() {\n return this._dependencies;\n }\n\n public setDependencies(dependencies: RNBleApduSenderDependencies) {\n this._dependencies = dependencies;\n }\n\n public async setupConnection() {\n this._dependencies.manager.monitorCharacteristicForDevice(\n this._dependencies.device.id,\n this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,\n this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,\n (error, characteristic) => {\n if (!error && characteristic) {\n this.onMonitor(characteristic);\n }\n },\n );\n this._isDeviceReady.next(false);\n const requestMtuFrame = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuFrame));\n let sub: Subscription | undefined;\n await new Promise<void>((resolve) => {\n if (sub) {\n sub.unsubscribe();\n }\n\n sub = this._isDeviceReady.subscribe({\n next: (isReady) => {\n if (isReady) {\n resolve();\n }\n },\n });\n });\n }\n\n async sendApdu(\n apdu: Uint8Array,\n _triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of((...args) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n return resolve(...args);\n });\n },\n );\n\n const frames = this._apduSender.caseOf({\n Just: (apduSender) => apduSender.getFrames(apdu),\n Nothing: () => [],\n });\n\n for (const frame of frames) {\n try {\n await this.write(Base64.fromUint8Array(frame.getRawData()));\n } catch (error) {\n this._logger.info(\"Error sending frame\", { data: { error } });\n }\n }\n\n if (abortTimeout) {\n timeout = setTimeout(() => {\n this._sendApduPromiseResolver.map((resolve) =>\n resolve(Left(new SendApduTimeoutError(\"Abort timeout\"))),\n );\n }, abortTimeout);\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAcO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD,gBAEnD,MAAMC,EAAoB,EAsBnB,MAAMN,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIR,YACE,CACE,kBAAAO,EACA,oBAAAC,EACA,aAAAC,CACF,EACAC,EACA,CACA,KAAK,cAAgBD,EACrB,KAAK,eAAiB,IAAI,kBAAyB,EAAK,EACxD,KAAK,QAAUC,EAAqB,iBAAiB,EACrD,KAAK,mBAAqBH,EAC1B,KAAK,YAAc,UACnB,KAAK,cAAgBC,EAAoB,EACzC,KAAK,yBAA2B,SAClC,CAEQ,2BAA2BG,EAAmB,CACpD,MAAMC,EAAc,IAAI,WAAWD,CAAK,EAClC,CAAE,OAAAE,CAAO,EAAI,KAAK,cAElB,CAACC,CAAS,EAAIF,EAAY,MAAM,CAAC,EACvC,IAAIG,EAAYF,EAAO,IAAMP,EACzBQ,GAAaA,IAAcC,IAE7BA,EAAYD,GAEd,KAAK,YAAc,QAAM,GAAG,KAAK,mBAAmB,CAAE,UAAAC,CAAU,CAAC,CAAC,EAClE,KAAK,eAAe,KAAK,EAAI,CAC/B,CAEQ,YAAYC,EAAkB,CACV,KAAK,cAAc,YAAYA,CAAI,EAG1D,IAAKC,GAAa,CACjBA,EAAS,IAAKC,GAAiB,CAC7B,KAAK,QAAQ,MAAM,yBAA0B,CAC3C,KAAM,CAAE,SAAUA,CAAa,CACjC,CAAC,EACD,KAAK,yBAAyB,IAAKC,GACjCA,KAAQ,SAAMD,CA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EAGF,IAAIC,EAEJ,MAAMC,EAAgB,IAAI,QACvBT,GAAY,CACX,KAAK,yBAA2B,QAAM,GAAG,IAAIU,KACvCF,GACF,aAAaA,CAAO,EAEfR,EAAQ,GAAGU,CAAI,EACvB,CACH,CACF,EAEMC,EAAS,KAAK,YAAY,OAAO,CACrC,KAAOC,GAAeA,EAAW,UAAUf,CAAI,EAC/C,QAAS,IAAM,CAAC,CAClB,CAAC,EAED,UAAWgB,KAASF,EAClB,GAAI,CACF,MAAM,KAAK,MAAM,SAAO,eAAeE,EAAM,WAAW,CAAC,CAAC,CAC5D,OAASZ,EAAO,CACd,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC9D,CAGF,OAAIM,IACFC,EAAU,WAAW,IAAM,CACzB,KAAK,yBAAyB,IAAKR,GACjCA,KAAQ,QAAK,IAAI,uBAAqB,eAAe,CAAC,CAAC,CACzD,CACF,EAAGO,CAAY,GAGVE,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
6
+ "names": ["RNBleApduSender_exports", "__export", "RNBleApduSender", "__toCommonJS", "import_device_management_kit", "import_js_base64", "import_purify_ts", "import_rxjs", "FRAME_HEADER_SIZE", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "response", "apduResponse", "resolve", "error", "characteristic", "requestMtuFrame", "sub", "isReady", "_triggersDisconnection", "abortTimeout", "timeout", "resultPromise", "args", "frames", "apduSender", "frame"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var s=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),w=require("./RNBleApduSender");vi.mock("react-native-ble-plx",()=>({BleManager:vi.fn()}));const f=3,C=156;class U{subscribers=[];tag;constructor(t,r){this.subscribers=t,this.tag=r}error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}let l,v,h,e,n;const p=vi.fn();describe("RNBleApduSender",()=>{beforeEach(()=>{l=i=>new U([],i),v=vi.fn(()=>(0,s.defaultApduSenderServiceStubBuilder)(void 0,l)),h=vi.fn(()=>(0,s.defaultApduReceiverServiceStubBuilder)(void 0,l)),e=new w.RNBleApduSender({dependencies:{device:{mtu:156,cancelConnection:p},internalDevice:{},manager:{}},apduReceiverFactory:h,apduSenderFactory:v},l)}),afterEach(()=>{vi.clearAllMocks()}),describe("constructor",()=>{it("should create an instance of RNBleApduSender",()=>{expect(e).toBeDefined()})}),describe("getDependencies",()=>{it("should return the dependencies",()=>{const i=e.getDependencies();expect(i).toStrictEqual({device:{mtu:156,cancelConnection:p},internalDevice:{},manager:{}})})}),describe("setDependencies",()=>{it("should set the dependencies",()=>{const i={device:{mtu:156,id:"deviceId",cancelConnection:p},internalDevice:{id:"deviceId",bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:{}};e.setDependencies(i);const t=e.getDependencies();expect(t).toStrictEqual(i)})}),describe("setupConnection",()=>{beforeEach(()=>{n={monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn()};const i={device:{mtu:156,id:"deviceId"},internalDevice:{bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:n};e.setDependencies(i)}),it("should setup the connection and resolve when the device is ready",async()=>{vi.spyOn(n,"monitorCharacteristicForDevice").mockImplementation((i,t,r,c)=>(c(null,{value:"BQAAAA8BBUJPTE9TBTEuMi4ykAA="}),{remove:vi.fn()})),vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((i,t,r,c)=>(e.onMonitor({value:c}),Promise.resolve({value:c}))),await e.setupConnection(),expect(n.monitorCharacteristicForDevice).toHaveBeenCalled(),expect(n.writeCharacteristicWithoutResponseForDevice).toHaveBeenCalled()})}),describe("closeConnection",()=>{it("should close the connection",()=>{e.closeConnection(),expect(p).toHaveBeenCalled()})}),describe("sendApdu",()=>{beforeEach(async()=>{n={monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn()};const i={device:{mtu:156,id:"deviceId"},internalDevice:{bleDeviceInfos:{serviceUuid:"serviceUuid",notifyUuid:"notifyUuid",writeCmdUuid:"writeCmdUuid"}},manager:n};vi.spyOn(n,"monitorCharacteristicForDevice").mockImplementationOnce((t,r,c,o)=>(o(null,{value:"BQAAAA8BBUJPTE9TBTEuMi4ykAA="}),{remove:vi.fn()})),vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((t,r,c,o)=>(e.onMonitor({value:o}),Promise.resolve({value:o}))),e.setDependencies(i),await e.setupConnection()}),describe("when the device is not ready",()=>{it("should return a DeviceNotInitializedError",async()=>{const i=new Uint8Array([8,0,0,0]);e._isDeviceReady.next(!1);const t=await e.sendApdu(i);expect(t).toStrictEqual((0,a.Left)(new s.DeviceNotInitializedError("Unknown MTU")))})}),describe("when the device is ready",()=>{it("should send the apdu",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new Uint8Array([5,0,0,0,15,1,5,66,79,76,79,83,5,49,46,50,46,50,144,0]),r=new Uint8Array([144,0]),c={data:t,statusCode:r};vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((u,d,y,m)=>(e.onMonitor({value:m}),Promise.resolve({value:m}))),vi.spyOn(e._apduReceiver,"handleFrame").mockImplementation(()=>(0,a.Right)(a.Maybe.of(c)));const o=await e.sendApdu(i);expect(v).toHaveBeenCalledTimes(2),expect(v).toHaveBeenNthCalledWith(1,{frameSize:1}),expect(v).toHaveBeenNthCalledWith(2,{frameSize:C-f}),expect(o).toStrictEqual((0,a.Right)(c))}),it("should return an error if the frame cannot be handled",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.GeneralDmkError("could not handle frame");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({value:d}),Promise.resolve({value:d}))),vi.spyOn(e._apduReceiver,"handleFrame").mockImplementation(()=>(0,a.Left)(t));const r=await e.sendApdu(i);expect(r).toStrictEqual((0,a.Left)(t))}),it("should return a SendApduTimeoutError if something takes too long",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new Uint8Array([5,0,0,0,15,1,5,66,79,76,79,83,5,49,46,50,46,50,144,0]),r=new Uint8Array([144,0]),c={data:t,statusCode:r},o=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((d,y,m,x)=>(e.onMonitor({value:x}),Promise.resolve({value:x}))),vi.spyOn(e,"onMonitor").mockImplementation(()=>{setTimeout(()=>(0,a.Right)(a.Maybe.of(c)),2e3)});const u=await e.sendApdu(i,!1,100);expect(u).toStrictEqual((0,a.Left)(o))}),it("should and and log an error if the this.write fails",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({value:d}),Promise.resolve({value:d}))),vi.spyOn(e,"write").mockImplementation(()=>Promise.reject(new Error("test")));const r=await e.sendApdu(i,!1,100);expect(r).toStrictEqual((0,a.Left)(t))}),it("should timeout if there are no characteristic.value",async()=>{const i=new Uint8Array([176,1,0,0,0]),t=new s.SendApduTimeoutError("Abort timeout");vi.spyOn(n,"writeCharacteristicWithoutResponseForDevice").mockImplementation((c,o,u,d)=>(e.onMonitor({}),Promise.resolve({}))),vi.spyOn(e,"write").mockImplementation(()=>Promise.reject(new Error("test")));const r=await e.sendApdu(i,!1,100);expect(r).toStrictEqual((0,a.Left)(t))})})})});
2
+ //# sourceMappingURL=RNBleApduSender.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/RNBleApduSender.test.ts"],
4
+ "sourcesContent": ["import {\n type BleManager,\n type Characteristic,\n type Device,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n GeneralDmkError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n SendApduTimeoutError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Maybe, Right } from \"purify-ts\";\n\nimport { RNBleApduSender, type RNBleInternalDevice } from \"./RNBleApduSender\";\n\nvi.mock(\"react-native-ble-plx\", () => ({\n BleManager: vi.fn(),\n}));\n\nconst FRAME_HEADER_SIZE = 3;\nconst LEDGER_MTU = 156;\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n subscribers: LoggerSubscriberService[] = [];\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n error = vi.fn();\n warn = vi.fn();\n info = vi.fn();\n debug = vi.fn();\n}\n\nlet logger: (tag: string) => LoggerPublisherService;\nlet apduSenderFactory: ApduSenderServiceFactory;\nlet apduReceiverFactory: ApduReceiverServiceFactory;\nlet apduSender: RNBleApduSender;\nlet manager: BleManager;\nconst cancelConnection = vi.fn();\ndescribe(\"RNBleApduSender\", () => {\n beforeEach(() => {\n logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n apduSenderFactory = vi.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = vi.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n apduSender = new RNBleApduSender(\n {\n dependencies: {\n device: {\n mtu: 156,\n cancelConnection,\n } as unknown as Device,\n internalDevice: {} as RNBleInternalDevice,\n manager: {} as BleManager,\n },\n apduReceiverFactory: apduReceiverFactory,\n apduSenderFactory: apduSenderFactory,\n },\n logger,\n );\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n });\n\n describe(\"constructor\", () => {\n it(\"should create an instance of RNBleApduSender\", () => {\n expect(apduSender).toBeDefined();\n });\n });\n\n describe(\"getDependencies\", () => {\n it(\"should return the dependencies\", () => {\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual({\n device: {\n mtu: 156,\n cancelConnection,\n },\n internalDevice: {},\n manager: {},\n });\n });\n });\n\n describe(\"setDependencies\", () => {\n it(\"should set the dependencies\", () => {\n const newDependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n cancelConnection,\n } as unknown as Device,\n internalDevice: {\n id: \"deviceId\",\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager: {} as BleManager,\n };\n apduSender.setDependencies(newDependencies);\n const dependencies = apduSender.getDependencies();\n expect(dependencies).toStrictEqual(newDependencies);\n });\n });\n\n describe(\"setupConnection\", () => {\n beforeEach(() => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n apduSender.setDependencies(dependencies);\n });\n\n it(\"should setup the connection and resolve when the device is ready\", async () => {\n vi.spyOn(manager, \"monitorCharacteristicForDevice\").mockImplementation(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n await apduSender.setupConnection();\n\n expect(manager.monitorCharacteristicForDevice).toHaveBeenCalled();\n expect(\n manager.writeCharacteristicWithoutResponseForDevice,\n ).toHaveBeenCalled();\n });\n });\n\n describe(\"closeConnection\", () => {\n it(\"should close the connection\", () => {\n apduSender.closeConnection();\n expect(cancelConnection).toHaveBeenCalled();\n });\n });\n\n describe(\"sendApdu\", () => {\n beforeEach(async () => {\n manager = {\n monitorCharacteristicForDevice: vi.fn(),\n writeCharacteristicWithoutResponseForDevice: vi.fn(),\n } as unknown as BleManager;\n\n const dependencies = {\n device: {\n mtu: 156,\n id: \"deviceId\",\n } as Device,\n internalDevice: {\n bleDeviceInfos: {\n serviceUuid: \"serviceUuid\",\n notifyUuid: \"notifyUuid\",\n writeCmdUuid: \"writeCmdUuid\",\n },\n } as RNBleInternalDevice,\n manager,\n };\n\n vi.spyOn(\n manager,\n \"monitorCharacteristicForDevice\",\n ).mockImplementationOnce(\n (_deviceId, _serviceUuid, _notifyUuid, callback) => {\n callback(null, {\n value: \"BQAAAA8BBUJPTE9TBTEuMi4ykAA=\",\n } as Characteristic);\n\n return {\n remove: vi.fn(),\n };\n },\n );\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation((_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n });\n\n apduSender.setDependencies(dependencies);\n await apduSender.setupConnection();\n });\n\n describe(\"when the device is not ready\", () => {\n it(\"should return a DeviceNotInitializedError\", async () => {\n const apdu = new Uint8Array([0x08, 0x00, 0x00, 0x00]);\n // @ts-expect-error private access for tests\n apduSender._isDeviceReady.next(false);\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n });\n\n describe(\"when the device is ready\", () => {\n it(\"should send the apdu\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Right(Maybe.of(response));\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(apduSenderFactory).toHaveBeenCalledTimes(2);\n\n // first call is for the setup\n expect(apduSenderFactory).toHaveBeenNthCalledWith(1, {\n frameSize: 1,\n });\n\n // second call is for the apdu\n expect(apduSenderFactory).toHaveBeenNthCalledWith(2, {\n frameSize: LEDGER_MTU - FRAME_HEADER_SIZE,\n });\n\n expect(result).toStrictEqual(Right(response));\n });\n\n it(\"should return an error if the frame cannot be handled\", async () => {\n // {\"error\": {\"_tag\": \"DeviceLockedError\", \"errorCode\": \"5515\", \"message\": \"Device is locked.\", \"originalError\": undefined}, \"status\": \"ERROR\"}\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedError = new GeneralDmkError(\"could not handle frame\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender._apduReceiver, \"handleFrame\").mockImplementation(\n () => {\n return Left(expectedError);\n },\n );\n\n const result = await apduSender.sendApdu(apdu);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should return a SendApduTimeoutError if something takes too long\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n\n const expectedResponse = new Uint8Array([\n 0x05, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x05, 0x42, 0x4f, 0x4c, 0x4f,\n 0x53, 0x05, 0x31, 0x2e, 0x32, 0x2e, 0x32, 0x90, 0x00,\n ]);\n\n const statusCode = new Uint8Array([0x90, 0x00]);\n\n const response = {\n data: expectedResponse,\n statusCode,\n };\n\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"onMonitor\").mockImplementation(() => {\n setTimeout(() => {\n return Right(Maybe.of(response));\n }, 2000);\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should and and log an error if the this.write fails\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({\n value: value,\n } as Characteristic);\n\n return Promise.resolve({\n value: value,\n } as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n\n it(\"should timeout if there are no characteristic.value\", async () => {\n // GetAppAndVersion APDU\n const apdu = new Uint8Array([0xb0, 0x01, 0x00, 0x00, 0x00]);\n const expectedError = new SendApduTimeoutError(\"Abort timeout\");\n\n vi.spyOn(\n manager,\n \"writeCharacteristicWithoutResponseForDevice\",\n ).mockImplementation(\n (_deviceId, _serviceUuid, _writeCmdUuid, _value) => {\n // @ts-expect-error needed for tests\n apduSender.onMonitor({} as Characteristic);\n\n return Promise.resolve({} as Characteristic);\n },\n );\n\n // @ts-expect-error private access for tests\n vi.spyOn(apduSender, \"write\").mockImplementation(() => {\n return Promise.reject(new Error(\"test\"));\n });\n\n const result = await apduSender.sendApdu(apdu, false, 100);\n expect(result).toStrictEqual(Left(expectedError));\n });\n });\n });\n});\n"],
5
+ "mappings": "aAKA,IAAAA,EAUO,2CACPC,EAAmC,qBAEnCC,EAA0D,6BAE1D,GAAG,KAAK,uBAAwB,KAAO,CACrC,WAAY,GAAG,GAAG,CACpB,EAAE,EAEF,MAAMC,EAAoB,EACpBC,EAAa,IAEnB,MAAMC,CAA6D,CACjE,YAAyC,CAAC,EAC1C,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,MAAQ,GAAG,GAAG,EACd,KAAO,GAAG,GAAG,EACb,KAAO,GAAG,GAAG,EACb,MAAQ,GAAG,GAAG,CAChB,CAEA,IAAIC,EACAC,EACAC,EACAC,EACAC,EACJ,MAAMC,EAAmB,GAAG,GAAG,EAC/B,SAAS,kBAAmB,IAAM,CAChC,WAAW,IAAM,CACfL,EAAUD,GAAgB,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,CAClD,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["import_device_management_kit", "import_purify_ts", "import_RNBleApduSender", "FRAME_HEADER_SIZE", "LEDGER_MTU", "LoggerPublisherServiceStub", "subscribers", "tag", "logger", "apduSenderFactory", "apduReceiverFactory", "apduSender", "manager", "cancelConnection", "dependencies", "newDependencies", "_deviceId", "_serviceUuid", "_notifyUuid", "callback", "_writeCmdUuid", "value", "apdu", "result", "expectedResponse", "statusCode", "response", "expectedError", "_value"]
7
+ }
@@ -0,0 +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});
2
+ //# sourceMappingURL=RNBleTransport.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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,IAAA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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"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var D=require("@ledgerhq/device-management-kit"),C=require("purify-ts"),A=require("rxjs"),s=require("vitest"),N=require("../model/Errors"),r=require("./RNBleTransport");const l={error:vi.fn(),info:vi.fn(),warn:vi.fn(),debug:vi.fn()};vi.mock("react-native",()=>({Platform:{},PermissionsAndroid:{}}));vi.mock("react-native-ble-plx",()=>({BleManager:vi.fn()}));const g=async(d,m)=>{const I={OS:"android",Version:d.version},O={request:vi.fn().mockImplementation(e=>Promise.resolve({ACCESS_FINE_LOCATION:d.accessFineLocationResult}[e])),PERMISSIONS:d.permissions,RESULTS:{GRANTED:"granted"},requestMultiple:vi.fn().mockImplementation(()=>Promise.resolve(d.requestPermissionResult))},u=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},I,O);await u.requestPermission();const n=u.isSupported();m.callRequestPermission&&(0,s.expect)(O.request).toHaveBeenCalledWith("ACCESS_FINE_LOCATION"),(0,s.expect)(n).toBe(m.isSupported)};describe("RNBleTransportFactory",()=>{it("should return a RNBleTransport",()=>{const m=(0,r.RNBleTransportFactory)({deviceModelDataSource:"DeviceModelDataSource",loggerServiceFactory:()=>l,apduSenderServiceFactory:()=>{},apduReceiverServiceFactory:()=>{},config:{}});(0,s.expect)(m).toBeInstanceOf(r.RNBleTransport)})});describe("RNBleTransport",()=>{const d={OS:"ios"},m=new D.TransportDeviceModel({id:D.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,masks:[858783744]}),I=vi.fn(()=>["ledgerId"]),O=vi.fn(()=>({ledgerId:new D.BleDeviceInfos(m,"serviceUuid","notifyUuid","writeCmdUuid","readCmdUuid")})),u={getBluetoothServices:I,getBluetoothServicesInfos:O};(0,s.beforeEach)(()=>{vi.clearAllMocks()}),describe("getIdentifier",()=>{it("should return rnBleTransportIdentifier",()=>{const e=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{}).getIdentifier();(0,s.expect)(e).toStrictEqual("RN_BLE")})}),describe("isSupported",()=>{it("should return true if platform is ios",async()=>{const n={OS:"ios"},e=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},n);await e.requestPermission();const i=e.isSupported();(0,s.expect)(i).toBe(!0)}),it("should return true if platform is android and apiLevel < 31 with good permissions",async()=>{await g({version:30,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!0})}),it("should return true if platform is android and apiLevel >= 31 with good permissions",async()=>{await g({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted","android.permission.ACCESS_FINE_LOCATION":"granted"}},{isSupported:!0,callRequestPermission:!1})}),it("should return false if platform is android with bad permissions",async()=>{await g({version:31,permissions:{ACCESS_FINE_LOCATION:"",BLUETOOTH_SCAN:"",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.ACCESS_FINE_LOCATION":"denied","android.permission.BLUETOOTH_CONNECT":"granted","android.permission.BLUETOOTH_SCAN":"granted"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform is android and denied permissions",async()=>{await g({version:31,permissions:{ACCESS_FINE_LOCATION:"ACCESS_FINE_LOCATION",BLUETOOTH_SCAN:"BLUETOOTH_SCAN",BLUETOOTH_CONNECT:"BLUETOOTH_CONNECT"},requestPermissionResult:{"android.permission.BLUETOOTH_CONNECT":"denied","android.permission.BLUETOOTH_SCAN":"denied","android.permission.ACCESS_FINE_LOCATION":"denied"}},{isSupported:!1,callRequestPermission:!1})}),it("should return false if platform isn't android nor ios",async()=>{const n=new r.RNBleTransport("DeviceModelDataSource",()=>l,()=>{},()=>{},{OS:"windows"});await n.requestPermission();const e=n.isSupported();(0,s.expect)(e).toBe(!1)})}),describe("startDiscovering",()=>{it("should throw error if transport is not supported",()=>{const n={OS:"windows"},e=new r.RNBleTransport(u,()=>l,()=>{},()=>{},n);try{e.startDiscovering()}catch(i){(0,s.expect)(i).toBeInstanceOf(N.BleNotSupported)}}),it("should emit discovered known device",()=>new Promise(n=>{const e={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValue({}),serviceUUIDs:["ledgerId"],rssi:42,id:"id",localName:"name"})})}]),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn()},c=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>e).startDiscovering().subscribe({next:t=>{(0,s.expect)(t).toStrictEqual({id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}),c.unsubscribe(),n(void 0)},error:t=>{throw c&&!c.closed&&c.unsubscribe(),t},complete:()=>{throw c&&!c.closed&&c.unsubscribe(),new Error("complete should not be called")}})})),it("should emit discovered new device",()=>new Promise(n=>{let e;const i=vi.fn((v,w,p)=>{e=setInterval(()=>{p(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),p(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),a=vi.fn(()=>{clearInterval(e)}),c={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:i,stopDeviceScan:a,onDeviceDisconnected:vi.fn()},o=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>c).startDiscovering().subscribe({next:v=>{(0,s.expect)(v).toStrictEqual({id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}),o.unsubscribe(),n(void 0)},error:v=>{throw o&&!o.closed&&o.unsubscribe(),v},complete:()=>{throw o&&!o.closed&&o.unsubscribe(),new Error("complete should not be called")}})})),it("should emit both known and new device",()=>new Promise(n=>{let e;const i=vi.fn((p,f,k)=>{e=setInterval(()=>{k(null,{id:"newDeviceId",localName:"newDeviceName",serviceUUIDs:["ledgerId"],rssi:42})},500),k(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),a=vi.fn(()=>{clearInterval(e)}),t={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})}]),startDeviceScan:i,stopDeviceScan:a,onDeviceDisconnected:vi.fn()},o=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>t).startDiscovering(),v={},w=o.subscribe({next:p=>{v[p.id]=p,Object.values(v).length===2&&(w.unsubscribe(),(0,s.expect)(Object.values(v)).toStrictEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:m,transport:"RN_BLE",rssi:64},{id:"newDeviceId",name:"newDeviceName",deviceModel:m,transport:"RN_BLE",rssi:42}]),n(void 0))}})}))}),describe("stopDiscovering",()=>{it("should call ble manager stop scan on stop discovering",()=>{const n=vi.fn(),e={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:vi.fn(),stopDeviceScan:n,onDeviceDisconnected:vi.fn()};new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>e).stopDiscovering(),(0,s.expect)(n).toHaveBeenCalled()}),it("should call ble manager stop scan when unsubscribe startDiscovering obs",()=>{let n;const e=vi.fn((t,S,o)=>{n=setInterval(()=>{o(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),o(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),i=vi.fn(()=>{clearInterval(n),n=void 0}),a={connectedDevices:vi.fn().mockResolvedValueOnce([]),startDeviceScan:e,stopDeviceScan:i,onDeviceDisconnected:vi.fn()};new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>a).startDiscovering().subscribe().unsubscribe(),(0,s.expect)(e).toHaveBeenCalled(),(0,s.expect)(i).toHaveBeenCalled()})}),describe("listenToAvailableDevices",()=>{it("should call startScan and connectedDevices from ble manager",()=>new Promise(n=>{let e;const i=vi.fn((v,w,p)=>{e=setInterval(()=>{p(null,{id:"id",localName:"name",serviceUUIDs:["ledgerId"],rssi:42})},500),p(null,{id:"43",localName:"name43",serviceUUIDs:["notLedgerId"],rssi:43})}),a=vi.fn(()=>{clearInterval(e),e=void 0}),t={connectedDevices:vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"knownDeviceId",localName:"knownDeviceName"})})}]),startDeviceScan:i,stopDeviceScan:a,onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()},o=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>t).listenToAvailableDevices().subscribe({next:v=>{v.length===2&&((0,s.expect)(v).toEqual([{id:"knownDeviceId",name:"knownDeviceName",deviceModel:m,transport:"RN_BLE",rssi:64},{id:"id",name:"name",deviceModel:m,transport:"RN_BLE",rssi:42}]),o.unsubscribe(),n(void 0))}})}))}),describe("connect",()=>{let n;(0,s.beforeEach)(()=>{n=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should throw an error if device id is unknown",async()=>{const e={connectedDevices:vi.fn(),startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn()},a=await new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>e).connect({deviceId:"42",onDisconnect:vi.fn()});(0,s.expect)(a).toEqual((0,C.Left)(new D.UnknownDeviceError("Unknown device 42")))}),it("should connect to a discovered device with correct MTU and discover services and setup apdu sender",async()=>{const e={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},i=vi.fn(),a=vi.fn().mockReturnValue({sendApdu:vi.fn()}),c=vi.fn().mockReturnValue({setupConnection:i}),t=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>e,a,c),S=await(0,A.firstValueFrom)(t.startDiscovering()),o=await t.connect({deviceId:S.id,onDisconnect:vi.fn()});(0,s.expect)(o.isRight()).toBe(!0),(0,s.expect)(e.connectToDevice).toHaveBeenCalledWith("deviceId",{requestMTU:156}),(0,s.expect)(e.discoverAllServicesAndCharacteristicsForDevice).toHaveBeenCalledWith("deviceId"),(0,s.expect)(i).toHaveBeenCalled()}),it("should return a connected device which calls state machine sendApdu",async()=>{const e={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:vi.fn(),isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},i=vi.fn(),a=vi.fn().mockReturnValue({sendApdu:i}),c=vi.fn().mockReturnValue({setupConnection:vi.fn()}),t=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>e,a,c),S=await(0,A.firstValueFrom)(t.startDiscovering()),o=await t.connect({deviceId:S.id,onDisconnect:vi.fn()});o.extract().sendApdu(Uint8Array.from([67,50])),(0,s.expect)(o).toEqual((0,C.Right)(new D.TransportConnectedDevice({id:"deviceId",deviceModel:m,type:"BLE",transport:"RN_BLE",sendApdu:s.expect.any(Function)}))),(0,s.expect)(i).toHaveBeenCalledWith(Uint8Array.from([67,50]))})}),describe("disconnect",()=>{let n;(0,s.beforeEach)(()=>{n=vi.fn().mockResolvedValueOnce([{readRSSI:vi.fn().mockResolvedValueOnce({discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})})}])}),it("should disconnect gracefully",async()=>{const e=vi.fn().mockImplementation((f,k)=>(k(null,{deviceId:"deviceId",connect:vi.fn().mockResolvedValue({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"}),discoverAllServicesAndCharacteristics:vi.fn().mockResolvedValueOnce({services:vi.fn().mockResolvedValueOnce({}),serviceUUIDs:["ledgerId"],rssi:64,id:"deviceId",localName:"knownDeviceName"})}),{remove:vi.fn()})),i={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:e,isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},a=vi.fn(),c=f=>new D.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:f.deviceApduSender,timeoutDuration:1e3,onTerminated:f.onTerminated}),t=vi.fn().mockReturnValue({setupConnection:vi.fn(),closeConnection:a}),S=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>i,c,t),o=vi.fn(),v=await(0,A.firstValueFrom)(S.startDiscovering()),w=await S.connect({deviceId:v.id,onDisconnect:o}),p=await S.disconnect({connectedDevice:w.extract()});(0,s.expect)(p).toEqual((0,C.Right)(void 0)),(0,s.expect)(o).toHaveBeenCalled(),(0,s.expect)(a).toHaveBeenCalled()}),it("should handle error while disconnecting",async()=>{const e=vi.fn().mockImplementation((f,k)=>(k(new Error("yolo"),null),{remove:vi.fn()})),i={connectedDevices:n,startDeviceScan:vi.fn(),stopDeviceScan:vi.fn(),onDeviceDisconnected:e,isDeviceConnected:vi.fn(),monitorCharacteristicForDevice:vi.fn(),writeCharacteristicWithoutResponseForDevice:vi.fn(),connectToDevice:vi.fn().mockResolvedValueOnce({id:"deviceId",rssi:64}),discoverAllServicesAndCharacteristicsForDevice:vi.fn()},a=vi.fn(),c=f=>new D.DeviceConnectionStateMachine({deviceId:"deviceId",deviceApduSender:f.deviceApduSender,timeoutDuration:1e3,onTerminated:f.onTerminated}),t=vi.fn().mockReturnValue({setupConnection:vi.fn(),closeConnection:a}),S=new r.RNBleTransport(u,()=>l,()=>{},()=>{},d,{},()=>i,c,t),o=vi.fn(),v=await(0,A.firstValueFrom)(S.startDiscovering()),w=await S.connect({deviceId:v.id,onDisconnect:o}),p=await S.disconnect({connectedDevice:w.extract()});(0,s.expect)(p).toEqual((0,C.Right)(void 0)),(0,s.expect)(o).toHaveBeenCalled()})})});
2
+ //# sourceMappingURL=RNBleTransport.test.js.map