- Mode schema wikideck.mode/2: required `engine` (editwar | duel); Night 1
wikideck.mode/1 documents are rejected with a clear message. Deck policies:
constructed (owned NFT token ids, minConfirmations), starter (Edit War only),
draft with source preview (Edit War only) or collections. limits.rated and
limits.accountsOnly.
- ModeHost runs every engine it is given, chosen per mode. Duel modes refuse
loaner policies at startup (BRIEF decision 1).
- Seats: eom.dev account via Dex ID token (body or JWT bearer on seat-creating
routes), player id sha256('acct:'+iss+'\n'+sub); guests only in Edit War.
- Constructed decks resolved through an injected OwnershipPort (#57), cards built
by the engine's fromChain; creator's deck re-resolved at join.
- Private lobbies + invite codes (GET /invites/:code, POST /invites/:code/join),
quick match (POST /modes/:id/quick), lobby state version with 204 on ?v=.
- Elo (1200, K 24) per mode for rated account-vs-account matches, recomputed
from matches.jsonl; records carry engine, rated, tokens. /modes/:id/ladder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
269 lines
17 KiB
TypeScript
269 lines
17 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, replay, parseRuleset, previewPool as engineLoaners } 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 === 'commit');
|
|
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.cardId)).size, 30);
|
|
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, engineLoaners(DEFAULT_RULESET).length * DEFAULT_RULESET.maxCopiesPerPage);
|
|
assert.ok(p1.every(c => c.check === 'loaner' && c.source === 'loaner'), 'only engine loaner data');
|
|
});
|
|
|
|
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
|
|
for (const rules of [
|
|
{ turns: 4, energyByTurn: [3, 4, 5, 6] },
|
|
{ onTopicBonus: [0, 2, 2, 3, 3, 4, 4], trendUp: 10, trendDown: -10 },
|
|
{ deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 },
|
|
{ turns: 6, turnSeconds: 40 },
|
|
]) {
|
|
const m = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
|
|
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules));
|
|
}
|
|
});
|
|
|
|
test('modes api: mode rules that make starter decks illegal fail at startup; live trend arrows follow the ruleset', async () => {
|
|
const { ModeHost } = await import('../server/game/host.ts');
|
|
const { MatchStore } = await import('../server/game/store.ts');
|
|
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
|
const big = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'big', version: 1, name: 'Big', description: 'x',
|
|
decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } });
|
|
assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding,
|
|
store: new MatchStore(null) }), /starter decks are illegal/);
|
|
const card = engineBinding.starterDeck(DEFAULT_RULESET, 's')[0]!;
|
|
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 30 }).trend, 1);
|
|
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: DEFAULT_RULESET.trendDown - 1 }).trend, -1);
|
|
assert.equal(engineBinding.applyLive!({ ...DEFAULT_RULESET, trendDown: -25 }, card, { trendPercent: -30 }).trend, -1);
|
|
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 5 }).trend, 0);
|
|
assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: null }).trend, 0);
|
|
assert.equal(engineBinding.withPower(card, 99).power, 30, 'power stays within engine bounds');
|
|
});
|
|
|
|
test('modes api: turn timer applies the engine timeout action; AFK forfeits are replayable', async () => {
|
|
const { ModeHost } = await import('../server/game/host.ts');
|
|
const { MatchStore } = await import('../server/game/store.ts');
|
|
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
|
let now = 0;
|
|
const classic = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } });
|
|
const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding,
|
|
store: new MatchStore(null), now: () => now });
|
|
const a = await host.createLobby('classic', alice);
|
|
const b = await host.join(a.lobbyId, bob);
|
|
// Bob plays normally; Alice never acts.
|
|
for (let turn = 0; turn < 6; turn++) {
|
|
const v = host.view(a.lobbyId, b.token) as any;
|
|
if (v.phase !== 'playing') break;
|
|
await host.act(a.lobbyId, b.token, { type: 'commit', player: 1 });
|
|
now += (DEFAULT_RULESET.turnSeconds + 6) * 1000; host.sweep();
|
|
}
|
|
const end = host.view(a.lobbyId, a.token) as any;
|
|
assert.equal(end.phase, 'finished');
|
|
assert.deepEqual(end.outcome, { winner: 1, reason: 'afk' });
|
|
const rec = host.matchRecord(end.matchId);
|
|
assert.ok(rec.actions.some(x => (x.action as any).type === 'timeout'));
|
|
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner, 1);
|
|
});
|
|
|
|
test('modes api: mode rules are checked beyond the engine schema and rejected, not passed on', async () => {
|
|
const { parseModeRuleset } = await import('../server/game/engine-binding.ts');
|
|
const bad = [
|
|
{ turns: 2, energyByTurn: [1, 2] }, // portalReveal has a turn > 2
|
|
{ distinctStats: true, topicCount: 2, portalReveal: [1, 2] },
|
|
{ turns: 12, turnSeconds: 25, energyByTurn: Array(12).fill(3), portalReveal: [1, 2, 3] },
|
|
{ powerByCost: [0, 1, 2] },
|
|
{ mulligan: true },
|
|
{ keywordParams: { notAKeyword: { amount: 1 } } },
|
|
{ keywordsEnabled: [...DEFAULT_RULESET.keywordsEnabled, 'obscure'] },
|
|
];
|
|
for (const rules of bad) assert.throws(() => resolveRuleset(DEFAULT_RULESET, rules as any, parseModeRuleset), JSON.stringify(rules));
|
|
assert.throws(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'obscure'] }, parseModeRuleset), /not hostable/);
|
|
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset));
|
|
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset));
|
|
});
|
|
|
|
test('modes api: live matches survive a node restart (snapshot on shutdown, restore on start)', async () => {
|
|
const { ModeHost } = await import('../server/game/host.ts');
|
|
const { MatchStore } = await import('../server/game/store.ts');
|
|
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
|
const { persistLive } = await import('../server/game/index.ts');
|
|
const { mkdtempSync, rmSync, existsSync } = await import('node:fs');
|
|
const { tmpdir } = await import('node:os');
|
|
const { join } = await import('node:path');
|
|
const dir = mkdtempSync(join(tmpdir(), 'modes-live-'));
|
|
try {
|
|
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
|
|
parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
|
|
const make = () => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes, engine: engineBinding, store: new MatchStore(dir) });
|
|
const first = make();
|
|
persistLive(first, dir, false);
|
|
const a = await first.createLobby('classic', alice);
|
|
const b = await first.join(a.lobbyId, bob);
|
|
// Random seed: the opening hand may have nothing playable on turn 1, so fall back to commit.
|
|
const legal = (first.view(a.lobbyId, a.token) as any).legalActions;
|
|
await first.act(a.lobbyId, a.token, legal.find((x: any) => x.type === 'play') ?? legal.find((x: any) => x.type === 'commit'));
|
|
const d = await first.createLobby('draft', alice);
|
|
const e = await first.join(d.lobbyId, bob);
|
|
const pick = (first.view(d.lobbyId, d.token) as any).draft;
|
|
await first.pick(d.lobbyId, [d.token, e.token][pick.toPick]!, 0);
|
|
const waiting = await first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
|
|
const before = first.view(a.lobbyId, b.token) as any;
|
|
persistLive(first, dir, false).save();
|
|
|
|
// "Restart": a fresh host restores the snapshot. Same tokens keep working.
|
|
const second = make();
|
|
persistLive(second, dir, false);
|
|
assert.ok(existsSync(join(dir, 'live.json.restored')));
|
|
const after = second.view(a.lobbyId, b.token) as any;
|
|
assert.equal(after.phase, 'playing');
|
|
assert.deepEqual(after.state, before.state, 'match state restored exactly');
|
|
assert.equal((second.view(d.lobbyId, d.token) as any).phase, 'drafting');
|
|
assert.equal((second.view(waiting.lobbyId) as any).phase, 'waiting');
|
|
// Finish the restored match: the record replays.
|
|
for (let i = 0; i < 200; i++) {
|
|
const v = second.view(a.lobbyId, a.token) as any;
|
|
if (v.phase !== 'playing') break;
|
|
for (const t of [a.token, b.token]) {
|
|
const w = second.view(a.lobbyId, t) as any;
|
|
const c = w.legalActions?.find((x: any) => x.type === 'commit');
|
|
if (c) await second.act(a.lobbyId, t, c);
|
|
}
|
|
}
|
|
const end = second.view(a.lobbyId, a.token) as any;
|
|
assert.equal(end.phase, 'finished');
|
|
const rec = second.matchRecord(end.matchId);
|
|
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner ?? null, rec.winner);
|
|
// Rules changed under a mode → its lobbies are dropped, not run under different rules.
|
|
const changed = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, engine: engineBinding, store: new MatchStore(null),
|
|
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
|
|
assert.equal(changed.restore(second.snapshot()), 0);
|
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
});
|