2020-07-13 16:58:49 +00:00
|
|
|
import { IpcMainInvokeEvent } from 'electron/main';
|
2019-08-23 22:45:50 +00:00
|
|
|
|
2024-10-03 03:52:01 +00:00
|
|
|
import { EventEmitter } from 'events';
|
|
|
|
|
2023-10-25 18:02:15 +00:00
|
|
|
export class IpcMainImpl extends EventEmitter implements Electron.IpcMain {
|
2019-08-23 22:45:50 +00:00
|
|
|
private _invokeHandlers: Map<string, (e: IpcMainInvokeEvent, ...args: any[]) => void> = new Map();
|
|
|
|
|
2022-08-03 23:55:12 +00:00
|
|
|
constructor () {
|
|
|
|
super();
|
|
|
|
|
|
|
|
// Do not throw exception when channel name is "error".
|
|
|
|
this.on('error', () => {});
|
|
|
|
}
|
|
|
|
|
2019-08-23 22:45:50 +00:00
|
|
|
handle: Electron.IpcMain['handle'] = (method, fn) => {
|
|
|
|
if (this._invokeHandlers.has(method)) {
|
|
|
|
throw new Error(`Attempted to register a second handler for '${method}'`);
|
|
|
|
}
|
|
|
|
if (typeof fn !== 'function') {
|
2023-07-25 16:08:46 +00:00
|
|
|
throw new TypeError(`Expected handler to be a function, but found type '${typeof fn}'`);
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
2023-02-13 21:39:18 +00:00
|
|
|
this._invokeHandlers.set(method, fn);
|
2023-05-30 11:10:22 +00:00
|
|
|
};
|
2019-08-23 22:45:50 +00:00
|
|
|
|
|
|
|
handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
|
|
|
|
this.handle(method, (e, ...args) => {
|
|
|
|
this.removeHandler(method);
|
|
|
|
return fn(e, ...args);
|
|
|
|
});
|
2023-05-30 11:10:22 +00:00
|
|
|
};
|
2019-08-23 22:45:50 +00:00
|
|
|
|
|
|
|
removeHandler (method: string) {
|
|
|
|
this._invokeHandlers.delete(method);
|
|
|
|
}
|
|
|
|
}
|