boardgame-core/src/utils/command/command-runner.ts

52 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-04-02 15:36:32 +08:00
import type { Command, CommandSchema } from './types';
import { parseCommand } from './command-parse';
import { applyCommandSchema } from './command-validate';
2026-04-02 08:58:11 +08:00
export type PromptEvent = {
schema: CommandSchema;
2026-04-04 10:30:00 +08:00
/** 当前等待输入的玩家 */
currentPlayer: string | null;
/**
*
* @param commandOrInput Command
* @returns null - Promise resolve
* @returns string - Promise resolve
*/
tryCommit: (commandOrInput: Command | string) => string | null;
/** 取消 promptPromise 被 reject */
cancel: (reason?: string) => void;
};
export type CommandRunnerEvents = {
prompt: PromptEvent;
2026-04-04 00:59:40 +08:00
/** 当 prompt 结束tryCommit 成功或 cancel时触发 */
promptEnd: void;
};
export type CommandResult<T=unknown> = {
success: true;
result: T;
} | {
success: false;
error: string;
}
2026-04-02 08:58:11 +08:00
export type CommandRunnerContext<TContext> = {
context: TContext;
run: <T=unknown>(input: string) => Promise<CommandResult<T>>;
2026-04-02 08:58:11 +08:00
runParsed: (command: Command) => Promise<{ success: true; result: unknown } | { success: false; error: string }>;
2026-04-04 10:30:00 +08:00
prompt: (schema: CommandSchema | string, validator?: (command: Command) => string | null, currentPlayer?: string | null) => Promise<Command>;
on: <T extends keyof CommandRunnerEvents>(event: T, listener: (e: CommandRunnerEvents[T]) => void) => void;
off: <T extends keyof CommandRunnerEvents>(event: T, listener: (e: CommandRunnerEvents[T]) => void) => void;
2026-04-02 08:58:11 +08:00
};
export type CommandRunnerHandler<TContext, TResult> = (
this: CommandRunnerContext<TContext>,
command: Command
) => Promise<TResult>;
export type CommandRunner<TContext, TResult = unknown> = {
schema: CommandSchema;
run: CommandRunnerHandler<TContext, TResult>;
};