@ledgerhq/device-transport-kit-react-native-ble 0.0.0-wip-20250214170223

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 (41) hide show
  1. package/LICENSE.MD +202 -0
  2. package/lib/cjs/api/index.js +2 -0
  3. package/lib/cjs/api/index.js.map +7 -0
  4. package/lib/cjs/api/model/Const.js +2 -0
  5. package/lib/cjs/api/model/Const.js.map +7 -0
  6. package/lib/cjs/api/model/Errors.js +2 -0
  7. package/lib/cjs/api/model/Errors.js.map +7 -0
  8. package/lib/cjs/api/transport/RNBleApduSender.js +2 -0
  9. package/lib/cjs/api/transport/RNBleApduSender.js.map +7 -0
  10. package/lib/cjs/api/transport/RNBleTransport.js +2 -0
  11. package/lib/cjs/api/transport/RNBleTransport.js.map +7 -0
  12. package/lib/cjs/index.js +2 -0
  13. package/lib/cjs/index.js.map +7 -0
  14. package/lib/cjs/package.json +62 -0
  15. package/lib/esm/api/index.js +2 -0
  16. package/lib/esm/api/index.js.map +7 -0
  17. package/lib/esm/api/model/Const.js +2 -0
  18. package/lib/esm/api/model/Const.js.map +7 -0
  19. package/lib/esm/api/model/Errors.js +2 -0
  20. package/lib/esm/api/model/Errors.js.map +7 -0
  21. package/lib/esm/api/transport/RNBleApduSender.js +2 -0
  22. package/lib/esm/api/transport/RNBleApduSender.js.map +7 -0
  23. package/lib/esm/api/transport/RNBleTransport.js +2 -0
  24. package/lib/esm/api/transport/RNBleTransport.js.map +7 -0
  25. package/lib/esm/index.js +2 -0
  26. package/lib/esm/index.js.map +7 -0
  27. package/lib/esm/package.json +62 -0
  28. package/lib/types/api/index.d.ts +3 -0
  29. package/lib/types/api/index.d.ts.map +1 -0
  30. package/lib/types/api/model/Const.d.ts +4 -0
  31. package/lib/types/api/model/Const.d.ts.map +1 -0
  32. package/lib/types/api/model/Errors.d.ts +22 -0
  33. package/lib/types/api/model/Errors.d.ts.map +1 -0
  34. package/lib/types/api/transport/RNBleApduSender.d.ts +41 -0
  35. package/lib/types/api/transport/RNBleApduSender.d.ts.map +1 -0
  36. package/lib/types/api/transport/RNBleTransport.d.ts +154 -0
  37. package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -0
  38. package/lib/types/index.d.ts +2 -0
  39. package/lib/types/index.d.ts.map +1 -0
  40. package/lib/types/tsconfig.prod.tsbuildinfo +1 -0
  41. package/package.json +61 -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.
