refactor: improved PromptEvent handling
This commit is contained in:
@@ -45,7 +45,7 @@ export type CommandRunnerContextExport<TContext> = CommandRunnerContext<TContext
|
||||
registry: CommandRegistry<TContext>;
|
||||
promptQueue: AsyncQueue<PromptEvent>;
|
||||
_activePrompt: PromptEvent | null;
|
||||
_tryCommit: (command: Command) => string | null;
|
||||
_tryCommit: (commandOrInput: Command | string) => string | null;
|
||||
_cancel: (reason?: string) => void;
|
||||
_pendingInput: string | null;
|
||||
};
|
||||
@@ -66,9 +66,9 @@ export function createCommandRunnerContext<TContext>(
|
||||
|
||||
let activePrompt: PromptEvent | null = null;
|
||||
|
||||
const tryCommit = (command: Command) => {
|
||||
const tryCommit = (commandOrInput: Command | string) => {
|
||||
if (activePrompt) {
|
||||
const result = activePrompt.tryCommit(command);
|
||||
const result = activePrompt.tryCommit(commandOrInput);
|
||||
if (result === null) {
|
||||
activePrompt = null;
|
||||
}
|
||||
@@ -90,10 +90,15 @@ export function createCommandRunnerContext<TContext>(
|
||||
): Promise<Command> => {
|
||||
const resolvedSchema = typeof schema === 'string' ? parseCommandSchema(schema) : schema;
|
||||
return new Promise((resolve, reject) => {
|
||||
const tryCommit = (command: Command) => {
|
||||
const error = validator?.(command);
|
||||
const tryCommit = (commandOrInput: Command | string) => {
|
||||
const command = typeof commandOrInput === 'string' ? parseCommand(commandOrInput) : commandOrInput;
|
||||
const schemaResult = applyCommandSchema(command, resolvedSchema);
|
||||
if (!schemaResult.valid) {
|
||||
return schemaResult.errors.join('; ');
|
||||
}
|
||||
const error = validator?.(schemaResult.command);
|
||||
if (error) return error;
|
||||
resolve(command);
|
||||
resolve(schemaResult.command);
|
||||
return null;
|
||||
};
|
||||
const cancel = (reason?: string) => {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import type { Command, CommandSchema } from './types';
|
||||
import { parseCommand } from './command-parse';
|
||||
import { applyCommandSchema } from './command-validate';
|
||||
|
||||
export type PromptEvent = {
|
||||
schema: CommandSchema;
|
||||
/**
|
||||
/**
|
||||
* 尝试提交命令
|
||||
* @param commandOrInput Command 对象或命令字符串
|
||||
* @returns null - 验证成功,Promise 已 resolve
|
||||
* @returns string - 验证失败,返回错误消息,Promise 未 resolve
|
||||
*/
|
||||
tryCommit: (command: Command) => string | null;
|
||||
tryCommit: (commandOrInput: Command | string) => string | null;
|
||||
/** 取消 prompt,Promise 被 reject */
|
||||
cancel: (reason?: string) => void;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user