Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 7 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fn watch_task_guard(
#[napi]
pub struct Emitter {
callbacks: Arc<Mutex<Callbacks>>,
watch_task: Arc<Mutex<Option<JoinHandle<()>>>>,
watch_task: Mutex<Option<JoinHandle<()>>>,
}

#[napi]
Expand All @@ -52,7 +52,7 @@ impl Emitter {
}));
Self {
callbacks,
watch_task: Arc::new(Mutex::new(None)),
watch_task: Mutex::new(None),
}
}

Expand Down
19 changes: 15 additions & 4 deletions tsc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,18 @@ class WebUSB extends EventTarget implements USB {
protected listenerCount = 0;
protected eventListeners = new Map<string, Set<EventListener>>();
protected knownDevices: Map<string, UsbDevice> = new Map();
protected nativeEmitterQueue: Promise<void> = Promise.resolve();

constructor(private options: USBOptions = {}) {
super();
}

private queueNativeEmitterOperation(operation: () => Promise<void>): void {
const pending = this.nativeEmitterQueue.then(operation);
this.nativeEmitterQueue = pending.catch(() => {});
pending.catch(error => setTimeout(() => { throw error; }, 0));
}

private deviceConnectCallback = async (device: UsbDevice) => {
this.knownDevices.set(device.handle, device);

Expand Down Expand Up @@ -183,8 +190,10 @@ class WebUSB extends EventTarget implements USB {
}

if (!hadListeners && this.listenerCount > 0) {
this.nativeEmitter.addAttach(this.deviceConnectCallback);
this.nativeEmitter.addDetach(this.deviceDisconnectCallback);
this.queueNativeEmitterOperation(async () => {
await this.nativeEmitter.addAttach(this.deviceConnectCallback);
await this.nativeEmitter.addDetach(this.deviceDisconnectCallback);
});
nativeGetDevices().then(devices => devices.forEach(device => this.knownDevices.set(device.handle, device)));
}
}
Expand All @@ -209,8 +218,10 @@ class WebUSB extends EventTarget implements USB {
}

if (removed && this.listenerCount === 0) {
this.nativeEmitter.removeAttach();
this.nativeEmitter.removeDetach();
this.queueNativeEmitterOperation(async () => {
await this.nativeEmitter.removeAttach();
await this.nativeEmitter.removeDetach();
});
this.knownDevices.clear();
}
}
Expand Down
Loading