import { ServerContentBase } from "../ContentBase.ts"; import { CommandSender, CommandSenderType } from "./cmdtypes.ts"; import type Command from "./command.ts"; export class CommandsBase extends ServerContentBase { #cmds: Set = 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 { 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(' ')}")`); } } }