@ledgerhq/device-transport-kit-web-ble 0.0.0-develop-20241219141541

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 (40) hide show
  1. package/LICENSE.MD +202 -0
  2. package/lib/esm/api/data/WebBleConfig.js +2 -0
  3. package/lib/esm/api/data/WebBleConfig.js.map +7 -0
  4. package/lib/esm/api/index.js +2 -0
  5. package/lib/esm/api/index.js.map +7 -0
  6. package/lib/esm/api/model/BleDevice.stub.js +2 -0
  7. package/lib/esm/api/model/BleDevice.stub.js.map +7 -0
  8. package/lib/esm/api/model/Errors.js +2 -0
  9. package/lib/esm/api/model/Errors.js.map +7 -0
  10. package/lib/esm/api/transport/BleDeviceConnection.js +2 -0
  11. package/lib/esm/api/transport/BleDeviceConnection.js.map +7 -0
  12. package/lib/esm/api/transport/BleDeviceConnection.test.js +2 -0
  13. package/lib/esm/api/transport/BleDeviceConnection.test.js.map +7 -0
  14. package/lib/esm/api/transport/WebBleTransport.js +2 -0
  15. package/lib/esm/api/transport/WebBleTransport.js.map +7 -0
  16. package/lib/esm/api/transport/WebBleTransport.test.js +2 -0
  17. package/lib/esm/api/transport/WebBleTransport.test.js.map +7 -0
  18. package/lib/esm/index.js +2 -0
  19. package/lib/esm/index.js.map +7 -0
  20. package/lib/esm/package.json +58 -0
  21. package/lib/types/api/data/WebBleConfig.d.ts +2 -0
  22. package/lib/types/api/data/WebBleConfig.d.ts.map +1 -0
  23. package/lib/types/api/index.d.ts +3 -0
  24. package/lib/types/api/index.d.ts.map +1 -0
  25. package/lib/types/api/model/BleDevice.stub.d.ts +3 -0
  26. package/lib/types/api/model/BleDevice.stub.d.ts.map +1 -0
  27. package/lib/types/api/model/Errors.d.ts +12 -0
  28. package/lib/types/api/model/Errors.d.ts.map +1 -0
  29. package/lib/types/api/transport/BleDeviceConnection.d.ts +98 -0
  30. package/lib/types/api/transport/BleDeviceConnection.d.ts.map +1 -0
  31. package/lib/types/api/transport/BleDeviceConnection.test.d.ts +2 -0
  32. package/lib/types/api/transport/BleDeviceConnection.test.d.ts.map +1 -0
  33. package/lib/types/api/transport/WebBleTransport.d.ts +91 -0
  34. package/lib/types/api/transport/WebBleTransport.d.ts.map +1 -0
  35. package/lib/types/api/transport/WebBleTransport.test.d.ts +2 -0
  36. package/lib/types/api/transport/WebBleTransport.test.d.ts.map +1 -0
  37. package/lib/types/index.d.ts +2 -0
  38. package/lib/types/index.d.ts.map +1 -0
  39. package/lib/types/tsconfig.prod.tsbuildinfo +1 -0
  40. package/package.json +57 -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
