Implement ChessUp server, vanilla TS UI, Stockfish analytics, and Docker/Cloudflared setup
This commit is contained in:
commit
e2e085b341
52 changed files with 15730 additions and 0 deletions
135
tests/chess.test.ts
Normal file
135
tests/chess.test.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { Chess, INITIAL_FEN } from '../src/shared/chess';
|
||||
|
||||
test('Perft startpos depths 1-4', () => {
|
||||
const c = new Chess(INITIAL_FEN);
|
||||
assert.equal(c.perft(1), 20);
|
||||
assert.equal(c.perft(2), 400);
|
||||
assert.equal(c.perft(3), 8902);
|
||||
assert.equal(c.perft(4), 197281);
|
||||
});
|
||||
|
||||
test('Perft Kiwipete depths 1-3', () => {
|
||||
const c = new Chess('r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1');
|
||||
assert.equal(c.perft(1), 48);
|
||||
assert.equal(c.perft(2), 2039);
|
||||
assert.equal(c.perft(3), 97862);
|
||||
});
|
||||
|
||||
test('Perft Position 3 (EP discovered check pin) depths 1-4', () => {
|
||||
const c = new Chess('8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1');
|
||||
assert.equal(c.perft(1), 14);
|
||||
assert.equal(c.perft(2), 191);
|
||||
assert.equal(c.perft(3), 2812);
|
||||
assert.equal(c.perft(4), 43238);
|
||||
});
|
||||
|
||||
test('Perft Position 4 (promotions & castling) depths 1-3', () => {
|
||||
const c = new Chess('r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1');
|
||||
assert.equal(c.perft(1), 6);
|
||||
assert.equal(c.perft(2), 264);
|
||||
assert.equal(c.perft(3), 9467);
|
||||
});
|
||||
|
||||
test('Perft Position 5 depths 1-3', () => {
|
||||
const c = new Chess('rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8');
|
||||
assert.equal(c.perft(1), 44);
|
||||
assert.equal(c.perft(2), 1486);
|
||||
assert.equal(c.perft(3), 62379);
|
||||
});
|
||||
|
||||
test('Rook capture clears opponent castling right', () => {
|
||||
const c = new Chess('r3k2r/8/8/8/8/8/7B/R3K2R w KQkq - 0 1');
|
||||
const mv = c.moveSan('Bxh8');
|
||||
//Wait h2 to h8 is blocked? Wait a1->h8 diagonal is b2..g7, h2->b8; let's use Bishop on g7 or a1
|
||||
assert.equal(mv, null);
|
||||
const c2 = new Chess('r3k2r/8/8/8/8/8/1B6/R3K2R w KQkq - 0 1');
|
||||
const cap = c2.moveSan('Bxh8');
|
||||
assert.ok(cap);
|
||||
assert.equal(c2.fen().split(' ')[2], 'KQq');
|
||||
});
|
||||
|
||||
test('SAN disambiguation, promotion, check, and checkmate symbols', () => {
|
||||
// Two rooks on same file + two knights on same rank targeting f4
|
||||
const c = new Chess('4k3/8/8/8/R7/8/4N1N1/R3K3 w - - 0 1');
|
||||
const rMove = c.moveSan('R1a3');
|
||||
assert.ok(rMove);
|
||||
assert.equal(rMove.san, 'R1a3');
|
||||
c.undo();
|
||||
|
||||
const nMove = c.moveSan('Nef4');
|
||||
assert.ok(nMove);
|
||||
assert.equal(nMove.san, 'Nef4');
|
||||
|
||||
// Promotion with checkmate
|
||||
const promo = new Chess('6k1/4P3/6K1/8/8/8/8/8 w - - 0 1');
|
||||
const mateMv = promo.moveUci('e7e8q');
|
||||
assert.ok(mateMv);
|
||||
assert.equal(mateMv.san, 'e8=Q#');
|
||||
});
|
||||
|
||||
test('PGN export and import with comments and variations', () => {
|
||||
const pgn = `[Event "Test Game"]
|
||||
[White "Alice"]
|
||||
[Black "Bob"]
|
||||
[Result "1-0"]
|
||||
|
||||
1. e4 {King's pawn} e5 (1... c5 2. Nf3) 2. Qh5 Nc6 3. Bc4 Nf6 $4 4. Qxf7# 1-0`;
|
||||
|
||||
const parsed = Chess.fromPgn(pgn);
|
||||
assert.equal(parsed.headers['White'], 'Alice');
|
||||
assert.equal(parsed.moves.length, 7);
|
||||
assert.equal(parsed.result, '1-0');
|
||||
assert.equal(parsed.chess.isCheckmate(), true);
|
||||
|
||||
const exported = parsed.chess.toPgn({ White: 'Alice', Black: 'Bob', Result: '1-0' });
|
||||
const reparsed = Chess.fromPgn(exported);
|
||||
assert.deepEqual(
|
||||
reparsed.moves.map((m) => m.uci),
|
||||
parsed.moves.map((m) => m.uci)
|
||||
);
|
||||
});
|
||||
|
||||
test('Draw conditions: stalemate, insufficient material, threefold repetition with EP rule, 50-move', () => {
|
||||
// Stalemate
|
||||
const stale = new Chess('7k/5Q2/6K1/8/8/8/8/8 b - - 0 1');
|
||||
assert.equal(stale.isStalemate(), true);
|
||||
assert.deepEqual(stale.gameOutcome(), { result: '1/2-1/2', termination: 'stalemate' });
|
||||
|
||||
// Insufficient material: same-color bishops (c3 dark & g1 dark) vs opposite-color bishops (c3 dark & h1 light)
|
||||
const sameColor = new Chess('4k3/8/8/8/8/2B5/8/4K1b1 w - - 0 1');
|
||||
assert.equal(sameColor.isInsufficientMaterial(), true);
|
||||
|
||||
const diffColor = new Chess('4k3/8/8/8/8/2B5/8/4K2b w - - 0 1');
|
||||
assert.equal(diffColor.isInsufficientMaterial(), false);
|
||||
|
||||
// 50-move rule
|
||||
const fifty = new Chess('4k3/8/8/8/8/8/R7/4K3 w - - 100 60');
|
||||
assert.equal(fifty.isFiftyMoveDraw(), true);
|
||||
|
||||
// Threefold repetition ignoring non-capturable EP square vs respecting capturable EP square
|
||||
const rep = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1');
|
||||
// Shuffle knights back and forth
|
||||
const seq = ['Nf6', 'Nf3', 'Ng8', 'Ng1', 'Nf6', 'Nf3', 'Ng8', 'Ng1'];
|
||||
for (let i = 0; i < seq.length - 1; i++) {
|
||||
assert.ok(rep.moveSan(seq[i]!));
|
||||
assert.equal(rep.isThreefoldRepetition(), false);
|
||||
}
|
||||
assert.ok(rep.moveSan(seq[seq.length - 1]!));
|
||||
assert.equal(rep.isThreefoldRepetition(), true);
|
||||
});
|
||||
|
||||
test('Undo restores exact FEN and repetition count', () => {
|
||||
const c = new Chess(INITIAL_FEN);
|
||||
const fens: string[] = [c.fen()];
|
||||
const moves = ['e2e4', 'e7e5', 'g1f3', 'b8c6', 'f1b5', 'a7a6', 'b5a4', 'g8f6', 'e1g1'];
|
||||
for (const uci of moves) {
|
||||
assert.ok(c.moveUci(uci));
|
||||
fens.push(c.fen());
|
||||
}
|
||||
for (let i = moves.length - 1; i >= 0; i--) {
|
||||
c.undo();
|
||||
assert.equal(c.fen(), fens[i]);
|
||||
}
|
||||
});
|
||||
49
tests/glicko2.test.ts
Normal file
49
tests/glicko2.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
INITIAL_RATING,
|
||||
INITIAL_RD,
|
||||
INITIAL_VOLATILITY,
|
||||
PROVISIONAL_RD_THRESHOLD,
|
||||
isProvisionalRd,
|
||||
updateGlicko2,
|
||||
updateGlicko2Pair
|
||||
} from '../src/server/glicko2';
|
||||
|
||||
test('Glicko-2 matches Mark Glickman official paper worked example', () => {
|
||||
// Paper example: player rating 1500, RD 200, vol 0.06
|
||||
// Opponents: (1400, 30, win=1), (1550, 100, loss=0), (1700, 300, loss=0)
|
||||
const res = updateGlicko2(
|
||||
{ rating: 1500, rd: 200, volatility: 0.06, gamesPlayed: 5 },
|
||||
[
|
||||
{ rating: 1400, rd: 30, score: 1 },
|
||||
{ rating: 1550, rd: 100, score: 0 },
|
||||
{ rating: 1700, rd: 300, score: 0 }
|
||||
]
|
||||
);
|
||||
|
||||
assert.ok(Math.abs(res.rating - 1464.06) < 0.05, `Expected ~1464.06, got ${res.rating}`);
|
||||
assert.ok(Math.abs(res.rd - 151.52) < 0.05, `Expected ~151.52, got ${res.rd}`);
|
||||
assert.ok(Math.abs(res.volatility - 0.05999) < 0.0005, `Expected ~0.05999, got ${res.volatility}`);
|
||||
assert.equal(res.gamesPlayed, 8);
|
||||
});
|
||||
|
||||
test('Glicko-2 pair update symmetry and RD decay', () => {
|
||||
const p1 = { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 };
|
||||
const p2 = { rating: INITIAL_RATING, rd: INITIAL_RD, volatility: INITIAL_VOLATILITY, gamesPlayed: 0 };
|
||||
|
||||
const out = updateGlicko2Pair(p1, p2, 1);
|
||||
assert.ok(out.whiteDiff > 0);
|
||||
assert.equal(out.whiteDiff, -out.blackDiff);
|
||||
assert.ok(out.nextWhite.rd < INITIAL_RD);
|
||||
assert.ok(out.nextBlack.rd < INITIAL_RD);
|
||||
|
||||
// Draw between equal players yields 0 rating change
|
||||
const drawOut = updateGlicko2Pair(p1, p2, 0.5);
|
||||
assert.equal(drawOut.whiteDiff, 0);
|
||||
assert.equal(drawOut.blackDiff, 0);
|
||||
|
||||
// Provisional threshold
|
||||
assert.equal(isProvisionalRd(PROVISIONAL_RD_THRESHOLD + 1), true);
|
||||
assert.equal(isProvisionalRd(PROVISIONAL_RD_THRESHOLD), false);
|
||||
});
|
||||
420
tests/server.test.ts
Normal file
420
tests/server.test.ts
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import WebSocket from 'ws';
|
||||
import { createApp, type ChessUpApp } from '../src/server/app';
|
||||
import type { ActiveGameState, GameAnalysisReport, ServerWsMessage } from '../src/shared/types';
|
||||
|
||||
class TestClient {
|
||||
public cookie = '';
|
||||
public ws: WebSocket | null = null;
|
||||
private msgQueue: ServerWsMessage[] = [];
|
||||
private waiters: Array<{
|
||||
pred: (m: ServerWsMessage) => boolean;
|
||||
resolve: (m: ServerWsMessage) => void;
|
||||
reject: (err: Error) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
}> = [];
|
||||
|
||||
constructor(private readonly baseUrl: string) {}
|
||||
|
||||
async req<T>(urlPath: string, init: RequestInit = {}): Promise<{ status: number; data: T; rawText: string }> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (init.body) headers['Content-Type'] = 'application/json';
|
||||
if (this.cookie) headers['Cookie'] = this.cookie;
|
||||
|
||||
const resp = await fetch(this.baseUrl + urlPath, {
|
||||
...init,
|
||||
headers: {
|
||||
...headers,
|
||||
...(init.headers as Record<string, string> | undefined)
|
||||
}
|
||||
});
|
||||
|
||||
const setCookie = resp.headers.get('set-cookie');
|
||||
if (setCookie) {
|
||||
const part = setCookie.split(';')[0]!;
|
||||
if (part.endsWith('=')) {
|
||||
this.cookie = '';
|
||||
} else {
|
||||
this.cookie = part;
|
||||
}
|
||||
}
|
||||
|
||||
const rawText = await resp.text();
|
||||
let data: unknown = {};
|
||||
try {
|
||||
data = rawText ? JSON.parse(rawText) : {};
|
||||
} catch {
|
||||
data = rawText;
|
||||
}
|
||||
return { status: resp.status, data: data as T, rawText };
|
||||
}
|
||||
|
||||
connectWs(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const wsUrl = this.baseUrl.replace(/^http/, 'ws') + '/ws';
|
||||
const headers: Record<string, string> = {};
|
||||
if (this.cookie) headers['Cookie'] = this.cookie;
|
||||
const ws = new WebSocket(wsUrl, { headers });
|
||||
this.ws = ws;
|
||||
|
||||
ws.once('open', () => resolve());
|
||||
ws.once('error', reject);
|
||||
ws.on('message', (buf) => {
|
||||
const msg = JSON.parse(buf.toString()) as ServerWsMessage;
|
||||
for (let i = 0; i < this.waiters.length; i++) {
|
||||
const w = this.waiters[i]!;
|
||||
if (w.pred(msg)) {
|
||||
this.waiters.splice(i, 1);
|
||||
clearTimeout(w.timer);
|
||||
w.resolve(msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.msgQueue.push(msg);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
sendWs(msg: unknown): void {
|
||||
assert.ok(this.ws && this.ws.readyState === WebSocket.OPEN, 'WS is not open');
|
||||
this.ws.send(JSON.stringify(msg));
|
||||
}
|
||||
|
||||
waitFor(pred: (m: ServerWsMessage) => boolean, timeoutMs: number = 8000): Promise<ServerWsMessage> {
|
||||
for (let i = 0; i < this.msgQueue.length; i++) {
|
||||
const m = this.msgQueue[i]!;
|
||||
if (pred(m)) {
|
||||
this.msgQueue.splice(i, 1);
|
||||
return Promise.resolve(m);
|
||||
}
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
const idx = this.waiters.findIndex((w) => w.timer === timer);
|
||||
if (idx >= 0) this.waiters.splice(idx, 1);
|
||||
reject(new Error('Timed out waiting for WS message'));
|
||||
}, timeoutMs);
|
||||
this.waiters.push({ pred, resolve, reject, timer });
|
||||
});
|
||||
}
|
||||
|
||||
closeWs(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
|
||||
this.ws = null;
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
this.ws.once('close', () => {
|
||||
this.ws = null;
|
||||
resolve();
|
||||
});
|
||||
this.ws.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, bots, friends, invites, spectating, disconnect forfeit', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chessup-test-'));
|
||||
const dbPath = path.join(tmpDir, 'test.db');
|
||||
|
||||
const app: ChessUpApp = createApp({
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
dbPath,
|
||||
stockfishWorkers: 2,
|
||||
analysisDepth: 8,
|
||||
disconnectForfeitMs: 450,
|
||||
disableRateLimit: true
|
||||
});
|
||||
|
||||
const port = await app.start();
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
|
||||
const alice = new TestClient(baseUrl);
|
||||
const bob = new TestClient(baseUrl);
|
||||
const spectator = new TestClient(baseUrl);
|
||||
|
||||
try {
|
||||
// 1. Auth: register, duplicate check, login, password update
|
||||
const regA = await alice.req<{ user: { id: number; username: string } }>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'Alice_01', password: 'password123' })
|
||||
});
|
||||
assert.equal(regA.status, 201);
|
||||
assert.equal(regA.data.user.username, 'Alice_01');
|
||||
|
||||
const dupA = await alice.req('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'alice_01', password: 'password123' })
|
||||
});
|
||||
assert.equal(dupA.status, 409);
|
||||
|
||||
const regB = await bob.req<{ user: { id: number; username: string } }>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'Bob_02', password: 'password456' })
|
||||
});
|
||||
assert.equal(regB.status, 201);
|
||||
|
||||
const badLogin = await new TestClient(baseUrl).req('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'Bob_02', password: 'wrong' })
|
||||
});
|
||||
assert.equal(badLogin.status, 401);
|
||||
|
||||
const meA = await alice.req<{ user: { username: string } | null }>('/api/auth/me');
|
||||
assert.equal(meA.status, 200);
|
||||
assert.equal(meA.data.user?.username, 'Alice_01');
|
||||
|
||||
// Connect WS clients
|
||||
await alice.connectWs();
|
||||
await bob.connectWs();
|
||||
await spectator.connectWs();
|
||||
|
||||
await alice.waitFor((m) => m.type === 'session:init');
|
||||
await bob.waitFor((m) => m.type === 'session:init');
|
||||
await spectator.waitFor((m) => m.type === 'session:init');
|
||||
|
||||
// 2. Open lobby seek -> accept -> Scholar's Mate -> DB persistence + Glicko-2 update
|
||||
alice.sendWs({ type: 'lobby:subscribe' });
|
||||
bob.sendWs({ type: 'lobby:subscribe' });
|
||||
await alice.waitFor((m) => m.type === 'lobby:state');
|
||||
await bob.waitFor((m) => m.type === 'lobby:state');
|
||||
|
||||
alice.sendWs({
|
||||
type: 'lobby:seek',
|
||||
initialMs: 180_000,
|
||||
incrementMs: 0,
|
||||
rated: true,
|
||||
colorPref: 'white'
|
||||
});
|
||||
|
||||
const seekMsg = (await bob.waitFor(
|
||||
(m) => m.type === 'lobby:state' && m.seeks.length === 1
|
||||
)) as Extract<ServerWsMessage, { type: 'lobby:state' }>;
|
||||
const seekId = seekMsg.seeks[0]!.id;
|
||||
|
||||
bob.sendWs({ type: 'lobby:accept_seek', seekId });
|
||||
const startA = (await alice.waitFor((m) => m.type === 'game:started')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'game:started' }
|
||||
>;
|
||||
const startB = (await bob.waitFor((m) => m.type === 'game:started')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'game:started' }
|
||||
>;
|
||||
assert.equal(startA.gameId, startB.gameId);
|
||||
const pvpGameId = startA.gameId;
|
||||
|
||||
alice.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
|
||||
bob.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
|
||||
spectator.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
|
||||
|
||||
const stateA = (await alice.waitFor((m) => m.type === 'game:state')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'game:state' }
|
||||
>;
|
||||
assert.equal(stateA.game.white.username, 'Alice_01');
|
||||
assert.equal(stateA.game.black.username, 'Bob_02');
|
||||
|
||||
// Unauthenticated spectator watches + authenticated player chats
|
||||
await spectator.waitFor((m) => m.type === 'game:state');
|
||||
alice.sendWs({ type: 'game:chat', gameId: pvpGameId, text: 'Good luck!' });
|
||||
const chatSpec = (await spectator.waitFor((m) => m.type === 'game:chat')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'game:chat' }
|
||||
>;
|
||||
assert.equal(chatSpec.message.text, 'Good luck!');
|
||||
|
||||
// Play Scholar's Mate
|
||||
const scholarMoves: Array<[TestClient, string]> = [
|
||||
[alice, 'e2e4'],
|
||||
[bob, 'e7e5'],
|
||||
[alice, 'd1h5'],
|
||||
[bob, 'b8c6'],
|
||||
[alice, 'f1c4'],
|
||||
[bob, 'g8f6'],
|
||||
[alice, 'h5f7']
|
||||
];
|
||||
for (const [player, uci] of scholarMoves) {
|
||||
player.sendWs({ type: 'game:move', gameId: pvpGameId, uci });
|
||||
await alice.waitFor((m) => m.type === 'game:move' && m.uci === uci);
|
||||
await bob.waitFor((m) => m.type === 'game:move' && m.uci === uci);
|
||||
}
|
||||
|
||||
const overA = (await alice.waitFor((m) => m.type === 'game:over')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'game:over' }
|
||||
>;
|
||||
assert.equal(overA.result, '1-0');
|
||||
assert.equal(overA.termination, 'checkmate');
|
||||
assert.equal(overA.saved, true);
|
||||
assert.ok(overA.whiteRatingDiff !== null && overA.whiteRatingDiff > 0);
|
||||
assert.ok(overA.blackRatingDiff !== null && overA.blackRatingDiff < 0);
|
||||
|
||||
// Check REST history, PGN, leaderboard
|
||||
const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`);
|
||||
assert.equal(storedRes.status, 200);
|
||||
assert.equal(storedRes.data.game.result, '1-0');
|
||||
|
||||
const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`);
|
||||
assert.equal(pgnRes.status, 200);
|
||||
assert.ok(pgnRes.rawText.includes('Qxf7#'));
|
||||
|
||||
const lbRes = await alice.req<{ entries: Array<{ username: string }> }>('/api/leaderboard?category=blitz');
|
||||
assert.equal(lbRes.status, 200);
|
||||
assert.equal(lbRes.data.entries[0]!.username, 'Alice_01');
|
||||
|
||||
// 3. Stockfish Post-Game Analysis + Cache verification
|
||||
alice.sendWs({ type: 'analysis:subscribe', gameId: pvpGameId });
|
||||
const triggerRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
assert.ok(triggerRes.status === 202 || triggerRes.status === 200);
|
||||
|
||||
const analysisDone = (await alice.waitFor(
|
||||
(m) => m.type === 'analysis:done' && m.gameId === pvpGameId,
|
||||
15_000
|
||||
)) as Extract<ServerWsMessage, { type: 'analysis:done' }>;
|
||||
assert.equal(analysisDone.report.status, 'done');
|
||||
assert.equal(analysisDone.report.plies.length, 7);
|
||||
assert.equal(analysisDone.report.plies[5]!.classification, 'blunder');
|
||||
|
||||
// Second POST returns cached 200 immediately
|
||||
const cachedRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
assert.equal(cachedRes.status, 200);
|
||||
assert.equal(cachedRes.data.report.status, 'done');
|
||||
|
||||
// 4. Play vs Stockfish Level 1 + takeback
|
||||
const botRes = await alice.req<{ gameId: string }>('/api/games/bot', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ level: 1, colorPref: 'white', initialMs: 0, incrementMs: 0 })
|
||||
});
|
||||
assert.equal(botRes.status, 201);
|
||||
const botGameId = botRes.data.gameId;
|
||||
alice.sendWs({ type: 'game:subscribe', gameId: botGameId });
|
||||
await alice.waitFor((m) => m.type === 'game:state' && m.game.id === botGameId);
|
||||
|
||||
alice.sendWs({ type: 'game:move', gameId: botGameId, uci: 'e2e4' });
|
||||
await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.uci === 'e2e4');
|
||||
// Wait for Stockfish Level 1 response
|
||||
await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.turn === 'w');
|
||||
|
||||
// Takeback restores back to 0 plies
|
||||
alice.sendWs({ type: 'game:takeback_offer', gameId: botGameId });
|
||||
const tbMsg = (await alice.waitFor(
|
||||
(m) => m.type === 'game:takeback' && m.gameId === botGameId
|
||||
)) as Extract<ServerWsMessage, { type: 'game:takeback' }>;
|
||||
assert.equal(tbMsg.game.movesUci.length, 0);
|
||||
|
||||
alice.sendWs({ type: 'game:abort', gameId: botGameId });
|
||||
await alice.waitFor((m) => m.type === 'game:over' && m.gameId === botGameId && m.termination === 'aborted');
|
||||
|
||||
// 5. Mutual friends + Direct challenge
|
||||
const frReq = await alice.req('/api/friends/request', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username: 'Bob_02' })
|
||||
});
|
||||
assert.equal(frReq.status, 200);
|
||||
|
||||
const frAcc = await bob.req('/api/friends/respond', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ userId: regA.data.user.id, accept: true })
|
||||
});
|
||||
assert.equal(frAcc.status, 200);
|
||||
|
||||
alice.sendWs({
|
||||
type: 'challenge:send',
|
||||
toUserId: regB.data.user.id,
|
||||
initialMs: 300_000,
|
||||
incrementMs: 0,
|
||||
rated: false,
|
||||
colorPref: 'white'
|
||||
});
|
||||
|
||||
const chalRecv = (await bob.waitFor((m) => m.type === 'challenge:received')) as Extract<
|
||||
ServerWsMessage,
|
||||
{ type: 'challenge:received' }
|
||||
>;
|
||||
bob.sendWs({ type: 'challenge:respond', challengeId: chalRecv.challenge.id, accept: true });
|
||||
|
||||
const chalStart = (await bob.waitFor(
|
||||
(m) => m.type === 'game:started' && m.gameId !== pvpGameId
|
||||
)) as Extract<ServerWsMessage, { type: 'game:started' }>;
|
||||
const chalGameId = chalStart.gameId;
|
||||
|
||||
alice.sendWs({ type: 'game:subscribe', gameId: chalGameId });
|
||||
bob.sendWs({ type: 'game:subscribe', gameId: chalGameId });
|
||||
await alice.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId);
|
||||
await bob.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId);
|
||||
|
||||
// Play 2 plies so game counts and test disconnect forfeit
|
||||
alice.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd2d4' });
|
||||
await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd2d4');
|
||||
bob.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd7d5' });
|
||||
await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd7d5');
|
||||
|
||||
// Alice disconnects -> after disconnectForfeitMs (450ms), Bob wins by abandonment!
|
||||
await alice.closeWs();
|
||||
const abandonOver = (await bob.waitFor(
|
||||
(m) => m.type === 'game:over' && m.gameId === chalGameId
|
||||
)) as Extract<ServerWsMessage, { type: 'game:over' }>;
|
||||
assert.equal(abandonOver.result, '0-1');
|
||||
assert.equal(abandonOver.termination, 'abandonment');
|
||||
|
||||
// 6. Shareable invite link flow
|
||||
await alice.connectWs();
|
||||
await alice.waitFor((m) => m.type === 'session:init');
|
||||
const invCreate = await alice.req<{ invite: { token: string } }>('/api/invites', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initialMs: 600_000, incrementMs: 5_000, rated: false, colorPref: 'black' })
|
||||
});
|
||||
assert.equal(invCreate.status, 201);
|
||||
const invToken = invCreate.data.invite.token;
|
||||
|
||||
const invGet = await bob.req<{ invite: { creatorUsername: string } }>(`/api/invites/${invToken}`);
|
||||
assert.equal(invGet.status, 200);
|
||||
assert.equal(invGet.data.invite.creatorUsername, 'Alice_01');
|
||||
|
||||
const invAcc = await bob.req<{ gameId: string }>(`/api/invites/${invToken}/accept`, { method: 'POST' });
|
||||
assert.equal(invAcc.status, 200);
|
||||
const invGame = await bob.req<{ kind: string; game: ActiveGameState }>(`/api/games/${invAcc.data.gameId}`);
|
||||
assert.equal(invGame.status, 200);
|
||||
assert.equal(invGame.data.game.white.username, 'Bob_02');
|
||||
assert.equal(invGame.data.game.black.username, 'Alice_01');
|
||||
|
||||
// 7. Health endpoint, malformed URL handling, and X-Forwarded-Host origin support
|
||||
const healthRes = await alice.req<{ ok: boolean }>('/api/health');
|
||||
assert.equal(healthRes.status, 200);
|
||||
assert.equal(healthRes.data.ok, true);
|
||||
|
||||
const badPathRes = await alice.req<{ error: string }>('/api/%E0%A4%A');
|
||||
assert.equal(badPathRes.status, 400);
|
||||
|
||||
const fwdOriginRes = await new TestClient(baseUrl).req('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'https://chess.example.com', 'X-Forwarded-Host': 'chess.example.com' }
|
||||
});
|
||||
assert.equal(fwdOriginRes.status, 200);
|
||||
|
||||
const badOriginPost = await alice.req('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'https://evil.example.com', 'X-Forwarded-Host': 'chess.example.com' }
|
||||
});
|
||||
assert.equal(badOriginPost.status, 403);
|
||||
} finally {
|
||||
await alice.closeWs();
|
||||
await bob.closeWs();
|
||||
await spectator.closeWs();
|
||||
await app.stop();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
65
tests/stockfish.test.ts
Normal file
65
tests/stockfish.test.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { Chess, INITIAL_FEN } from '../src/shared/chess';
|
||||
import { StockfishPool } from '../src/server/stockfish';
|
||||
|
||||
test('StockfishPool bot moves, MultiPV perspective normalization, cancellation, and full-game analysis', async () => {
|
||||
const pool = new StockfishPool(2);
|
||||
try {
|
||||
await pool.warmup();
|
||||
|
||||
// 1. Bot Level 1 and Level 8 return legal UCI moves
|
||||
const c = new Chess(INITIAL_FEN);
|
||||
const lv1Move = await pool.getBotMove(c.fen(), 1);
|
||||
assert.ok(c.legalMoves().some((m) => m.uci === lv1Move), `Illegal lv1 move: ${lv1Move}`);
|
||||
|
||||
const lv8Move = await pool.getBotMove(c.fen(), 8);
|
||||
assert.ok(c.legalMoves().some((m) => m.uci === lv8Move), `Illegal lv8 move: ${lv8Move}`);
|
||||
|
||||
// 2. MultiPV on Black-to-move position where White is up a Queen -> scoreCp MUST be positive (White's perspective)!
|
||||
const whiteUpQueenBlackToMove = 'rnb1kbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1';
|
||||
const lines = await pool.analyzePositionMultiPv(whiteUpQueenBlackToMove, 8, 2);
|
||||
assert.ok(lines.length >= 1);
|
||||
assert.ok(
|
||||
lines[0]!.scoreCp !== null && lines[0]!.scoreCp > 400,
|
||||
`Expected White-perspective positive cp > 400, got ${lines[0]!.scoreCp}`
|
||||
);
|
||||
|
||||
// 3. Cancellation works cleanly
|
||||
const ac = new AbortController();
|
||||
const cancelPromise = pool.analyzePositionMultiPv(INITIAL_FEN, 18, 3, ac.signal);
|
||||
setTimeout(() => ac.abort(), 30);
|
||||
const cancelledLines = await cancelPromise;
|
||||
assert.ok(Array.isArray(cancelledLines));
|
||||
|
||||
// 4. Full-game analysis on Scholar's Mate
|
||||
const gameChess = new Chess(INITIAL_FEN);
|
||||
const uciList = ['e2e4', 'e7e5', 'd1h5', 'b8c6', 'f1c4', 'g8f6', 'h5f7'];
|
||||
const sanList: string[] = [];
|
||||
for (const u of uciList) {
|
||||
const mv = gameChess.moveUci(u);
|
||||
assert.ok(mv);
|
||||
sanList.push(mv.san);
|
||||
}
|
||||
|
||||
let sawProgress = false;
|
||||
const report = await pool.analyzeFullGame('test-scholar', INITIAL_FEN, uciList, sanList, 10, (done, total) => {
|
||||
assert.ok(done <= total);
|
||||
sawProgress = true;
|
||||
});
|
||||
|
||||
assert.equal(sawProgress, true);
|
||||
assert.equal(report.status, 'done');
|
||||
assert.equal(report.plies.length, 7);
|
||||
assert.ok(report.whiteSummary && report.blackSummary);
|
||||
// 3... Nf6?? allows 4. Qxf7# -> blunder!
|
||||
const nf6Ply = report.plies[5]!;
|
||||
assert.equal(nf6Ply.moveSan, 'Nf6');
|
||||
assert.equal(nf6Ply.classification, 'blunder');
|
||||
// 4. Qxf7# delivers mate -> 100% win percent after
|
||||
const matePly = report.plies[6]!;
|
||||
assert.equal(matePly.winPercentAfter, 100);
|
||||
} finally {
|
||||
pool.shutdown();
|
||||
}
|
||||
});
|
||||
87
tests/winProb.test.ts
Normal file
87
tests/winProb.test.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
classifyMove,
|
||||
computeMoveAccuracy,
|
||||
computePlayerSummary,
|
||||
cpToWinPercent,
|
||||
formatEvalShort
|
||||
} from '../src/shared/winProb';
|
||||
import type { PlyAnalysis } from '../src/shared/types';
|
||||
|
||||
test('cpToWinPercent symmetry and mate bounds', () => {
|
||||
assert.equal(cpToWinPercent(0, null), 50);
|
||||
assert.equal(cpToWinPercent(null, 3), 100);
|
||||
assert.equal(cpToWinPercent(null, -2), 0);
|
||||
|
||||
const pos = cpToWinPercent(250, null);
|
||||
const neg = cpToWinPercent(-250, null);
|
||||
assert.ok(pos > 65 && pos < 80);
|
||||
assert.ok(Math.abs(pos + neg - 100) < 1e-6);
|
||||
});
|
||||
|
||||
test('classifyMove thresholds and accuracy', () => {
|
||||
assert.equal(classifyMove(60, 60, true), 'best');
|
||||
assert.equal(classifyMove(60, 59, false), 'best');
|
||||
assert.equal(classifyMove(60, 55, false), 'good');
|
||||
assert.equal(classifyMove(60, 49, false), 'inaccuracy');
|
||||
assert.equal(classifyMove(60, 39, false), 'mistake');
|
||||
assert.equal(classifyMove(60, 29, false), 'blunder');
|
||||
|
||||
assert.equal(computeMoveAccuracy(0), 100);
|
||||
assert.ok(computeMoveAccuracy(35) < 25);
|
||||
});
|
||||
|
||||
test('computePlayerSummary calculates ACPL and counts accurately', () => {
|
||||
const plies: PlyAnalysis[] = [
|
||||
{
|
||||
ply: 1,
|
||||
moveUci: 'e2e4',
|
||||
moveSan: 'e4',
|
||||
color: 'w',
|
||||
evalCpBefore: 20,
|
||||
evalMateBefore: null,
|
||||
evalCpAfter: 20,
|
||||
evalMateAfter: null,
|
||||
winPercentBefore: 51,
|
||||
winPercentAfter: 51,
|
||||
winDrop: 0,
|
||||
accuracy: 100,
|
||||
bestMoveUci: 'e2e4',
|
||||
bestMoveSan: 'e4',
|
||||
pvUci: ['e2e4'],
|
||||
pvSan: ['e4'],
|
||||
classification: 'best'
|
||||
},
|
||||
{
|
||||
ply: 2,
|
||||
moveUci: 'g7g5',
|
||||
moveSan: 'g5',
|
||||
color: 'b',
|
||||
evalCpBefore: 20,
|
||||
evalMateBefore: null,
|
||||
evalCpAfter: 320,
|
||||
evalMateAfter: null,
|
||||
winPercentBefore: 51,
|
||||
winPercentAfter: 76,
|
||||
winDrop: 25,
|
||||
accuracy: 31.6,
|
||||
bestMoveUci: 'e7e5',
|
||||
bestMoveSan: 'e5',
|
||||
pvUci: ['e7e5'],
|
||||
pvSan: ['e5'],
|
||||
classification: 'mistake'
|
||||
}
|
||||
];
|
||||
|
||||
const wSum = computePlayerSummary(plies, 'w');
|
||||
assert.equal(wSum.accuracy, 100);
|
||||
assert.equal(wSum.acpl, 0);
|
||||
assert.equal(wSum.best, 1);
|
||||
|
||||
const bSum = computePlayerSummary(plies, 'b');
|
||||
assert.equal(bSum.acpl, 300);
|
||||
assert.equal(bSum.mistakes, 1);
|
||||
assert.equal(formatEvalShort(145, null), '+1.5');
|
||||
assert.equal(formatEvalShort(null, -4), '-M4');
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue