silverbullet/common/syscalls/system.ts

74 lines
2.1 KiB
TypeScript
Raw Normal View History

import { SysCallMapping, System } from "../../plugos/system.ts";
import type { Client } from "../../web/client.ts";
import { CommandDef } from "../../web/hooks/command.ts";
import { proxySyscall } from "../../web/syscalls/util.ts";
2022-03-25 19:03:06 +08:00
export function systemSyscalls(
system: System<any>,
readOnlyMode: boolean,
2023-08-30 03:17:29 +08:00
client?: Client,
): SysCallMapping {
2023-08-27 20:13:18 +08:00
const api: SysCallMapping = {
2022-10-14 21:11:33 +08:00
"system.invokeFunction": (
2023-08-27 20:13:18 +08:00
ctx,
fullName: string, // plug.function
2023-08-27 20:13:18 +08:00
...args: any[]
) => {
const [plugName, functionName] = fullName.split(".");
if (!plugName || !functionName) {
throw Error(`Invalid function name ${fullName}`);
2023-08-28 23:12:15 +08:00
}
const plug = system.loadedPlugs.get(plugName);
if (!plug) {
throw Error(`Plug ${plugName} not found`);
}
const functionDef = plug.manifest!.functions[functionName];
2023-08-27 20:13:18 +08:00
if (!functionDef) {
throw Error(`Function ${functionName} not found`);
2023-08-27 20:13:18 +08:00
}
2023-08-30 03:17:29 +08:00
if (
client && functionDef.env && system.env &&
functionDef.env !== system.env
) {
2023-08-27 20:13:18 +08:00
// Proxy to another environment
return proxySyscall(
ctx,
client.httpSpacePrimitives,
"system.invokeFunction",
[fullName, ...args],
);
2023-08-27 20:13:18 +08:00
}
return plug.invoke(functionName, args);
2022-04-27 01:04:36 +08:00
},
"system.invokeCommand": (_ctx, name: string, args?: string[]) => {
2023-08-30 03:17:29 +08:00
if (!client) {
throw new Error("Not supported");
}
return client.runCommandByName(name, args);
2022-07-11 15:08:22 +08:00
},
2022-10-14 21:11:33 +08:00
"system.listCommands": (): { [key: string]: CommandDef } => {
2023-08-30 03:17:29 +08:00
if (!client) {
throw new Error("Not supported");
}
2022-10-14 21:11:33 +08:00
const allCommands: { [key: string]: CommandDef } = {};
2023-08-30 03:17:29 +08:00
for (const [cmd, def] of client.system.commandHook.editorCommands) {
2022-09-06 20:36:06 +08:00
allCommands[cmd] = def.command;
}
return allCommands;
},
2022-10-14 21:11:33 +08:00
"system.reloadPlugs": () => {
2023-08-30 03:17:29 +08:00
if (!client) {
throw new Error("Not supported");
}
return client.loadPlugs();
2022-03-25 19:03:06 +08:00
},
2023-01-15 01:51:00 +08:00
"system.getEnv": () => {
return system.env;
},
"system.getMode": () => {
return readOnlyMode ? "ro" : "rw";
},
2022-03-25 19:03:06 +08:00
};
2023-08-27 20:13:18 +08:00
return api;
2022-03-25 19:03:06 +08:00
}