Improve commands
This commit is contained in:
@@ -0,0 +1,375 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
// what server scripts get, see "Server scripts" in MODS.md
|
||||
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
|
||||
import type { ArgumentType, CommandNode } from "../commands.ts";
|
||||
|
||||
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
|
||||
|
||||
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
|
||||
|
||||
@@ -58,8 +61,16 @@ export interface ComponentRegistry {
|
||||
register_item<P>(id: Id, component: ItemComponent<P>): void;
|
||||
}
|
||||
|
||||
// commands
|
||||
// commands, fabric's (brigadier's) way: see common/commands.ts and "Commands" in MODS.md
|
||||
|
||||
// who ran a command
|
||||
export interface CommandSource {
|
||||
readonly player: Player;
|
||||
// answers them in chat
|
||||
send_message(text: string): void;
|
||||
}
|
||||
|
||||
// the simple way: the words after the name, split on spaces
|
||||
export interface Command {
|
||||
description: string;
|
||||
usage: string;
|
||||
@@ -67,7 +78,25 @@ export interface Command {
|
||||
}
|
||||
|
||||
export interface CommandRegistry {
|
||||
// a tree of literal() and argument() nodes, like fabric's dispatcher.register(literal("heal").then(...))
|
||||
register(node: CommandNode<CommandSource>): void;
|
||||
register(name: string, command: Command): void;
|
||||
literal(name: string): CommandNode<CommandSource>;
|
||||
argument<T>(name: string, type: ArgumentType<T, CommandSource>): CommandNode<CommandSource>;
|
||||
// argument types. they parse their text and suggest what could go there as players type
|
||||
types: {
|
||||
integer(min?: number, max?: number): ArgumentType<number, CommandSource>;
|
||||
number(min?: number, max?: number): ArgumentType<number, CommandSource>;
|
||||
boolean(): ArgumentType<boolean, CommandSource>;
|
||||
word(): ArgumentType<string, CommandSource>;
|
||||
greedy_string(): ArgumentType<string, CommandSource>;
|
||||
choice<T extends string>(options: readonly T[]): ArgumentType<T, CommandSource>;
|
||||
// an item or block id. without a namespace, whichever has that name
|
||||
item(): ArgumentType<Id, CommandSource>;
|
||||
block(): ArgumentType<Id, CommandSource>;
|
||||
// an online player's name
|
||||
player(): ArgumentType<Player, CommandSource>;
|
||||
};
|
||||
}
|
||||
|
||||
// events
|
||||
|
||||
+6
-2
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
|
||||
|
||||
// bump when a client and server of different versions can't play together.
|
||||
// the server rejects a different version before the client downloads anything
|
||||
export const PROTOCOL_VERSION = 5;
|
||||
export const PROTOCOL_VERSION = 6;
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
@@ -75,7 +75,9 @@ export type ClientMessage =
|
||||
| { type: "drop_item"; container: ContainerKey; index: number; all: boolean }
|
||||
// closes the open screen, including the player's own inventory screen
|
||||
| { type: "close_screen" }
|
||||
| { type: "chat"; text: string };
|
||||
| { type: "chat"; text: string }
|
||||
// what could come next in a command being typed, answered with suggestions. id matches them up
|
||||
| { type: "suggest"; id: number; text: string };
|
||||
|
||||
export type ServerMessage =
|
||||
// what to download before joining, see "Delivery to clients" in MODS.md
|
||||
@@ -124,6 +126,8 @@ export type ServerMessage =
|
||||
| { type: "close_screen" }
|
||||
// the world time, every second and when it's changed. clients count ticks in between
|
||||
| { type: "time"; time: number }
|
||||
// answers suggest: start is where in the text the suggestions replace from, up to the caret
|
||||
| { type: "suggestions"; id: number; start: number; suggestions: { text: string; tooltip?: string }[] }
|
||||
// the player's own health, hunger and saturation, when they change
|
||||
| { type: "vitals"; health: number; food: number; saturation: number };
|
||||
|
||||
|
||||
Reference in New Issue
Block a user