forked from WikiDeck/wikideck
Modes are inert JSON (shared/game/modes.ts): rule overrides on the engine's DEFAULT_RULESET, re-validated by parseRuleset; card-mapping presets from a fixed list; deck policy and limits. server/game/ publishes this node's modes, discovers configured peers' modes as data (byte cap, timeout, pinned origin), and hosts lobbies, snake drafts and matches with the deterministic engine. Finished matches are off-chain JSONL records with seed, decks and action log (replayable). Per-mode and host leaderboards. Docs in docs/game/HOSTING.md, including security notes and an on-chain host-reward proposal. One mount line in server/testnet/http.ts; no consensus changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
9.0 KiB
TypeScript
151 lines
9.0 KiB
TypeScript
// End to end over HTTP with the real engine: publish, discover, host all three example modes.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import express from 'express';
|
|
import type { AddressInfo } from 'node:net';
|
|
import { gameRouter } from '../server/game/index.ts';
|
|
import { previewPool } from '../server/game/engine-binding.ts';
|
|
import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts';
|
|
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
|
import { ModeListSchema } from '../shared/game/modes.ts';
|
|
|
|
async function serve(env: NodeJS.ProcessEnv, enrichment?: any) {
|
|
const app = express();
|
|
app.use(express.json({ limit: '68kb' }));
|
|
app.use('/api/game', await gameRouter({ dataDir: null, env, enrichment }));
|
|
app.use((err: Error, _q: express.Request, res: express.Response, _n: express.NextFunction) => res.status(400).json({ error: err.message }));
|
|
const server = app.listen(0, '127.0.0.1');
|
|
await new Promise(r => server.once('listening', r));
|
|
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
return { base, close: () => new Promise(r => server.close(r)) };
|
|
}
|
|
const call = async (base: string, path: string, body?: unknown, token?: string) => {
|
|
const res = await fetch(base + path, { method: body === undefined ? 'GET' : 'POST',
|
|
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
|
|
body: body === undefined ? undefined : JSON.stringify(body) });
|
|
return { status: res.status, json: await res.json() as any };
|
|
};
|
|
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
|
|
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
|
|
|
|
async function playToEnd(base: string, lobby: string, tokens: string[]) {
|
|
for (let i = 0; i < 400; i++) {
|
|
let moved = false;
|
|
for (const t of tokens) {
|
|
const v = (await call(base, `/api/game/lobbies/${lobby}`, undefined, t)).json;
|
|
if (v.phase !== 'playing') return v;
|
|
// Play the first card if possible, else end the turn.
|
|
const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'endTurn');
|
|
if (a) { const r = await call(base, `/api/game/lobbies/${lobby}/actions`, { action: a }, t); assert.equal(r.status, 200, JSON.stringify(r.json)); moved = true; }
|
|
}
|
|
if (!moved) break;
|
|
}
|
|
return (await call(base, `/api/game/lobbies/${lobby}`, undefined, tokens[0])).json;
|
|
}
|
|
|
|
test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => {
|
|
const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101',
|
|
WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' },
|
|
{ get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) });
|
|
try {
|
|
const list = (await call(node.base, '/api/game/modes')).json;
|
|
ModeListSchema.parse(list);
|
|
assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']);
|
|
assert.equal(list.host.operator, 'Node A');
|
|
|
|
for (const id of ['classic', 'trending']) {
|
|
const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice);
|
|
assert.equal(a.status, 201);
|
|
const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob);
|
|
assert.equal(b.status, 200, JSON.stringify(b.json));
|
|
const peek = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`)).json;
|
|
assert.equal(peek.state, undefined);
|
|
const wrongSeat = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`, undefined, a.json.token)).json.legalActions[0];
|
|
const cheat = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/actions`, { action: { ...wrongSeat, player: 1 } }, a.json.token);
|
|
assert.equal(cheat.status, 400, 'cannot act for the other seat');
|
|
const end = await playToEnd(node.base, a.json.lobbyId, [a.json.token, b.json.token]);
|
|
assert.equal(end.phase, 'finished', JSON.stringify(end).slice(0, 300));
|
|
const rec = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
|
|
assert.equal(rec.modeId, id);
|
|
assert.equal(rec.decks[0].length, 12);
|
|
}
|
|
|
|
// Draft: 20 snake picks, 10-card decks.
|
|
const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json;
|
|
const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
|
|
const tokens = [a.token, b.token];
|
|
let picks = 0;
|
|
for (;;) {
|
|
const v = (await call(node.base, `/api/game/lobbies/${a.lobbyId}`, undefined, a.token)).json;
|
|
if (v.phase !== 'drafting') { assert.equal(v.phase, 'playing'); break; }
|
|
const free = v.draft.pool.find((c: any) => c.takenBy === null);
|
|
const r = await call(node.base, `/api/game/lobbies/${a.lobbyId}/pick`, { index: free.index }, tokens[v.draft.toPick]);
|
|
assert.equal(r.status, 200, JSON.stringify(r.json));
|
|
picks++;
|
|
}
|
|
assert.equal(picks, 20);
|
|
const end = await playToEnd(node.base, a.lobbyId, tokens);
|
|
assert.equal(end.phase, 'finished');
|
|
const record = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
|
|
assert.equal(record.decks[1].length, 10);
|
|
// Anyone can audit a match: replaying the published record reproduces the result.
|
|
const replayed = replay(record.rules, record.decks, record.seed, record.actions.map((a: any) => a.action));
|
|
assert.equal(replayed.phase, 'over');
|
|
assert.equal(replayed.result?.winner ?? null, record.winner);
|
|
|
|
const after = (await call(node.base, '/api/game/modes')).json;
|
|
assert.equal(after.matchesHosted, 3);
|
|
const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json;
|
|
assert.equal(board.entries.length, 2);
|
|
assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404);
|
|
assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404);
|
|
} finally { await node.close(); }
|
|
});
|
|
|
|
test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => {
|
|
const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' });
|
|
const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A',
|
|
WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' });
|
|
try {
|
|
// One match on B so it leads the host leaderboard.
|
|
const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json;
|
|
const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
|
|
await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match
|
|
const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json;
|
|
const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json;
|
|
assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0);
|
|
const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json;
|
|
const rec = (await call(peerB.base, `/api/game/matches/${resigned.matchId}`)).json;
|
|
assert.equal(replay(rec.rules, rec.decks, rec.seed, rec.actions.map((x: any) => x.action)).result?.winner, 0, 'resign replays as concede');
|
|
const net = (await call(nodeA.base, '/api/game/network/modes')).json;
|
|
assert.equal(net.self.host.operator, 'Node A');
|
|
assert.equal(net.peers.length, 2);
|
|
assert.equal(net.peers[0].ok, true);
|
|
assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer');
|
|
assert.equal(net.peers[0].list.modes[0].mode.id, 'draft');
|
|
assert.equal(net.peers[1].ok, false);
|
|
const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts;
|
|
assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]);
|
|
} finally { await nodeA.close(); await peerB.close(); }
|
|
});
|
|
|
|
test('modes api: draft preview pool is deterministic and deck-legal', () => {
|
|
const p1 = previewPool(DEFAULT_RULESET, 'seed', 30), p2 = previewPool(DEFAULT_RULESET, 'seed', 30);
|
|
assert.deepEqual(p1, p2);
|
|
assert.equal(p1.length, 30);
|
|
assert.equal(new Set(p1.map(c => c.id)).size, 30);
|
|
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.deck.maxCopiesPerPage);
|
|
});
|
|
|
|
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
|
|
for (const rules of [
|
|
{ maxTurns: 4, energy: { start: 3, perTurn: 1, max: 6 } },
|
|
{ lanes: 4, laneModifiers: { pool: ['plain', 'portal', 'narrow', 'plain'], revealTurns: [1, 2, 3, 4] } },
|
|
{ deck: { min: 16, max: 16, maxCopiesPerPage: 2 } },
|
|
{ maxTurns: 6, energy: { max: 7 } },
|
|
]) {
|
|
const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
|
|
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules));
|
|
}
|
|
});
|