usb 2.17.0 → 3.0.0-alpha.2

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 (207) hide show
  1. package/LICENSE +18 -4
  2. package/README.md +25 -516
  3. package/dist/index.d.ts +67 -13
  4. package/dist/index.js +333 -64
  5. package/index.d.ts +89 -0
  6. package/index.js +583 -0
  7. package/package.json +53 -33
  8. package/CHANGELOG.md +0 -294
  9. package/binding.gyp +0 -128
  10. package/dist/index.js.map +0 -1
  11. package/dist/usb/bindings.d.ts +0 -266
  12. package/dist/usb/bindings.js +0 -10
  13. package/dist/usb/bindings.js.map +0 -1
  14. package/dist/usb/capability.d.ts +0 -13
  15. package/dist/usb/capability.js +0 -17
  16. package/dist/usb/capability.js.map +0 -1
  17. package/dist/usb/descriptors.d.ts +0 -128
  18. package/dist/usb/descriptors.js +0 -3
  19. package/dist/usb/descriptors.js.map +0 -1
  20. package/dist/usb/device.d.ts +0 -100
  21. package/dist/usb/device.js +0 -297
  22. package/dist/usb/device.js.map +0 -1
  23. package/dist/usb/endpoint.d.ts +0 -94
  24. package/dist/usb/endpoint.js +0 -219
  25. package/dist/usb/endpoint.js.map +0 -1
  26. package/dist/usb/index.d.ts +0 -31
  27. package/dist/usb/index.js +0 -116
  28. package/dist/usb/index.js.map +0 -1
  29. package/dist/usb/interface.d.ts +0 -80
  30. package/dist/usb/interface.js +0 -133
  31. package/dist/usb/interface.js.map +0 -1
  32. package/dist/webusb/index.d.ts +0 -64
  33. package/dist/webusb/index.js +0 -295
  34. package/dist/webusb/index.js.map +0 -1
  35. package/dist/webusb/webusb-device.d.ts +0 -54
  36. package/dist/webusb/webusb-device.js +0 -434
  37. package/dist/webusb/webusb-device.js.map +0 -1
  38. package/libusb/.clang-tidy +0 -34
  39. package/libusb/.codespellrc +0 -3
  40. package/libusb/.private/README.txt +0 -5
  41. package/libusb/.private/appveyor_build.sh +0 -26
  42. package/libusb/.private/bm.sh +0 -54
  43. package/libusb/.private/ci-build.sh +0 -92
  44. package/libusb/.private/ci-container-build.sh +0 -67
  45. package/libusb/.private/post-rewrite.sh +0 -32
  46. package/libusb/.private/pre-commit.sh +0 -52
  47. package/libusb/.private/wbs.txt +0 -43
  48. package/libusb/.travis.yml +0 -58
  49. package/libusb/AUTHORS +0 -231
  50. package/libusb/COPYING +0 -504
  51. package/libusb/ChangeLog +0 -365
  52. package/libusb/HACKING +0 -25
  53. package/libusb/INSTALL_WIN.txt +0 -52
  54. package/libusb/KEYS +0 -123
  55. package/libusb/Makefile.am +0 -50
  56. package/libusb/NEWS +0 -2
  57. package/libusb/PORTING +0 -94
  58. package/libusb/README +0 -29
  59. package/libusb/README.git +0 -41
  60. package/libusb/TODO +0 -2
  61. package/libusb/Xcode/common.xcconfig +0 -92
  62. package/libusb/Xcode/config.h +0 -31
  63. package/libusb/Xcode/debug.xcconfig +0 -32
  64. package/libusb/Xcode/libusb.xcconfig +0 -21
  65. package/libusb/Xcode/libusb.xcodeproj/project.pbxproj +0 -1391
  66. package/libusb/Xcode/libusb_debug.xcconfig +0 -21
  67. package/libusb/Xcode/libusb_release.xcconfig +0 -21
  68. package/libusb/Xcode/release.xcconfig +0 -30
  69. package/libusb/android/README +0 -152
  70. package/libusb/android/config.h +0 -55
  71. package/libusb/android/examples/unrooted_android.c +0 -301
  72. package/libusb/android/examples/unrooted_android.h +0 -36
  73. package/libusb/android/jni/Android.mk +0 -23
  74. package/libusb/android/jni/Application.mk +0 -40
  75. package/libusb/android/jni/examples.mk +0 -168
  76. package/libusb/android/jni/libusb.mk +0 -60
  77. package/libusb/android/jni/tests.mk +0 -45
  78. package/libusb/appveyor.yml +0 -108
  79. package/libusb/autogen.sh +0 -10
  80. package/libusb/bootstrap.sh +0 -10
  81. package/libusb/configure.ac +0 -450
  82. package/libusb/doc/Makefile.in +0 -22
  83. package/libusb/doc/doxygen.cfg.in +0 -2571
  84. package/libusb/doc/libusb.png +0 -0
  85. package/libusb/examples/Makefile.am +0 -12
  86. package/libusb/examples/dpfp.c +0 -711
  87. package/libusb/examples/ezusb.c +0 -846
  88. package/libusb/examples/ezusb.h +0 -109
  89. package/libusb/examples/fxload.c +0 -310
  90. package/libusb/examples/hotplugtest.c +0 -147
  91. package/libusb/examples/listdevs.c +0 -73
  92. package/libusb/examples/sam3u_benchmark.c +0 -228
  93. package/libusb/examples/testlibusb.c +0 -312
  94. package/libusb/examples/xusb.c +0 -1254
  95. package/libusb/libusb/Makefile.am +0 -98
  96. package/libusb/libusb/Makefile.am.extra +0 -26
  97. package/libusb/libusb/core.c +0 -2925
  98. package/libusb/libusb/descriptor.c +0 -1558
  99. package/libusb/libusb/hotplug.c +0 -489
  100. package/libusb/libusb/io.c +0 -2865
  101. package/libusb/libusb/libusb-1.0.def +0 -199
  102. package/libusb/libusb/libusb-1.0.rc +0 -53
  103. package/libusb/libusb/libusb.h +0 -2421
  104. package/libusb/libusb/libusbi.h +0 -1535
  105. package/libusb/libusb/os/darwin_usb.c +0 -2977
  106. package/libusb/libusb/os/darwin_usb.h +0 -156
  107. package/libusb/libusb/os/emscripten_webusb.cpp +0 -875
  108. package/libusb/libusb/os/events_posix.c +0 -340
  109. package/libusb/libusb/os/events_posix.h +0 -62
  110. package/libusb/libusb/os/events_windows.c +0 -214
  111. package/libusb/libusb/os/events_windows.h +0 -46
  112. package/libusb/libusb/os/haiku_pollfs.cpp +0 -372
  113. package/libusb/libusb/os/haiku_usb.h +0 -113
  114. package/libusb/libusb/os/haiku_usb_backend.cpp +0 -532
  115. package/libusb/libusb/os/haiku_usb_raw.cpp +0 -231
  116. package/libusb/libusb/os/haiku_usb_raw.h +0 -188
  117. package/libusb/libusb/os/linux_netlink.c +0 -401
  118. package/libusb/libusb/os/linux_udev.c +0 -321
  119. package/libusb/libusb/os/linux_usbfs.c +0 -2829
  120. package/libusb/libusb/os/linux_usbfs.h +0 -221
  121. package/libusb/libusb/os/netbsd_usb.c +0 -617
  122. package/libusb/libusb/os/null_usb.c +0 -111
  123. package/libusb/libusb/os/openbsd_usb.c +0 -700
  124. package/libusb/libusb/os/sunos_usb.c +0 -1619
  125. package/libusb/libusb/os/sunos_usb.h +0 -79
  126. package/libusb/libusb/os/threads_posix.c +0 -126
  127. package/libusb/libusb/os/threads_posix.h +0 -98
  128. package/libusb/libusb/os/threads_windows.c +0 -40
  129. package/libusb/libusb/os/threads_windows.h +0 -113
  130. package/libusb/libusb/os/windows_common.c +0 -923
  131. package/libusb/libusb/os/windows_common.h +0 -424
  132. package/libusb/libusb/os/windows_usbdk.c +0 -724
  133. package/libusb/libusb/os/windows_usbdk.h +0 -106
  134. package/libusb/libusb/os/windows_winusb.c +0 -4766
  135. package/libusb/libusb/os/windows_winusb.h +0 -787
  136. package/libusb/libusb/strerror.c +0 -223
  137. package/libusb/libusb/sync.c +0 -342
  138. package/libusb/libusb/version.h +0 -18
  139. package/libusb/libusb/version_nano.h +0 -1
  140. package/libusb/libusb-1.0.pc.in +0 -11
  141. package/libusb/msvc/Base.props +0 -60
  142. package/libusb/msvc/Configuration.Application.props +0 -7
  143. package/libusb/msvc/Configuration.Base.props +0 -47
  144. package/libusb/msvc/Configuration.DynamicLibrary.props +0 -21
  145. package/libusb/msvc/Configuration.StaticLibrary.props +0 -7
  146. package/libusb/msvc/ProjectConfigurations.Base.props +0 -69
  147. package/libusb/msvc/build_all.ps1 +0 -17
  148. package/libusb/msvc/config.h +0 -58
  149. package/libusb/msvc/dpfp.vcxproj +0 -33
  150. package/libusb/msvc/dpfp_threaded.vcxproj +0 -38
  151. package/libusb/msvc/fxload.vcxproj +0 -46
  152. package/libusb/msvc/getopt/getopt.c +0 -1060
  153. package/libusb/msvc/getopt/getopt.h +0 -180
  154. package/libusb/msvc/getopt/getopt1.c +0 -188
  155. package/libusb/msvc/getopt.vcxproj +0 -33
  156. package/libusb/msvc/hotplugtest.vcxproj +0 -32
  157. package/libusb/msvc/init_context.vcxproj +0 -35
  158. package/libusb/msvc/libusb.sln +0 -542
  159. package/libusb/msvc/libusb_dll.vcxproj +0 -61
  160. package/libusb/msvc/libusb_static.vcxproj +0 -49
  161. package/libusb/msvc/listdevs.vcxproj +0 -32
  162. package/libusb/msvc/sam3u_benchmark.vcxproj +0 -33
  163. package/libusb/msvc/set_option.vcxproj +0 -35
  164. package/libusb/msvc/stress.vcxproj +0 -35
  165. package/libusb/msvc/stress_mt.vcxproj +0 -33
  166. package/libusb/msvc/testlibusb.vcxproj +0 -32
  167. package/libusb/msvc/xusb.vcxproj +0 -38
  168. package/libusb/tests/Makefile.am +0 -40
  169. package/libusb/tests/init_context.c +0 -153
  170. package/libusb/tests/libusb_testlib.h +0 -76
  171. package/libusb/tests/macos.c +0 -130
  172. package/libusb/tests/set_option.c +0 -253
  173. package/libusb/tests/stress.c +0 -172
  174. package/libusb/tests/stress_mt.c +0 -267
  175. package/libusb/tests/testlib.c +0 -184
  176. package/libusb/tests/umockdev.c +0 -1175
  177. package/libusb/tests/webusb-test-shim/index.js +0 -12
  178. package/libusb/tests/webusb-test-shim/package-lock.json +0 -50
  179. package/libusb/tests/webusb-test-shim/package.json +0 -10
  180. package/libusb.gypi +0 -154
  181. package/libusb_config/config.h +0 -1
  182. package/prebuilds/android-arm/node.napi.armv7.node +0 -0
  183. package/prebuilds/android-arm64/node.napi.armv8.node +0 -0
  184. package/prebuilds/darwin-x64+arm64/node.napi.node +0 -0
  185. package/prebuilds/linux-arm/node.napi.armv6.node +0 -0
  186. package/prebuilds/linux-arm/node.napi.armv7.node +0 -0
  187. package/prebuilds/linux-arm64/node.napi.armv8.node +0 -0
  188. package/prebuilds/linux-ia32/node.napi.node +0 -0
  189. package/prebuilds/linux-x64/node.napi.glibc.node +0 -0
  190. package/prebuilds/linux-x64/node.napi.musl.node +0 -0
  191. package/prebuilds/win32-arm64/node.napi.node +0 -0
  192. package/prebuilds/win32-ia32/node.napi.node +0 -0
  193. package/prebuilds/win32-x64/node.napi.node +0 -0
  194. package/src/device.cc +0 -439
  195. package/src/helpers.h +0 -64
  196. package/src/hotplug/hotplug.h +0 -22
  197. package/src/hotplug/libusb.cc +0 -90
  198. package/src/hotplug/windows.cc +0 -168
  199. package/src/node_usb.cc +0 -314
  200. package/src/node_usb.h +0 -131
  201. package/src/thread_name.cc +0 -79
  202. package/src/thread_name.h +0 -11
  203. package/src/transfer.cc +0 -143
  204. package/src/uv_async_queue.h +0 -41
  205. package/test/usb.coffee +0 -250
  206. package/test/webusb.coffee +0 -227
  207. package/test/worker.cjs +0 -13