@@ -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=5e3,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 = 5e3; // 5s;\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 a=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var u=(o,r)=>{for(var e in r)a(o,e,{get:r[e],enumerable:!0})},p=(o,r,e,d)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of c(r))!l.call(o,n)&&n!==e&&a(o,n,{get:()=>r[n],enumerable:!(d=s(r,n))||d.enumerable});return o};var i=o=>p(a({},"__esModule",{value:!0}),o);var N={};u(N,{BleDeviceGattServerError:()=>x,BleTransportNotSupportedError:()=>v,DeviceConnectionNotFound:()=>y,InternalDeviceNotFound:()=>D});module.exports=i(N);var t=require("@ledgerhq/device-management-kit");class v extends t.GeneralDmkError{constructor(e){super(e);this.err=e}_tag="BleTransportNotSupportedError"}class x extends t.GeneralDmkError{constructor(e){super(e);this.err=e}_tag="BleDeviceGattServerError"}class y extends t.GeneralDmkError{constructor(e){super(e);this.err=e}_tag="DeviceConnectionNotFound"}class D extends t.GeneralDmkError{constructor(e){super(e);this.err=e}_tag="InternalDeviceNotFound"}0&&(module.exports={BleDeviceGattServerError,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"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,EAAA,kCAAAC,EAAA,6BAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAN,GAAA,IAAAO,EAAgC,2CAEzB,MAAMJ,UAAsC,iBAAgB,CAEjE,YAAqBK,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,+BAI3B,CACO,MAAMN,UAAiC,iBAAgB,CAE5D,YAAqBM,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",
6
+ "names": ["Errors_exports", "__export", "BleDeviceGattServerError", "BleTransportNotSupportedError", "DeviceConnectionNotFound", "InternalDeviceNotFound", "__toCommonJS", "import_device_management_kit", "err"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var h=(s,i)=>{for(var r in i)c(s,r,{get:i[r],enumerable:!0})},y=(s,i,r,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let e of v(i))!l.call(s,e)&&e!==r&&c(s,e,{get:()=>i[e],enumerable:!(t=u(i,e))||t.enumerable});return s};var m=s=>y(c({},"__esModule",{value:!0}),s);var S={};h(S,{RNBleApduSender:()=>R});module.exports=m(S);var p=require("@ledgerhq/device-management-kit"),o=require("js-base64"),n=require("purify-ts"),a=require("rxjs");const D=3;class R{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:i,apduReceiverFactory:r,dependencies:t},e){this._dependencies=t,this._isDeviceReady=new a.BehaviorSubject(!1),this._logger=e("RNBleDeviceConnection"),this._apduSenderFactory=i,this._apduSender=n.Nothing,this._apduReceiver=r(),this._sendApduPromiseResolver=n.Nothing}onReceiveSetupApduResponse(i){const r=new Uint8Array(i),{device:t}=this._dependencies,[e]=r.slice(5);let d=t.mtu;e&&e+D>t.mtu&&(d=e),this._apduSender=n.Maybe.of(this._apduSenderFactory({frameSize:d})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(t=>{t.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduPromiseResolver.map(d=>d((0,n.Right)(e)))})}).mapLeft(t=>{this._sendApduPromiseResolver.map(e=>e((0,n.Left)(t)))})}onMonitor(i){if(!i.value)return;const r=o.Base64.toUint8Array(i.value);console.log("onMonitor:apdu",r),this._isDeviceReady.value?this.receiveApdu(r):this.onReceiveSetupApduResponse(r)}write(i){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(t,e)=>{!t&&e&&this.onMonitor(e)}),this._isDeviceReady.next(!1);const i=Uint8Array.from([8,0,0,0,0]);await this.write(o.Base64.fromUint8Array(i));let r;await new Promise(t=>{r=this._isDeviceReady.subscribe(e=>{e&&(t(),r.unsubscribe())})})}async sendApdu(i){if(!this._isDeviceReady.value)return Promise.resolve((0,n.Left)(new p.DeviceNotInitializedError("Unknown MTU")));const r=new Promise(e=>{this._sendApduPromiseResolver=n.Maybe.of(e)}),t=this._apduSender.caseOf({Just:e=>e.getFrames(i),Nothing:()=>[]});for(const e of t)try{await this.write(o.Base64.fromUint8Array(e.getRawData()))}catch(d){this._logger.error("Error sending frame",{data:{error:d}})}return r}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 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\ntype 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(\"RNBleDeviceConnection\");\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;\n\n if (ledgerMtu && ledgerMtu + FRAME_HEADER_SIZE > device.mtu) {\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 response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.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 console.log(\"onMonitor:apdu\", apdu);\n\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 requestMtuApdu = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuApdu));\n let sub: Subscription;\n await new Promise<void>((resolve) => {\n sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\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.error(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAaO,2CACPC,EAAuB,qBACvBC,EAAyD,qBACzDC,EAAmD,gBAEnD,MAAMC,EAAoB,EAsBnB,MAAMN,CAEb,CACU,cACA,eACA,QACA,YACS,mBACA,cACT,yBAIR,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,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", "maybeApduResponse", "apduResponse", "resolve", "error", "characteristic", "requestMtuApdu", "sub", "isReady", "resultPromise", "frames", "apduSender", "frame"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var h=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var T=(v,e)=>{for(var i in e)h(v,i,{get:e[i],enumerable:!0})},f=(v,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of y(e))!g.call(v,t)&&t!==i&&h(v,t,{get:()=>e[t],enumerable:!(r=I(e,t))||r.enumerable});return v};var N=v=>f(h({},"__esModule",{value:!0}),v);var B={};T(B,{RNBleTransport:()=>m,RNBleTransportFactory:()=>C,rnBleTransportIdentifier:()=>E});module.exports=N(B);var c=require("react-native"),S=require("react-native-ble-plx"),p=require("@ledgerhq/device-management-kit"),n=require("purify-ts"),s=require("rxjs"),l=require("../model/Const"),D=require("../model/Errors"),_=require("../transport/RNBleApduSender");const E="RN_BLE";class m{constructor(e,i,r,t){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=r;this._apduReceiverFactory=t;this._logger=i("ReactNativeBleTransport"),this._manager=new S.BleManager,this._isSupported=n.Maybe.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return this._internalDevicesById.clear(),(0,s.from)(this.requestPermission()).pipe((0,s.switchMap)(i=>{if(!i)throw new Error("BLE not supported");return(0,s.merge)(this._discoverKnownDevices(e),this._discoverNewDevices(e))}))}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return(0,n.EitherAsync)(async({liftEither:i,throwE:r})=>{const t=await i(n.Maybe.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new p.UnknownDeviceError(`Unknown device ${e.deviceId}`)));let o;try{o=await this._manager.connectToDevice(e.deviceId,{requestMTU:l.DEFAULT_MTU}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(d){return r(new p.OpeningConnectionError(d))}const a=new _.RNBleApduSender({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:o,internalDevice:t,manager:this._manager}},this._loggerServiceFactory),u=new p.DeviceConnectionStateMachine({deviceId:e.deviceId,deviceApduSender:a,timeoutDuration:l.BLE_DISCONNECT_TIMEOUT,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const d=this._internalDevicesById.get(e.deviceId);d&&d.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await a.setupConnection(),this._deviceConnectionsById.set(t.id,u),t.disconnectionSubscription=this._manager.onDeviceDisconnected(t.id,(...d)=>{this._handleDeviceDisconnected(...d)}),t.lastDiscoveredTimeStamp=n.Maybe.zero(),new p.TransportConnectedDevice({id:t.id,deviceModel:t.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...d)=>u.sendApdu(...d),transport:this.identifier})}).run()}async disconnect(e){return n.Maybe.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(r=>{r.closeConnection()}),Promise.resolve((0,n.Right)(void 0))}_isDiscoveredDeviceLost(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+l.CONNECTION_LOST_DELAY,Nothing:()=>(e.lastDiscoveredTimeStamp=n.Maybe.of(Date.now()),!0)})}listenToKnownDevices(){return(0,s.from)([])}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(c.Platform.OS==="ios")return this._isSupported=n.Maybe.of(!0),!0;if(c.Platform.OS==="android"&&c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(c.Platform.Version.toString(),10)<31){const i=await c.PermissionsAndroid.request(c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=n.Maybe.of(i===c.PermissionsAndroid.RESULTS.GRANTED)}if(c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN&&c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT){const i=await c.PermissionsAndroid.requestMultiple([c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,c.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,c.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=n.Maybe.of(i["android.permission.BLUETOOTH_CONNECT"]===c.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===c.PermissionsAndroid.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===c.PermissionsAndroid.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=n.Maybe.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const r=n.Maybe.fromNullable(e?.serviceUUIDs?.find(o=>i.includes(o)));return n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).isJust()?n.Nothing:r.mapOrDefault(o=>{const a=this._deviceModelDataSource.getBluetoothServicesInfos();return n.Maybe.fromNullable(a[o]).map(d=>({discoveredDevice:{id:e.id,name:e.localName||d.deviceModel.productName,deviceModel:d.deviceModel,transport:this.identifier},bleDeviceInfos:d}))},n.Nothing)}_handleLostDiscoveredDevices(e){this._internalDevicesById.forEach(i=>{this._isDiscoveredDeviceLost(i)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,available:!1}))})}_emitDiscoveredDevice(e,i,r){e.next(r);const t={id:r.id,bleDeviceInfos:i,discoveredDevice:r,available:!0,lastDiscoveredTimeStamp:n.Maybe.of(Date.now())};this._internalDevicesById.set(r.id,{...t,disconnectionSubscription:this._manager.onDeviceDisconnected(r.id,()=>{e.next({...r,available:!1})})})}_discoverNewDevices(e){return new s.Observable(i=>{this._manager.startDeviceScan(null,null,(r,t)=>{if(this._handleLostDiscoveredDevices(i),r||!t){i.error(r);return}this._getDiscoveredDeviceFrom(t,e).map(({discoveredDevice:o,bleDeviceInfos:a})=>{this._emitDiscoveredDevice(i,a,o)})})})}_discoverKnownDevices(e){return(0,s.from)(this._manager.connectedDevices(e)).pipe((0,s.switchMap)(i=>new s.Observable(r=>{i.forEach(t=>{this._getDiscoveredDeviceFrom(t,e).map(({bleDeviceInfos:o,discoveredDevice:a})=>{this._emitDiscoveredDevice(r,o,a)})})})))}_handleDeviceDisconnected(e,i){if(e&&this._logger.error("device disconnected error",{data:{error:e,device:i}}),!i){this._logger.info("disconnected handler didn't found device");return}n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id)).map(o=>{o.eventDeviceDetached()});let t;(0,s.from)([0]).pipe((0,s.switchMap)(async()=>{try{t=await i.connect({requestMTU:l.DEFAULT_MTU}),t=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(t)}catch(o){throw this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:o}}),n.Maybe.fromNullable(this._deviceConnectionsById.get(i.id)).map(a=>{a.closeConnection()}),o}return i}),(0,s.retry)({count:5,delay:l.BLE_DISCONNECT_TIMEOUT/5})).subscribe({next:o=>this._logger.info("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:o}}),error:o=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:o}})}})}async _handleDeviceReconnected(e){const i=n.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new D.DeviceConnectionNotFound),r=n.Maybe.fromNullable(this._internalDevicesById.get(e.id)).toEither(new D.InternalDeviceNotFound);return(0,n.EitherAsync)(async({liftEither:t})=>{const o=await t(i),a=await t(r);o.setDependencies({device:e,manager:this._manager,internalDevice:a}),await o.setupConnection(),o.eventDeviceAttached()}).run()}}const C=({deviceModelDataSource:v,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:r})=>new m(v,e,i,r);0&&(module.exports={RNBleTransport,RNBleTransportFactory,rnBleTransportIdentifier});
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 DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDiscoveredDevice,\n type TransportFactory,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, EitherAsync, Maybe, Nothing, Right } from \"purify-ts\";\nimport {\n from,\n merge,\n Observable,\n retry,\n type Subscriber,\n switchMap,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n DeviceConnectionNotFound,\n InternalDeviceNotFound,\n} from \"@api/model/Errors\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _isSupported: Maybe<boolean>;\n private _internalDevicesById: Map<DeviceId, RNBleInternalDevice>;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._manager = new BleManager();\n this._isSupported = Maybe.zero();\n this._internalDevicesById = new Map();\n this._deviceConnectionsById = new Map();\n this.requestPermission();\n }\n\n /**\n * Starts the discovery process to find Bluetooth devices that match specific criteria.\n *\n * This method clears the internal device cache and requests necessary permissions\n * before initiating the discovery of both known and new devices. If the Bluetooth\n * Low Energy (BLE) feature is not supported, an error is thrown.\n *\n * @return {Observable<TransportDiscoveredDevice>} An observable emitting discovered devices\n * that match the specified Bluetooth services.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n const ledgerUuids = this._deviceModelDataSource.getBluetoothServices();\n this._internalDevicesById.clear();\n return from(this.requestPermission()).pipe(\n switchMap((isSupported) => {\n if (!isSupported) {\n throw new Error(\"BLE not supported\");\n }\n return merge(\n this._discoverKnownDevices(ledgerUuids),\n this._discoverNewDevices(ledgerUuids),\n );\n }),\n );\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._manager.stopDeviceScan();\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ liftEither, throwE }) => {\n const internalDevice = await liftEither(\n Maybe.fromNullable(\n this._internalDevicesById.get(params.deviceId),\n ).toEither(\n new UnknownDeviceError(`Unknown device ${params.deviceId}`),\n ),\n );\n\n let device: Device;\n\n try {\n device = await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n } catch (error) {\n return throwE(new OpeningConnectionError(error));\n }\n\n const deviceApduSender = new RNBleApduSender(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: {\n device,\n internalDevice,\n manager: this._manager,\n },\n },\n this._loggerServiceFactory,\n );\n\n const deviceConnectionStateMachine =\n new DeviceConnectionStateMachine<RNBleApduSenderDependencies>({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: BLE_DISCONNECT_TIMEOUT,\n onTerminated: () => {\n params.onDisconnect(params.deviceId);\n this._deviceConnectionsById.delete(params.deviceId);\n const iDevice = this._internalDevicesById.get(params.deviceId);\n\n if (iDevice) {\n iDevice.disconnectionSubscription.remove();\n }\n\n this._internalDevicesById.delete(params.deviceId);\n },\n });\n\n await deviceApduSender.setupConnection();\n\n this._deviceConnectionsById.set(\n internalDevice.id,\n deviceConnectionStateMachine,\n );\n\n internalDevice.disconnectionSubscription =\n this._manager.onDeviceDisconnected(internalDevice.id, (...args) => {\n this._handleDeviceDisconnected(...args);\n });\n\n internalDevice.lastDiscoveredTimeStamp = Maybe.zero();\n\n return new TransportConnectedDevice({\n id: internalDevice.id,\n deviceModel: internalDevice.discoveredDevice.deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(params.connectedDevice.id),\n );\n\n deviceConnection.map((d) => {\n d.closeConnection();\n });\n\n return Promise.resolve(Right(undefined));\n }\n\n private _isDiscoveredDeviceLost(internalDevice: RNBleInternalDevice) {\n return internalDevice.lastDiscoveredTimeStamp.caseOf({\n Just: (lastDiscoveredTimeStamp) =>\n Date.now() > lastDiscoveredTimeStamp + CONNECTION_LOST_DELAY,\n Nothing: () => {\n internalDevice.lastDiscoveredTimeStamp = Maybe.of(Date.now());\n return true;\n },\n });\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return this._isSupported.caseOf({\n Just: (isSupported) => isSupported,\n Nothing: () => {\n throw new Error(\"Should initialize permission\");\n },\n });\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Requests the necessary permissions based on the operating system.\n * For iOS, it automatically sets the permissions as granted.\n * For Android, it checks and requests location, Bluetooth scan, and Bluetooth connect permissions, depending on the API level.\n * If permissions are granted, updates the internal support state and logs the result.\n *\n * @return {Promise<boolean>} A promise that resolves to true if the required permissions are granted, otherwise false.\n */\n async requestPermission(): Promise<boolean> {\n if (Platform.OS === \"ios\") {\n this._isSupported = Maybe.of(true);\n return true;\n }\n\n if (\n Platform.OS === \"android\" &&\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"]\n ) {\n const apiLevel = parseInt(Platform.Version.toString(), 10);\n\n if (apiLevel < 31) {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n );\n this._isSupported = Maybe.of(\n granted === PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n }\n if (\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"] &&\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"]\n ) {\n const result = await PermissionsAndroid.requestMultiple([\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_SCAN\"],\n PermissionsAndroid.PERMISSIONS[\"BLUETOOTH_CONNECT\"],\n PermissionsAndroid.PERMISSIONS[\"ACCESS_FINE_LOCATION\"],\n ]);\n\n this._isSupported = Maybe.of(\n result[\"android.permission.BLUETOOTH_CONNECT\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.BLUETOOTH_SCAN\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"] &&\n result[\"android.permission.ACCESS_FINE_LOCATION\"] ===\n PermissionsAndroid.RESULTS[\"GRANTED\"],\n );\n\n return true;\n }\n }\n\n this._logger.error(\"Permission have not been granted\", {\n data: { isSupported: this.isSupported() },\n });\n\n this._isSupported = Maybe.of(false);\n return false;\n }\n\n /**\n * Retrieves a discovered device and its BLE device information, if available, from the provided input.\n *\n * @param {Device} rnDevice - The Bluetooth device to analyze for discovery.\n * @param {string[]} ledgerUuids - A list of UUIDs associated with the target Ledger devices.\n * @return {Maybe<{ bleDeviceInfos: BleDeviceInfos; discoveredDevice: TransportDiscoveredDevice }>} A Maybe object containing the discovered device and its BLE information, or Nothing if the device or information cannot be determined.\n */\n private _getDiscoveredDeviceFrom(\n rnDevice: Device,\n ledgerUuids: string[],\n ): Maybe<{\n bleDeviceInfos: BleDeviceInfos;\n discoveredDevice: TransportDiscoveredDevice;\n }> {\n const maybeUuid = Maybe.fromNullable(\n rnDevice?.serviceUUIDs?.find((uuid) => ledgerUuids.includes(uuid)),\n );\n\n const existingInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(rnDevice.id),\n );\n\n if (existingInternalDevice.isJust()) {\n return Nothing;\n }\n\n return maybeUuid.mapOrDefault((uuid) => {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const maybeBleDeviceInfos = Maybe.fromNullable(serviceToBleInfos[uuid]);\n\n return maybeBleDeviceInfos.map((bleDeviceInfos) => {\n const discoveredDevice: TransportDiscoveredDevice = {\n id: rnDevice.id,\n name: rnDevice.localName || bleDeviceInfos.deviceModel.productName,\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n };\n\n return {\n discoveredDevice,\n bleDeviceInfos,\n };\n });\n }, Nothing);\n }\n\n /**\n * Handles the processing of devices that have been determined to be \"lost\" by iterating\n * through a collection of internal devices, identifying lost devices, updating their status,\n * and notifying a subscriber about the change.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber - The observer that will be notified\n * when a device is marked as lost, including updated device information with its availability set to false.\n * @return {void} This method does not return a value.\n */\n private _handleLostDiscoveredDevices(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n ) {\n this._internalDevicesById.forEach((internalDevice) => {\n if (this._isDiscoveredDeviceLost(internalDevice)) {\n this._internalDevicesById.delete(internalDevice.id);\n subscriber.next({\n ...internalDevice.discoveredDevice,\n available: false,\n });\n }\n });\n }\n\n /**\n * Emits a discovered device to the provided subscriber and manages internal state\n * for the discovered device, including handling its availability status and disconnection events.\n *\n * @param {Subscriber<TransportDiscoveredDevice>} subscriber The subscriber to emit the discovered device to.\n * @param {BleDeviceInfos} bleDeviceInfos The BLE device information associated with the discovered device.\n * @param {TransportDiscoveredDevice} discoveredDevice The newly discovered device to be emitted.\n * @return {void} Does*/\n private _emitDiscoveredDevice(\n subscriber: Subscriber<TransportDiscoveredDevice>,\n bleDeviceInfos: BleDeviceInfos,\n discoveredDevice: TransportDiscoveredDevice,\n ) {\n subscriber.next(discoveredDevice);\n const internalDevice = {\n id: discoveredDevice.id,\n bleDeviceInfos,\n discoveredDevice,\n available: true,\n lastDiscoveredTimeStamp: Maybe.of(Date.now()),\n };\n this._internalDevicesById.set(discoveredDevice.id, {\n ...internalDevice,\n disconnectionSubscription: this._manager.onDeviceDisconnected(\n discoveredDevice.id,\n () => {\n // this._internalDevicesById.delete(discoveredDevice.id);\n subscriber.next({ ...discoveredDevice, available: false });\n },\n ),\n });\n }\n\n /**\n * Discovers new devices by scanning for BLE devices and filtering them based on the provided ledger UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs used to identify relevant ledger devices.\n * @return {Observable<TransportDiscoveredDevice>} An observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverNewDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return new Observable<TransportDiscoveredDevice>((subscriber) => {\n this._manager.startDeviceScan(null, null, (error, device) => {\n this._handleLostDiscoveredDevices(subscriber);\n\n if (error || !device) {\n subscriber.error(error);\n return;\n }\n\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ discoveredDevice, bleDeviceInfos }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n });\n }\n\n /**\n * Discovers and emits known ledger devices based on the provided UUIDs.\n *\n * @param {string[]} ledgerUuids - An array of UUIDs representing the target ledger devices to discover.\n * @return {Observable<TransportDiscoveredDevice>} An Observable that emits discovered devices matching the provided UUIDs.\n */\n private _discoverKnownDevices(\n ledgerUuids: string[],\n ): Observable<TransportDiscoveredDevice> {\n return from(this._manager.connectedDevices(ledgerUuids)).pipe(\n switchMap(\n (devices) =>\n new Observable<TransportDiscoveredDevice>((subscriber) => {\n devices.forEach((device) => {\n this._getDiscoveredDeviceFrom(device, ledgerUuids).map(\n ({ bleDeviceInfos, discoveredDevice }) => {\n this._emitDiscoveredDevice(\n subscriber,\n bleDeviceInfos,\n discoveredDevice,\n );\n },\n );\n });\n }),\n ),\n );\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @param {DisconnectHandler} onDisconnect - A callback function to be called if the reconnection attempts fail completely.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n }\n\n if (!device) {\n this._logger.info(\"disconnected handler didn't found device\");\n return;\n }\n\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n );\n\n errorOrDeviceConnection.map((deviceConnection) => {\n deviceConnection.eventDeviceDetached();\n });\n\n let reconnectedDevice: Device;\n\n from([0])\n .pipe(\n switchMap(async () => {\n try {\n reconnectedDevice = await device.connect({\n requestMTU: DEFAULT_MTU,\n });\n reconnectedDevice =\n await device.discoverAllServicesAndCharacteristics();\n await this._handleDeviceReconnected(reconnectedDevice);\n } catch (e) {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnecting failed\",\n { data: { e } },\n );\n\n Maybe.fromNullable(this._deviceConnectionsById.get(device.id)).map(\n (deviceConnection) => {\n deviceConnection.closeConnection();\n },\n );\n\n throw e;\n }\n\n return device;\n }),\n retry({\n count: 5,\n delay: BLE_DISCONNECT_TIMEOUT / 5,\n }),\n )\n .subscribe({\n next: (value) =>\n this._logger.info(\n \"[_handleDeviceDisconnected] Got new device after reconnection\",\n { data: { value } },\n ),\n error: (e) => {\n this._logger.error(\n \"[_handleDeviceDisconnected] Reconnection failed after all retries\",\n { data: { e } },\n );\n },\n });\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The device object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n const errorOrInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(device.id),\n ).toEither(new InternalDeviceNotFound());\n\n return EitherAsync(async ({ liftEither }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const internalDevice = await liftEither(errorOrInternalDevice);\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection();\n\n deviceConnectionStateMachine.eventDeviceAttached();\n }).run();\n }\n}\n\nexport const RNBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new RNBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,0BAAAC,EAAA,6BAAAC,IAAA,eAAAC,EAAAL,GAAA,IAAAM,EAA6C,wBAC7CC,EAAuD,g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ClC,CAAC,CACH,EACC,UAAU,CACT,KAAOqB,GACL,KAAK,QAAQ,KACX,gEACA,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CACpB,EACF,MAAQD,GAAM,CACZ,KAAK,QAAQ,MACX,oEACA,CAAE,KAAM,CAAE,EAAAA,CAAE,CAAE,CAChB,CACF,CACF,CAAC,CACL,CAaA,MAAc,yBAAyBpB,EAAgB,CACrD,MAAMsB,EAA0B,QAAM,aACpC,KAAK,uBAAuB,IAAItB,EAAO,EAAE,CAC3C,EAAE,SAAS,IAAI,0BAA0B,EAEnCuB,EAAwB,QAAM,aAClC,KAAK,qBAAqB,IAAIvB,EAAO,EAAE,CACzC,EAAE,SAAS,IAAI,wBAAwB,EAEvC,SAAO,eAAY,MAAO,CAAE,WAAAH,CAAW,IAAM,CAC3C,MAAMM,EAA+B,MAAMN,EACzCyB,CACF,EAEMvB,EAAiB,MAAMF,EAAW0B,CAAqB,EAE7DpB,EAA6B,gBAAgB,CAC3C,OAAAH,EACA,QAAS,KAAK,SACd,eAAAD,CACF,CAAC,EAED,MAAMI,EAA6B,gBAAgB,EAEnDA,EAA6B,oBAAoB,CACnD,CAAC,EAAE,IAAI,CACT,CACF,CAEO,MAAMxB,EAA0C,CAAC,CACtD,sBAAA6C,EACA,qBAAAC,EACA,yBAAAC,EACA,2BAAAC,CACF,IACE,IAAIjD,EACF8C,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", "ledgerUuids", "isSupported", "params", "liftEither", "throwE", "internalDevice", "device", "error", "deviceApduSender", "deviceConnectionStateMachine", "iDevice", "args", "d", "lastDiscoveredTimeStamp", "granted", "result", "rnDevice", "maybeUuid", "uuid", "serviceToBleInfos", "bleDeviceInfos", "subscriber", "discoveredDevice", "devices", "deviceConnection", "reconnectedDevice", "e", "value", "errorOrDeviceConnection", "errorOrInternalDevice", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var a=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var p=(r,o,f,x)=>{if(o&&typeof o=="object"||typeof o=="function")for(let e of c(o))!d.call(r,e)&&e!==f&&a(r,e,{get:()=>o[e],enumerable:!(x=b(o,e))||x.enumerable});return r},t=(r,o,f)=>(p(r,o,"default"),f&&p(f,o,"default"));var g=r=>p(a({},"__esModule",{value:!0}),r);var m={};module.exports=g(m);t(m,require("./api"),module.exports);0&&(module.exports={...require("./api")});
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts"],
4
+ "sourcesContent": ["export * from \"./api\";\n"],
5
+ "mappings": "iaAAA,IAAAA,EAAA,kBAAAC,EAAAD,GAAAE,EAAAF,EAAc,iBAAd",
6
+ "names": ["src_exports", "__toCommonJS", "__reExport"]
7
+ }
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@ledgerhq/device-transport-kit-react-native-ble",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "private": false,
6
+ "exports": {
7
+ ".": {
8
+ "types": "./lib/types/index.d.ts",
9
+ "import": "./lib/esm/index.js",
10
+ "require": "./lib/cjs/index.js"
11
+ },
12
+ "./*": {
13
+ "types": "./lib/types/*",
14
+ "import": "./lib/esm/*",
15
+ "require": "./lib/cjs/*"
16
+ }
17
+ },
18
+ "files": [
19
+ "./lib"
20
+ ],
21
+ "scripts": {
22
+ "prebuild": "rimraf lib",
23
+ "build": "pnpm lmdk-build --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
24
+ "dev": "concurrently \"pnpm watch:builds\" \"pnpm watch:types\"",
25
+ "watch:builds": "pnpm lmdk-watch --entryPoints src/index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
26
+ "watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\"",
27
+ "lint": "eslint",
28
+ "lint:fix": "pnpm lint --fix",
29
+ "postpack": "find . -name '*.tgz' -exec cp {} ../../../dist/ \\; ",
30
+ "prettier": "prettier . --check",
31
+ "prettier:fix": "prettier . --write",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest run --passWithNoTests",
34
+ "test:watch": "vitest --passWithNoTests",
35
+ "test:coverage": "vitest run --coverage --passWithNoTests"
36
+ },
37
+ "dependencies": {
38
+ "@sentry/minimal": "^6.19.7",
39
+ "js-base64": "^3.7.7",
40
+ "purify-ts": "^2.1.0",
41
+ "uuid": "^10.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "@ledgerhq/device-management-kit": "workspace:*",
45
+ "@ledgerhq/esbuild-tools": "workspace:*",
46
+ "@ledgerhq/eslint-config-dsdk": "workspace:*",
47
+ "@ledgerhq/vitest-config-dmk": "workspace:*",
48
+ "@ledgerhq/prettier-config-dsdk": "workspace:*",
49
+ "@ledgerhq/tsconfig-dsdk": "workspace:*",
50
+ "@types/uuid": "^10.0.0",
51
+ "react-native": "^0.76.3",
52
+ "react-native-ble-plx": "^3.2.1",
53
+ "rxjs": "^7.8.1",
54
+ "ts-node": "^10.9.2"
55
+ },
56
+ "peerDependencies": {
57
+ "@ledgerhq/device-management-kit": "workspace:*",
58
+ "react-native-ble-plx": "^3.2.1",
59
+ "react-native": ">0.70",
60
+ "rxjs": "^7.8.1"
61
+ }
62
+ }
@@ -0,0 +1,2 @@
1
+ export*from"./model/Errors";import{RNBleTransport as t,RNBleTransportFactory as n,rnBleTransportIdentifier as p}from"./transport/RNBleTransport";export{t as RNBleTransport,n as RNBleTransportFactory,p as rnBleTransportIdentifier};
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": "AAAA,WAAc,iBACd,OACE,kBAAAA,EACA,yBAAAC,EACA,4BAAAC,MACK",
6
+ "names": ["RNBleTransport", "RNBleTransportFactory", "rnBleTransportIdentifier"]
7
+ }
@@ -0,0 +1,2 @@
1
+ const T=156,o=5e3,t=1e4;export{t as BLE_DISCONNECT_TIMEOUT,o as CONNECTION_LOST_DELAY,T as 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 = 5e3; // 5s;\nexport const BLE_DISCONNECT_TIMEOUT = 10e3; // 10s;\n"],
5
+ "mappings": "AAAO,MAAMA,EAAc,IACdC,EAAwB,IACxBC,EAAyB",
6
+ "names": ["DEFAULT_MTU", "CONNECTION_LOST_DELAY", "BLE_DISCONNECT_TIMEOUT"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{GeneralDmkError as e}from"@ledgerhq/device-management-kit";class a extends e{constructor(r){super(r);this.err=r}_tag="BleTransportNotSupportedError"}class d extends e{constructor(r){super(r);this.err=r}_tag="BleDeviceGattServerError"}class s extends e{constructor(r){super(r);this.err=r}_tag="DeviceConnectionNotFound"}class c extends e{constructor(r){super(r);this.err=r}_tag="InternalDeviceNotFound"}export{d as BleDeviceGattServerError,a as BleTransportNotSupportedError,s as DeviceConnectionNotFound,c as 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"],
5
+ "mappings": "AAAA,OAAS,mBAAAA,MAAuB,kCAEzB,MAAMC,UAAsCD,CAAgB,CAEjE,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,+BAI3B,CACO,MAAMC,UAAiCH,CAAgB,CAE5D,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAME,UAAiCJ,CAAgB,CAE5D,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,0BAI3B,CACO,MAAMG,UAA+BL,CAAgB,CAE1D,YAAqBE,EAAe,CAClC,MAAMA,CAAG,EADU,SAAAA,CAErB,CAHkB,KAAO,wBAI3B",
6
+ "names": ["GeneralDmkError", "BleTransportNotSupportedError", "err", "BleDeviceGattServerError", "DeviceConnectionNotFound", "InternalDeviceNotFound"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{DeviceNotInitializedError as p}from"@ledgerhq/device-management-kit";import{Base64 as s}from"js-base64";import{Left as d,Maybe as o,Nothing as c,Right as a}from"purify-ts";import{BehaviorSubject as u}from"rxjs";const v=3;class R{_dependencies;_isDeviceReady;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_sendApduPromiseResolver;constructor({apduSenderFactory:i,apduReceiverFactory:t,dependencies:r},e){this._dependencies=r,this._isDeviceReady=new u(!1),this._logger=e("RNBleDeviceConnection"),this._apduSenderFactory=i,this._apduSender=c,this._apduReceiver=t(),this._sendApduPromiseResolver=c}onReceiveSetupApduResponse(i){const t=new Uint8Array(i),{device:r}=this._dependencies,[e]=t.slice(5);let n=r.mtu;e&&e+v>r.mtu&&(n=e),this._apduSender=o.of(this._apduSenderFactory({frameSize:n})),this._isDeviceReady.next(!0)}receiveApdu(i){this._apduReceiver.handleFrame(i).map(r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduPromiseResolver.map(n=>n(a(e)))})}).mapLeft(r=>{this._sendApduPromiseResolver.map(e=>e(d(r)))})}onMonitor(i){if(!i.value)return;const t=s.toUint8Array(i.value);console.log("onMonitor:apdu",t),this._isDeviceReady.value?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)}write(i){return this._dependencies.manager.writeCharacteristicWithoutResponseForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.writeCmdUuid,i)}getDependencies(){return this._dependencies}setDependencies(i){this._dependencies=i}async setupConnection(){this._dependencies.manager.monitorCharacteristicForDevice(this._dependencies.device.id,this._dependencies.internalDevice.bleDeviceInfos.serviceUuid,this._dependencies.internalDevice.bleDeviceInfos.notifyUuid,(r,e)=>{!r&&e&&this.onMonitor(e)}),this._isDeviceReady.next(!1);const i=Uint8Array.from([8,0,0,0,0]);await this.write(s.fromUint8Array(i));let t;await new Promise(r=>{t=this._isDeviceReady.subscribe(e=>{e&&(r(),t.unsubscribe())})})}async sendApdu(i){if(!this._isDeviceReady.value)return Promise.resolve(d(new p("Unknown MTU")));const t=new Promise(e=>{this._sendApduPromiseResolver=o.of(e)}),r=this._apduSender.caseOf({Just:e=>e.getFrames(i),Nothing:()=>[]});for(const e of r)try{await this.write(s.fromUint8Array(e.getRawData()))}catch(n){this._logger.error("Error sending frame",{data:{error:n}})}return t}closeConnection(){this._dependencies.device.cancelConnection()}}export{R as 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 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\ntype 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(\"RNBleDeviceConnection\");\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;\n\n if (ledgerMtu && ledgerMtu + FRAME_HEADER_SIZE > device.mtu) {\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 response = this._apduReceiver.handleFrame(apdu);\n\n response\n .map((maybeApduResponse) => {\n maybeApduResponse.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 console.log(\"onMonitor:apdu\", apdu);\n\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 requestMtuApdu = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n await this.write(Base64.fromUint8Array(requestMtuApdu));\n let sub: Subscription;\n await new Promise<void>((resolve) => {\n sub = this._isDeviceReady.subscribe((isReady) => {\n if (isReady) {\n resolve();\n sub.unsubscribe();\n }\n });\n });\n }\n\n async sendApdu(apdu: Uint8Array): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady.value) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of(resolve);\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.error(\"Error sending frame\", { data: { error } });\n }\n }\n\n return resultPromise;\n }\n\n public closeConnection() {\n this._dependencies.device.cancelConnection();\n }\n}\n"],
5
+ "mappings": "AAMA,OASE,6BAAAA,MAIK,kCACP,OAAS,UAAAC,MAAc,YACvB,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,mBAAAC,M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AASR,EAAO,CACd,KAAK,QAAQ,MAAM,sBAAuB,CAAE,KAAM,CAAE,MAAAA,CAAM,CAAE,CAAC,CAC/D,CAGF,OAAOK,CACT,CAEO,iBAAkB,CACvB,KAAK,cAAc,OAAO,iBAAiB,CAC7C,CACF",
6
+ "names": ["DeviceNotInitializedError", "Base64", "Left", "Maybe", "Nothing", "Right", "BehaviorSubject", "FRAME_HEADER_SIZE", "RNBleApduSender", "apduSenderFactory", "apduReceiverFactory", "dependencies", "loggerServiceFactory", "value", "mtuResponse", "device", "ledgerMtu", "frameSize", "apdu", "maybeApduResponse", "apduResponse", "resolve", "error", "characteristic", "requestMtuApdu", "sub", "isReady", "resultPromise", "frames", "apduSender", "frame"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{PermissionsAndroid as c,Platform as l}from"react-native";import{BleManager as I}from"react-native-ble-plx";import{DeviceConnectionStateMachine as y,OpeningConnectionError as g,TransportConnectedDevice as T,UnknownDeviceError as f}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Maybe as o,Nothing as h,Right as N}from"purify-ts";import{from as d,merge as E,Observable as S,retry as C,switchMap as p}from"rxjs";import{BLE_DISCONNECT_TIMEOUT as _,CONNECTION_LOST_DELAY as B,DEFAULT_MTU as m}from"../model/Const";import{DeviceConnectionNotFound as O,InternalDeviceNotFound as w}from"../model/Errors";import{RNBleApduSender as b}from"../transport/RNBleApduSender";const G="RN_BLE";class R{constructor(e,i,t,r){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=r;this._logger=i("ReactNativeBleTransport"),this._manager=new I,this._isSupported=o.zero(),this._internalDevicesById=new Map,this._deviceConnectionsById=new Map,this.requestPermission()}_logger;_isSupported;_internalDevicesById;_deviceConnectionsById;_manager;identifier="RN_BLE";startDiscovering(){const e=this._deviceModelDataSource.getBluetoothServices();return this._internalDevicesById.clear(),d(this.requestPermission()).pipe(p(i=>{if(!i)throw new Error("BLE not supported");return E(this._discoverKnownDevices(e),this._discoverNewDevices(e))}))}async stopDiscovering(){await this._manager.stopDeviceScan()}async connect(e){return u(async({liftEither:i,throwE:t})=>{const r=await i(o.fromNullable(this._internalDevicesById.get(e.deviceId)).toEither(new f(`Unknown device ${e.deviceId}`)));let n;try{n=await this._manager.connectToDevice(e.deviceId,{requestMTU:m}),await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId)}catch(a){return t(new g(a))}const s=new b({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:n,internalDevice:r,manager:this._manager}},this._loggerServiceFactory),v=new y({deviceId:e.deviceId,deviceApduSender:s,timeoutDuration:_,onTerminated:()=>{e.onDisconnect(e.deviceId),this._deviceConnectionsById.delete(e.deviceId);const a=this._internalDevicesById.get(e.deviceId);a&&a.disconnectionSubscription.remove(),this._internalDevicesById.delete(e.deviceId)}});return await s.setupConnection(),this._deviceConnectionsById.set(r.id,v),r.disconnectionSubscription=this._manager.onDeviceDisconnected(r.id,(...a)=>{this._handleDeviceDisconnected(...a)}),r.lastDiscoveredTimeStamp=o.zero(),new T({id:r.id,deviceModel:r.discoveredDevice.deviceModel,type:"BLE",sendApdu:(...a)=>v.sendApdu(...a),transport:this.identifier})}).run()}async disconnect(e){return o.fromNullable(this._deviceConnectionsById.get(e.connectedDevice.id)).map(t=>{t.closeConnection()}),Promise.resolve(N(void 0))}_isDiscoveredDeviceLost(e){return e.lastDiscoveredTimeStamp.caseOf({Just:i=>Date.now()>i+B,Nothing:()=>(e.lastDiscoveredTimeStamp=o.of(Date.now()),!0)})}listenToKnownDevices(){return d([])}isSupported(){return this._isSupported.caseOf({Just:e=>e,Nothing:()=>{throw new Error("Should initialize permission")}})}getIdentifier(){return this.identifier}async requestPermission(){if(l.OS==="ios")return this._isSupported=o.of(!0),!0;if(l.OS==="android"&&c.PERMISSIONS.ACCESS_FINE_LOCATION){if(parseInt(l.Version.toString(),10)<31){const i=await c.request(c.PERMISSIONS.ACCESS_FINE_LOCATION);this._isSupported=o.of(i===c.RESULTS.GRANTED)}if(c.PERMISSIONS.BLUETOOTH_SCAN&&c.PERMISSIONS.BLUETOOTH_CONNECT){const i=await c.requestMultiple([c.PERMISSIONS.BLUETOOTH_SCAN,c.PERMISSIONS.BLUETOOTH_CONNECT,c.PERMISSIONS.ACCESS_FINE_LOCATION]);return this._isSupported=o.of(i["android.permission.BLUETOOTH_CONNECT"]===c.RESULTS.GRANTED&&i["android.permission.BLUETOOTH_SCAN"]===c.RESULTS.GRANTED&&i["android.permission.ACCESS_FINE_LOCATION"]===c.RESULTS.GRANTED),!0}}return this._logger.error("Permission have not been granted",{data:{isSupported:this.isSupported()}}),this._isSupported=o.of(!1),!1}_getDiscoveredDeviceFrom(e,i){const t=o.fromNullable(e?.serviceUUIDs?.find(n=>i.includes(n)));return o.fromNullable(this._internalDevicesById.get(e.id)).isJust()?h:t.mapOrDefault(n=>{const s=this._deviceModelDataSource.getBluetoothServicesInfos();return o.fromNullable(s[n]).map(a=>({discoveredDevice:{id:e.id,name:e.localName||a.deviceModel.productName,deviceModel:a.deviceModel,transport:this.identifier},bleDeviceInfos:a}))},h)}_handleLostDiscoveredDevices(e){this._internalDevicesById.forEach(i=>{this._isDiscoveredDeviceLost(i)&&(this._internalDevicesById.delete(i.id),e.next({...i.discoveredDevice,available:!1}))})}_emitDiscoveredDevice(e,i,t){e.next(t);const r={id:t.id,bleDeviceInfos:i,discoveredDevice:t,available:!0,lastDiscoveredTimeStamp:o.of(Date.now())};this._internalDevicesById.set(t.id,{...r,disconnectionSubscription:this._manager.onDeviceDisconnected(t.id,()=>{e.next({...t,available:!1})})})}_discoverNewDevices(e){return new S(i=>{this._manager.startDeviceScan(null,null,(t,r)=>{if(this._handleLostDiscoveredDevices(i),t||!r){i.error(t);return}this._getDiscoveredDeviceFrom(r,e).map(({discoveredDevice:n,bleDeviceInfos:s})=>{this._emitDiscoveredDevice(i,s,n)})})})}_discoverKnownDevices(e){return d(this._manager.connectedDevices(e)).pipe(p(i=>new S(t=>{i.forEach(r=>{this._getDiscoveredDeviceFrom(r,e).map(({bleDeviceInfos:n,discoveredDevice:s})=>{this._emitDiscoveredDevice(t,n,s)})})})))}_handleDeviceDisconnected(e,i){if(e&&this._logger.error("device disconnected error",{data:{error:e,device:i}}),!i){this._logger.info("disconnected handler didn't found device");return}o.fromNullable(this._deviceConnectionsById.get(i.id)).map(n=>{n.eventDeviceDetached()});let r;d([0]).pipe(p(async()=>{try{r=await i.connect({requestMTU:m}),r=await i.discoverAllServicesAndCharacteristics(),await this._handleDeviceReconnected(r)}catch(n){throw this._logger.error("[_handleDeviceDisconnected] Reconnecting failed",{data:{e:n}}),o.fromNullable(this._deviceConnectionsById.get(i.id)).map(s=>{s.closeConnection()}),n}return i}),C({count:5,delay:_/5})).subscribe({next:n=>this._logger.info("[_handleDeviceDisconnected] Got new device after reconnection",{data:{value:n}}),error:n=>{this._logger.error("[_handleDeviceDisconnected] Reconnection failed after all retries",{data:{e:n}})}})}async _handleDeviceReconnected(e){const i=o.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new O),t=o.fromNullable(this._internalDevicesById.get(e.id)).toEither(new w);return u(async({liftEither:r})=>{const n=await r(i),s=await r(t);n.setDependencies({device:e,manager:this._manager,internalDevice:s}),await n.setupConnection(),n.eventDeviceAttached()}).run()}}const k=({deviceModelDataSource:D,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new R(D,e,i,t);export{R as RNBleTransport,k as RNBleTransportFactory,G as rnBleTransportIdentifier};
2
+ //# sourceMappingURL=RNBleTransport.js.map