1
0
silverbullet/plugos/hooks/event.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-04-04 09:51:41 +00:00
import {Hook, Manifest} from "../types";
import {System} from "../system";
import {safeRun} from "../util";
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>;
2022-03-25 11:03:06 +00:00
2022-03-29 10:13:46 +00:00
async dispatchEvent(eventName: string, data?: any): Promise<void> {
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
}
for (const plug of this.system.loadedPlugs.values()) {
2022-03-27 09:26:13 +00:00
for (const [name, functionDef] of Object.entries(
plug.manifest!.functions
)) {
if (functionDef.events && functionDef.events.includes(eventName)) {
2022-03-28 06:51:24 +00:00
// Only dispatch functions that can run in this environment
if (plug.canInvoke(name)) {
2022-04-04 09:51:41 +00:00
await plug.invoke(name, [data]);
2022-03-28 06:51:24 +00:00
}
2022-03-27 09:26:13 +00:00
}
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: (name) => {
2022-03-29 10:13:46 +00:00
safeRun(async () => {
await this.dispatchEvent("plug:load", name);
});
2022-03-28 06:51:24 +00:00
},
});
2022-03-25 11:03:06 +00:00
}
validateManifest(manifest: Manifest<EventHookT>): string[] {
2022-03-27 09:26:13 +00:00
let errors = [];
for (const [name, functionDef] of Object.entries(manifest.functions)) {
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
}
}