package/dist/index.d.ts CHANGED
@@ -1,22 +1,76 @@
1
- import { WebUSB } from './webusb';
2
- import * as usb from './usb';
1
+ import { Emitter } from '../index.js';
2
+ import { EventEmitter } from 'events';
3
+ /**
4
+ * USB Options
5
+ */
6
+ interface USBOptions {
7
+ /**
8
+ * Optional `device found` callback function to allow the user to select a device
9
+ */
10
+ devicesFound?: (devices: USBDevice[]) => Promise<USBDevice | void>;
11
+ /**
12
+ * Optional array of preconfigured allowed devices
13
+ */
14
+ allowedDevices?: USBDeviceFilter[];
15
+ /**
16
+ * Optional flag to automatically allow all devices
17
+ */
18
+ allowAllDevices?: boolean;
19
+ /**
20
+ * Optional timeout (in milliseconds) to use for the device control transfers
21
+ */
22
+ deviceTimeout?: number;
23
+ /**
24
+ * Optional flag to enable/disable automatic kernal driver detaching (defaults to true)
25
+ */
26
+ autoDetachKernelDriver?: boolean;
27
+ }
28
+ declare class WebUSB implements USB {
29
+ private options;
30
+ protected nativeEmitter: Emitter;
31
+ protected emitter: EventEmitter<any>;
32
+ protected authorisedDevices: Set<USBDeviceFilter>;
33
+ protected knownDevices: Map<string, USBDevice>;
34
+ constructor(options?: USBOptions);
35
+ private _onconnect;
36
+ set onconnect(fn: (ev: USBConnectionEvent) => void);
37
+ private _ondisconnect;
38
+ set ondisconnect(fn: (ev: USBConnectionEvent) => void);
39
+ addEventListener(type: 'connect' | 'disconnect', listener: (this: this, ev: USBConnectionEvent) => void): void;
40
+ addEventListener(type: 'connect' | 'disconnect', listener: EventListener): void;
41
+ removeEventListener(type: 'connect' | 'disconnect', callback: (this: this, ev: USBConnectionEvent) => void): void;
42
+ removeEventListener(type: 'connect' | 'disconnect', callback: EventListener): void;
43
+ dispatchEvent(_event: Event): boolean;
44
+ /**
45
+ * Requests a single Web USB device
46
+ * @param options The options to use when scanning
47
+ * @returns Promise containing the selected device
48
+ */
49
+ requestDevice(options?: USBDeviceRequestOptions): Promise<USBDevice>;
50
+ /**
51
+ * Gets all allowed Web USB devices which are connected
52
+ * @returns Promise containing an array of devices
53
+ */
54
+ getDevices(): Promise<USBDevice[]>;
55
+ private loadDevices;
56
+ private quickFilter;
57
+ private filterDevice;
58
+ private isAuthorisedDevice;
59
+ }
60
+ /**
61
+ * Convenience method to get an array of all connected devices.
62
+ */
63
+ declare const getDeviceList: () => Promise<USBDevice[]>;
3
64
  /**
4
65
  * Convenience method to get the first device with the specified VID and PID, or `undefined` if no such device is present.
5
66
  * @param vid
6
67
  * @param pid
7
68
  */
