silverbullet/common/hooks/plug_namespace.ts

84 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-07-30 23:33:33 +08:00
import type { NamespaceOperation } from "$lib/plugos/namespace.ts";
import type { PlugNamespaceHookT } from "$lib/manifest.ts";
import type { Plug } from "../../lib/plugos/plug.ts";
import type { System } from "../../lib/plugos/system.ts";
import type { Hook, Manifest } from "../../lib/plugos/types.ts";
2022-05-17 17:53:17 +08:00
type SpaceFunction = {
2022-09-12 20:50:37 +08:00
operation: NamespaceOperation;
2022-05-17 17:53:17 +08:00
pattern: RegExp;
2023-07-14 22:48:35 +08:00
plug: Plug<PlugNamespaceHookT>;
2022-05-17 17:53:17 +08:00
name: string;
2022-11-24 19:04:00 +08:00
env?: string;
2022-05-17 17:53:17 +08:00
};
2023-07-14 22:48:35 +08:00
export class PlugNamespaceHook implements Hook<PlugNamespaceHookT> {
2022-05-17 17:53:17 +08:00
spaceFunctions: SpaceFunction[] = [];
constructor() {}
2023-07-14 22:48:35 +08:00
apply(system: System<PlugNamespaceHookT>): void {
2022-05-17 17:53:17 +08:00
system.on({
plugLoaded: () => {
this.updateCache(system);
},
plugUnloaded: () => {
this.updateCache(system);
},
});
}
2023-07-14 22:48:35 +08:00
updateCache(system: System<PlugNamespaceHookT>) {
2022-05-17 17:53:17 +08:00
this.spaceFunctions = [];
2022-11-24 19:04:00 +08:00
for (const plug of system.loadedPlugs.values()) {
2022-05-17 17:53:17 +08:00
if (plug.manifest?.functions) {
for (
2022-11-24 19:04:00 +08:00
const [funcName, funcDef] of Object.entries(
plug.manifest.functions,
)
) {
2022-05-17 17:53:17 +08:00
if (funcDef.pageNamespace) {
this.spaceFunctions.push({
operation: funcDef.pageNamespace.operation,
pattern: new RegExp(funcDef.pageNamespace.pattern),
plug,
name: funcName,
2022-11-24 19:04:00 +08:00
env: funcDef.env,
2022-05-17 17:53:17 +08:00
});
}
}
}
}
}
2023-07-14 22:48:35 +08:00
validateManifest(manifest: Manifest<PlugNamespaceHookT>): string[] {
2022-11-24 19:04:00 +08:00
const errors: string[] = [];
2022-05-17 17:53:17 +08:00
if (!manifest.functions) {
return [];
}
for (const [funcName, funcDef] of Object.entries(manifest.functions)) {
2022-05-17 17:53:17 +08:00
if (funcDef.pageNamespace) {
if (!funcDef.pageNamespace.pattern) {
errors.push(`Function ${funcName} has a namespace but no pattern`);
}
if (!funcDef.pageNamespace.operation) {
errors.push(`Function ${funcName} has a namespace but no operation`);
}
if (
2022-07-06 18:18:33 +08:00
![
2022-09-12 20:50:37 +08:00
"readFile",
"writeFile",
"getFileMeta",
"listFiles",
"deleteFile",
2022-07-06 18:18:33 +08:00
].includes(funcDef.pageNamespace.operation)
2022-05-17 17:53:17 +08:00
) {
errors.push(
`Function ${funcName} has an invalid operation ${funcDef.pageNamespace.operation}`,
2022-05-17 17:53:17 +08:00
);
}
}
}
return errors;
}
}