376 lines
12 KiB
TypeScript
376 lines
12 KiB
TypeScript
// 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 "Commands" in MODS.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<T = unknown, S = unknown> {
|
|
// 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<S> {
|
|
source: S;
|
|
// the value of an argument by its name, as its type parsed it
|
|
get<T>(name: string): T;
|
|
// what was typed, without the /
|
|
input: string;
|
|
}
|
|
|
|
export type CommandFunction<S> = (context: CommandContext<S>) => 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<S = unknown> {
|
|
readonly children: CommandNode<S>[] = [];
|
|
command?: CommandFunction<S>;
|
|
requirement?: (source: S) => boolean;
|
|
suggestion_provider?: (partial: string, source: S) => Suggestion[];
|
|
// for /help
|
|
description?: string;
|
|
|
|
constructor(readonly name: string, readonly type?: ArgumentType<unknown, S>) {}
|
|
|
|
then(child: CommandNode<S>): 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<S>): 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<S = unknown>(name: string): CommandNode<S> {
|
|
return new CommandNode<S>(name);
|
|
}
|
|
|
|
export function argument<T, S = unknown>(name: string, type: ArgumentType<T, S>): CommandNode<S> {
|
|
return new CommandNode<S>(name, type as ArgumentType<unknown, S>);
|
|
}
|
|
|
|
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<S> {
|
|
readonly root = new CommandNode<S>("");
|
|
|
|
// 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<S>): CommandNode<S> {
|
|
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<S> | 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<T>(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<string>();
|
|
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 <item> [<count>]"
|
|
usage(node: CommandNode<S>, 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<S>,
|
|
tokens: Token[],
|
|
index: number,
|
|
args: Map<string, unknown>,
|
|
source: S,
|
|
input: string,
|
|
failures: Failure[],
|
|
): { command: CommandFunction<S>; args: Map<string, unknown> } | 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<S>, tokens: Token[], index: number, source: S): CommandNode<S>[] {
|
|
if (index === tokens.length) return [node];
|
|
const reached: CommandNode<S>[] = [];
|
|
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<S>, tokens: Token[]): CommandNode<S> {
|
|
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<T>(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<number> {
|
|
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<number> {
|
|
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<boolean> {
|
|
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<string> {
|
|
return {
|
|
parse(text) {
|
|
if (text === "") throw new CommandError("Expected a word");
|
|
return text;
|
|
},
|
|
};
|
|
}
|
|
|
|
// the rest of the line
|
|
export function greedy_string(): ArgumentType<string> {
|
|
return { greedy: true, parse: (text) => text };
|
|
}
|
|
|
|
// one of a few words, suggested
|
|
export function choice<T extends string>(options: readonly T[]): ArgumentType<T> {
|
|
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, names: (id: string) => string | undefined): ArgumentType<string> {
|
|
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, tooltip: names(id) }));
|
|
},
|
|
};
|
|
}
|
|
|
|
export function item(names: (id: string) => string | undefined = () => undefined): ArgumentType<string> {
|
|
return registry_id("items", "item", names);
|
|
}
|
|
|
|
export function block(names: (id: string) => string | undefined = () => undefined): ArgumentType<string> {
|
|
return registry_id("blocks", "block", names);
|
|
}
|