8
- declare const findByIds: (vid: number, pid: number) => usb.Device | undefined;
69
+ declare const findByIds: (vid: number, pid: number) => Promise<USBDevice | undefined>;
9
70
  /**
10
71
  * Convenience method to get the device with the specified serial number, or `undefined` if no such device is present.
11
72
  * @param serialNumber
12
73
  */
13
- declare const findBySerialNumber: (serialNumber: string) => Promise<usb.Device | undefined>;
14
- declare const webusb: WebUSB;
15
- export { usb, findByIds, findBySerialNumber, webusb };
16
- export { Device, Transfer, DeviceEvents, getDeviceList, useUsbDkBackend, LibUSBException } from './usb';
17
- export * from './usb/capability';
18
- export * from './usb/descriptors';
19
- export * from './usb/endpoint';
20
- export * from './usb/interface';
21
- export * from './webusb';
22
- export * from './webusb/webusb-device';
74
+ declare const findBySerialNumber: (serialNumber: string) => Promise<USBDevice | undefined>;
75
+ declare const webusb: WebUSB | USB;
76
+ export { webusb, WebUSB, USBOptions, getDeviceList, findByIds, findBySerialNumber, };
package/dist/index.js CHANGED
@@ -1,32 +1,341 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findBySerialNumber = exports.findByIds = exports.getDeviceList = exports.WebUSB = exports.webusb = void 0;
4
+ const index_js_1 = require("../index.js");
5
+ const events_1 = require("events");
6
+ class NamedError extends Error {
7
+ constructor(message, name) {
8
+ super(message);
9
+ this.name = name;
7
10
  }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ }
12
+ const augmentDevice = (device) => {
13
+ const toUint8Array = (data) => {
14
+ if (data instanceof ArrayBuffer) {
15
+ return new Uint8Array(data);
16
+ }
17
+ // ArrayBufferView
18
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
19
+ };
20
+ Object.defineProperty(device, 'controlTransferIn', {
21
+ enumerable: false,
22
+ configurable: false,
23
+ value: async function (setup, length) {
24
+ const res = await this.nativeControlTransferIn(setup, length);
25
+ return {
26
+ data: res ? new DataView(res.buffer) : undefined,
27
+ status: res ? 'ok' : 'stall',
28
+ };
29
+ },
30
+ });
31
+ Object.defineProperty(device, 'controlTransferOut', {
32
+ enumerable: false,
33
+ configurable: false,
34
+ value: async function (setup, data) {
35
+ const res = await this.nativeControlTransferOut(setup, toUint8Array(data));
36
+ return {
37
+ bytesWritten: res,
38
+ status: res >= 0 ? 'ok' : 'stall',
39
+ };
40
+ },
41
+ });
42
+ Object.defineProperty(device, 'transferIn', {
43
+ enumerable: false,
44
+ configurable: false,
45
+ value: async function (endpointNumber, length) {
46
+ const res = await this.nativeTransferIn(endpointNumber, length);
47
+ return {
48
+ data: res ? new DataView(res.buffer) : undefined,
49
+ status: res ? 'ok' : 'stall',
50
+ };
51
+ },
52
+ });
53
+ Object.defineProperty(device, 'transferOut', {
54
+ enumerable: false,
55
+ configurable: false,
56
+ value: async function (endpointNumber, data) {
57
+ const res = await this.nativeTransferOut(endpointNumber, toUint8Array(data));
58
+ return {
59
+ bytesWritten: res,
60
+ status: res >= 0 ? 'ok' : 'stall',
61
+ };
62
+ },
63
+ });
64
+ return device;
15
65
  };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.LibUSBException = exports.useUsbDkBackend = exports.getDeviceList = exports.Transfer = exports.Device = exports.webusb = exports.findBySerialNumber = exports.findByIds = exports.usb = void 0;
