@ledgerhq/device-transport-kit-web-hid 0.0.0-develop-20250106155104 → 0.0.0-rnble-transport-20250219100517

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,77 @@
1
+ # Transport Device Kit Web HID
2
+
3
+ > [!CAUTION]
4
+ > This is still under development and we are free to make new interfaces which may lead to breaking changes.
5
+
6
+ - [Transport Device Kit Web HID Documentation](#transport-device-kit-web-hid)
7
+ - [Description](#description)
8
+ - [Installation](#installation)
9
+ - [Usage](#usage)
10
+ - [Compatibility](#compatibility)
11
+ - [Pre-requisites](#pre-requisites)
12
+ - [Main Features](#main-features)
13
+ - [How To](#how-to)
14
+
15
+ ## Description
16
+
17
+ This transport is used to interact with a Ledger device through the Web HID (usb) implementation by the Device Management Kit.
18
+
19
+ ## Installation
20
+
21
+ To install the core package, run the following command:
22
+
23
+ ```sh
24
+ npm install @ledgerhq/device-transport-kit-web-hid
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Compatibility
30
+
31
+ This library works in [any browser supporting the WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API#browser_compatibility).
32
+
33
+ ### Pre-requisites
34
+
35
+ To use this transport, ensure you have the Device Magement Kit installed in your project.
36
+
37
+ ### Main Features
38
+
39
+ - Exposing a transport factory to be injected into the DeviceManagementKit
40
+ - Exposing the transport directly for a custom configuration
41
+
42
+ ### How To
43
+
44
+ To use the transport, you need to inject it in the DeviceManagementKitBuilder before the build. This will allow the Devivce Management Kit to find and interact with devices on the Web HID protocol.
45
+
46
+ ```typescript
47
+ import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit"
48
+ import { webHidTransportFactory, WebHidTransport } from "@ledgerhq/device-transport-kit-web-hid"
49
+
50
+ // Easy setup with the factory
51
+ const dmk = new DeviceManagementKitBuilder()
52
+ .addTransport(webHidTransportFactory)
53
+ .build();
54
+
55
+
56
+ // With custom config
57
+ const dmk = new DeviceManagementKitBuilder()
58
+ .addTransport(({
59
+ deviceModelDataSource: DeviceModelDataSource;
60
+ loggerServiceFactory: (tag: string) => LoggerPublisherService;
61
+ config: DmkConfig;
62
+ apduSenderServiceFactory: ApduSenderServiceFactory;
63
+ apduReceiverServiceFactory: ApduReceiverServiceFactory;
64
+ }) => {
65
+ // custom code
66
+ return new WebHidTransport(
67
+ deviceModelDataSource,
68
+ loggerServiceFactory,
69
+ config,
70
+ apduSenderServiceFactory,
71
+ apduReceiverServiceFactory,
72
+ );
73
+ })
74
+ .build();
75
+
76
+ // You can then make use of the Device Management Kit
77
+ ```
@@ -1,2 +1,2 @@
1
- const e=jest.fn().mockResolvedValue(void 0),n=(t={})=>({opened:!1,productId:16401,vendorId:11415,productName:"Ledger Nano X",collections:[],open:jest.fn().mockResolvedValue(void 0),oninputreport:e,close:jest.fn().mockResolvedValue(void 0),sendReport:jest.fn().mockResolvedValue(e()),sendFeatureReport:jest.fn(),forget:jest.fn(),receiveFeatureReport:jest.fn(),addEventListener:jest.fn(),removeEventListener:jest.fn(),dispatchEvent:jest.fn(),...t});export{n as hidDeviceStubBuilder};
1
+ const e=vi.fn().mockResolvedValue(void 0),o=(n={})=>({opened:!1,productId:16401,vendorId:11415,productName:"Ledger Nano X",collections:[],open:vi.fn().mockResolvedValue(void 0),oninputreport:e,close:vi.fn().mockResolvedValue(void 0),sendReport:vi.fn().mockResolvedValue(e()),sendFeatureReport:vi.fn(),forget:vi.fn(),receiveFeatureReport:vi.fn(),addEventListener:vi.fn(),removeEventListener:vi.fn(),dispatchEvent:vi.fn(),...n});export{o as hidDeviceStubBuilder};
2
2
  //# sourceMappingURL=HIDDevice.stub.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/model/HIDDevice.stub.ts"],
4
- "sourcesContent": ["const oninputreport = jest.fn().mockResolvedValue(void 0);\n\nexport const hidDeviceStubBuilder = (\n props: Partial<HIDDevice> = {},\n): HIDDevice => ({\n opened: false,\n productId: 0x4011,\n vendorId: 0x2c97,\n productName: \"Ledger Nano X\",\n collections: [],\n open: jest.fn().mockResolvedValue(undefined),\n oninputreport,\n close: jest.fn().mockResolvedValue(undefined),\n sendReport: jest.fn().mockResolvedValue(oninputreport()),\n sendFeatureReport: jest.fn(),\n forget: jest.fn(),\n receiveFeatureReport: jest.fn(),\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n ...props,\n});\n"],
5
- "mappings": "AAAA,MAAMA,EAAgB,KAAK,GAAG,EAAE,kBAAkB,MAAM,EAE3CC,EAAuB,CAClCC,EAA4B,CAAC,KACd,CACf,OAAQ,GACR,UAAW,MACX,SAAU,MACV,YAAa,gBACb,YAAa,CAAC,EACd,KAAM,KAAK,GAAG,EAAE,kBAAkB,MAAS,EAC3C,cAAAF,EACA,MAAO,KAAK,GAAG,EAAE,kBAAkB,MAAS,EAC5C,WAAY,KAAK,GAAG,EAAE,kBAAkBA,EAAc,CAAC,EACvD,kBAAmB,KAAK,GAAG,EAC3B,OAAQ,KAAK,GAAG,EAChB,qBAAsB,KAAK,GAAG,EAC9B,iBAAkB,KAAK,GAAG,EAC1B,oBAAqB,KAAK,GAAG,EAC7B,cAAe,KAAK,GAAG,EACvB,GAAGE,CACL",
4
+ "sourcesContent": ["const oninputreport = vi.fn().mockResolvedValue(void 0);\n\nexport const hidDeviceStubBuilder = (\n props: Partial<HIDDevice> = {},\n): HIDDevice => ({\n opened: false,\n productId: 0x4011,\n vendorId: 0x2c97,\n productName: \"Ledger Nano X\",\n collections: [],\n open: vi.fn().mockResolvedValue(undefined),\n oninputreport,\n close: vi.fn().mockResolvedValue(undefined),\n sendReport: vi.fn().mockResolvedValue(oninputreport()),\n sendFeatureReport: vi.fn(),\n forget: vi.fn(),\n receiveFeatureReport: vi.fn(),\n addEventListener: vi.fn(),\n removeEventListener: vi.fn(),\n dispatchEvent: vi.fn(),\n ...props,\n});\n"],
5
+ "mappings": "AAAA,MAAMA,EAAgB,GAAG,GAAG,EAAE,kBAAkB,MAAM,EAEzCC,EAAuB,CAClCC,EAA4B,CAAC,KACd,CACf,OAAQ,GACR,UAAW,MACX,SAAU,MACV,YAAa,gBACb,YAAa,CAAC,EACd,KAAM,GAAG,GAAG,EAAE,kBAAkB,MAAS,EACzC,cAAAF,EACA,MAAO,GAAG,GAAG,EAAE,kBAAkB,MAAS,EAC1C,WAAY,GAAG,GAAG,EAAE,kBAAkBA,EAAc,CAAC,EACrD,kBAAmB,GAAG,GAAG,EACzB,OAAQ,GAAG,GAAG,EACd,qBAAsB,GAAG,GAAG,EAC5B,iBAAkB,GAAG,GAAG,EACxB,oBAAqB,GAAG,GAAG,EAC3B,cAAe,GAAG,GAAG,EACrB,GAAGE,CACL",
6
6
  "names": ["oninputreport", "hidDeviceStubBuilder", "props"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{CommandUtils as g,ReconnectionFailedError as h}from"@ledgerhq/device-management-kit";import{Left as c,Maybe as m,Nothing as s,Right as d}from"purify-ts";import{Subject as a}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as l}from"../data/WebHidConfig";import{WebHidSendReportError as u}from"../model/Errors";class D{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new a;_logger;_pendingApdu=s;_onConnectionTerminated;reconnectionSubject=new a;waitingForReconnection=!1;lostConnectionTimeout=null;terminated=!1;constructor({device:t,deviceId:n,apduSender:o,apduReceiver:r,onConnectionTerminated:e},i){this._apduSender=o,this._apduReceiver=r,this._onConnectionTerminated=e,this._logger=i("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=p=>this.receiveHidInputReport(p),this._deviceId=n,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,n){this._sendApduSubject=new a,this._pendingApdu=m.of(t),this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const o=new Promise(e=>{this._sendApduSubject.subscribe({next:async i=>{this._pendingApdu=s,n&&g.isSuccessResponse(i)?(await this.waitForReconnection()).caseOf({Left:v=>e(c(v)),Right:()=>e(d(i))}):e(d(i))},error:i=>{this._pendingApdu=s,e(c(i))}})});if(this.waitingForReconnection||!this.device.opened){const e=this.device.opened&&this._pendingApdu.isJust(),i=await this.waitForReconnection(e);if(i.isLeft())return i}const r=this._apduSender.getFrames(t);for(const e of r){this._logger.debug("Sending Frame",{data:{frame:e.getRawData()}});try{await this._device.sendReport(0,e.getRawData())}catch(i){return this._logger.error("Error sending frame",{data:{error:i}}),Promise.resolve(c(new u(i)))}}return o}receiveHidInputReport(t){const n=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:n},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(n).caseOf({Right:r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduSubject.next(e),this._sendApduSubject.complete()})},Left:r=>{this._sendApduSubject.error(r)}})}waitForReconnection(t=!1){return this.terminated?Promise.resolve(c(new h)):new Promise(n=>{const o=this.reconnectionSubject.subscribe({next:r=>{t&&this._sendApduSubject.error(new u),n(r==="success"?d(void 0):c(r)),o.unsubscribe()}})})}lostConnection(){this._logger.info("\u23F1\uFE0F Lost connection, starting timer"),this.waitingForReconnection=!0,this.lostConnectionTimeout=setTimeout(()=>{this._logger.info("\u274C Disconnection timeout, terminating connection"),this.disconnect()},l)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=n=>this.receiveHidInputReport(n),this.lostConnectionTimeout&&(this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),clearTimeout(this.lostConnectionTimeout)),await t.open(),this._pendingApdu.isJust()&&this._sendApduSubject.error(new u),this.waitingForReconnection=!1,this.reconnectionSubject.next("success")}disconnect(){this._logger.info("\u{1F51A} Disconnect"),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this.terminated=!0,this._onConnectionTerminated(),this.reconnectionSubject.next(new h)}}export{D as WebHidDeviceConnection};
1
+ import{CommandUtils as g,ReconnectionFailedError as h}from"@ledgerhq/device-management-kit";import{Left as c,Maybe as m,Nothing as d,Right as u}from"purify-ts";import{firstValueFrom as l,from as _,retry as b,Subject as p}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as f}from"../data/WebHidConfig";import{WebHidSendReportError as s}from"../model/Errors";class C{_device;_deviceId;_apduSender;_apduReceiver;_sendApduSubject=new p;_logger;_pendingApdu=d;_onConnectionTerminated;reconnectionSubject=new p;waitingForReconnection=!1;lostConnectionTimeout=null;terminated=!1;constructor({device:t,deviceId:n,apduSender:o,apduReceiver:r,onConnectionTerminated:e},i){this._apduSender=o,this._apduReceiver=r,this._onConnectionTerminated=e,this._logger=i("WebHidDeviceConnection"),this._device=t,this._device.oninputreport=a=>this.receiveHidInputReport(a),this._deviceId=n,this._logger.info("\u{1F50C} Connected to device")}get device(){return this._device}get deviceId(){return this._deviceId}async sendApdu(t,n){this._sendApduSubject=new p,this._pendingApdu=m.of(t),this._logger.debug("Sending APDU",{data:{apdu:t},tag:"apdu-sender"});const o=new Promise(e=>{this._sendApduSubject.subscribe({next:async i=>{this._pendingApdu=d,n&&g.isSuccessResponse(i)?(await this.waitForReconnection()).caseOf({Left:v=>e(c(v)),Right:()=>e(u(i))}):e(u(i))},error:i=>{this._pendingApdu=d,e(c(i))}})});if(this.waitingForReconnection||!this.device.opened){const e=this.device.opened&&this._pendingApdu.isJust(),i=await this.waitForReconnection(e);if(i.isLeft())return i}const r=this._apduSender.getFrames(t);for(const e of r){this._logger.debug("Sending Frame",{data:{frame:e.getRawData()}});try{await l(_(this._device.sendReport(0,e.getRawData())).pipe(b({count:3,delay:500})))}catch(i){return this._logger.error("Error sending frame",{data:{error:i}}),Promise.resolve(c(new s(i)))}}return o}receiveHidInputReport(t){const n=new Uint8Array(t.data.buffer);this._logger.debug("Received Frame",{data:{frame:n},tag:"apdu-receiver"}),this._apduReceiver.handleFrame(n).caseOf({Right:r=>{r.map(e=>{this._logger.debug("Received APDU Response",{data:{response:e}}),this._sendApduSubject.next(e),this._sendApduSubject.complete()})},Left:r=>{this._sendApduSubject.error(r)}})}waitForReconnection(t=!1){return this.terminated?Promise.resolve(c(new h)):new Promise(n=>{const o=this.reconnectionSubject.subscribe({next:r=>{t&&this._sendApduSubject.error(new s(new Error("Device disconnected while waiting for device response"))),n(r==="success"?u(void 0):c(r)),o.unsubscribe()}})})}lostConnection(){this._logger.info("\u23F1\uFE0F Lost connection, starting timer"),this.waitingForReconnection=!0,this.lostConnectionTimeout=setTimeout(()=>{this._logger.info("\u274C Disconnection timeout, terminating connection"),this.disconnect()},f)}async reconnectHidDevice(t){this._device=t,this._device.oninputreport=n=>this.receiveHidInputReport(n),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this._pendingApdu.isJust()&&this._sendApduSubject.error(new s),await t.open(),this._logger.info("\u23F1\uFE0F\u{1F50C} Device reconnected"),this.waitingForReconnection=!1,this.reconnectionSubject.next("success")}disconnect(){this._pendingApdu.isJust()&&this._sendApduSubject.error(new s),this._logger.info("\u{1F51A} Disconnect"),this.lostConnectionTimeout&&clearTimeout(this.lostConnectionTimeout),this.terminated=!0,this._onConnectionTerminated(),this.reconnectionSubject.next(new h)}}export{C as WebHidDeviceConnection};
2
2
  //# sourceMappingURL=WebHidDeviceConnection.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebHidDeviceConnection.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: NodeJS.Timeout | null = null;\n /** Flag to indicate if the connection is terminated */\n private terminated = false;\n\n constructor(\n {\n device,\n deviceId,\n apduSender,\n apduReceiver,\n onConnectionTerminated,\n }: WebHidDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSender = apduSender;\n this._apduReceiver = apduReceiver;\n this._onConnectionTerminated = onConnectionTerminated;\n this._logger = loggerServiceFactory(\"WebHidDeviceConnection\");\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n this._deviceId = deviceId;\n this._logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n public get device() {\n return this._device;\n }\n\n public get deviceId() {\n return this._deviceId;\n }\n\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._sendApduSubject = new Subject();\n this._pendingApdu = Maybe.of(apdu);\n this._logger.debug(\"Sending APDU\", {\n data: { apdu },\n tag: \"apdu-sender\",\n });\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduSubject.subscribe({\n next: async (r) => {\n this._pendingApdu = Nothing;\n if (triggersDisconnection && CommandUtils.isSuccessResponse(r)) {\n // Anticipate the disconnection and wait for the reconnection before resolving\n const reconnectionRes = await this.waitForReconnection();\n reconnectionRes.caseOf({\n Left: (err) => resolve(Left(err)),\n Right: () => resolve(Right(r)),\n });\n } else {\n resolve(Right(r));\n }\n },\n error: (err) => {\n this._pendingApdu = Nothing;\n resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const waitingForDeviceResponse =\n this.device.opened && this._pendingApdu.isJust();\n\n const reconnectionRes = await this.waitForReconnection(\n waitingForDeviceResponse,\n );\n\n if (reconnectionRes.isLeft()) {\n return reconnectionRes;\n }\n }\n\n const frames = this._apduSender.getFrames(apdu);\n for (const frame of frames) {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n try {\n await this._device.sendReport(0, frame.getRawData());\n } catch (error) {\n this._logger.error(\"Error sending frame\", { data: { error } });\n return Promise.resolve(Left(new WebHidSendReportError(error)));\n }\n }\n\n return resultPromise;\n }\n\n private receiveHidInputReport(event: HIDInputReportEvent) {\n const data = new Uint8Array(event.data.buffer);\n this._logger.debug(\"Received Frame\", {\n data: { frame: data },\n tag: \"apdu-receiver\",\n });\n const response = this._apduReceiver.handleFrame(data);\n response.caseOf({\n Right: (maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduSubject.next(apduResponse);\n this._sendApduSubject.complete();\n });\n },\n Left: (err) => {\n this._sendApduSubject.error(err);\n },\n });\n }\n\n private waitForReconnection(\n waitingForDeviceResponse: boolean = false,\n ): Promise<Either<DmkError, void>> {\n if (this.terminated) {\n return Promise.resolve(Left(new ReconnectionFailedError()));\n }\n\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (waitingForDeviceResponse) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n if (res === \"success\") {\n resolve(Right(undefined));\n } else {\n resolve(Left(res));\n }\n sub.unsubscribe();\n },\n });\n });\n }\n\n /**\n * Method called when the HIDDevice gets disconnected.\n * It starts a timeout to wait for the device to reconnect.\n * */\n public lostConnection() {\n this._logger.info(\"\u23F1\uFE0F Lost connection, starting timer\");\n this.waitingForReconnection = true;\n this.lostConnectionTimeout = setTimeout(() => {\n this._logger.info(\"\u274C Disconnection timeout, terminating connection\");\n this.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }\n\n /** Reconnect the device after a disconnection */\n public async reconnectHidDevice(device: HIDDevice) {\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n\n if (this.lostConnectionTimeout) {\n this._logger.info(\"\u23F1\uFE0F\uD83D\uDD0C Device reconnected\");\n clearTimeout(this.lostConnectionTimeout);\n }\n\n await device.open();\n\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n this.waitingForReconnection = false;\n this.reconnectionSubject.next(\"success\");\n }\n\n public disconnect() {\n this._logger.info(\"\uD83D\uDD1A Disconnect\");\n if (this.lostConnectionTimeout) clearTimeout(this.lostConnectionTimeout);\n this.terminated = true;\n this._onConnectionTerminated();\n this.reconnectionSubject.next(new ReconnectionFailedError());\n }\n}\n"],
5
- "mappings": "AAAA,OAIE,gBAAAA,EAKA,2BAAAC,MACK,kCACP,OAAsB,QAAAC,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAS,WAAAC,MAAe,OAExB,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBAe/B,MAAMC,CAAmD,CACtD,QACA,UACS,YACA,cACT,iBAA0C,IAAIH,EACrC,QACT,aAAkCF,EAGlC,wBAEA,oBAAqD,IAAIE,EAEzD,uBAAyB,GAEzB,sBAA+C,KAE/C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,CAAC,CACH,CAMO,gBAAiB,CACtB,KAAK,QAAQ,KAAK,8CAAoC,EACtD,KAAK,uBAAyB,GAC9B,KAAK,sBAAwB,WAAW,IAAM,CAC5C,KAAK,QAAQ,KAAK,sDAAiD,EACnE,KAAK,WAAW,CAClB,EAAGxB,CAAwB,CAC7B,CAGA,MAAa,mBAAmBG,EAAmB,CACjD,KAAK,QAAUA,EACf,KAAK,QAAQ,cAAiBM,GAAU,KAAK,sBAAsBA,CAAK,EAEpE,KAAK,wBACP,KAAK,QAAQ,KAAK,0CAAyB,EAC3C,aAAa,KAAK,qBAAqB,GAGzC,MAAMN,EAAO,KAAK,EAEd,KAAK,aAAa,OAAO,GAC3B,KAAK,iBAAiB,MAAM,IAAIF,CAAuB,EAGzD,KAAK,uBAAyB,GAC9B,KAAK,oBAAoB,KAAK,SAAS,CACzC,CAEO,YAAa,CAClB,KAAK,QAAQ,KAAK,sBAAe,EAC7B,KAAK,uBAAuB,aAAa,KAAK,qBAAqB,EACvE,KAAK,WAAa,GAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,KAAK,IAAIP,CAAyB,CAC7D,CACF",
6
- "names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
4
+ "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduResponse,\n type ApduSenderService,\n CommandUtils,\n type DeviceConnection,\n type DeviceId,\n type DmkError,\n type LoggerPublisherService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { firstValueFrom, from, retry, Subject } from \"rxjs\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\n\ntype WebHidDeviceConnectionConstructorArgs = {\n device: HIDDevice;\n deviceId: DeviceId;\n apduSender: ApduSenderService;\n apduReceiver: ApduReceiverService;\n onConnectionTerminated: () => void;\n};\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Class to manage the connection with a USB HID device.\n * It sends APDU commands to the device and receives the responses.\n * It handles temporary disconnections and reconnections.\n */\nexport class WebHidDeviceConnection implements DeviceConnection {\n private _device: HIDDevice;\n private _deviceId: DeviceId;\n private readonly _apduSender: ApduSenderService;\n private readonly _apduReceiver: ApduReceiverService;\n private _sendApduSubject: Subject<ApduResponse> = new Subject();\n private readonly _logger: LoggerPublisherService;\n private _pendingApdu: Maybe<Uint8Array> = Nothing;\n\n /** Callback to notify the connection termination */\n private _onConnectionTerminated: () => void;\n /** Subject to notify the reconnection status */\n private reconnectionSubject: Subject<\"success\" | DmkError> = new Subject();\n /** Flag to indicate if the connection is waiting for a reconnection */\n private waitingForReconnection = false;\n /** Timeout to wait for the device to reconnect */\n private lostConnectionTimeout: Timer | null = null;\n /** Flag to indicate if the connection is terminated */\n private terminated = false;\n\n constructor(\n {\n device,\n deviceId,\n apduSender,\n apduReceiver,\n onConnectionTerminated,\n }: WebHidDeviceConnectionConstructorArgs,\n loggerServiceFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._apduSender = apduSender;\n this._apduReceiver = apduReceiver;\n this._onConnectionTerminated = onConnectionTerminated;\n this._logger = loggerServiceFactory(\"WebHidDeviceConnection\");\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n this._deviceId = deviceId;\n this._logger.info(\"\uD83D\uDD0C Connected to device\");\n }\n\n public get device() {\n return this._device;\n }\n\n public get deviceId() {\n return this._deviceId;\n }\n\n async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n ): Promise<Either<DmkError, ApduResponse>> {\n this._sendApduSubject = new Subject();\n this._pendingApdu = Maybe.of(apdu);\n this._logger.debug(\"Sending APDU\", {\n data: { apdu },\n tag: \"apdu-sender\",\n });\n\n const resultPromise = new Promise<Either<DmkError, ApduResponse>>(\n (resolve) => {\n this._sendApduSubject.subscribe({\n next: async (r) => {\n this._pendingApdu = Nothing;\n if (triggersDisconnection && CommandUtils.isSuccessResponse(r)) {\n // Anticipate the disconnection and wait for the reconnection before resolving\n const reconnectionRes = await this.waitForReconnection();\n reconnectionRes.caseOf({\n Left: (err) => resolve(Left(err)),\n Right: () => resolve(Right(r)),\n });\n } else {\n resolve(Right(r));\n }\n },\n error: (err) => {\n this._pendingApdu = Nothing;\n resolve(Left(err));\n },\n });\n },\n );\n\n if (this.waitingForReconnection || !this.device.opened) {\n const waitingForDeviceResponse =\n this.device.opened && this._pendingApdu.isJust();\n const reconnectionRes = await this.waitForReconnection(\n waitingForDeviceResponse,\n );\n if (reconnectionRes.isLeft()) {\n return reconnectionRes;\n }\n }\n\n const frames = this._apduSender.getFrames(apdu);\n for (const frame of frames) {\n this._logger.debug(\"Sending Frame\", {\n data: { frame: frame.getRawData() },\n });\n\n try {\n await firstValueFrom(\n from(this._device.sendReport(0, frame.getRawData())).pipe(\n retry({\n count: 3,\n delay: 500,\n }),\n ),\n );\n } catch (error) {\n this._logger.error(\"Error sending frame\", { data: { error } });\n return Promise.resolve(Left(new WebHidSendReportError(error)));\n }\n }\n\n return resultPromise;\n }\n\n private receiveHidInputReport(event: HIDInputReportEvent) {\n const data = new Uint8Array(event.data.buffer);\n this._logger.debug(\"Received Frame\", {\n data: { frame: data },\n tag: \"apdu-receiver\",\n });\n const response = this._apduReceiver.handleFrame(data);\n response.caseOf({\n Right: (maybeApduResponse) => {\n maybeApduResponse.map((apduResponse) => {\n this._logger.debug(\"Received APDU Response\", {\n data: { response: apduResponse },\n });\n this._sendApduSubject.next(apduResponse);\n this._sendApduSubject.complete();\n });\n },\n Left: (err) => {\n this._sendApduSubject.error(err);\n },\n });\n }\n\n private waitForReconnection(\n waitingForDeviceResponse: boolean = false,\n ): Promise<Either<DmkError, void>> {\n if (this.terminated) {\n return Promise.resolve(Left(new ReconnectionFailedError()));\n }\n\n return new Promise<Either<DmkError, void>>((resolve) => {\n const sub = this.reconnectionSubject.subscribe({\n next: (res) => {\n if (waitingForDeviceResponse) {\n this._sendApduSubject.error(\n new WebHidSendReportError(\n new Error(\n \"Device disconnected while waiting for device response\",\n ),\n ),\n );\n }\n\n if (res === \"success\") {\n resolve(Right(undefined));\n } else {\n resolve(Left(res));\n }\n\n sub.unsubscribe();\n },\n });\n });\n }\n\n /**\n * Method called when the HIDDevice gets disconnected.\n * It starts a timeout to wait for the device to reconnect.\n * */\n public lostConnection() {\n this._logger.info(\"\u23F1\uFE0F Lost connection, starting timer\");\n this.waitingForReconnection = true;\n this.lostConnectionTimeout = setTimeout(() => {\n this._logger.info(\"\u274C Disconnection timeout, terminating connection\");\n this.disconnect();\n }, RECONNECT_DEVICE_TIMEOUT);\n }\n\n /** Reconnect the device after a disconnection */\n public async reconnectHidDevice(device: HIDDevice) {\n this._device = device;\n this._device.oninputreport = (event) => this.receiveHidInputReport(event);\n\n if (this.lostConnectionTimeout) {\n clearTimeout(this.lostConnectionTimeout);\n }\n\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n await device.open();\n\n this._logger.info(\"\u23F1\uFE0F\uD83D\uDD0C Device reconnected\");\n this.waitingForReconnection = false;\n this.reconnectionSubject.next(\"success\");\n }\n\n public disconnect() {\n if (this._pendingApdu.isJust()) {\n this._sendApduSubject.error(new WebHidSendReportError());\n }\n\n this._logger.info(\"\uD83D\uDD1A Disconnect\");\n if (this.lostConnectionTimeout) clearTimeout(this.lostConnectionTimeout);\n this.terminated = true;\n this._onConnectionTerminated();\n this.reconnectionSubject.next(new ReconnectionFailedError());\n }\n}\n"],
5
+ "mappings": "AAAA,OAIE,gBAAAA,EAKA,2BAAA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",
6
+ "names": ["CommandUtils", "ReconnectionFailedError", "Left", "Maybe", "Nothing", "Right", "firstValueFrom", "from", "retry", "Subject", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "WebHidDeviceConnection", "device", "deviceId", "apduSender", "apduReceiver", "onConnectionTerminated", "loggerServiceFactory", "event", "apdu", "triggersDisconnection", "resultPromise", "resolve", "r", "err", "waitingForDeviceResponse", "reconnectionRes", "frames", "frame", "error", "data", "maybeApduResponse", "apduResponse", "sub", "res"]
7
7
  }
@@ -1,2 +1,2 @@
1
- class n{sendApdu=jest.fn()}export{n as WebHidDeviceConnectionStub};
1
+ class n{sendApdu=vi.fn()}export{n as WebHidDeviceConnectionStub};
2
2
  //# sourceMappingURL=WebHidDeviceConnection.stub.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebHidDeviceConnection.stub.ts"],
4
- "sourcesContent": ["import {\n type DeviceConnection,\n type SendApduFnType,\n} from \"@ledgerhq/device-management-kit\";\n\nexport class WebHidDeviceConnectionStub implements DeviceConnection {\n sendApdu: SendApduFnType = jest.fn();\n}\n"],
5
- "mappings": "AAKO,MAAMA,CAAuD,CAClE,SAA2B,KAAK,GAAG,CACrC",
4
+ "sourcesContent": ["import {\n type DeviceConnection,\n type SendApduFnType,\n} from \"@ledgerhq/device-management-kit\";\n\nexport class WebHidDeviceConnectionStub implements DeviceConnection {\n sendApdu: SendApduFnType = vi.fn();\n}\n"],
5
+ "mappings": "AAKO,MAAMA,CAAuD,CAClE,SAA2B,GAAG,GAAG,CACnC",
6
6
  "names": ["WebHidDeviceConnectionStub"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as v}from"@ledgerhq/device-management-kit";import{Left as l,Right as w}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as h}from"../model/Errors";import{hidDeviceStubBuilder as b}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";jest.useFakeTimers();const S=new Uint8Array([170,170,5,0,0,0,2,85,21,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),p=new Uint8Array([170,170,5,0,0,0,2,144,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class g{tag;constructor(r,o){this.subscribers=r,this.tag=o}subscribers=[];error=jest.fn();warn=jest.fn();debug=jest.fn();info=jest.fn()}const x=()=>new Promise(jest.requireActual("timers").setImmediate);jest.useFakeTimers();describe("WebHidDeviceConnection",()=>{let e,r,o;const i=()=>{},a="test-device-id",s=t=>new g([],t);beforeEach(()=>{e=b({opened:!0}),r=y(void 0,s),o=A(void 0,s)}),it("should get device",()=>{const n=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).device;expect(n).toStrictEqual(e)}),it("should send APDU through hid report",()=>{new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(new Uint8Array(0)),expect(e.sendReport).toHaveBeenCalled()}),it("should receive APDU through hid report",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]));expect(n).toEqual(w({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),describe("anticipating loss of connection after sending an APDU",()=>{test("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);let n=!1;const d=t.sendApdu(Uint8Array.from([]),!0).then(f=>(n=!0,f));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(w({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),test("sendApdu(whatever, true) should not wait for reconnection if the response is not a success",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(S).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(w({statusCode:new Uint8Array([85,21]),data:new Uint8Array([])}))}),test("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s),n=t.sendApdu(Uint8Array.from([]),!0);t.lostConnection(),jest.advanceTimersByTime(m),await x();const d=await n;expect(d).toEqual(l(new v))})}),describe("connection lost before sending an APDU",()=>{test("sendApdu(whatever, false) should return an error if the device connection has been lost and times out",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);t.lostConnection(),jest.advanceTimersByTime(m),await x();const n=await t.sendApdu(Uint8Array.from([]),!1);await x(),expect(n).toEqual(l(new v))}),test("sendApdu(whatever, false) should wait for reconnection to resolve",async()=>{e.sendReport=jest.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(p).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:i,deviceId:a},s);t.lostConnection();let n=!1;const d=t.sendApdu(Uint8Array.from([]),!1).then(f=>(n=!0,f));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await d;expect(u).toEqual(l(new h))})})});
1
+ import{defaultApduReceiverServiceStubBuilder as A,defaultApduSenderServiceStubBuilder as y,ReconnectionFailedError as w}from"@ledgerhq/device-management-kit";import{Left as f,Right as l}from"purify-ts";import{RECONNECT_DEVICE_TIMEOUT as m}from"../data/WebHidConfig";import{WebHidSendReportError as h}from"../model/Errors";import{hidDeviceStubBuilder as b}from"../model/HIDDevice.stub";import{WebHidDeviceConnection as c}from"./WebHidDeviceConnection";vi.useFakeTimers();const S=new Uint8Array([170,170,5,0,0,0,2,85,21,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),d=new Uint8Array([170,170,5,0,0,0,2,144,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class g{tag;constructor(r,o){this.subscribers=r,this.tag=o}subscribers=[];error=vi.fn();warn=vi.fn();debug=vi.fn();info=vi.fn()}const x=async()=>{const e=await vi.importActual("timers");return new Promise(e.setImmediate)};vi.useFakeTimers();describe("WebHidDeviceConnection",()=>{let e,r,o;const s=()=>{},a="test-device-id",i=t=>new g([],t);beforeEach(()=>{e=b({opened:!0}),r=y(void 0,i),o=A(void 0,i)}),it("should get device",()=>{const n=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).device;expect(n).toStrictEqual(e)}),it("should send APDU through hid report",()=>{new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(new Uint8Array(0)),expect(e.sendReport).toHaveBeenCalled()}),it("should receive APDU through hid report",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]));expect(n).toEqual(l({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),describe("anticipating loss of connection after sending an APDU",()=>{it("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);let n=!1;const p=t.sendApdu(Uint8Array.from([]),!0).then(v=>(n=!0,v));t.lostConnection(),await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await p;expect(u).toEqual(l({statusCode:new Uint8Array([144,0]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should not wait for reconnection if the response is not a success",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(S).buffer)})));const n=await new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i).sendApdu(Uint8Array.from([]),!0);expect(n).toEqual(l({statusCode:new Uint8Array([85,21]),data:new Uint8Array([])}))}),it("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i),n=t.sendApdu(Uint8Array.from([]),!0);t.lostConnection(),vi.advanceTimersByTime(m),await x();const p=await n;expect(p).toEqual(f(new w))})}),describe("connection lost before sending an APDU",()=>{it("sendApdu(whatever, false) should return an error if the device connection has been lost and times out",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection(),vi.advanceTimersByTime(m),await x();const n=await t.sendApdu(Uint8Array.from([]),!1);await x(),expect(n).toEqual(f(new w))}),it("sendApdu(whatever, false) should wait for reconnection to resolve",async()=>{e.sendReport=vi.fn(()=>Promise.resolve(e.oninputreport({type:"inputreport",data:new DataView(Uint8Array.from(d).buffer)})));const t=new c({device:e,apduSender:r,apduReceiver:o,onConnectionTerminated:s,deviceId:a},i);t.lostConnection();let n=!1;const p=t.sendApdu(Uint8Array.from([]),!1).then(v=>(n=!0,v));await x(),expect(n).toBe(!1),t.reconnectHidDevice(e),await x(),expect(n).toBe(!0);const u=await p;expect(u).toEqual(f(new h))})})});
2
2
  //# sourceMappingURL=WebHidDeviceConnection.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/transport/WebHidDeviceConnection.test.ts"],
4
- "sourcesContent": ["import {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\njest.useFakeTimers();\n\nconst RESPONSE_LOCKED_DEVICE = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nconst RESPONSE_SUCCESS = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n error = jest.fn();\n warn = jest.fn();\n debug = jest.fn();\n info = jest.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = () =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n new Promise(jest.requireActual(\"timers\").setImmediate);\n\njest.useFakeTimers();\n\ndescribe(\"WebHidDeviceConnection\", () => {\n let device: HIDDevice;\n let apduSender: ApduSenderService;\n let apduReceiver: ApduReceiverService;\n const onConnectionTerminated = () => {};\n const deviceId: DeviceId = \"test-device-id\";\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n device = hidDeviceStubBuilder({ opened: true });\n apduSender = defaultApduSenderServiceStubBuilder(undefined, logger);\n apduReceiver = defaultApduReceiverServiceStubBuilder(undefined, logger);\n });\n\n it(\"should get device\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const cDevice = connection.device;\n // then\n expect(cDevice).toStrictEqual(device);\n });\n\n it(\"should send APDU through hid report\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n connection.sendApdu(new Uint8Array(0));\n // then\n expect(device.sendReport).toHaveBeenCalled();\n });\n\n it(\"should receive APDU through hid report\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n test(\"sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n let hasResolved = false;\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), true)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n connection.lostConnection();\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n test(\"sendApdu(whatever, true) should not wait for reconnection if the response is not a success\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_LOCKED_DEVICE).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when\n const response = await connection.sendApdu(Uint8Array.from([]), true);\n\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x55, 0x15]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n test(\"sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n const responsePromise = connection.sendApdu(Uint8Array.from([]), true);\n\n // when disconnecting\n connection.lostConnection();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await responsePromise;\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n });\n\n describe(\"connection lost before sending an APDU\", () => {\n test(\"sendApdu(whatever, false) should return an error if the device connection has been lost and times out\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n jest.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await connection.sendApdu(Uint8Array.from([]), false);\n await flushPromises();\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n\n test(\"sendApdu(whatever, false) should wait for reconnection to resolve\", async () => {\n // given\n device.sendReport = jest.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n\n let hasResolved = false;\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), false)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(Left(new WebHidSendReportError()));\n });\n });\n});\n"],
5
- "mappings": "AAAA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBACtC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,0BAAAC,MAA8B,2BAEvC,KAAK,cAAc,EAEnB,MAAMC,EAAyB,IAAI,WAAW,CAC5C,IAAM,IAAM,EAAM,EAAM,EAAM,EAAM,EAAM,GAAM,GAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAA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,EAAK,EACnC,KAAMD,IACLE,EAAc,GACPF,EACR,EAGH,MAAMR,EAAc,EACpB,OAAOU,CAAW,EAAE,KAAK,EAAK,EAG9BD,EAAW,mBAAmBR,CAAM,EACpC,MAAMD,EAAc,EACpB,OAAOU,CAAW,EAAE,KAAK,EAAI,EAE7B,MAAMF,EAAW,MAAMG,EAEvB,OAAOH,CAAQ,EAAE,QAAQnB,EAAK,IAAIG,CAAuB,CAAC,CAC5D,CAAC,CACH,CAAC,CACH,CAAC",
6
- "names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
4
+ "sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports: off */\nimport {\n type ApduReceiverService,\n type ApduSenderService,\n defaultApduReceiverServiceStubBuilder,\n defaultApduSenderServiceStubBuilder,\n type DeviceId,\n type LoggerPublisherService,\n type LoggerSubscriberService,\n ReconnectionFailedError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { RECONNECT_DEVICE_TIMEOUT } from \"@api/data/WebHidConfig\";\nimport { WebHidSendReportError } from \"@api/model/Errors\";\nimport { hidDeviceStubBuilder } from \"@api/model/HIDDevice.stub\";\n\nimport { WebHidDeviceConnection } from \"./WebHidDeviceConnection\";\n\nvi.useFakeTimers();\n\nconst RESPONSE_LOCKED_DEVICE = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nconst RESPONSE_SUCCESS = new Uint8Array([\n 0xaa, 0xaa, 0x05, 0x00, 0x00, 0x00, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n]);\n\nclass LoggerPublisherServiceStub implements LoggerPublisherService {\n tag: string;\n constructor(subscribers: LoggerSubscriberService[], tag: string) {\n this.subscribers = subscribers;\n this.tag = tag;\n }\n subscribers: LoggerSubscriberService[] = [];\n error = vi.fn();\n warn = vi.fn();\n debug = vi.fn();\n info = vi.fn();\n}\n\n/**\n * Flushes all pending promises\n */\nconst flushPromises = async () => {\n const timers = await vi.importActual<typeof import(\"timers\")>(\"timers\");\n return new Promise(timers.setImmediate);\n};\n\nvi.useFakeTimers();\n\ndescribe(\"WebHidDeviceConnection\", () => {\n let device: HIDDevice;\n let apduSender: ApduSenderService;\n let apduReceiver: ApduReceiverService;\n const onConnectionTerminated = () => {};\n const deviceId: DeviceId = \"test-device-id\";\n const logger = (tag: string) => new LoggerPublisherServiceStub([], tag);\n\n beforeEach(() => {\n device = hidDeviceStubBuilder({ opened: true });\n apduSender = defaultApduSenderServiceStubBuilder(undefined, logger);\n apduReceiver = defaultApduReceiverServiceStubBuilder(undefined, logger);\n });\n\n it(\"should get device\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const cDevice = connection.device;\n // then\n expect(cDevice).toStrictEqual(device);\n });\n\n it(\"should send APDU through hid report\", () => {\n // given\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n connection.sendApdu(new Uint8Array(0));\n // then\n expect(device.sendReport).toHaveBeenCalled();\n });\n\n it(\"should receive APDU through hid report\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n // when\n const response = await connection.sendApdu(Uint8Array.from([]));\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n describe(\"anticipating loss of connection after sending an APDU\", () => {\n it(\"sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n let hasResolved = false;\n\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), true)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n connection.lostConnection();\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x90, 0x00]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should not wait for reconnection if the response is not a success\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_LOCKED_DEVICE).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when\n const response = await connection.sendApdu(Uint8Array.from([]), true);\n\n // then\n expect(response).toEqual(\n Right({\n statusCode: new Uint8Array([0x55, 0x15]),\n data: new Uint8Array([]),\n }),\n );\n });\n\n it(\"sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n const responsePromise = connection.sendApdu(Uint8Array.from([]), true);\n\n // when disconnecting\n connection.lostConnection();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await responsePromise;\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n });\n\n describe(\"connection lost before sending an APDU\", () => {\n it(\"sendApdu(whatever, false) should return an error if the device connection has been lost and times out\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n vi.advanceTimersByTime(RECONNECT_DEVICE_TIMEOUT);\n await flushPromises();\n\n // then\n const response = await connection.sendApdu(Uint8Array.from([]), false);\n await flushPromises();\n expect(response).toEqual(Left(new ReconnectionFailedError()));\n });\n\n it(\"sendApdu(whatever, false) should wait for reconnection to resolve\", async () => {\n // given\n device.sendReport = vi.fn(() =>\n Promise.resolve(\n device.oninputreport!({\n type: \"inputreport\",\n data: new DataView(Uint8Array.from(RESPONSE_SUCCESS).buffer),\n } as HIDInputReportEvent),\n ),\n );\n const connection = new WebHidDeviceConnection(\n { device, apduSender, apduReceiver, onConnectionTerminated, deviceId },\n logger,\n );\n\n // when losing connection\n connection.lostConnection();\n\n let hasResolved = false;\n const responsePromise = connection\n .sendApdu(Uint8Array.from([]), false)\n .then((response) => {\n hasResolved = true;\n return response;\n });\n\n // before reconnecting\n await flushPromises();\n expect(hasResolved).toBe(false);\n\n // when reconnecting\n connection.reconnectHidDevice(device);\n await flushPromises();\n expect(hasResolved).toBe(true);\n\n const response = await responsePromise;\n\n expect(response).toEqual(Left(new WebHidSendReportError()));\n });\n });\n});\n"],
5
+ "mappings": "AACA,OAGE,yCAAAA,EACA,uCAAAC,EAIA,2BAAAC,MACK,kCACP,OAAS,QAAAC,EAAM,SAAAC,MAAa,YAE5B,OAAS,4BAAAC,MAAgC,yBACzC,OAAS,yBAAAC,MAA6B,oBACtC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,0BAAAC,MAA8B,2BAEvC,GAAG,cAAc,EAEjB,MAAMC,EAAyB,IAAI,WAAW,CAC5C,IAAM,IAAM,EAAM,EAAM,EAAM,EAAM,EAAM,GAAM,GAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EACxE,E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EACrB,SAAS,WAAW,KAAK,CAAC,CAAC,EAAG,EAAK,EACnC,KAAMD,IACLE,EAAc,GACPF,EACR,EAGH,MAAMT,EAAc,EACpB,OAAOW,CAAW,EAAE,KAAK,EAAK,EAG9BD,EAAW,mBAAmBR,CAAM,EACpC,MAAMF,EAAc,EACpB,OAAOW,CAAW,EAAE,KAAK,EAAI,EAE7B,MAAMF,EAAW,MAAMG,EAEvB,OAAOH,CAAQ,EAAE,QAAQpB,EAAK,IAAIG,CAAuB,CAAC,CAC5D,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "ReconnectionFailedError", "Left", "Right", "RECONNECT_DEVICE_TIMEOUT", "WebHidSendReportError", "hidDeviceStubBuilder", "WebHidDeviceConnection", "RESPONSE_LOCKED_DEVICE", "RESPONSE_SUCCESS", "LoggerPublisherServiceStub", "subscribers", "tag", "flushPromises", "timers", "device", "apduSender", "apduReceiver", "onConnectionTerminated", "deviceId", "logger", "cDevice", "response", "connection", "hasResolved", "responsePromise"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{connectedDeviceStubBuilder as T,DeviceModelId as u,DeviceNotRecognizedError as S,NoAccessibleDeviceError as E,OpeningConnectionError as B,StaticDeviceModelDataSource as H,UnknownDeviceError as C}from"@ledgerhq/device-management-kit";import{Left as g,Right as R}from"purify-ts";import{Subject as y}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as p}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as N}from"../model/Errors";import{hidDeviceStubBuilder as l}from"../model/HIDDevice.stub";import{WebHidTransport as O}from"./WebHidTransport";class V{constructor(D,f){this.subscribers=D,this.tag=f}subscribers=[];tag="";error=jest.fn();warn=jest.fn();info=jest.fn();debug=jest.fn()}const x=new H,P=new V([],"web-usb-hid"),a=l(),m=()=>new Promise(jest.requireActual("timers").setImmediate);describe("WebHidTransport",()=>{let i,D,f;function w(){D=jest.fn(),f=jest.fn(),i=new O(x,()=>P,f,D)}beforeEach(()=>{w(),jest.useFakeTimers()}),afterEach(()=>{jest.restoreAllMocks()});const d=(s,r)=>{i.startDiscovering().subscribe({next:s,error:r})};describe("When WebHID API is not supported",()=>{it("should not support the transport",()=>{expect(i.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",s=>{d(()=>{s("Should not emit any value")},r=>{expect(r).toBeInstanceOf(N),s()})})}),describe("When WebHID API is supported",()=>{const s=jest.fn(),r=jest.fn(),I=new y,k=new y;function b(t){I.next({device:t})}function h(t){k.next({device:t})}beforeEach(()=>{global.navigator={hid:{getDevices:s,requestDevice:r,addEventListener:(t,e)=>{t==="disconnect"?k.subscribe(e):t==="connect"&&I.subscribe(e)}}},w()}),afterEach(()=>{jest.clearAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(i.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{x.getAllDeviceModels().flatMap(e=>[{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName})`,hidDevice:l({productId:e.usbProductId<<8,productName:e.productName}),expectedDeviceModel:e},{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName}, bootloader)`,hidDevice:l({productId:e.bootloaderUsbProductId,productName:e.productName}),expectedDeviceModel:e}]).forEach(e=>{it(e.testTitle,c=>{r.mockResolvedValueOnce([e.hidDevice]),d(o=>{try{expect(o).toEqual(expect.objectContaining({deviceModel:e.expectedDeviceModel})),c()}catch(n){c(n)}},o=>{c(o)})})}),it("should emit devices if new grant accesses",e=>{r.mockResolvedValueOnce([a,{...a,productId:20497,productName:"Ledger Nano S Plus"}]);let c=0;d(o=>{try{switch(c){case 0:expect(o).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X,productName:"Ledger Nano X",usbProductId:64})}));break;case 1:expect(o).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80})})),e();break}c++}catch(n){e(n)}},o=>{e(o)})}),it("should throw DeviceNotRecognizedError if the device is not recognized",e=>{r.mockResolvedValueOnce([{...a,productId:16962}]),d(()=>{e("should not return a device")},c=>{expect(c).toBeInstanceOf(S),e()})}),it("should emit an error if the request device is in error",e=>{const c="request device error";r.mockImplementationOnce(()=>{throw new Error(c)}),d(()=>{e("should not return a device")},o=>{expect(o).toBeInstanceOf(E),expect(o).toStrictEqual(new E(new Error(c))),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=>{r.mockResolvedValueOnce([]),d(c=>{e(`Should not emit any value, but emitted ${JSON.stringify(c)}`)},c=>{try{expect(c).toBeInstanceOf(E),e()}catch(o){e(o)}})}),it("should emit the same discoveredDevice object if its discovered twice in a row",async()=>{r.mockResolvedValue([a]),s.mockResolvedValue([a]);const e=await new Promise((o,n)=>{d(o,v=>n(v))}),c=await new Promise((o,n)=>{d(o,v=>n(v))});expect(c).toBe(e)})}),describe("destroy",()=>{it("should stop monitoring connections if the discovery process is halted",()=>{const t=jest.spyOn(AbortController.prototype,"abort");i.destroy(),expect(t).toHaveBeenCalled()})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const t={deviceId:"fake",onDisconnect:jest.fn()},e=await i.connect(t);expect(e).toStrictEqual(g(new C("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const t={deviceId:"fake",onDisconnect:jest.fn()},e=await i.connect(t);expect(e).toStrictEqual(g(new C("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",t=>{const e="cannot be opened",c={...a,open:()=>{throw new Error(e)}};r.mockResolvedValueOnce([c]),s.mockResolvedValue([c]),d(o=>{i.connect({deviceId:o.id,onDisconnect:jest.fn()}).then(n=>{expect(n).toStrictEqual(g(new B(new Error(e)))),t()}).catch(n=>{t(n)})},o=>{t(o)})}),it("should return the opened device",t=>{const e={...a,opened:!1,open:()=>(e.opened=!0,Promise.resolve())};r.mockResolvedValue([e]),s.mockResolvedValue([e]),d(c=>{i.connect({deviceId:c.id,onDisconnect:jest.fn()}).then(o=>{o.ifRight(n=>{expect(n).toEqual(expect.objectContaining({id:c.id})),t()}).ifLeft(()=>{t(o)})}).catch(o=>{t(o)})},c=>{t(c)})}),it("should return a device if available",t=>{r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),d(e=>{i.connect({deviceId:e.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(o=>{expect(o).toEqual(expect.objectContaining({id:e.id})),t()}).ifLeft(()=>{t(c)})}).catch(c=>{t(c)})},e=>{t(e)})})}),describe("disconnect",()=>{it("should throw an error if the device is not connected",async()=>{const t=T(),e=await i.disconnect({connectedDevice:t});expect(e).toStrictEqual(g(new C(`Unknown device ${t.id}`)))}),it("should disconnect if the device is connected",t=>{r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),d(e=>{i.connect({deviceId:e.id,onDisconnect:jest.fn()}).then(c=>{c.ifRight(o=>{i.disconnect({connectedDevice:o}).then(n=>{expect(n).toStrictEqual(R(void 0)),t()}).catch(n=>{t(n)})}).ifLeft(()=>{t(c)})}).catch(c=>{t(c)})},e=>{t(e)})}),it("should call disconnect handler if a connected device is unplugged",t=>{const e=jest.fn();r.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),i.startDiscovering().subscribe({next:c=>{const o={sendApdu:jest.fn(),device:a,deviceId:c.id,disconnect:e,lostConnection:jest.fn().mockImplementation(()=>{setTimeout(()=>{o.disconnect()},p)})};i.connect({deviceId:c.id,onDisconnect:e}).then(async()=>{h(a),expect(a.close).toHaveBeenCalled(),await Promise.resolve(),expect(e).not.toHaveBeenCalled(),jest.advanceTimersByTime(p/2),expect(e).not.toHaveBeenCalled(),jest.advanceTimersByTime(p/2),expect(e).toHaveBeenCalled(),t()}).catch(n=>{t(n)})}})})}),describe("reconnect",()=>{it.only("should stop disconnection if reconnection happen",t=>{const e=jest.fn(),c=l(),o=l();r.mockResolvedValueOnce([c]),s.mockResolvedValue([c,o]),d(async n=>{const v={sendApdu:jest.fn(),device:o,deviceId:n.id,disconnect:e,lostConnection:jest.fn().mockImplementation(()=>{setTimeout(()=>{v.disconnect()},p)})};try{await i.connect({deviceId:n.id,onDisconnect:e}),h(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(o),expect(o.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),t()}catch(j){t(j)}})}),it("should be able to reconnect twice in a row if the device is unplugged and replugged twice",t=>{const e=jest.fn(),c=l(),o=l(),n=l();r.mockResolvedValueOnce([c]),s.mockResolvedValue([c,o,n]),d(async v=>{await i.connect({deviceId:v.id,onDisconnect:e});try{h(c),expect(c.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(o),expect(o.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p/3),b(n),expect(n.open).toHaveBeenCalled(),await Promise.resolve(),jest.advanceTimersByTime(p),expect(e).not.toHaveBeenCalled(),t()}catch(j){t(j)}})})}),describe("Connection event typeguard",()=>{it("should validate type of an HIDConnectionEvent",()=>{const t={device:a},e=i.isHIDConnectionEvent(t);expect(e).toBe(!0)}),it("should not validate type of another event",()=>{const t=new Event("disconnect",{}),e=i.isHIDConnectionEvent(t);expect(e).toBe(!1)})}),describe("listenToKnownDevices",()=>{it("should emit the devices already connected before listening",async()=>{const t=l();s.mockResolvedValue([t]);const e=jest.fn(),c=jest.fn();let o=[];i.listenToKnownDevices().subscribe({next:n=>{o=n},complete:e,error:c}),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(e).not.toHaveBeenCalled(),expect(c).not.toHaveBeenCalled()}),it("should emit the new list of devices after connection and disconnection events",async()=>{w();const t=l({productId:x.getDeviceModel({id:u.NANO_X}).usbProductId<<8}),e=l({productId:x.getDeviceModel({id:u.STAX}).usbProductId<<8});s.mockResolvedValue([t]);const c=jest.fn(),o=jest.fn();let n=[];i.listenToKnownDevices().subscribe({next:v=>{n=v},complete:c,error:o}),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),s.mockResolvedValue([t,e]),b(e),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})}),expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),s.mockResolvedValue([e]),h(t),await m(),expect(n).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),expect(c).not.toHaveBeenCalled(),expect(o).not.toHaveBeenCalled()}),it("should preserve DeviceId in case the device has been disconnected and reconnected before the timeout",async()=>{const t=l();s.mockResolvedValue([t]);const e=jest.fn(),c=jest.fn();let o=[];i.listenToKnownDevices().subscribe({next:v=>{o=v},complete:e,error:c}),await m();const n=o[0]?.id;expect(n).toBeTruthy(),expect(o[0]?.deviceModel?.id).toBe(u.NANO_X),await i.connect({deviceId:o[0].id,onDisconnect:jest.fn()}),await m(),s.mockResolvedValue([]),h(t),await m(),expect(o).toEqual([]),s.mockResolvedValue([t]),b(t),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(o[0]?.id).toBeTruthy(),expect(o[0]?.id).toBe(n)})})})});
1
+ import{connectedDeviceStubBuilder as B,DeviceModelId as u,DeviceNotRecognizedError as P,NoAccessibleDeviceError as y,OpeningConnectionError as H,StaticDeviceModelDataSource as R,UnknownDeviceError as k}from"@ledgerhq/device-management-kit";import{Left as w,Right as N}from"purify-ts";import{Subject as S}from"rxjs";import{RECONNECT_DEVICE_TIMEOUT as p}from"../data/WebHidConfig";import{WebHidTransportNotSupportedError as O}from"../model/Errors";import{hidDeviceStubBuilder as l}from"../model/HIDDevice.stub";import{WebHidTransport as V}from"./WebHidTransport";class M{constructor(D,f){this.subscribers=D,this.tag=f}subscribers=[];tag="";error=vi.fn();warn=vi.fn();info=vi.fn();debug=vi.fn()}const x=new R,A=new M([],"web-usb-hid"),a=l(),m=async()=>{const r=await vi.importActual("timers");return new Promise(r.setImmediate)};describe("WebHidTransport",()=>{let r,D,f;function E(){D=vi.fn(),f=vi.fn(),r=new V(x,()=>A,f,D)}beforeEach(()=>{E(),vi.useFakeTimers()}),afterEach(()=>{vi.restoreAllMocks()});const v=(s,d)=>{r.startDiscovering().subscribe({next:s,error:d})};describe("When WebHID API is not supported",()=>{it("should not support the transport",()=>{expect(r.isSupported()).toBe(!1)}),it("should emit a startDiscovering error",()=>new Promise((s,d)=>{v(()=>{d("Should not emit any value")},g=>{expect(g).toBeInstanceOf(O),s()})}))}),describe("When WebHID API is supported",()=>{const s=vi.fn(),d=vi.fn(),g=new S,T=new S;function b(i){g.next({device:i})}function h(i){T.next({device:i})}beforeEach(()=>{global.navigator={hid:{getDevices:s,requestDevice:d,addEventListener:(i,e)=>{i==="disconnect"?T.subscribe(e):i==="connect"&&g.subscribe(e)}}},E()}),afterEach(()=>{vi.clearAllMocks(),global.navigator=void 0}),it("should support the transport",()=>{expect(r.isSupported()).toBe(!0)}),describe("startDiscovering",()=>{x.getAllDeviceModels().flatMap(e=>[{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName})`,hidDevice:l({productId:e.usbProductId<<8,productName:e.productName}),expectedDeviceModel:e},{testTitle:`should emit device if user grants access through hid.requestDevice (${e.productName}, bootloader)`,hidDevice:l({productId:e.bootloaderUsbProductId,productName:e.productName}),expectedDeviceModel:e}]).forEach(e=>{it(e.testTitle,()=>new Promise((n,o)=>{d.mockResolvedValueOnce([e.hidDevice]),v(t=>{try{expect(t).toEqual(expect.objectContaining({deviceModel:e.expectedDeviceModel})),n()}catch(c){o(c)}},t=>{o(t)})}))}),it("should emit devices if new grant accesses",()=>new Promise((e,n)=>{d.mockResolvedValueOnce([a,{...a,productId:20497,productName:"Ledger Nano S Plus"}]);let o=0;v(t=>{try{switch(o){case 0:expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X,productName:"Ledger Nano X",usbProductId:64})}));break;case 1:expect(t).toEqual(expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80})})),e();break}o++}catch(c){n(c)}},t=>{n(t)})})),it("should throw DeviceNotRecognizedError if the device is not recognized",()=>new Promise((e,n)=>{d.mockResolvedValueOnce([{...a,productId:16962}]),v(()=>{n("should not return a device")},o=>{expect(o).toBeInstanceOf(P),e()})})),it("should emit an error if the request device is in error",()=>new Promise((e,n)=>{const o="request device error";d.mockImplementationOnce(()=>{throw new Error(o)}),v(()=>{n("should not return a device")},t=>{expect(t).toBeInstanceOf(y),expect(t).toStrictEqual(new y(new Error(o))),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)",()=>new Promise((e,n)=>{d.mockResolvedValueOnce([]),v(o=>{n(`Should not emit any value, but emitted ${JSON.stringify(o)}`)},o=>{try{expect(o).toBeInstanceOf(y),e()}catch(t){n(t)}})})),it("should emit the same discoveredDevice object if its discovered twice in a row",async()=>{d.mockResolvedValue([a]),s.mockResolvedValue([a]);const e=await new Promise((o,t)=>{v(()=>o(),c=>t(c))}),n=await new Promise((o,t)=>{v(()=>o(),c=>t(c))});expect(n).toBe(e)})}),describe("destroy",()=>{it("should stop monitoring connections if the discovery process is halted",()=>{const i=vi.spyOn(AbortController.prototype,"abort");r.destroy(),expect(i).toHaveBeenCalled()})}),describe("connect",()=>{it("should throw UnknownDeviceError if no internal device",async()=>{const i={deviceId:"fake",onDisconnect:vi.fn()},e=await r.connect(i);expect(e).toStrictEqual(w(new k("Unknown device fake")))}),it("should throw OpeningConnectionError if the device is already opened",async()=>{const i={deviceId:"fake",onDisconnect:vi.fn()},e=await r.connect(i);expect(e).toStrictEqual(w(new k("Unknown device fake")))}),it("should throw OpeningConnectionError if the device cannot be opened",()=>new Promise((i,e)=>{const n="cannot be opened",o={...a,open:()=>{throw new Error(n)}};d.mockResolvedValueOnce([o]),s.mockResolvedValue([o]),v(t=>{r.connect({deviceId:t.id,onDisconnect:vi.fn()}).then(c=>{expect(c).toStrictEqual(w(new H(new Error(n)))),i()}).catch(c=>{e(c)})},t=>{e(t)})})),it("should return the opened device",()=>new Promise((i,e)=>{const n={...a,opened:!1,open:()=>(n.opened=!0,Promise.resolve())};d.mockResolvedValue([n]),s.mockResolvedValue([n]),v(o=>{r.connect({deviceId:o.id,onDisconnect:vi.fn()}).then(t=>{t.ifRight(c=>{expect(c).toEqual(expect.objectContaining({id:o.id})),i()}).ifLeft(()=>{e(t)})}).catch(t=>{e(t)})},o=>{e(o)})})),it("should return a device if available",()=>new Promise((i,e)=>{d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),v(n=>{r.connect({deviceId:n.id,onDisconnect:vi.fn()}).then(o=>{o.ifRight(t=>{expect(t).toEqual(expect.objectContaining({id:n.id})),i()}).ifLeft(()=>{e(o)})}).catch(o=>{e(o)})},n=>{e(n)})}))}),describe("disconnect",()=>{it("should throw an error if the device is not connected",async()=>{const i=B(),e=await r.disconnect({connectedDevice:i});expect(e).toStrictEqual(w(new k(`Unknown device ${i.id}`)))}),it("should disconnect if the device is connected",()=>new Promise((i,e)=>{d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),v(n=>{r.connect({deviceId:n.id,onDisconnect:vi.fn()}).then(o=>{o.ifRight(t=>{r.disconnect({connectedDevice:t}).then(c=>{expect(c).toStrictEqual(N(void 0)),i()}).catch(c=>{e(c)})}).ifLeft(()=>{e(o)})}).catch(o=>{e(o)})},n=>{e(n)})})),it("should call disconnect handler if a connected device is unplugged",()=>new Promise((i,e)=>{const n=vi.fn();d.mockResolvedValueOnce([a]),s.mockResolvedValue([a]),r.startDiscovering().subscribe({next:o=>{const t={sendApdu:vi.fn(),device:a,deviceId:o.id,disconnect:n,lostConnection:vi.fn().mockImplementation(()=>{setTimeout(()=>{t.disconnect()},p)})};r.connect({deviceId:o.id,onDisconnect:n}).then(async()=>{h(a),expect(a.close).toHaveBeenCalled(),await Promise.resolve(),expect(n).not.toHaveBeenCalled(),vi.advanceTimersByTime(p/2),expect(n).not.toHaveBeenCalled(),vi.advanceTimersByTime(p/2),expect(n).toHaveBeenCalled(),i()}).catch(c=>{e(c)})}})}))}),describe("reconnect",()=>{it("should stop disconnection if reconnection happen",()=>new Promise((i,e)=>{const n=vi.fn(),o=l(),t=l();d.mockResolvedValueOnce([o]),s.mockResolvedValue([o,t]),v(async c=>{const C={sendApdu:vi.fn(),device:t,deviceId:c.id,disconnect:n,lostConnection:vi.fn().mockImplementation(()=>{setTimeout(()=>{C.disconnect()},p)})};try{await r.connect({deviceId:c.id,onDisconnect:n}),h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(t),expect(t.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),i()}catch(I){e(I)}})})),it("should be able to reconnect twice in a row if the device is unplugged and replugged twice",()=>new Promise((i,e)=>{const n=vi.fn(),o=l(),t=l(),c=l();d.mockResolvedValueOnce([o]),s.mockResolvedValue([o,t,c]),v(async C=>{await r.connect({deviceId:C.id,onDisconnect:n});try{h(o),expect(o.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(t),expect(t.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),h(t),expect(t.close).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p/3),b(c),expect(c.open).toHaveBeenCalled(),await Promise.resolve(),vi.advanceTimersByTime(p),expect(n).not.toHaveBeenCalled(),i()}catch(I){e(I)}})}))}),describe("Connection event typeguard",()=>{it("should validate type of an HIDConnectionEvent",()=>{const i={device:a},e=r.isHIDConnectionEvent(i);expect(e).toBe(!0)}),it("should not validate type of another event",()=>{const i=new Event("disconnect",{}),e=r.isHIDConnectionEvent(i);expect(e).toBe(!1)})}),describe("listenToKnownDevices",()=>{it("should emit the devices already connected before listening",async()=>{const i=l();s.mockResolvedValue([i]);const e=vi.fn(),n=vi.fn();let o=[];r.listenToKnownDevices().subscribe({next:t=>{o=t},complete:e,error:n}),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(e).not.toHaveBeenCalled(),expect(n).not.toHaveBeenCalled()}),it("should emit the new list of devices after connection and disconnection events",async()=>{E();const i=l({productId:x.getDeviceModel({id:u.NANO_X}).usbProductId<<8}),e=l({productId:x.getDeviceModel({id:u.STAX}).usbProductId<<8});s.mockResolvedValue([i]);const n=vi.fn(),o=vi.fn();let t=[];r.listenToKnownDevices().subscribe({next:c=>{t=c},complete:n,error:o}),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),s.mockResolvedValue([i,e]),b(e),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})}),expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),s.mockResolvedValue([e]),h(i),await m(),expect(t).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.STAX})})]),expect(n).not.toHaveBeenCalled(),expect(o).not.toHaveBeenCalled()}),it("should preserve DeviceId in case the device has been disconnected and reconnected before the timeout",async()=>{const i=l();s.mockResolvedValue([i]);const e=vi.fn(),n=vi.fn();let o=[];r.listenToKnownDevices().subscribe({next:c=>{o=c},complete:e,error:n}),await m();const t=o[0]?.id;expect(t).toBeTruthy(),expect(o[0]?.deviceModel?.id).toBe(u.NANO_X),await r.connect({deviceId:o[0].id,onDisconnect:vi.fn()}),await m(),s.mockResolvedValue([]),h(i),await m(),expect(o).toEqual([]),s.mockResolvedValue([i]),b(i),await m(),expect(o).toEqual([expect.objectContaining({deviceModel:expect.objectContaining({id:u.NANO_X})})]),expect(o[0]?.id).toBeTruthy(),expect(o[0]?.id).toBe(t)})})})});
2
2
  //# sourceMappingURL=WebHidTransport.test.js.map