// commands the way minecraft's brigadier (and so fabric's command api) does them: a tree of literal words and typed // arguments, each argument type parsing its text and suggesting what could go there. the server runs them, and players // get its suggestions as they type. see docs/modding/misc/commands.md import { EverythingRegistry } from "./everything_registry.ts"; export interface Suggestion { text: string; // shown next to it, like an item's name tooltip?: string; } // what went wrong, told to the player who typed it export class CommandError extends Error { constructor(message: string) { super(message); this.name = "CommandError"; } } // how an argument reads its text, and what could go there export interface ArgumentType { // takes the rest of the line, spaces and all, like a chat message readonly greedy?: boolean; // throws CommandError when the text doesn't fit parse(text: string, source: S): T; suggest?(partial: string, source: S): Suggestion[]; } export interface CommandContext { source: S; // the value of an argument by its name, as its type parsed it get(name: string): T; // what was typed, without the / input: string; } export type CommandFunction = (context: CommandContext) => void; // a word or an argument, and what can follow it. like brigadier's builders, the methods chain: // literal("give").then(argument("item", item()).executes(...)) export class CommandNode { readonly children: CommandNode[] = []; command?: CommandFunction; requirement?: (source: S) => boolean; suggestion_provider?: (partial: string, source: S) => Suggestion[]; // for /help description?: string; constructor(readonly name: string, readonly type?: ArgumentType) {} then(child: CommandNode): this { this.children.push(child); // words before arguments, so a literal wins over an argument that would take the same word this.children.sort((a, b) => Number(a.type !== undefined) - Number(b.type !== undefined)); return this; } executes(command: CommandFunction): this { this.command = command; return this; } // only for sources this is true for, like operators. others can't run it or see it suggested requires(requirement: (source: S) => boolean): this { this.requirement = requirement; return this; } // suggestions for this argument instead of its type's suggests(provider: (partial: string, source: S) => Suggestion[]): this { this.suggestion_provider = provider; return this; } describe(description: string): this { this.description = description; return this; } get is_literal() { return this.type === undefined; } } export function literal(name: string): CommandNode { return new CommandNode(name); } export function argument(name: string, type: ArgumentType): CommandNode { return new CommandNode(name, type as ArgumentType); } interface Token { text: string; start: number; } interface Failure { // how far it got, the error from the furthest attempt is the one worth showing at: number; message: string; } export class CommandDispatcher { readonly root = new CommandNode(""); // adds a command at the top. a second one with the same name is an error, use then() to add to an existing one register(node: CommandNode): CommandNode { if (!node.is_literal) throw new Error("commands start with a word, use literal()"); if (this.get(node.name)) throw new Error(`/${node.name} already exists`); this.root.then(node); return node; } get(name: string): CommandNode | undefined { return this.root.children.find((child) => child.name === name); } // runs what was typed, without the /. throws CommandError saying what's wrong execute(input: string, source: S) { const tokens = tokenize(input); const failures: Failure[] = []; const found = this.#parse(this.root, tokens, 0, new Map(), source, input, failures); if (!found) { const failure = failures.sort((a, b) => b.at - a.at)[0]; throw new CommandError(failure?.message ?? `Unknown command /${tokens[0]?.text ?? ""}`); } const args = found.args; found.command({ source, input, get(name: string) { if (!args.has(name)) throw new Error(`there's no argument "${name}"`); return args.get(name) as T; }, }); } // what could come at the end of input, for the word being typed: start is where it begins in input suggest(input: string, source: S): { start: number; suggestions: Suggestion[] } { const tokens = tokenize(input); const partial = tokens.pop() ?? { text: "", start: input.length }; const nodes = this.#walk(this.root, tokens, 0, source); const seen = new Set(); const suggestions: Suggestion[] = []; for (const node of nodes) { for (const child of node.children) { if (child.requirement && !safe(() => child.requirement!(source), false)) continue; let found: Suggestion[]; if (child.is_literal) { found = child.name.startsWith(partial.text) ? [{ text: child.name }] : []; } else { const provider = child.suggestion_provider ?? child.type!.suggest?.bind(child.type); found = provider ? safe(() => provider(partial.text, source), []) : []; } for (const suggestion of found) { if (seen.has(suggestion.text)) continue; seen.add(suggestion.text); suggestions.push(suggestion); } } } suggestions.sort((a, b) => a.text.localeCompare(b.text)); return { start: partial.start, suggestions }; } // how to use a command, like brigadier's smart usage: "give []" usage(node: CommandNode, source: S): string { const own = node.is_literal ? node.name : `<${node.name}>`; const children = node.children.filter((child) => !child.requirement || safe(() => child.requirement!(source), false) ); if (children.length === 0) return own; const inner = children.length === 1 ? this.usage(children[0], source) : children.map((child) => child.is_literal ? child.name : `<${child.name}>`).join("|"); if (node.command) return `${own} [${inner}]`; return children.length === 1 ? `${own} ${inner}` : `${own} (${inner})`; } #parse( node: CommandNode, tokens: Token[], index: number, args: Map, source: S, input: string, failures: Failure[], ): { command: CommandFunction; args: Map } | undefined { if (index === tokens.length) { if (node.command) return { command: node.command, args }; failures.push({ at: index, message: `Not enough: /${this.usage(this.#top(node, tokens), source)}` }); return undefined; } const token = tokens[index]; for (const child of node.children) { if (child.requirement && !safe(() => child.requirement!(source), false)) continue; if (child.is_literal) { if (child.name !== token.text) continue; const found = this.#parse(child, tokens, index + 1, args, source, input, failures); if (found) return found; continue; } const type = child.type!; const text = type.greedy ? input.slice(token.start) : token.text; let value: unknown; try { value = type.parse(text, source); } catch (e) { failures.push({ at: index, message: e instanceof CommandError ? e.message : `Can't read "${text}"` }); continue; } const next = new Map(args).set(child.name, value); const found = this.#parse( child, tokens, type.greedy ? tokens.length : index + 1, next, source, input, failures, ); if (found) return found; } if (index === 0) { failures.push({ at: 0, message: `Unknown command /${token.text}` }); } else { failures.push({ at: index, message: `Didn't expect "${token.text}": /${this.usage(this.#top(node, tokens), source)}`, }); } return undefined; } // the nodes reachable after the whole tokens, where the next word could go #walk(node: CommandNode, tokens: Token[], index: number, source: S): CommandNode[] { if (index === tokens.length) return [node]; const reached: CommandNode[] = []; for (const child of node.children) { if (child.requirement && !safe(() => child.requirement!(source), false)) continue; if (child.is_literal) { if (child.name === tokens[index].text) reached.push(...this.#walk(child, tokens, index + 1, source)); } else if ( !child.type!.greedy && safe(() => (child.type!.parse(tokens[index].text, source), true), false) ) { reached.push(...this.#walk(child, tokens, index + 1, source)); } } return reached; } // the command a parse was in, for its usage #top(node: CommandNode, tokens: Token[]): CommandNode { return node === this.root ? node : this.get(tokens[0]?.text ?? "") ?? node; } } // words split on single spaces, remembering where each starts. "a b" has an empty word between, which nothing matches function tokenize(input: string): Token[] { const tokens: Token[] = []; let start = 0; for (const text of input.split(" ")) { tokens.push({ text, start }); start += text.length + 1; } return tokens; } function safe(fn: () => T, fallback: T): T { try { return fn(); } catch { return fallback; } } // argument types, like brigadier's and minecraft's export function integer(min = -Infinity, max = Infinity): ArgumentType { return { parse(text) { const value = Number(text); if (!/^-?\d+$/.test(text) || !Number.isSafeInteger(value)) { throw new CommandError(`"${text}" isn't a whole number`); } if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`); if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`); return value; }, }; } export function number(min = -Infinity, max = Infinity): ArgumentType { return { parse(text) { const value = Number(text); if (text === "" || !Number.isFinite(value)) throw new CommandError(`"${text}" isn't a number`); if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`); if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`); return value; }, }; } export function boolean(): ArgumentType { return { parse(text) { if (text === "true") return true; if (text === "false") return false; throw new CommandError(`"${text}" isn't true or false`); }, suggest: (partial) => ["true", "false"].filter((b) => b.startsWith(partial)).map((text) => ({ text })), }; } // one word, anything without spaces export function word(): ArgumentType { return { parse(text) { if (text === "") throw new CommandError("Expected a word"); return text; }, }; } // the rest of the line export function greedy_string(): ArgumentType { return { greedy: true, parse: (text) => text }; } // one of a few words, suggested export function choice(options: readonly T[]): ArgumentType { return { parse(text) { if (!options.includes(text as T)) throw new CommandError(`"${text}" isn't one of ${options.join(", ")}`); return text as T; }, suggest: (partial) => options.filter((o) => o.startsWith(partial)).map((text) => ({ text })), }; } // an id from a registry. without a namespace it's whichever id has that name, as long as only one does function registry_id(registry: string, what: string): ArgumentType { return { parse(text) { if (text.includes(":")) { if (!EverythingRegistry.get(registry, text)) throw new CommandError(`There's no ${what} ${text}`); return text; } const matches = EverythingRegistry.entries(registry).map(([id]) => id).filter((id) => id.endsWith(`:${text}`) ); if (matches.length === 0) throw new CommandError(`There's no ${what} called ${text}`); if (matches.length > 1) throw new CommandError(`Which one? ${matches.join(", ")}`); return matches[0]; }, // full ids starting with it, or whose name part does, like minecraft suggest(partial) { return EverythingRegistry.entries(registry) .map(([id]) => id) .filter((id) => id !== "bworld:air" && (id.startsWith(partial) || id.split(":")[1].startsWith(partial))) .map((id) => ({ text: id })); }, }; } export function item(): ArgumentType { return registry_id("items", "item"); } export function block(): ArgumentType { return registry_id("blocks", "block"); }