Files
galvanic-corrosion-rewrite/src/server/commands/commands.ts
2025-09-11 13:47:30 -04:00

48 lines
1.8 KiB
TypeScript

import { ServerContentBase } from "../ContentBase.ts";
import { CommandSender, CommandSenderType } from "./cmdtypes.ts";
import type Command from "./command.ts";
export class CommandsBase extends ServerContentBase {
#cmds: Set<Command> = new Set();
addRootCommand(cmd: Command) {
this.#cmds.add(cmd);
}
removeRootCommandByKey(key: string) {
for (const cmd of this.#cmds) if (cmd.getKey().includes(key))
this.#cmds.delete(cmd);
}
removeRootCommand(cmd: Command) {
this.#cmds.delete(cmd);
}
async dispatch(sender: CommandSender, ...args: string[]): Promise<unknown> {
if (sender.type == CommandSenderType.Profile)
if (await sender.prof.getRole() !== "developer") return new Error("Unauthorized");
const root = args[0];
if (typeof root !== 'string') return new Error("Root command must be of primitive type 'string'");
else {
if (root === "help") return JSON.stringify(this.#cmds.values()
.map(cmd => cmd.getKey()).toArray()
.reduce((prev, accumulator) => prev.concat(accumulator), []));
const cmd = this.#cmds.values().toArray().find(cmd => cmd.getKey().includes(root));
if (cmd) {
const val = await cmd.dispatch(...args.slice(1));
if (val == null) return "null";
else if (typeof val == 'string') return `"${val}"`;
else if (typeof val == 'undefined') return "undefined";
else if (val instanceof Error) return val;
else if (typeof val == 'object') return JSON.stringify(val);
else return String(val);
}
else return new Error(`'${root.trim()}': Command not found (args: "${args.join(' ')}")`);
}
}
}