1
0
silverbullet/plugos/hooks/event.ts

131 lines
3.7 KiB
TypeScript
Raw Normal View History

import type { Hook, Manifest } from "../types.ts";
import { System } from "../system.ts";
2022-03-25 11:03:06 +00:00
2022-03-28 06:51:24 +00:00
// System events:
// - plug:load (plugName: string)
export type EventHookT = {
2022-03-27 09:26:13 +00:00
events?: string[];
2022-03-25 11:03:06 +00:00
};
export class EventHook implements Hook<EventHookT> {
private system?: System<EventHookT>;
public localListeners: Map<string, ((...args: any[]) => any)[]> = new Map();
2022-04-26 17:04:36 +00:00
addLocalListener(eventName: string, callback: (...args: any[]) => any) {
2022-04-26 17:04:36 +00:00
if (!this.localListeners.has(eventName)) {
this.localListeners.set(eventName, []);
}
this.localListeners.get(eventName)!.push(callback);
}
2022-03-25 11:03:06 +00:00
// Pull all events listened to
listEvents(): string[] {
if (!this.system) {
throw new Error("Event hook is not initialized");
}
const eventNames = new Set<string>();
for (const plug of this.system.loadedPlugs.values()) {
for (const functionDef of Object.values(plug.manifest!.functions)) {
if (functionDef.events) {
for (const eventName of functionDef.events) {
eventNames.add(eventName);
}
}
}
}
for (const eventName of this.localListeners.keys()) {
eventNames.add(eventName);
}
return [...eventNames];
}
async dispatchEvent(eventName: string, ...args: any[]): Promise<any[]> {
2022-03-25 11:03:06 +00:00
if (!this.system) {
throw new Error("Event hook is not initialized");
2022-03-25 11:03:06 +00:00
}
const responses: any[] = [];
const promises: Promise<void>[] = [];
2022-03-25 11:03:06 +00:00
for (const plug of this.system.loadedPlugs.values()) {
const manifest = plug.manifest;
for (
const [name, functionDef] of Object.entries(
manifest!.functions,
)
) {
if (functionDef.events) {
for (const event of functionDef.events) {
if (
event === eventName || eventNameToRegex(event).test(eventName)
) {
// Only dispatch functions that can run in this environment
if (await plug.canInvoke(name)) {
// Queue the promise
promises.push((async () => {
try {
const result = await plug.invoke(name, args);
if (result !== undefined) {
responses.push(result);
}
} catch (e: any) {
console.error(
`Error dispatching event ${eventName} to plug ${plug.name}: ${e.message}`,
);
}
})());
}
}
2022-03-28 06:51:24 +00:00
}
2022-03-27 09:26:13 +00:00
}
2022-03-25 11:03:06 +00:00
}
}
const localListeners = this.localListeners.get(eventName);
2022-04-26 17:04:36 +00:00
if (localListeners) {
for (const localListener of localListeners) {
// Queue the promise
promises.push((async () => {
const result = await Promise.resolve(localListener(...args));
if (result) {
responses.push(result);
}
})());
2022-04-26 17:04:36 +00:00
}
}
// Wait for all promises to resolve
await Promise.all(promises);
return responses;
2022-03-25 11:03:06 +00:00
}
apply(system: System<EventHookT>): void {
2022-03-25 11:03:06 +00:00
this.system = system;
2022-03-28 06:51:24 +00:00
this.system.on({
plugLoaded: async (plug) => {
await this.dispatchEvent("plug:load", plug.name);
2022-03-28 06:51:24 +00:00
},
});
2022-03-25 11:03:06 +00:00
}
validateManifest(manifest: Manifest<EventHookT>): string[] {
const errors = [];
for (
const [_, functionDef] of Object.entries(
manifest.functions || {},
)
) {
2022-03-27 09:26:13 +00:00
if (functionDef.events && !Array.isArray(functionDef.events)) {
errors.push("'events' key must be an array of strings");
}
}
return errors;
2022-03-25 11:03:06 +00:00
}
}
function eventNameToRegex(eventName: string): RegExp {
return new RegExp(
`^${eventName.replace(/\*/g, ".*").replace(/\//g, "\\/")}$`,
);
}