2022-03-29 09:21:32 +00:00
|
|
|
import { Hook, Manifest } from "../types";
|
2022-03-25 11:03:06 +00:00
|
|
|
import { System } from "../system";
|
2022-03-29 10:13:46 +00:00
|
|
|
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)
|
|
|
|
|
2022-03-29 09:21:32 +00:00
|
|
|
export type EventHookT = {
|
2022-03-27 09:26:13 +00:00
|
|
|
events?: string[];
|
2022-03-25 11:03:06 +00:00
|
|
|
};
|
|
|
|
|
2022-03-29 09:21:32 +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) {
|
2022-03-29 09:21:32 +00:00
|
|
|
throw new Error("Event hook is not initialized");
|
2022-03-25 11:03:06 +00:00
|
|
|
}
|
2022-03-29 10:13:46 +00:00
|
|
|
let promises: Promise<void>[] = [];
|
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)) {
|
|
|
|
promises.push(plug.invoke(name, [data]));
|
|
|
|
}
|
2022-03-27 09:26:13 +00:00
|
|
|
}
|
2022-03-25 11:03:06 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-29 10:13:46 +00:00
|
|
|
await Promise.all(promises);
|
2022-03-25 11:03:06 +00:00
|
|
|
}
|
|
|
|
|
2022-03-29 09:21:32 +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
|
|
|
}
|
|
|
|
|
2022-03-29 09:21:32 +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
|
|
|
}
|
|
|
|
}
|