+ const E=6e3;export{E as RECONNECT_DEVICE_TIMEOUT};
2
+ //# sourceMappingURL=WebBleConfig.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/data/WebBleConfig.ts"],
4
+ "sourcesContent": ["export const RECONNECT_DEVICE_TIMEOUT = 6000;\n"],
5
+ "mappings": "AAAO,MAAMA,EAA2B",
6
+ "names": ["RECONNECT_DEVICE_TIMEOUT"]
7
+ }
@@ -0,0 +1,2 @@
1
+ export*from"./model/Errors";import{webBleIdentifier as t,WebBleTransport as p,webBleTransportFactory as a}from"./transport/WebBleTransport";export{p as WebBleTransport,t as webBleIdentifier,a as webBleTransportFactory};
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 webBleIdentifier,\n WebBleTransport,\n webBleTransportFactory,\n} from \"./transport/WebBleTransport\";\n"],
5
+ "mappings": "AAAA,WAAc,iBACd,OACE,oBAAAA,EACA,mBAAAC,EACA,0BAAAC,MACK",
6
+ "names": ["webBleIdentifier", "WebBleTransport", "webBleTransportFactory"]
7
+ }
@@ -0,0 +1,2 @@
1
+ const t={name:"Ledger Nano X",id:"42",forget:jest.fn(),watchAdvertisements:jest.fn(),dispatchEvent:jest.fn(),watchingAdvertisements:!1,addEventListener:jest.fn(),removeEventListener:jest.fn(),onadvertisementreceived:jest.fn(),ongattserverdisconnected:jest.fn(),oncharacteristicvaluechanged:jest.fn(),onserviceadded:jest.fn(),onservicechanged:jest.fn(),onserviceremoved:jest.fn()},n={device:t,uuid:"13d63400-2c97-0004-0000-4c6564676572",isPrimary:!0,getCharacteristic:jest.fn(()=>Promise.resolve(s())),getCharacteristics:jest.fn(),getIncludedService:jest.fn(),getIncludedServices:jest.fn(),addEventListener:jest.fn(),dispatchEvent:jest.fn(),removeEventListener:jest.fn(),oncharacteristicvaluechanged:jest.fn(),onserviceadded:jest.fn(),onservicechanged:jest.fn(),onserviceremoved:jest.fn()},s=(e={})=>({...e,addEventListener:jest.fn(),removeEventListener:jest.fn(),startNotifications:jest.fn(),writeValueWithResponse:jest.fn(),writeValueWithoutResponse:jest.fn()}),i=(e={})=>({...t,gatt:{device:t,connected:!0,connect:jest.fn(),disconnect:jest.fn(),getPrimaryService:jest.fn(),getPrimaryServices:jest.fn(()=>Promise.resolve([n]))},...e});export{s as bleCharacteristicStubBuilder,i as bleDeviceStubBuilder};
2
+ //# sourceMappingURL=BleDevice.stub.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/model/BleDevice.stub.ts"],
4
+ "sourcesContent": ["const bleDeviceWithoutGatt: BluetoothDevice = {\n name: \"Ledger Nano X\",\n id: \"42\",\n forget: jest.fn(),\n watchAdvertisements: jest.fn(),\n dispatchEvent: jest.fn(),\n watchingAdvertisements: false,\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n onadvertisementreceived: jest.fn(),\n ongattserverdisconnected: jest.fn(),\n oncharacteristicvaluechanged: jest.fn(),\n onserviceadded: jest.fn(),\n onservicechanged: jest.fn(),\n onserviceremoved: jest.fn(),\n};\n\nconst bluetoothGattPrimaryService: BluetoothRemoteGATTService = {\n device: bleDeviceWithoutGatt,\n uuid: \"13d63400-2c97-0004-0000-4c6564676572\",\n isPrimary: true,\n getCharacteristic: jest.fn(() =>\n Promise.resolve(bleCharacteristicStubBuilder()),\n ),\n getCharacteristics: jest.fn(),\n getIncludedService: jest.fn(),\n getIncludedServices: jest.fn(),\n addEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n removeEventListener: jest.fn(),\n oncharacteristicvaluechanged: jest.fn(),\n onserviceadded: jest.fn(),\n onservicechanged: jest.fn(),\n onserviceremoved: jest.fn(),\n};\n\nexport const bleCharacteristicStubBuilder = (\n props: Partial<BluetoothRemoteGATTCharacteristic> = {},\n): BluetoothRemoteGATTCharacteristic =>\n ({\n ...props,\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n startNotifications: jest.fn(),\n writeValueWithResponse: jest.fn(),\n writeValueWithoutResponse: jest.fn(),\n }) as BluetoothRemoteGATTCharacteristic;\n\nexport const bleDeviceStubBuilder = (\n props: Partial<BluetoothDevice> = {},\n): BluetoothDevice => ({\n ...bleDeviceWithoutGatt,\n gatt: {\n device: bleDeviceWithoutGatt,\n connected: true,\n connect: jest.fn(),\n disconnect: jest.fn(),\n getPrimaryService: jest.fn(),\n getPrimaryServices: jest.fn(() =>\n Promise.resolve([bluetoothGattPrimaryService]),\n ),\n },\n ...props,\n});\n"],
5
+ "mappings": "AAAA,MAAMA,EAAwC,CAC5C,KAAM,gBACN,GAAI,KACJ,OAAQ,KAAK,GAAG,EAChB,oBAAqB,KAAK,GAAG,EAC7B,cAAe,KAAK,GAAG,EACvB,uBAAwB,GACxB,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,wBAAyB,KAAK,GAAG,EACjC,yBAA0B,KAAK,GAAG,EAClC,6BAA8B,KAAK,GAAG,EACtC,eAAgB,KAAK,GAAG,EACxB,iBAAkB,KAAK,GAAG,EAC1B,iBAAkB,KAAK,GAAG,CAC5B,EAEMC,EAA0D,CAC9D,OAAQD,EACR,KAAM,uCACN,UAAW,GACX,kBAAmB,KAAK,GAAG,IACzB,QAAQ,QAAQE,EAA6B,CAAC,CAChD,EACA,mBAAoB,KAAK,GAAG,EAC5B,mBAAoB,KAAK,GAAG,EAC5B,oBAAqB,KAAK,GAAG,EAC7B,iBAAkB,KAAK,GAAG,EAC1B,cAAe,KAAK,GAAG,EACvB,oBAAqB,KAAK,GAAG,EAC7B,6BAA8B,KAAK,GAAG,EACtC,eAAgB,KAAK,GAAG,EACxB,iBAAkB,KAAK,GAAG,EAC1B,iBAAkB,KAAK,GAAG,CAC5B,EAEaA,EAA+B,CAC1CC,EAAoD,CAAC,KAEpD,CACC,GAAGA,EACH,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,mBAAoB,KAAK,GAAG,EAC5B,uBAAwB,KAAK,GAAG,EAChC,0BAA2B,KAAK,GAAG,CACrC,GAEWC,EAAuB,CAClCD,EAAkC,CAAC,KACd,CACrB,GAAGH,EACH,KAAM,CACJ,OAAQA,EACR,UAAW,GACX,QAAS,KAAK,GAAG,EACjB,WAAY,KAAK,GAAG,EACpB,kBAAmB,KAAK,GAAG,EAC3B,mBAAoB,KAAK,GAAG,IAC1B,QAAQ,QAAQ,CAACC,CAA2B,CAAC,CAC/C,CACF,EACA,GAAGE,CACL",
6
+ "names": ["bleDeviceWithoutGatt", "bluetoothGattPrimaryService", "bleCharacteristicStubBuilder", "props", "bleDeviceStubBuilder"]
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 s extends e{constructor(r){super(r);this.err=r}_tag="BleDeviceGattServerError"}export{s as BleDeviceGattServerError,a as BleTransportNotSupportedError};
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}\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",
6
+ "names": ["GeneralDmkError", "BleTransportNotSupportedError", "err", "BleDeviceGattServerError"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{CommandUtils as u,DeviceNotInitializedError as p,ReconnectionFailedError as d}from"@ledgerhq/device-management-kit";import{Left as c,Maybe as o,Nothing as v,Right as n}from"purify-ts";class y{_writeCharacteristic;_notifyCharacteristic;_logger;_apduSender;_apduSenderFactory;_apduReceiver;_isDeviceReady;_sendApduPromiseResolver;_settleReconnectionPromiseResolvers;constructor({writeCharacteristic:e,notifyCharacteristic:t,apduSenderFactory:i,apduReceiverFactory:s},a){this._apduSenderFactory=i,this._apduSender=v,this._apduReceiver=s(),this._logger=a("BleDeviceConnection"),this._writeCharacteristic=e,this._notifyCharacteristic=t,this._notifyCharacteristic.oncharacteristicvaluechanged=this.onNotifyCharacteristicValueChanged,this._isDeviceReady=!1,this._sendApduPromiseResolver=o.zero(),this._settleReconnectionPromiseResolvers=o.zero()}set notifyCharacteristic(e){this._notifyCharacteristic=e,this._notifyCharacteristic.oncharacteristicvaluechanged=this.onNotifyCharacteristicValueChanged}set writeCharacteristic(e){this._writeCharacteristic=e}onReceiveSetupApduResponse(e){const t=new Uint8Array(e),[i]=t.slice(5);i&&(this._apduSender=o.of(this._apduSenderFactory({frameSize:i})),this._settleReconnectionPromiseResolvers.ifJust(s=>{s.resolve(),this._settleReconnectionPromiseResolvers=o.zero()}),this._isDeviceReady=!0)}onNotifyCharacteristicValueChanged=e=>{if(!this.isDataViewEvent(e))return;const{target:{value:{buffer:t}}}=e;this._isDeviceReady?this.receiveApdu(t):this.onReceiveSetupApduResponse(t)};async setup(){const e=Uint8Array.from([8,0,0,0,0]);await this._notifyCharacteristic.startNotifications(),await this._writeCharacteristic.writeValueWithoutResponse(e)}receiveApdu(e){this._apduReceiver.handleFrame(new Uint8Array(e)).map(i=>{i.map(s=>{this._logger.debug("Received APDU Response",{data:{response:s}}),this._sendApduPromiseResolver.map(({resolve:a})=>a(n(s)))})}).mapLeft(i=>{this._sendApduPromiseResolver.map(({resolve:s})=>s(c(i)))})}async sendApdu(e,t){if(!this._isDeviceReady)return Promise.resolve(c(new p("Unknown MTU")));const i=new Promise(r=>{this._sendApduPromiseResolver=o.of({resolve:r})}),s=this._apduSender.mapOrDefault(r=>r.getFrames(e),[]);for(const r of s)try{this._logger.debug("Sending Frame",{data:{frame:r.getRawData()}}),await this._writeCharacteristic.writeValueWithoutResponse(r.getRawData())}catch(h){this._logger.error("Error sending frame",{data:{error:h}})}const a=await i;return this._sendApduPromiseResolver=o.zero(),a.caseOf({Right:async r=>t&&u.isSuccessResponse(r)?(await this.setupWaitForReconnection()).map(()=>r):n(r),Left:async r=>Promise.resolve(c(r))})}isDataViewEvent(e){return e.target!==null&&"value"in e.target&&e.target.value instanceof DataView}setupWaitForReconnection(){return new Promise(e=>{this._settleReconnectionPromiseResolvers=o.of({resolve:()=>e(n(void 0)),reject:t=>e(c(t))})})}async reconnect(e,t){this._isDeviceReady=!1,this.notifyCharacteristic=t,this.writeCharacteristic=e,await this.setup()}disconnect(){this._settleReconnectionPromiseResolvers.ifJust(e=>{e.reject(new d),this._settleReconnectionPromiseResolvers=o.zero()}),this._isDeviceReady=!1}}export{y as BleDeviceConnection};
2
+ //# sourceMappingURL=BleDeviceConnection.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/BleDeviceConnection.ts"],
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduReceiverServiceFactory,\n type ApduResponse,\n type ApduSenderService,\n type ApduSenderServiceFactory,\n CommandUtils,\n type DeviceConnection,\n DeviceNotInitializedError,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\n\ntype BleDeviceConnectionConstructorArgs = {\n writeCharacteristic: BluetoothRemoteGATTCharacteristic;\n notifyCharacteristic: BluetoothRemoteGATTCharacteristic;\n apduSenderFactory: ApduSenderServiceFactory;\n apduReceiverFactory: ApduReceiverServiceFactory;\n};\n\nexport type DataViewEvent = Event & {\n target: {\n value: DataView;\n };\n};\n\nexport class BleDeviceConnection implements DeviceConnection {\n private _writeCharacteristic: BluetoothRemoteGATTCharacteristic;\n private _notifyCharacteristic: BluetoothRemoteGATTCharacteristic;\n private readonly _logger: LoggerPublisherService;\n private _apduSender: Maybe<ApduSenderService>;\n private readonly _apduSenderFactory: ApduSenderServiceFactory;\n private readonly _apduReceiver: ApduReceiverService;\n private _isDeviceReady: boolean;\n private _sendApduPromiseResolver: Maybe<{\n resolve(value: Either<DmkError, ApduResponse>): void;\n }>;\n private _settleReconnectionPromiseResolvers: Maybe<{\n resolve(): void;\n reject(err: DmkError): void;\n }>;\n\n constructor(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n }: BleDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSenderFactory = apduSenderFactory;\n this._apduSender = Nothing;\n this._apduReceiver = apduReceiverFactory();\n this._logger = loggerServiceFactory(\"BleDeviceConnection\");\n this._writeCharacteristic = writeCharacteristic;\n this._notifyCharacteristic = notifyCharacteristic;\n this._notifyCharacteristic.oncharacteristicvaluechanged =\n this.onNotifyCharacteristicValueChanged;\n this._isDeviceReady = false;\n this._sendApduPromiseResolver = Maybe.zero();\n this._settleReconnectionPromiseResolvers = Maybe.zero();\n }\n\n /**\n * NotifyCharacteristic setter\n * Register a listener on characteristic value change\n * @param notifyCharacteristic\n * @private\n */\n private set notifyCharacteristic(\n notifyCharacteristic: BluetoothRemoteGATTCharacteristic,\n ) {\n this._notifyCharacteristic = notifyCharacteristic;\n this._notifyCharacteristic.oncharacteristicvaluechanged =\n this.onNotifyCharacteristicValueChanged;\n }\n\n /**\n * WriteCharacteristic setter\n * @param writeCharacteristic\n * @private\n */\n private set writeCharacteristic(\n writeCharacteristic: BluetoothRemoteGATTCharacteristic,\n ) {\n this._writeCharacteristic = writeCharacteristic;\n }\n\n /**\n * Event handler to setup the mtu size in response of 0x0800000000 APDU\n * @param value\n * @private\n */\n private onReceiveSetupApduResponse(value: ArrayBuffer) {\n const mtuResponse = new Uint8Array(value);\n // the mtu is the 5th byte of the response\n const [frameSize] = mtuResponse.slice(5);\n if (frameSize) {\n this._apduSender = Maybe.of(this._apduSenderFactory({ frameSize }));\n this._settleReconnectionPromiseResolvers.ifJust((promise) => {\n promise.resolve();\n this._settleReconnectionPromiseResolvers = Maybe.zero();\n });\n this._isDeviceReady = true;\n }\n }\n\n /**\n * Main event handler for BLE notify characteristic\n * Call _onReceiveSetupApduResponse if device mtu is not set\n * Call receiveApdu otherwise\n * @param event\n */\n private onNotifyCharacteristicValueChanged = (event: Event) => {\n if (!this.isDataViewEvent(event)) {\n return;\n }\n const {\n target: {\n value: { buffer },\n },\n } = event;\n if (!this._isDeviceReady) {\n this.onReceiveSetupApduResponse(buffer);\n } else {\n this.receiveApdu(buffer);\n }\n };\n\n /**\n * Setup BleDeviceConnection\n *\n * The device is considered as ready once the mtu had been set\n * APDU 0x0800000000 is used to get this mtu size\n */\n public async setup() {\n const requestMtuApdu = Uint8Array.from([0x08, 0x00, 0x00, 0x00, 0x00]);\n\n await this._notifyCharacteristic.startNotifications();\n await this._writeCharacteristic.writeValueWithoutResponse(requestMtuApdu);\n }\n\n /**\n * Receive APDU response\n * Resolve sendApdu promise once the framer receives all the frames of the response\n * @param data\n */\n receiveApdu(data: ArrayBuffer) {\n const response = this._apduReceiver.handleFrame(new Uint8Array(data));\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 }) =>\n resolve(Left(error)),\n );\n });\n }\n\n /**\n * Send apdu if the mtu had been set\n *\n * Get all frames for a given APDU\n * Save a promise that would be completed once the response had been received\n * @param apdu\n * @param triggersDisconnection\n */\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n if (!this._isDeviceReady) {\n return Promise.resolve(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n }\n // Create a promise that would be resolved once the response had been received\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduPromiseResolver = Maybe.of({\n resolve,\n });\n },\n );\n const frames = this._apduSender.mapOrDefault(\n (apduSender) => apduSender.getFrames(apdu),\n [],\n );\n for (const frame of frames) {\n try {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n await this._writeCharacteristic.writeValueWithoutResponse(\n frame.getRawData(),\n );\n } catch (error) {\n this._logger.error(\"Error sending frame\", { data: { error } });\n }\n }\n const response = await resultPromise;\n this._sendApduPromiseResolver = Maybe.zero();\n return response.caseOf({\n Right: async (apduResponse) => {\n if (\n triggersDisconnection &&\n CommandUtils.isSuccessResponse(apduResponse)\n ) {\n const reconnectionRes = await this.setupWaitForReconnection();\n return reconnectionRes.map(() => apduResponse);\n } else {\n return Right(apduResponse);\n }\n },\n Left: async (error) => Promise.resolve(Left(error)),\n });\n }\n\n /**\n * Typeguard to check if an event contains target value of type DataView\n *\n * @param event\n * @private\n */\n private isDataViewEvent(event: Event): event is DataViewEvent {\n return (\n event.target !== null &&\n \"value\" in event.target &&\n event.target.value instanceof DataView\n );\n }\n\n /**\n * Setup a promise that would be resolved once the device is reconnected\n *\n * @private\n */\n private setupWaitForReconnection(): Promise<Either<DmkError, void>> {\n return new Promise<Either<DmkError, void>>((resolve) => {\n this._settleReconnectionPromiseResolvers = Maybe.of({\n resolve: () => resolve(Right(undefined)),\n reject: (error: DmkError) => resolve(Left(error)),\n });\n });\n }\n\n /**\n * Reconnect to the device by resetting new ble characteristics\n * @param writeCharacteristic\n * @param notifyCharacteristic\n */\n public async reconnect(\n writeCharacteristic: BluetoothRemoteGATTCharacteristic,\n notifyCharacteristic: BluetoothRemoteGATTCharacteristic,\n ) {\n this._isDeviceReady = false;\n this.notifyCharacteristic = notifyCharacteristic;\n this.writeCharacteristic = writeCharacteristic;\n await this.setup();\n }\n\n /**\n * Disconnect from the device\n */\n public disconnect() {\n // if a reconnection promise is pending, reject it\n this._settleReconnectionPromiseResolvers.ifJust((promise) => {\n promise.reject(new ReconnectionFailedError());\n this._settleReconnectionPromiseResolvers = Maybe.zero();\n });\n this._isDeviceReady = false;\n }\n}\n"],
5
+ "mappings": "AAAA,OAME,gBAAAA,EAEA,6BAAAC,EAGA,2BAAAC,MACK,kCACP,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YAelD,MAAMC,CAAgD,CACnD,qBACA,sBACS,QACT,YACS,mBACA,cACT,eACA,yBAGA,oCAKR,YACE,CACE,oBAAAC,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,EACA,CACA,KAAK,mBAAqBF,EAC1B,KAAK,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,UAAWA,EAAM,QACjBA,EAAM,OAAO,iBAAiB,QAElC,CAOQ,0BAA4D,CAClE,OAAO,IAAI,QAAiCM,GAAY,CACtD,KAAK,oCAAsCnB,EAAM,GAAG,CAClD,QAAS,IAAMmB,EAAQjB,EAAM,MAAS,CAAC,EACvC,OAASkB,GAAoBD,EAAQpB,EAAKqB,CAAK,CAAC,CAClD,CAAC,CACH,CAAC,CACH,CAOA,MAAa,UACXhB,EACAC,EACA,CACA,KAAK,eAAiB,GACtB,KAAK,qBAAuBA,EAC5B,KAAK,oBAAsBD,EAC3B,MAAM,KAAK,MAAM,CACnB,CAKO,YAAa,CAElB,KAAK,oCAAoC,OAAQQ,GAAY,CAC3DA,EAAQ,OAAO,IAAId,CAAyB,EAC5C,KAAK,oCAAsCE,EAAM,KAAK,CACxD,CAAC,EACD,KAAK,eAAiB,EACxB,CACF",
6
+ "names": ["CommandUtils", "DeviceNotInitializedError", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "BleDeviceConnection", "writeCharacteristic", "notifyCharacteristic", "apduSenderFactory", "apduReceiverFactory", "loggerServiceFactory", "value", "mtuResponse", "frameSize", "promise", "event", "buffer", "requestMtuApdu", "data", "maybeApduResponse", "apduResponse", "resolve", "error", "apdu", "triggersDisconnection", "resultPromise", "frames", "apduSender", "frame", "response"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{ApduResponse as p,defaultApduReceiverServiceStubBuilder as l,defaultApduSenderServiceStubBuilder as S,DeviceNotInitializedError as f}from"@ledgerhq/device-management-kit";import{Left as h,Right as v}from"purify-ts";import{bleCharacteristicStubBuilder as u}from"../model/BleDevice.stub";import{BleDeviceConnection as s}from"./BleDeviceConnection";const A=new Uint8Array([8,0,0,0,0]),d=new Uint8Array([0,0,0,0,0,66]),x=Uint8Array.from([0,0,0,0,0,0,0,0]);class w{subscribers=[];tag;constructor(i,r){this.subscribers=i,this.tag=r}error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}describe("BleDeviceConnection",()=>{let t,i,r,o;const n=e=>new w([],e);beforeEach(()=>{t=u(),i=u(),r=jest.fn(()=>S(void 0,n)),o=jest.fn(()=>l(void 0,n))});function a(e,c=Uint8Array.from([])){e.onNotifyCharacteristicValueChanged({target:{value:new DataView(c.buffer)}})}describe("sendApdu",()=>{it("should return an error if the device isn't setup",async()=>{const c=await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).sendApdu(Uint8Array.from([]));expect(c).toStrictEqual(h(new f("Unknown MTU")))}),it("should send apdu without error if device is setup",async()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d);const c=e.sendApdu(new Uint8Array([]));a(e,x),expect(t.writeValueWithoutResponse).toHaveBeenCalledTimes(1),expect(await c).toStrictEqual(v(new p({statusCode:Uint8Array.from([]),data:Uint8Array.from([])})))})}),describe("setup",()=>{it("should send the apdu 0x0800000000 to get mtu size",async()=>{await new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n).setup(),expect(t.writeValueWithoutResponse).toHaveBeenCalledWith(new Uint8Array(A))}),it("should setup apduSender with the correct mtu size",()=>{const e=new s({writeCharacteristic:t,notifyCharacteristic:i,apduSenderFactory:r,apduReceiverFactory:o},n);a(e,d),expect(r).toHaveBeenCalledWith({frameSize:66})})})});
2
+ //# sourceMappingURL=BleDeviceConnection.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/BleDeviceConnection.test.ts"],
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n ApduResponse,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n DeviceNotInitializedError,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { bleCharacteristicStubBuilder } from \"@api/model/BleDevice.stub\";\n\nimport { BleDeviceConnection, type DataViewEvent } from \"./BleDeviceConnection\";\n\nconst GET_MTU_APDU = new Uint8Array([0x08, 0x00, 0x00, 0x00, 0x00]);\nconst GET_MTU_APDU_RESPONSE = new Uint8Array([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x42,\n]);\nconst EMPTY_APDU_RESPONSE = Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\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 = jest.fn();\n warn = jest.fn();\n info = jest.fn();\n debug = jest.fn();\n}\n\ndescribe(\"BleDeviceConnection\", () => {\n let writeCharacteristic: BluetoothRemoteGATTCharacteristic;\n let notifyCharacteristic: BluetoothRemoteGATTCharacteristic;\n let apduSenderFactory: () => ApduSenderService;\n let apduReceiverFactory: () => ApduReceiverService;\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n writeCharacteristic = bleCharacteristicStubBuilder();\n notifyCharacteristic = bleCharacteristicStubBuilder();\n apduSenderFactory = jest.fn(() =>\n defaultApduSenderServiceStubBuilder(undefined, logger),\n );\n apduReceiverFactory = jest.fn(() =>\n defaultApduReceiverServiceStubBuilder(undefined, logger),\n );\n });\n\n function receiveApdu(\n connection: BleDeviceConnection,\n buffer: Uint8Array = Uint8Array.from([]),\n ) {\n // @ts-expect-error private function call to mock web ble response\n connection.onNotifyCharacteristicValueChanged({\n target: {\n value: new DataView(buffer.buffer),\n },\n } as DataViewEvent);\n }\n\n describe(\"sendApdu\", () => {\n it(\"should return an error if the device isn't setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n const errorOrApduResponse = await connection.sendApdu(\n Uint8Array.from([]),\n );\n // then\n expect(errorOrApduResponse).toStrictEqual(\n Left(new DeviceNotInitializedError(\"Unknown MTU\")),\n );\n });\n\n it(\"should send apdu without error if device is setup\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n const response = connection.sendApdu(new Uint8Array([]));\n receiveApdu(connection, EMPTY_APDU_RESPONSE);\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledTimes(1);\n expect(await response).toStrictEqual(\n Right(\n new ApduResponse({\n statusCode: Uint8Array.from([]),\n data: Uint8Array.from([]),\n }),\n ),\n );\n });\n });\n describe(\"setup\", () => {\n it(\"should send the apdu 0x0800000000 to get mtu size\", async () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n await connection.setup();\n // then\n expect(\n writeCharacteristic.writeValueWithoutResponse,\n ).toHaveBeenCalledWith(new Uint8Array(GET_MTU_APDU));\n });\n it(\"should setup apduSender with the correct mtu size\", () => {\n // given\n const connection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduSenderFactory,\n apduReceiverFactory,\n },\n logger,\n );\n // when\n receiveApdu(connection, GET_MTU_APDU_RESPONSE);\n // then\n expect(apduSenderFactory).toHaveBeenCalledWith({ frameSize: 0x42 });\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAEE,gBAAAA,EAEA,yCAAAC,EACA,uCAAAC,EACA,6BAAAC,MAGK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,gCAAAC,MAAoC,4BAE7C,OAAS,uBAAAC,MAA+C,wBAExD,MAAMC,EAAe,IAAI,WAAW,CAAC,EAAM,EAAM,EAAM,EAAM,CAAI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BAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEAC,EAAYC,EAAYX,CAAqB,EAC7C,MAAMc,EAAWH,EAAW,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,EACvDD,EAAYC,EAAYV,CAAmB,EAE3C,OACEI,EAAoB,yBACtB,EAAE,sBAAsB,CAAC,EACzB,OAAO,MAAMS,CAAQ,EAAE,cACrBlB,EACE,IAAIL,EAAa,CACf,WAAY,WAAW,KAAK,CAAC,CAAC,EAC9B,KAAM,WAAW,KAAK,CAAC,CAAC,CAC1B,CAAC,CACH,CACF,CACF,CAAC,CACH,CAAC,EACD,SAAS,QAAS,IAAM,CACtB,GAAG,oDAAqD,SAAY,CAYlE,MAVmB,IAAIO,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEiB,MAAM,EAEvB,OACEJ,EAAoB,yBACtB,EAAE,qBAAqB,IAAI,WAAWN,CAAY,CAAC,CACrD,CAAC,EACD,GAAG,oDAAqD,IAAM,CAE5D,MAAMY,EAAa,IAAIb,EACrB,CACE,oBAAAO,EACA,qBAAAC,EACA,kBAAAC,EACA,oBAAAC,CACF,EACAC,CACF,EAEAC,EAAYC,EAAYX,CAAqB,EAE7C,OAAOO,CAAiB,EAAE,qBAAqB,CAAE,UAAW,EAAK,CAAC,CACpE,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["ApduResponse", "defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "DeviceNotInitializedError", "Left", "Right", "bleCharacteristicStubBuilder", "BleDeviceConnection", "GET_MTU_APDU", "GET_MTU_APDU_RESPONSE", "EMPTY_APDU_RESPONSE", "LoggerPublisherServiceStub", "subscribers", "tag", "writeCharacteristic", "notifyCharacteristic", "apduSenderFactory", "apduReceiverFactory", "logger", "receiveApdu", "connection", "buffer", "errorOrApduResponse", "response"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{DeviceAlreadyConnectedError as b,DeviceNotRecognizedError as f,NoAccessibleDeviceError as m,OpeningConnectionError as p,TransportConnectedDevice as I,UnknownDeviceError as h}from"@ledgerhq/device-management-kit";import{EitherAsync as u,Left as c,Maybe as d,Right as a}from"purify-ts";import{from as g,switchMap as _,timer as w}from"rxjs";import{v4 as T}from"uuid";import{RECONNECT_DEVICE_TIMEOUT as S}from"../data/WebBleConfig";import{BleDeviceGattServerError as v,BleTransportNotSupportedError as E}from"../model/Errors";import{BleDeviceConnection as C}from"../transport/BleDeviceConnection";const A="WEB-BLE";class F{constructor(e,i,t,n){this._deviceModelDataSource=e;this._loggerServiceFactory=i;this._apduSenderFactory=t;this._apduReceiverFactory=n;this._connectedDevices=[],this._internalDevicesById=new Map,this._deviceConnectionById=new Map,this._disconnectionHandlersById=new Map,this._logger=i("WebBleTransport")}_connectedDevices;_internalDevicesById;_deviceConnectionById;_disconnectionHandlersById;_logger;connectionType="BLE";identifier=A;getBluetoothApi(){return this.isSupported()?a(navigator.bluetooth):c(new E("WebBle not supported"))}isSupported(){try{return!!navigator?.bluetooth}catch{return!1}}getIdentifier(){return this.identifier}listenToKnownDevices(){return g([])}async getBleGattService(e){if(!e.gatt)return c(new v("Device gatt not found"));try{const[i]=await e.gatt.getPrimaryServices();return i?a(i):c(new v("bluetooth service not found"))}catch(i){return c(new v(i))}}getBleDeviceInfos(e){const t=this._deviceModelDataSource.getBluetoothServicesInfos()[e.uuid];return t?a(t):(this._logger.error(`Device not recognized: ${e.device.name}`),c(new f(`Device not recognized: ${e.device.name}`)))}promptDeviceAccess(){return u(async({liftEither:e,throwE:i})=>{const t=await e(this.getBluetoothApi());let n;try{n=await t.requestDevice({filters:this._deviceModelDataSource.getBluetoothServices().map(r=>({services:[r]}))})}catch(r){return i(new m(r))}return n})}getDiscoveredDeviceFrom(e){return{id:T(),deviceModel:e.deviceModel,transport:this.identifier}}setInternalDeviceFrom(e,i,t,n){const r={id:e.id,bleDevice:i,bleGattService:n,bleDeviceInfos:t,discoveredDevice:e};this._logger.debug(`Discovered device ${r.id} ${e.deviceModel.productName}`),this._internalDevicesById.set(r.id,r)}startDiscovering(){return this._logger.debug("startDiscovering"),g(this.promptDeviceAccess()).pipe(_(async e=>u(async({liftEither:i,fromPromise:t})=>{const n=await i(e);if(n.gatt)try{await n.gatt.connect()}catch(r){throw new p(r)}try{const r=await t(this.getBleGattService(n)),o=await i(this.getBleDeviceInfos(r)),s=this.getDiscoveredDeviceFrom(o);return this.setInternalDeviceFrom(s,n,o,r),s}catch(r){throw await n.forget(),r}}).caseOf({Right:i=>i,Left:i=>{throw this._logger.error("Error while getting accessible device",{data:{error:i}}),i}})))}stopDiscovering(){this._logger.debug("stopDiscovering")}async connect({deviceId:e,onDisconnect:i}){const t=this._internalDevicesById.get(e);if(!t)return this._logger.error(`Unknown device ${e}`,{data:{internalDevices:this._internalDevicesById}}),this._logger.debug("Available devices",{data:{devices:this._internalDevicesById}}),c(new h(`Unknown device ${e}`));if(this._connectedDevices.includes(t.bleDevice))return this._internalDevicesById.delete(e),c(new b("Device already connected"));const{discoveredDevice:{deviceModel:n}}=t;try{const[r,o]=await Promise.all([t.bleGattService.getCharacteristic(t.bleDeviceInfos.writeCmdUuid),t.bleGattService.getCharacteristic(t.bleDeviceInfos.notifyUuid)]),s=new C({writeCharacteristic:r,notifyCharacteristic:o,apduReceiverFactory:this._apduReceiverFactory,apduSenderFactory:this._apduSenderFactory},this._loggerServiceFactory);await s.setup();const D=new I({sendApdu:(y,B)=>s.sendApdu(y,B),deviceModel:n,id:e,type:this.connectionType,transport:this.identifier});return t.bleDevice.ongattserverdisconnected=this._getDeviceDisconnectedHandler(t,s),this._deviceConnectionById.set(t.id,s),this._disconnectionHandlersById.set(t.id,()=>{this.disconnect({connectedDevice:D}).then(()=>i(e))}),this._connectedDevices.push(t.bleDevice),a(D)}catch(r){return await t.bleDevice.forget(),this._internalDevicesById.delete(e),this._logger.error("Error while getting characteristics",{data:{error:r}}),c(new p(r))}}_getDeviceDisconnectedHandler(e,i){return async()=>{const t=w(S).subscribe(()=>{this._logger.debug("disconnection timer over"),d.fromNullable(this._disconnectionHandlersById.get(e.id)).map(o=>o())});await e.bleDevice.gatt?.connect(),t.unsubscribe();const n=await this.getBleGattService(e.bleDevice);if(n.isRight()){const[r,o]=await Promise.all([n.extract().getCharacteristic(e.bleDeviceInfos.writeCmdUuid),n.extract().getCharacteristic(e.bleDeviceInfos.notifyUuid)]);await i.reconnect(r,o)}}}async disconnect(e){const i=d.fromNullable(this._internalDevicesById.get(e.connectedDevice.id));return this._logger.debug("disconnect device",{data:{connectedDevice:e.connectedDevice}}),i.isNothing()?(this._logger.error(`Unknown device ${e.connectedDevice.id}`),Promise.resolve(c(new h(`Unknown device ${e.connectedDevice.id}`)))):(i.map(t=>{const{bleDevice:n}=t;d.fromNullable(this._deviceConnectionById.get(t.id)).map(o=>o.disconnect()),n.gatt?.connected&&n.gatt.disconnect(),this._internalDevicesById.delete(t.id),this._deviceConnectionById.delete(t.id),this._disconnectionHandlersById.delete(t.id),this._connectedDevices.includes(n)&&delete this._connectedDevices[this._connectedDevices.indexOf(n)]}),Promise.resolve(a(void 0)))}}const O=({deviceModelDataSource:l,loggerServiceFactory:e,apduSenderServiceFactory:i,apduReceiverServiceFactory:t})=>new F(l,e,i,t);export{F as WebBleTransport,A as webBleIdentifier,O as webBleTransportFactory};
2
+ //# sourceMappingURL=WebBleTransport.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/WebBleTransport.ts"],
4
+ "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n type ConnectionType,\n DeviceAlreadyConnectedError,\n type DeviceId,\n type DeviceModelDataSource,\n DeviceNotRecognizedError,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n NoAccessibleDeviceError,\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, Left, Maybe, Right } from \"purify-ts\";\nimport { from, type Observable, switchMap, timer } from \"rxjs\";\nimport { v4 as uuid } from \"uuid\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport {\n BleDeviceGattServerError,\n BleTransportNotSupportedError,\n} from \"@api/model/Errors\";\nimport { BleDeviceConnection } from \"@api/transport/BleDeviceConnection\";\n\ntype PromptDeviceAccessError =\n | NoAccessibleDeviceError\n | BleTransportNotSupportedError;\n\n// An attempt to manage the state of several devices with one transport. Not final.\ntype WebBleInternalDevice = {\n id: DeviceId;\n bleDevice: BluetoothDevice;\n bleDeviceInfos: BleDeviceInfos;\n bleGattService: BluetoothRemoteGATTService;\n discoveredDevice: TransportDiscoveredDevice;\n};\n\nexport const webBleIdentifier: TransportIdentifier = \"WEB-BLE\";\n\nexport class WebBleTransport implements Transport {\n private readonly _connectedDevices: Array<BluetoothDevice>;\n private readonly _internalDevicesById: Map<DeviceId, WebBleInternalDevice>;\n private _deviceConnectionById: Map<DeviceId, BleDeviceConnection>;\n private _disconnectionHandlersById: Map<DeviceId, () => void>;\n private _logger: LoggerPublisherService;\n private readonly connectionType: ConnectionType = \"BLE\";\n private readonly identifier: TransportIdentifier = webBleIdentifier;\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._connectedDevices = [];\n this._internalDevicesById = new Map();\n this._deviceConnectionById = new Map();\n this._disconnectionHandlersById = new Map();\n this._logger = _loggerServiceFactory(\"WebBleTransport\");\n }\n\n /**\n * Get the Bluetooth API if supported or error\n * @returns `Either<BleTransportNotSupportedError, Bluetooth>`\n */\n private getBluetoothApi(): Either<BleTransportNotSupportedError, Bluetooth> {\n if (this.isSupported()) {\n return Right(navigator.bluetooth);\n }\n\n return Left(new BleTransportNotSupportedError(\"WebBle not supported\"));\n }\n\n isSupported(): boolean {\n try {\n const result = !!navigator?.bluetooth;\n return result;\n } catch {\n return false;\n }\n }\n\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n listenToKnownDevices(): Observable<TransportDiscoveredDevice[]> {\n return from([]);\n }\n\n /**\n * Get Bluetooth GATT Primary service that is used to get writeCharacteristic and notifyCharacteristic\n * @param bleDevice\n * @private\n */\n private async getBleGattService(\n bleDevice: BluetoothDevice,\n ): Promise<Either<BleDeviceGattServerError, BluetoothRemoteGATTService>> {\n if (!bleDevice.gatt) {\n return Left(new BleDeviceGattServerError(\"Device gatt not found\"));\n }\n try {\n const [bleGattService] = await bleDevice.gatt.getPrimaryServices();\n if (!bleGattService) {\n return Left(\n new BleDeviceGattServerError(\"bluetooth service not found\"),\n );\n }\n return Right(bleGattService);\n } catch (e) {\n return Left(new BleDeviceGattServerError(e));\n }\n }\n\n /**\n * BleDeviceInfos to map primary service uuid to device model & characteristics uuid\n * @param bleGattService\n * @private\n */\n private getBleDeviceInfos(\n bleGattService: BluetoothRemoteGATTService,\n ): Either<DeviceNotRecognizedError, BleDeviceInfos> {\n const serviceToBleInfos =\n this._deviceModelDataSource.getBluetoothServicesInfos();\n const bleDeviceInfos = serviceToBleInfos[bleGattService.uuid];\n\n if (!bleDeviceInfos) {\n this._logger.error(\n `Device not recognized: ${bleGattService.device.name}`,\n );\n return Left(\n new DeviceNotRecognizedError(\n `Device not recognized: ${bleGattService.device.name}`,\n ),\n );\n }\n return Right(bleDeviceInfos);\n }\n\n /**\n * Prompt device selection in navigator\n *\n * @private\n */\n private promptDeviceAccess(): EitherAsync<\n PromptDeviceAccessError,\n BluetoothDevice\n > {\n return EitherAsync(async ({ liftEither, throwE }) => {\n const bluetoothApi = await liftEither(this.getBluetoothApi());\n let bleDevice: BluetoothDevice;\n\n try {\n bleDevice = await bluetoothApi.requestDevice({\n filters: this._deviceModelDataSource\n .getBluetoothServices()\n .map((serviceUuid) => ({\n services: [serviceUuid],\n })),\n });\n } catch (error) {\n return throwE(new NoAccessibleDeviceError(error));\n }\n\n return bleDevice;\n });\n }\n\n /**\n * Generate a discovered device from BluetoothDevice, BleGATT primary service and BLE device infos\n * @param bleDeviceInfos\n * @private\n */\n private getDiscoveredDeviceFrom(\n bleDeviceInfos: BleDeviceInfos,\n ): TransportDiscoveredDevice {\n return {\n id: uuid(),\n deviceModel: bleDeviceInfos.deviceModel,\n transport: this.identifier,\n };\n }\n\n /**\n * Generate an InternalDevice from a unique id, a BluetoothDevice, BleGATT primary service and BLE device infos\n * @param discoveredDevice\n * @param bleDevice\n * @param bleDeviceInfos\n * @param bleGattService\n * @private\n */\n private setInternalDeviceFrom(\n discoveredDevice: TransportDiscoveredDevice,\n bleDevice: BluetoothDevice,\n bleDeviceInfos: BleDeviceInfos,\n bleGattService: BluetoothRemoteGATTService,\n ) {\n const internalDevice: WebBleInternalDevice = {\n id: discoveredDevice.id,\n bleDevice,\n bleGattService,\n bleDeviceInfos,\n discoveredDevice,\n };\n\n this._logger.debug(\n `Discovered device ${internalDevice.id} ${discoveredDevice.deviceModel.productName}`,\n );\n this._internalDevicesById.set(internalDevice.id, internalDevice);\n }\n\n /**\n * Main method to get a device from a button click handler\n * The GATT connection is done here in order to populate TransportDiscoveredDevice with deviceModel\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n this._logger.debug(\"startDiscovering\");\n\n return from(this.promptDeviceAccess()).pipe(\n switchMap(async (errorOrBleDevice) =>\n EitherAsync(async ({ liftEither, fromPromise }) => {\n const bleDevice = await liftEither(errorOrBleDevice);\n if (bleDevice.gatt) {\n try {\n await bleDevice.gatt.connect();\n } catch (error) {\n throw new OpeningConnectionError(error);\n }\n }\n try {\n const bleGattService = await fromPromise(\n this.getBleGattService(bleDevice),\n );\n const bleDeviceInfos = await liftEither(\n this.getBleDeviceInfos(bleGattService),\n );\n const discoveredDevice =\n this.getDiscoveredDeviceFrom(bleDeviceInfos);\n this.setInternalDeviceFrom(\n discoveredDevice,\n bleDevice,\n bleDeviceInfos,\n bleGattService,\n );\n return discoveredDevice;\n } catch (error) {\n await bleDevice.forget();\n throw error;\n }\n }).caseOf({\n Right: (discoveredDevice) => discoveredDevice,\n Left: (error) => {\n this._logger.error(\"Error while getting accessible device\", {\n data: { error },\n });\n throw error;\n },\n }),\n ),\n );\n }\n\n stopDiscovering(): void {\n this._logger.debug(\"stopDiscovering\");\n }\n\n /**\n * Connect to a BLE device and update the internal state of the associated device\n * Handle ondisconnect event on the device in order to try a reconnection\n */\n async connect({\n deviceId,\n onDisconnect,\n }: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n const internalDevice = this._internalDevicesById.get(deviceId);\n\n if (!internalDevice) {\n this._logger.error(`Unknown device ${deviceId}`, {\n data: { internalDevices: this._internalDevicesById },\n });\n this._logger.debug(\"Available devices\", {\n data: { devices: this._internalDevicesById },\n });\n return Left(new UnknownDeviceError(`Unknown device ${deviceId}`));\n }\n // if device already connected, remove device id from internal state and remove error\n if (this._connectedDevices.includes(internalDevice.bleDevice)) {\n this._internalDevicesById.delete(deviceId);\n return Left(new DeviceAlreadyConnectedError(\"Device already connected\"));\n }\n\n const {\n discoveredDevice: { deviceModel },\n } = internalDevice;\n\n try {\n const [writeCharacteristic, notifyCharacteristic] = await Promise.all([\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.writeCmdUuid,\n ),\n internalDevice.bleGattService.getCharacteristic(\n internalDevice.bleDeviceInfos.notifyUuid,\n ),\n ]);\n\n const deviceConnection = new BleDeviceConnection(\n {\n writeCharacteristic,\n notifyCharacteristic,\n apduReceiverFactory: this._apduReceiverFactory,\n apduSenderFactory: this._apduSenderFactory,\n },\n this._loggerServiceFactory,\n );\n\n await deviceConnection.setup();\n\n const connectedDevice = new TransportConnectedDevice({\n sendApdu: (apdu, triggersDisconnection) =>\n deviceConnection.sendApdu(apdu, triggersDisconnection),\n deviceModel,\n id: deviceId,\n type: this.connectionType,\n transport: this.identifier,\n });\n\n internalDevice.bleDevice.ongattserverdisconnected =\n this._getDeviceDisconnectedHandler(internalDevice, deviceConnection);\n\n this._deviceConnectionById.set(internalDevice.id, deviceConnection);\n this._disconnectionHandlersById.set(internalDevice.id, () => {\n this.disconnect({ connectedDevice }).then(() => onDisconnect(deviceId));\n });\n\n this._connectedDevices.push(internalDevice.bleDevice);\n\n return Right(connectedDevice);\n } catch (error) {\n await internalDevice.bleDevice.forget();\n\n this._internalDevicesById.delete(deviceId);\n\n this._logger.error(\"Error while getting characteristics\", {\n data: { error },\n });\n\n return Left(new OpeningConnectionError(error));\n }\n }\n\n /**\n * Get the device disconnected handler\n * @param internalDevice WebBleInternalDevice\n * @param deviceConnection BleDeviceConnection\n * @returns async () => void\n * @private\n */\n private _getDeviceDisconnectedHandler(\n internalDevice: WebBleInternalDevice,\n deviceConnection: BleDeviceConnection,\n ) {\n return async () => {\n // start a timer to disconnect the device if it does not reconnect\n const disconnectObserver = timer(RECONNECT_DEVICE_TIMEOUT).subscribe(\n () => {\n this._logger.debug(\"disconnection timer over\");\n // retrieve the disconnect handler and call it\n const disconnectHandler = Maybe.fromNullable(\n this._disconnectionHandlersById.get(internalDevice.id),\n );\n disconnectHandler.map((handler) => handler());\n },\n );\n\n // connect to the navigator device\n await internalDevice.bleDevice.gatt?.connect();\n\n // cancel disconnection timeout\n disconnectObserver.unsubscribe();\n\n // retrieve new ble characteristics\n const service = await this.getBleGattService(internalDevice.bleDevice);\n\n if (service.isRight()) {\n const [writeC, notifyC] = await Promise.all([\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.writeCmdUuid),\n service\n .extract()\n .getCharacteristic(internalDevice.bleDeviceInfos.notifyUuid),\n ]);\n\n // reconnect device connection\n await deviceConnection.reconnect(writeC, notifyC);\n }\n };\n }\n\n /**\n * Disconnect from a BLE device and delete its handlers\n *\n * @param params { connectedDevice: TransportConnectedDevice }\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n // retrieve internal device\n const maybeInternalDevice = Maybe.fromNullable(\n this._internalDevicesById.get(params.connectedDevice.id),\n );\n\n this._logger.debug(\"disconnect device\", {\n data: { connectedDevice: params.connectedDevice },\n });\n\n if (maybeInternalDevice.isNothing()) {\n this._logger.error(`Unknown device ${params.connectedDevice.id}`);\n\n return Promise.resolve(\n Left(\n new UnknownDeviceError(`Unknown device ${params.connectedDevice.id}`),\n ),\n );\n }\n\n maybeInternalDevice.map((device) => {\n const { bleDevice } = device;\n\n // retrieve device connection and disconnect it\n const maybeDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionById.get(device.id),\n );\n\n maybeDeviceConnection.map((dConnection) => dConnection.disconnect());\n\n // disconnect device gatt server\n if (bleDevice.gatt?.connected) {\n bleDevice.gatt.disconnect();\n }\n // clean up objects\n this._internalDevicesById.delete(device.id);\n this._deviceConnectionById.delete(device.id);\n this._disconnectionHandlersById.delete(device.id);\n\n if (this._connectedDevices.includes(bleDevice)) {\n delete this._connectedDevices[\n this._connectedDevices.indexOf(bleDevice)\n ];\n }\n });\n\n return Promise.resolve(Right(undefined));\n }\n}\n\nexport const webBleTransportFactory: TransportFactory = ({\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n}) =>\n new WebBleTransport(\n deviceModelDataSource,\n loggerServiceFactory,\n apduSenderServiceFactory,\n apduReceiverServiceFactory,\n );\n"],
5
+ "mappings": "AAAA,OAME,+BAAAA,EAGA,4BAAAC,EAIA,2BAAAC,EACA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAsB,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YAC7D,OAAS,QAAAC,EAAuB,aAAAC,EAAW,S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 "names": ["DeviceAlreadyConnectedError", "DeviceNotRecognizedError", "NoAccessibleDeviceError", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "EitherAsync", "Left", "Maybe", "Right", "from", "switchMap", "timer", "uuid", "RECONNECT_DEVICE_TIMEOUT", "BleDeviceGattServerError", "BleTransportNotSupportedError", "BleDeviceConnection", "webBleIdentifier", "WebBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "bleDevice", "bleGattService", "e", "bleDeviceInfos", "liftEither", "throwE", "bluetoothApi", "serviceUuid", "error", "discoveredDevice", "internalDevice", "errorOrBleDevice", "fromPromise", "deviceId", "onDisconnect", "deviceModel", "writeCharacteristic", "notifyCharacteristic", "deviceConnection", "connectedDevice", "apdu", "triggersDisconnection", "disconnectObserver", "handler", "service", "writeC", "notifyC", "params", "maybeInternalDevice", "device", "dConnection", "webBleTransportFactory", "deviceModelDataSource", "loggerServiceFactory", "apduSenderServiceFactory", "apduReceiverServiceFactory"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{NoAccessibleDeviceError as v,OpeningConnectionError as b,StaticDeviceModelDataSource as m,UnknownDeviceError as p}from"@ledgerhq/device-management-kit";import{Left as h,Right as S}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as f}from"../data/WebBleConfig";import{bleDeviceStubBuilder as w}from"../model/BleDevice.stub";import{BleTransportNotSupportedError as D}from"../model/Errors";import{BleDeviceGattServerError as g}from"../model/Errors";import{WebBleTransport as E}from"./WebBleTransport";class j{subscribers=[];tag;constructor(a,d){this.subscribers=a,this.tag=d}error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}const y=new m,k=new j([],"web-ble"),r=w();describe("WebBleTransport",()=>{let n,a,d;beforeEach(()=>{a=jest.fn(),d=jest.fn(),n=new E(y,()=>k,d,a),jest.useFakeTimers()}),afterEach(()=>{jest.restoreAllMocks()});const i=(o,e)=>{n.startDiscovering().subscribe({next:o,error:e})};describe("When Web bluetooth API is not supported",()=>{it("should not support the transport",()=>{expect(n.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",o=>{i(()=>{o("Should not emit any value")},e=>{expect(e).toBeInstanceOf(D),o()})})}),describe("When Web Bluetooth API is supported",()=>{const o=jest.fn();beforeAll(()=>{global.navigator={bluetooth:{requestDevice:o}}}),afterAll(()=>{jest.restoreAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(n.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{it("should emit device if one new grant access",e=>{o.mockResolvedValueOnce(r),i(t=>{try{expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:"nanoX",productName:"Ledger Nano X"})})),e()}catch(c){e(c)}},t=>{e(t)})}),it("should throw DeviceNotRecognizedError if the device is not recognized",e=>{o.mockResolvedValueOnce({...r,gatt:{...r.gatt,getPrimaryServices:jest.fn(()=>Promise.resolve([]))},productId:16962}),i(()=>{e("should not return a device")},t=>{expect(t).toBeInstanceOf(g),e()})}),it("should emit an error if the request device is in error",e=>{const t="request device error";o.mockImplementationOnce(()=>{throw new Error(t)}),i(()=>{e("should not return a device")},c=>{expect(c).toBeInstanceOf(v),expect(c).toStrictEqual(new v(new Error(t))),e()})}),it("should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)",e=>{o.mockResolvedValueOnce({forget:jest.fn()}),i(t=>{e(`Should not emit any value, but emitted ${JSON.stringify(t)}`)},t=>{try{expect(t).toBeInstanceOf(g),e()}catch(c){e(c)}})})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const e={deviceId:"fake",onDisconnect:jest.fn()},t=await n.connect(e);expect(t).toStrictEqual(h(new p("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const e={deviceId:"fake",onDisconnect:jest.fn()},t=await n.connect(e);expect(t).toStrictEqual(h(new p("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",e=>{const t="cannot be opened";o.mockResolvedValueOnce({...r,gatt:{connect:()=>{throw new Error(t)}}}),i(()=>{e()},c=>{expect(c).toBeInstanceOf(b),e()})}),it("should return the opened device",e=>{o.mockResolvedValueOnce({...r,gatt:{...r.gatt,connected:!0}}),i(t=>{n.connect({deviceId:t.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(s=>{expect(s).toEqual(expect.objectContaining({id:t.id})),e()}).ifLeft(()=>{e(c)})}).catch(c=>{e(c)})},t=>{e(t)})}),it("should return a device if available",e=>{o.mockResolvedValueOnce(r),i(t=>{n.connect({deviceId:t.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(s=>{expect(s).toEqual(expect.objectContaining({id:t.id})),e()}).ifLeft(()=>{e(c)})}).catch(c=>{e(c)})},t=>{e(t)})})}),describe("disconnect",()=>{it("should disconnect the device",e=>{o.mockResolvedValueOnce(r);const t=jest.fn();i(c=>{n.connect({deviceId:c.id,onDisconnect:t}).then(s=>{s.ifRight(l=>{n.disconnect({connectedDevice:l}).then(u=>{expect(u).toStrictEqual(S(void 0)),e()}).catch(u=>{e(u)})})})},c=>{e(c)})}),it("should call disconnect handler if device is hardware disconnected",e=>{const t=jest.fn(),c=jest.spyOn(n,"disconnect");o.mockResolvedValueOnce(r),i(s=>{n.connect({deviceId:s.id,onDisconnect:t}).then(()=>{r.ongattserverdisconnected(new Event("")),jest.advanceTimersByTime(f),expect(c).toHaveBeenCalled(),e()})},s=>{e(s)})})}),describe("reconnect",()=>{it("should not call disconnection if reconnection happen",e=>{const t=jest.fn(),c=jest.spyOn(n,"disconnect");o.mockResolvedValueOnce(r),i(s=>{n.connect({deviceId:s.id,onDisconnect:t}).then(()=>{r.ongattserverdisconnected(new Event("")),jest.advanceTimersByTime(f/3),expect(c).toHaveBeenCalledTimes(0),e()}).catch(l=>{e(l)})})})})})});
2
+ //# sourceMappingURL=WebBleTransport.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/api/transport/WebBleTransport.test.ts"],
4
+ "sourcesContent": ["import {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type DeviceModel,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n NoAccessibleDeviceError,\n OpeningConnectionError,\n StaticDeviceModelDataSource,\n type TransportDiscoveredDevice,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebBleConfig\";\nimport { bleDeviceStubBuilder } from \"@api/model/BleDevice.stub\";\nimport { BleTransportNotSupportedError } from \"@api/model/Errors\";\nimport { BleDeviceGattServerError } from \"@api/model/Errors\";\n\nimport { WebBleTransport } from \"./WebBleTransport\";\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 = jest.fn();\n warn = jest.fn();\n info = jest.fn();\n debug = jest.fn();\n}\n\n// Our StaticDeviceModelDataSource can directly be used in our unit tests\nconst bleDeviceModelDataSource = new StaticDeviceModelDataSource();\nconst logger = new LoggerPublisherServiceStub([], \"web-ble\");\n\nconst stubDevice: BluetoothDevice = bleDeviceStubBuilder();\n\ndescribe(\"WebBleTransport\", () => {\n let transport: WebBleTransport;\n let apduReceiverServiceFactoryStub: ApduReceiverServiceFactory;\n let apduSenderServiceFactoryStub: ApduSenderServiceFactory;\n\n beforeEach(() => {\n apduReceiverServiceFactoryStub = jest.fn();\n apduSenderServiceFactoryStub = jest.fn();\n transport = new WebBleTransport(\n bleDeviceModelDataSource,\n () => logger,\n apduSenderServiceFactoryStub,\n apduReceiverServiceFactoryStub,\n );\n jest.useFakeTimers();\n });\n\n afterEach(() => {\n jest.restoreAllMocks();\n });\n\n const discoverDevice = (\n onSuccess: (discoveredDevice: TransportDiscoveredDevice) => void,\n onError?: (error: unknown) => void,\n ) => {\n transport.startDiscovering().subscribe({\n next: onSuccess,\n error: onError,\n });\n };\n\n describe(\"When Web bluetooth API is not supported\", () => {\n it(\"should not support the transport\", () => {\n expect(transport.isSupported()).toBe(false);\n });\n\n it(\"should emit a startDiscovering error\", (done) => {\n discoverDevice(\n () => {\n done(\"Should not emit any value\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleTransportNotSupportedError);\n done();\n },\n );\n });\n });\n\n describe(\"When Web Bluetooth API is supported\", () => {\n const mockedRequestDevice = jest.fn();\n\n beforeAll(() => {\n global.navigator = {\n bluetooth: {\n requestDevice: mockedRequestDevice,\n },\n } as unknown as Navigator;\n });\n\n afterAll(() => {\n jest.restoreAllMocks();\n global.navigator = undefined as unknown as Navigator;\n });\n\n it(\"should support the transport\", () => {\n expect(transport.isSupported()).toBe(true);\n });\n\n describe(\"startDiscovering\", () => {\n it(\"should emit device if one new grant access\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n try {\n expect(discoveredDevice).toEqual(\n expect.objectContaining({\n deviceModel: expect.objectContaining({\n id: \"nanoX\",\n productName: \"Ledger Nano X\",\n }) as DeviceModel,\n }),\n );\n\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should throw DeviceNotRecognizedError if the device is not recognized\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n getPrimaryServices: jest.fn(() => Promise.resolve([])),\n },\n productId: 0x4242,\n });\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n done();\n },\n );\n });\n\n it(\"should emit an error if the request device is in error\", (done) => {\n const message = \"request device error\";\n mockedRequestDevice.mockImplementationOnce(() => {\n throw new Error(message);\n });\n\n discoverDevice(\n () => {\n done(\"should not return a device\");\n },\n (error) => {\n expect(error).toBeInstanceOf(NoAccessibleDeviceError);\n expect(error).toStrictEqual(\n new NoAccessibleDeviceError(new Error(message)),\n );\n done();\n },\n );\n });\n\n it(\"should emit an error if the user did not grant us access to a device (clicking on cancel on the browser popup for ex)\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({ forget: jest.fn() });\n\n discoverDevice(\n (discoveredDevice) => {\n done(\n `Should not emit any value, but emitted ${JSON.stringify(\n discoveredDevice,\n )}`,\n );\n },\n (error) => {\n try {\n expect(error).toBeInstanceOf(BleDeviceGattServerError);\n done();\n } catch (expectError) {\n done(expectError);\n }\n },\n );\n });\n });\n\n describe(\"connect\", () => {\n it(\"should throw UnknownDeviceError if no internal device\", async () => {\n const connectParams = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(connectParams);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device is already opened\", async () => {\n const device = {\n deviceId: \"fake\",\n onDisconnect: jest.fn(),\n };\n\n const connect = await transport.connect(device);\n\n expect(connect).toStrictEqual(\n Left(new UnknownDeviceError(\"Unknown device fake\")),\n );\n });\n\n it(\"should throw OpeningConnectionError if the device cannot be opened\", (done) => {\n const message = \"cannot be opened\";\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n connect: () => {\n throw new Error(message);\n },\n },\n });\n\n discoverDevice(\n () => {\n done();\n },\n (error) => {\n expect(error).toBeInstanceOf(OpeningConnectionError);\n done();\n },\n );\n });\n\n it(\"should return the opened device\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce({\n ...stubDevice,\n gatt: {\n ...stubDevice.gatt,\n connected: true,\n },\n });\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n\n it(\"should return a device if available\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect: jest.fn(),\n })\n .then((connectedDevice) => {\n connectedDevice\n .ifRight((device) => {\n expect(device).toEqual(\n expect.objectContaining({ id: discoveredDevice.id }),\n );\n done();\n })\n .ifLeft(() => {\n done(connectedDevice);\n });\n })\n .catch((error) => {\n done(error);\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n describe(\"disconnect\", () => {\n it(\"should disconnect the device\", (done) => {\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n const onDisconnect = jest.fn();\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then((connectedDevice) => {\n connectedDevice.ifRight((device) => {\n transport\n .disconnect({ connectedDevice: device })\n .then((value) => {\n expect(value).toStrictEqual(Right(void 0));\n done();\n })\n .catch((error) => {\n done(error);\n });\n });\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n it(\"should call disconnect handler if device is hardware disconnected\", (done) => {\n const onDisconnect = jest.fn();\n const disconnectSpy = jest.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n discoverDevice(\n (discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n expect(disconnectSpy).toHaveBeenCalled();\n done();\n });\n },\n (error) => {\n done(error);\n },\n );\n });\n });\n\n describe(\"reconnect\", () => {\n it(\"should not call disconnection if reconnection happen\", (done) => {\n // given\n const onDisconnect = jest.fn();\n const disconnectSpy = jest.spyOn(transport, \"disconnect\");\n mockedRequestDevice.mockResolvedValueOnce(stubDevice);\n\n // when\n discoverDevice((discoveredDevice) => {\n transport\n .connect({\n deviceId: discoveredDevice.id,\n onDisconnect,\n })\n .then(() => {\n stubDevice.ongattserverdisconnected(new Event(\"\"));\n\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT / 3);\n\n // then\n expect(disconnectSpy).toHaveBeenCalledTimes(0);\n done();\n })\n .catch((error) => {\n done(error);\n });\n });\n });\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAME,2BAAAA,EACA,0BAAAC,EACA,+BAAAC,EAEA,sBAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,wBAAAC,MAA4B,4BACrC,OAAS,iCAAAC,MAAqC,oBAC9C,OAAS,4BAAAC,MAAgC,oBAEzC,OAAS,mBAAAC,MAAuB,oBAEhC,MAAMC,CAA6D,CACjE,YAAyC,CAAC,EAC1C,IACA,YAAYC,EAAwCC,EAAa,CAC/D,KAAK,YAAcD,EACnB,KAAK,IAAMC,CACb,CACA,MAAQ,KAAK,GAAG,EAChB,KAAO,KAAK,GAAG,EACf,KAAO,KAAK,GAAG,EACf,MAAQ,KAAK,GAAG,CAClB,CAGA,MAAMC,EAA2B,IAAIZ,EAC/Ba,EAAS,IAAIJ,EAA2B,CAAC,EAAG,SAAS,EAErDK,EAA8BT,EAAqB,EAEzD,SAAS,kBAAmB,IAAM,CAChC,IAAIU,EACAC,EACAC,EAEJ,WAAW,IAAM,CACfD,EAAiC,KAAK,GAAG,EACzCC,EAA+B,KAAK,GAAG,EACvCF,EAAY,IAAIP,EACdI,EACA,IAAMC,EACNI,EACAD,CACF,EACA,KAAK,cAAc,CACrB,CAAC,EAED,UAAU,IAAM,CACd,KAAK,gBAAgB,CACvB,CAAC,EAED,MAAME,EAAiB,CACrBC,EACAC,IACG,CACHL,EAAU,iBAAiB,EAAE,UAAU,CACrC,KAAMI,EACN,MAAO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A2B,CAAC,EAGrD,OAAO6B,CAAa,EAAE,sBAAsB,CAAC,EAC7CZ,EAAK,CACP,CAAC,EACA,MAAOC,GAAU,CAChBD,EAAKC,CAAK,CACZ,CAAC,CACL,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["NoAccessibleDeviceError", "OpeningConnectionError", "StaticDeviceModelDataSource", "UnknownDeviceError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "bleDeviceStubBuilder", "BleTransportNotSupportedError", "BleDeviceGattServerError", "WebBleTransport", "LoggerPublisherServiceStub", "subscribers", "tag", "bleDeviceModelDataSource", "logger", "stubDevice", "transport", "apduReceiverServiceFactoryStub", "apduSenderServiceFactoryStub", "discoverDevice", "onSuccess", "onError", "done", "error", "mockedRequestDevice", "discoveredDevice", "expectError", "message", "connectParams", "connect", "device", "connectedDevice", "onDisconnect", "value", "disconnectSpy"]
7
+ }
@@ -0,0 +1,2 @@
1
+ export*from"./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": "AAAA,WAAc",
6
+ "names": []
7
+ }
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@ledgerhq/device-transport-kit-web-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 --platform web",
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 --platform web",
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": "jest --passWithNoTests",
34
+ "test:watch": "pnpm test -- --watch",
35
+ "test:coverage": "pnpm test -- --coverage"
36
+ },
37
+ "dependencies": {
38
+ "@sentry/minimal": "^6.19.7",
39
+ "purify-ts": "^2.1.0",
40
+ "uuid": "^11.0.3"
41
+ },
42
+ "devDependencies": {
43
+ "@ledgerhq/device-management-kit": "workspace:*",
44
+ "@ledgerhq/esbuild-tools": "workspace:*",
45
+ "@ledgerhq/eslint-config-dsdk": "workspace:*",
46
+ "@ledgerhq/jest-config-dsdk": "workspace:*",
47
+ "@ledgerhq/prettier-config-dsdk": "workspace:*",
48
+ "@ledgerhq/tsconfig-dsdk": "workspace:*",
49
+ "@types/uuid": "^10.0.0",
50
+ "@types/web-bluetooth": "^0.0.20",
51
+ "rxjs": "^7.8.1",
52
+ "ts-node": "^10.9.2"
53
+ },
54
+ "peerDependencies": {
55
+ "@ledgerhq/device-management-kit": "workspace:*",
56
+ "rxjs": "^7.8.1"
57
+ }
58
+ }
@@ -0,0 +1,2 @@
1
+ export declare const RECONNECT_DEVICE_TIMEOUT = 6000;
2
+ //# sourceMappingURL=WebBleConfig.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebBleConfig.d.ts","sourceRoot":"","sources":["../../../../src/api/data/WebBleConfig.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,wBAAwB,OAAO,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./model/Errors";
2
+ export { webBleIdentifier, WebBleTransport, webBleTransportFactory, } from "./transport/WebBleTransport";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,sBAAsB,GACvB,MAAM,6BAA6B,CAAC"}
@@ -0,0 +1,3 @@
1
+ export declare const bleCharacteristicStubBuilder: (props?: Partial<BluetoothRemoteGATTCharacteristic>) => BluetoothRemoteGATTCharacteristic;
2
+ export declare const bleDeviceStubBuilder: (props?: Partial<BluetoothDevice>) => BluetoothDevice;
3
+ //# sourceMappingURL=BleDevice.stub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BleDevice.stub.d.ts","sourceRoot":"","sources":["../../../../src/api/model/BleDevice.stub.ts"],"names":[],"mappings":"AAoCA,eAAO,MAAM,4BAA4B,WAChC,OAAO,CAAC,iCAAiC,CAAC,KAChD,iCAQsC,CAAC;AAE1C,eAAO,MAAM,oBAAoB,WACxB,OAAO,CAAC,eAAe,CAAC,KAC9B,eAaD,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { GeneralDmkError } from "@ledgerhq/device-management-kit";
2
+ export declare class BleTransportNotSupportedError extends GeneralDmkError {
3
+ readonly err?: unknown;
4
+ readonly _tag = "BleTransportNotSupportedError";
5
+ constructor(err?: unknown);
6
+ }
7
+ export declare class BleDeviceGattServerError extends GeneralDmkError {
8
+ readonly err?: unknown;
9
+ readonly _tag = "BleDeviceGattServerError";
10
+ constructor(err?: unknown);
11
+ }
12
+ //# sourceMappingURL=Errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Errors.d.ts","sourceRoot":"","sources":["../../../../src/api/model/Errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAElE,qBAAa,6BAA8B,SAAQ,eAAe;IAEpD,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,mCAAmC;gBACpC,GAAG,CAAC,EAAE,OAAO;CAGnC;AACD,qBAAa,wBAAyB,SAAQ,eAAe;IAE/C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO;IADlC,SAAkB,IAAI,8BAA8B;gBAC/B,GAAG,CAAC,EAAE,OAAO;CAGnC"}