18
- const util_1 = require("util");
19
- const webusb_1 = require("./webusb");
20
- const usb = require("./usb");
21
- exports.usb = usb;
66
+ class WebUSB {
67
+ constructor(options = {}) {
68
+ this.options = options;
69
+ this.nativeEmitter = new index_js_1.Emitter();
70
+ this.emitter = new events_1.EventEmitter();
71
+ this.authorisedDevices = new Set();
72
+ this.knownDevices = new Map();
73
+ const deviceConnectCallback = async (device) => {
74
+ const webDevice = augmentDevice(device);
75
+ this.knownDevices.set(device.handle, webDevice);
76
+ // When connected, emit an event if it is an allowed device
77
+ if (webDevice && this.isAuthorisedDevice(webDevice)) {
78
+ const event = {
79
+ type: 'connect',
80
+ device: webDevice
81
+ };
82
+ this.emitter.emit('connect', event);
83
+ }
84
+ };
85
+ const deviceDisconnectCallback = async (handle) => {
86
+ // When disconnected, emit an event if the device was a known allowed device
87
+ if (this.knownDevices.has(handle)) {
88
+ const webDevice = this.knownDevices.get(handle);
89
+ if (webDevice && this.isAuthorisedDevice(webDevice)) {
90
+ const event = {
91
+ type: 'disconnect',
92
+ device: webDevice
93
+ };
94
+ this.emitter.emit('disconnect', event);
95
+ }
96
+ this.knownDevices.delete(handle);
97
+ }
98
+ };
99
+ this.emitter.on('newListener', async (event) => {
100
+ const listenerCount = this.emitter.listenerCount(event);
101
+ if (listenerCount !== 0) {
102
+ return;
103
+ }
104
+ if (event === 'connect') {
105
+ this.nativeEmitter.addAttach(deviceConnectCallback);
106
+ }
107
+ else if (event === 'disconnect') {
108
+ // Ensure we know the current devices
109
+ this.knownDevices.clear();
110
+ const devices = await (0, index_js_1.nativeGetDeviceList)();
111
+ devices.forEach(device => {
112
+ this.knownDevices.set(device.handle, augmentDevice(device));
113
+ });
114
+ this.nativeEmitter.addDetach(deviceDisconnectCallback);
115
+ }
116
+ });
117
+ this.emitter.on('removeListener', event => {
118
+ const listenerCount = this.emitter.listenerCount(event);
119
+ if (listenerCount !== 0) {
120
+ return;
121
+ }
122
+ if (event === 'connect') {
123
+ this.nativeEmitter.removeAttach(deviceConnectCallback);
124
+ }
125
+ else if (event === 'disconnect') {
126
+ this.knownDevices.clear();
127
+ this.nativeEmitter.removeDetach(deviceDisconnectCallback);
128
+ }
129
+ });
130
+ this.nativeEmitter.start();
131
+ }
132
+ set onconnect(fn) {
133
+ if (this._onconnect) {
134
+ this.removeEventListener('connect', this._onconnect);
135
+ this._onconnect = undefined;
136
+ }
137
+ if (fn) {
138
+ this._onconnect = fn;
139
+ this.addEventListener('connect', this._onconnect);
140
+ }
141
+ }
142
+ set ondisconnect(fn) {
143
+ if (this._ondisconnect) {
144
+ this.removeEventListener('disconnect', this._ondisconnect);
145
+ this._ondisconnect = undefined;
146
+ }
147
+ if (fn) {
148
+ this._ondisconnect = fn;
149
+ this.addEventListener('disconnect', this._ondisconnect);
150
+ }
151
+ }
152
+ addEventListener(type, listener) {
153
+ this.emitter.addListener(type, listener);
154
+ }
155
+ removeEventListener(type, callback) {
156
+ this.emitter.removeListener(type, callback);
157
+ }
158
+ dispatchEvent(_event) {
159
+ // Don't dispatch from here
160
+ return false;
161
+ }
162
+ /**
163
+ * Requests a single Web USB device
164
+ * @param options The options to use when scanning
165
+ * @returns Promise containing the selected device
166
+ */
167
+ async requestDevice(options) {
168
+ // Must have options
169
+ if (!options) {
170
+ throw new TypeError('requestDevice error: 1 argument required, but only 0 present');
171
+ }
172
+ // Options must be an object
173
+ if (options.constructor !== {}.constructor) {
174
+ throw new TypeError('requestDevice error: parameter 1 (options) is not an object');
175
+ }
176
+ // Must have a filter
177
+ if (!options.filters) {
178
+ throw new TypeError('requestDevice error: required member filters is undefined');
179
+ }
180
+ // Filter must be an array
181
+ if (options.filters.constructor !== [].constructor) {
182
+ throw new TypeError('requestDevice error: the provided value cannot be converted to a sequence');
183
+ }
184
+ // Check filters
185
+ options.filters.forEach(filter => {
186
+ // Protocol & Subclass
187
+ if (filter.protocolCode && !filter.subclassCode) {
188
+ throw new TypeError('requestDevice error: subclass code is required');
189
+ }
190
+ // Subclass & Class
191
+ if (filter.subclassCode && !filter.classCode) {
192
+ throw new TypeError('requestDevice error: class code is required');
193
+ }
194
+ });
195
+ let devices = await this.loadDevices(options.filters);
196
+ devices = devices.filter(device => this.filterDevice(device, options.filters));
197
+ if (devices.length === 0) {
198
+ throw new NamedError('Failed to execute \'requestDevice\' on \'USB\': No device selected.', 'NotFoundError');
199
+ }
200
+ try {
201
+ // If no devicesFound function, select the first device found
202
+ const device = this.options.devicesFound ? await this.options.devicesFound(devices) : devices[0];
203
+ if (!device) {
204
+ throw new NamedError('Failed to execute \'requestDevice\' on \'USB\': No device selected.', 'NotFoundError');
205
+ }
206
+ this.authorisedDevices.add({
207
+ vendorId: device.vendorId,
208
+ productId: device.productId,
209
+ classCode: device.deviceClass,
210
+ subclassCode: device.deviceSubclass,
211
+ protocolCode: device.deviceProtocol,
212
+ serialNumber: device.serialNumber || undefined
213
+ });
214
+ return device;
215
+ }
216
+ catch (error) {
217
+ throw new NamedError('Failed to execute \'requestDevice\' on \'USB\': No device selected.', 'NotFoundError');
218
+ }
219
+ }
220
+ /**
221
+ * Gets all allowed Web USB devices which are connected
222
+ * @returns Promise containing an array of devices
223
+ */
224
+ async getDevices() {
225
+ const preFilters = this.options.allowAllDevices ? undefined : this.options.allowedDevices;
226
+ // Refresh devices and filter for allowed ones
227
+ const devices = await this.loadDevices(preFilters);
228
+ return devices.filter(device => this.isAuthorisedDevice(device));
229
+ }
230
+ async loadDevices(preFilters) {
231
+ let devices = await getDeviceList();
232
+ // Pre-filter devices
233
+ devices = this.quickFilter(devices, preFilters);
234
+ return devices;
235
+ }
236
+ // Undertake quick filter on devices before creating WebUSB devices if possible
237
+ quickFilter(devices, preFilters) {
238
+ if (!preFilters || !preFilters.length) {
239
+ return devices;
240
+ }
241
+ // Just pre-filter on vid/pid
242
+ return devices.filter(device => preFilters.some(filter => {
243
+ // Vendor
244
+ if (filter.vendorId && filter.vendorId !== device.vendorId)
245
+ return false;
246
+ // Product
247
+ if (filter.productId && filter.productId !== device.productId)
248
+ return false;
249
+ // Ignore Class, Subclass and Protocol as these need to check interfaces, too
250
+ // Ignore serial number for node-usb as it requires device connection
251
+ return true;
252
+ }));
253
+ }
254
+ // Filter WebUSB devices
255
+ filterDevice(device, filters) {
256
+ if (!filters || !filters.length) {
257
+ return true;
258
+ }
259
+ return filters.some(filter => {
260
+ // Vendor
261
+ if (filter.vendorId && filter.vendorId !== device.vendorId)
262
+ return false;
263
+ // Product
264
+ if (filter.productId && filter.productId !== device.productId)
265
+ return false;
266
+ // Class
267
+ if (filter.classCode) {
268
+ if (!device.configuration) {
269
+ return false;
270
+ }
271
+ // Interface Descriptors
272
+ const match = device.configuration.interfaces.some(iface => {
273
+ // Class
274
+ if (filter.classCode && filter.classCode !== iface.alternate.interfaceClass)
275
+ return false;
276
+ // Subclass
277
+ if (filter.subclassCode && filter.subclassCode !== iface.alternate.interfaceSubclass)
278
+ return false;
279
+ // Protocol
280
+ if (filter.protocolCode && filter.protocolCode !== iface.alternate.interfaceProtocol)
281
+ return false;
282
+ return true;
283
+ });
284
+ if (match) {
285
+ return true;
286
+ }
287
+ }
288
+ // Class
289
+ if (filter.classCode && filter.classCode !== device.deviceClass)
290
+ return false;
291
+ // Subclass
292
+ if (filter.subclassCode && filter.subclassCode !== device.deviceSubclass)
293
+ return false;
294
+ // Protocol
295
+ if (filter.protocolCode && filter.protocolCode !== device.deviceProtocol)
296
+ return false;
297
+ // Serial
298
+ if (filter.serialNumber && filter.serialNumber !== device.serialNumber)
299
+ return false;
300
+ return true;
301
+ });
302
+ }
303
+ // Check whether a device is authorised
304
+ isAuthorisedDevice(device) {
305
+ // All devices are authorised
306
+ if (this.options.allowAllDevices) {
307
+ return true;
308
+ }
309
+ // Check any allowed device filters
310
+ if (this.options.allowedDevices && this.filterDevice(device, this.options.allowedDevices)) {
311
+ return true;
312
+ }
313
+ // Check authorised devices
314
+ return [...this.authorisedDevices.values()].some(authorised => authorised.vendorId === device.vendorId
315
+ && authorised.productId === device.productId
316
+ && authorised.classCode === device.deviceClass
317
+ && authorised.subclassCode === device.deviceSubclass
318
+ && authorised.protocolCode === device.deviceProtocol
319
+ && authorised.serialNumber === device.serialNumber);
320
+ }
321
+ }
322
+ exports.WebUSB = WebUSB;
323
+ /**
324
+ * Convenience method to get an array of all connected devices.
325
+ */
326
+ const getDeviceList = async () => {
327
+ const devices = await (0, index_js_1.nativeGetDeviceList)();
328
+ return devices.map(device => augmentDevice(device));
329
+ };
330
+ exports.getDeviceList = getDeviceList;
22
331
  /**
23
332
  * Convenience method to get the first device with the specified VID and PID, or `undefined` if no such device is present.
24
333
  * @param vid
25
334
  * @param pid
26
335
  */
