refactor: fix command parsing
This commit is contained in:
+6
-29
@@ -1,5 +1,4 @@
|
||||
import {Command, CommandSchema, parseCommand, parseCommandSchema} from "../utils/command";
|
||||
import { defineSchema, type ParseError } from 'inline-schema';
|
||||
import {Command, CommandSchema, parseCommand, parseCommandSchema, applyCommandSchema} from "../utils/command";
|
||||
|
||||
export type RuleState = 'running' | 'yielded' | 'waiting' | 'invoking' | 'done';
|
||||
|
||||
@@ -50,31 +49,7 @@ function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
|
||||
}
|
||||
|
||||
function parseCommandWithSchema(command: Command, schema: CommandSchema): Command {
|
||||
const parsedParams: unknown[] = [...command.params];
|
||||
for (let i = 0; i < command.params.length; i++) {
|
||||
const paramSchema = schema.params[i]?.schema;
|
||||
if (paramSchema && typeof command.params[i] === 'string') {
|
||||
try {
|
||||
parsedParams[i] = paramSchema.parse(command.params[i] as string);
|
||||
} catch {
|
||||
// keep original value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parsedOptions: Record<string, unknown> = { ...command.options };
|
||||
for (const [key, value] of Object.entries(command.options)) {
|
||||
const optSchema = schema.options.find(o => o.name === key || o.short === key);
|
||||
if (optSchema?.schema && typeof value === 'string') {
|
||||
try {
|
||||
parsedOptions[key] = optSchema.schema.parse(value);
|
||||
} catch {
|
||||
// keep original value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { ...command, params: parsedParams, options: parsedOptions };
|
||||
return applyCommandSchema(command, schema).command;
|
||||
}
|
||||
|
||||
function pushContextToGame(game: GameContextLike, ctx: RuleContext<unknown>) {
|
||||
@@ -231,17 +206,19 @@ export function dispatchCommand(game: GameContextLike, input: string): RuleConte
|
||||
|
||||
if (game.rules.has(command.name)) {
|
||||
const ruleDef = game.rules.get(command.name)!;
|
||||
const typedCommand = parseCommandWithSchema(command, ruleDef.schema);
|
||||
|
||||
const parent = findYieldedParent(game);
|
||||
|
||||
return invokeRule(game, command, ruleDef, parent);
|
||||
return invokeRule(game, typedCommand, ruleDef, parent);
|
||||
}
|
||||
|
||||
for (let i = game.ruleContexts.length - 1; i >= 0; i--) {
|
||||
const ctx = game.ruleContexts[i];
|
||||
if (ctx.state === 'yielded' && ctx.schema) {
|
||||
if (validateYieldedSchema(command, ctx.schema)) {
|
||||
const result = ctx.generator.next(command);
|
||||
const typedCommand = parseCommandWithSchema(command, ctx.schema);
|
||||
const result = ctx.generator.next(typedCommand);
|
||||
if (result.done) {
|
||||
ctx.resolution = result.value;
|
||||
ctx.state = 'done';
|
||||
|
||||
Reference in New Issue
Block a user