2024-02-09 04:00:45 +08:00
|
|
|
import { syscall } from "../syscall.ts";
|
2022-04-01 23:07:08 +08:00
|
|
|
|
2024-08-09 15:27:58 +08:00
|
|
|
/**
|
|
|
|
* Exposes the SilverBullet event bus.
|
|
|
|
* @module
|
|
|
|
*/
|
|
|
|
|
2024-08-07 19:27:25 +08:00
|
|
|
/**
|
|
|
|
* Triggers an event on the SilverBullet event bus.
|
|
|
|
* This can be used to implement an RPC-style system too, because event handlers can return values,
|
|
|
|
* which are then accumulated in an array and returned to the caller.
|
|
|
|
* @param eventName the name of the event to trigger
|
|
|
|
* @param data payload to send with the event
|
|
|
|
* @param timeout optional timeout in milliseconds to wait for a response
|
|
|
|
* @returns an array of responses from the event handlers (if any)
|
|
|
|
*/
|
2022-10-14 21:11:33 +08:00
|
|
|
export function dispatchEvent(
|
2022-04-19 22:54:47 +08:00
|
|
|
eventName: string,
|
|
|
|
data: any,
|
2022-10-10 20:50:21 +08:00
|
|
|
timeout?: number,
|
2022-04-19 22:54:47 +08:00
|
|
|
): Promise<any[]> {
|
|
|
|
return new Promise((resolve, reject) => {
|
2022-04-20 16:56:43 +08:00
|
|
|
let timeouter: any = -1;
|
|
|
|
if (timeout) {
|
|
|
|
timeouter = setTimeout(() => {
|
|
|
|
console.log("Timeout!");
|
|
|
|
reject("timeout");
|
|
|
|
}, timeout);
|
|
|
|
}
|
2022-04-19 22:54:47 +08:00
|
|
|
syscall("event.dispatch", eventName, data)
|
2024-07-30 23:24:17 +08:00
|
|
|
.then((r: any) => {
|
2022-04-20 16:56:43 +08:00
|
|
|
if (timeouter !== -1) {
|
|
|
|
clearTimeout(timeouter);
|
|
|
|
}
|
2022-04-19 22:54:47 +08:00
|
|
|
resolve(r);
|
|
|
|
})
|
|
|
|
.catch(reject);
|
|
|
|
});
|
2022-04-01 23:07:08 +08:00
|
|
|
}
|
2022-07-04 21:07:27 +08:00
|
|
|
|
2024-08-07 19:27:25 +08:00
|
|
|
/**
|
|
|
|
* List all events currently registered (listened to) on the SilverBullet event bus.
|
|
|
|
* @returns an array of event names
|
|
|
|
*/
|
2022-10-10 20:50:21 +08:00
|
|
|
export function listEvents(): Promise<string[]> {
|
2022-07-04 21:07:27 +08:00
|
|
|
return syscall("event.list");
|
|
|
|
}
|