refactor: update api

This commit is contained in:
2026-04-02 12:48:29 +08:00
parent 846badc081
commit 004d49c36f
4 changed files with 128 additions and 66 deletions
+56 -2
View File
@@ -1,7 +1,15 @@
import { describe, it, expect } from 'vitest';
import { createGameContext, createGameCommand } from '../../src/core/game';
import { createGameContext, createGameCommand, IGameContext } from '../../src/core/game';
import { createCommandRegistry, parseCommandSchema, type CommandRegistry } from '../../src/utils/command';
import type { IGameContext } from '../../src/core/game';
type MyState = {
score: number;
round: number;
};
type MyContext = IGameContext & {
state: MyState;
};
describe('createGameContext', () => {
it('should create a game context with empty parts and regions', () => {
@@ -21,6 +29,26 @@ describe('createGameContext', () => {
expect(ctx.commands.context).toBe(ctx);
});
it('should accept initial state as an object', () => {
const registry = createCommandRegistry<MyContext>();
const ctx = createGameContext<MyContext>(registry, {
state: { score: 0, round: 1 },
});
expect(ctx.state.score).toBe(0);
expect(ctx.state.round).toBe(1);
});
it('should accept initial state as a factory function', () => {
const registry = createCommandRegistry<MyContext>();
const ctx = createGameContext<MyContext>(registry, () => ({
state: { score: 10, round: 3 },
}));
expect(ctx.state.score).toBe(10);
expect(ctx.state.round).toBe(3);
});
it('should forward prompt events to the prompts queue', async () => {
const registry = createCommandRegistry<IGameContext>();
const ctx = createGameContext(registry);
@@ -123,4 +151,30 @@ describe('createGameCommand', () => {
}
expect(ctx.parts.get('piece-1')).not.toBeNull();
});
it('should run a typed command with extended context', async () => {
const registry = createCommandRegistry<MyContext>();
const addScore = createGameCommand<MyContext, number>(
'add-score <amount:number>',
async function (cmd) {
const amount = cmd.params[0] as number;
this.context.state.score += amount;
return this.context.state.score;
}
);
registry.set('add-score', addScore);
const ctx = createGameContext<MyContext>(registry, () => ({
state: { score: 0, round: 1 },
}));
const result = await ctx.commands.run('add-score 5');
expect(result.success).toBe(true);
if (result.success) {
expect(result.result).toBe(5);
}
expect(ctx.state.score).toBe(5);
});
});