1
0
silverbullet/plugos/feature/event.ts

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-03-25 11:03:06 +00:00
import { Feature, Manifest } from "../types";
import { System } from "../system";
export type EventHook = {
2022-03-27 09:26:13 +00:00
events?: string[];
2022-03-25 11:03:06 +00:00
};
export class EventFeature implements Feature<EventHook> {
private system?: System<EventHook>;
2022-03-27 09:26:13 +00:00
async dispatchEvent(eventName: string, data?: any): Promise<any[]> {
2022-03-25 11:03:06 +00:00
if (!this.system) {
throw new Error("EventFeature is not initialized");
}
let promises: Promise<any>[] = [];
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)) {
promises.push(plug.invoke(name, [data]));
}
2022-03-25 11:03:06 +00:00
}
}
return Promise.all(promises);
}
apply(system: System<EventHook>): void {
this.system = system;
}
validateManifest(manifest: Manifest<EventHook>): 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
}
}