27
- const findByIds = (vid, pid) => {
28
- const devices = usb.getDeviceList();
29
- return devices.find(item => item.deviceDescriptor.idVendor === vid && item.deviceDescriptor.idProduct === pid);
336
+ const findByIds = async (vid, pid) => {
337
+ const device = await (0, index_js_1.nativeFindByIds)(vid, pid);
338
+ return device ? augmentDevice(device) : undefined;
30
339
  };
31
340
  exports.findByIds = findByIds;
32
341
  /**
@@ -34,50 +343,10 @@ exports.findByIds = findByIds;
34
343
  * @param serialNumber
35
344
  */
36
345
  const findBySerialNumber = async (serialNumber) => {
37
- const devices = usb.getDeviceList();
38
- const opened = (device) => !!device.interfaces;
39
- for (const device of devices) {
40
- try {
41
- if (!opened(device)) {
42
- device.open();
43
- }
44
- const getStringDescriptor = (0, util_1.promisify)(device.getStringDescriptor).bind(device);
45
- const buffer = await getStringDescriptor(device.deviceDescriptor.iSerialNumber);
46
- if (buffer && buffer.toString() === serialNumber) {
47
- return device;
48
- }
49
- }
50
- catch {
51
- // Ignore any errors, device may be a system device or inaccessible
52
- }
53
- finally {
54
- try {
55
- if (opened(device)) {
56
- device.close();
57
- }
58
- }
59
- catch {
60
- // Ignore any errors, device may be a system device or inaccessible
61
- }
62
- }
63
- }
64
- return undefined;
346
+ const device = await (0, index_js_1.nativeFindBySerialNumber)(serialNumber);
347
+ return device ? augmentDevice(device) : undefined;
65
348
  };
66
349
  exports.findBySerialNumber = findBySerialNumber;
67
- const webusb = new webusb_1.WebUSB();
350
+ const webusb = typeof navigator !== 'undefined' && navigator.usb ? navigator.usb : new WebUSB();
68
351
  exports.webusb = webusb;
69
- // Usb types
70
- var usb_1 = require("./usb");
71
- Object.defineProperty(exports, "Device", { enumerable: true, get: function () { return usb_1.Device; } });
72
- Object.defineProperty(exports, "Transfer", { enumerable: true, get: function () { return usb_1.Transfer; } });
73
- Object.defineProperty(exports, "getDeviceList", { enumerable: true, get: function () { return usb_1.getDeviceList; } });
74
- Object.defineProperty(exports, "useUsbDkBackend", { enumerable: true, get: function () { return usb_1.useUsbDkBackend; } });
75
- Object.defineProperty(exports, "LibUSBException", { enumerable: true, get: function () { return usb_1.LibUSBException; } });
76
- __exportStar(require("./usb/capability"), exports);
77
- __exportStar(require("./usb/descriptors"), exports);
78
- __exportStar(require("./usb/endpoint"), exports);
79
- __exportStar(require("./usb/interface"), exports);
80
- // WebUSB types
81
- __exportStar(require("./webusb"), exports);
82
- __exportStar(require("./webusb/webusb-device"), exports);
83
352
  //# sourceMappingURL=index.js.map
package/index.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ /* auto-generated by NAPI-RS */
2
+ /* eslint-disable */
3
+ export declare class Emitter {
4
+ constructor()
5
+ start(): Promise<void>
6
+ addAttach(callback: ((arg: UsbDevice) => void)): void
7
+ removeAttach(callback: ((arg: UsbDevice) => void)): void
8
+ addDetach(callback: ((arg: string) => void)): void
9
+ removeDetach(callback: ((arg: string) => void)): void
10
+ }
11
+
12
+ export declare class UsbDevice {
13
+ vendorId: number
14
+ productId: number
15
+ deviceVersionMajor: number
16
+ deviceVersionMinor: number
17
+ deviceVersionSubminor: number
18
+ usbVersionMajor: number
19
+ usbVersionMinor: number
20
+ usbVersionSubminor: number
21
+ deviceClass: number
22
+ deviceSubclass: number
23
+ deviceProtocol: number
24
+ get handle(): string
25
+ get manufacturerName(): string | null
26
+ get productName(): string | null
27
+ get serialNumber(): string | null
28
+ get opened(): boolean
29
+ get configuration(): USBConfiguration | null
30
+ get configurations(): Array<USBConfiguration>
31
+ open(): Promise<void>
32
+ close(): Promise<void>
33
+ forget(): Promise<void>
34
+ reset(): Promise<void>
35
+ selectConfiguration(configurationValue: number): Promise<void>
36
+ claimInterface(interfaceNumber: number): Promise<void>
37
+ releaseInterface(interfaceNumber: number): Promise<void>
38
+ selectAlternateInterface(interfaceNumber: number, alternateSetting: number): Promise<void>
39
+ nativeControlTransferIn(setup: USBControlTransferParameters, length: number): Promise<Uint8Array | null>
40
+ nativeControlTransferOut(setup: USBControlTransferParameters, data?: Uint8Array | undefined | null): Promise<number>
41
+ nativeTransferIn(endpointNumber: number, length: number): Promise<Uint8Array | null>
42
+ nativeTransferOut(endpointNumber: number, data: Uint8Array): Promise<number>
43
+ isochronousTransferIn(endpointNumber: number, packetLengths: Array<number>): Promise<USBIsochronousInTransferResult>
44
+ isochronousTransferOut(endpointNumber: number, data: Uint8Array, packetLengths: Array<number>): Promise<USBIsochronousOutTransferResult>
45
+ clearHalt(direction: USBDirection, endpointNumber: number): Promise<void>
46
+ }
47
+
48
+ export declare function nativeFindByIds(vendorId: number, productId: number): Promise<UsbDevice>
49
+
50
+ export declare function nativeFindBySerialNumber(serialNumber: string): Promise<UsbDevice>
51
+
52
+ export declare function nativeGetDeviceList(): Promise<Array<UsbDevice>>
53
+
54
+ export interface USBAlternateInterface {
55
+ alternateSetting: number
56
+ interfaceClass: number
57
+ interfaceSubclass: number
58
+ interfaceProtocol: number
59
+ interfaceName?: string
60
+ endpoints: Array<USBEndpoint>
61
+ }
62
+
63
+ export interface USBConfiguration {
64
+ configurationValue: number
65
+ configurationName?: string
66
+ interfaces: Array<USBInterface>
67
+ }
68
+
69
+ export interface USBControlTransferParameters {
70
+ requestType: USBRequestType
71
+ recipient: USBRecipient
72
+ request: number
73
+ value: number
74
+ index: number
75
+ }
76
+
77
+ export interface USBEndpoint {
78
+ endpointNumber: number
79
+ direction: USBDirection
80
+ type: USBEndpointType
81
+ packetSize: number
82
+ }
83
+
84
+ export interface USBInterface {
85
+ interfaceNumber: number
86
+ claimed: boolean
87
+ alternate: USBAlternateInterface
88
+ alternates: Array<USBAlternateInterface>
89
+ }