sokko-g/tests/nebula-cards-mirror.test.mjs
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:42:13 +01:00

457 lines
26 KiB
JavaScript

/**
* @file Vérifie le Miroir brisé : règles pures (mélange, rangée ou colonne, référence de l'ordinateur),
* illustrations jouables, réglages, parties côté serveur (échanges, coups de main, gains, Difficile
* commun) et API.
*/
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { Readable } from "node:stream";
import { test } from "node:test";
import { createCardsApiHandler } from "../services/cards/api.js";
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
import { CardsDatabase, MIGRATIONS } from "../services/cards/database.js";
import {
aligned, BALANCED_HELP, cellCount, drawIllustration, HELPERS_PER_GAME, helpsOf, isSolved, EXTRA_MOVES, minSwaps, previousMode, MAX_AMBIGUOUS_SHARE, MAX_FIXED_AT_START, mirrorCandidates, mirrorReward, MIRROR_MODES, pieceAt, placedCells, placedCount, scramble, solve, swapCells, swapLimit
} from "../services/cards/mirror-rules.js";
import { loadMirrorMeasures } from "../services/cards/mirror-service.js";
import { DEFAULT_MIRROR_SETTINGS, mirrorSettingsError, readMirrorSettings } from "../services/cards/mirror-settings.js";
import { CardsService } from "../services/cards/service.js";
import { DEFAULT_DAILY_TEAM_SETTINGS } from "../services/cards/team-settings.js";
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
const RATES = { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 };
const published = (active) => buildPublishedCatalog(baseCatalog, { variations: [], collectionStates: baseCatalog.collections.map(({ id }) => ({ collectionId: id, active: active(id) })), dropRates: baseCatalog.collections.map(({ id }) => ({ collectionId: id, rarityWeights: RATES })) });
const catalog = published(() => true);
const measures = loadMirrorMeasures();
function seeded(seed) {
let state = seed >>> 0;
return (max) => {
state = (state + 0x6d2b79f5) >>> 0;
let value = Math.imul(state ^ (state >>> 15), 1 | state);
value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
return ((value ^ (value >>> 14)) >>> 0) % max;
};
}
// --- Règles pures ----------------------------------------------------------------------------------------------------------
test("a scramble is a permutation with at most two pieces already in place", () => {
const random = seeded(1);
for (const mode of Object.keys(MIRROR_MODES)) for (let round = 0; round < 200; round += 1) {
const pos = scramble(cellCount(mode), random);
assert.deepEqual([...pos].sort((a, b) => a - b), Array.from({ length: cellCount(mode) }, (_, index) => index));
assert.ok(placedCount(pos) <= MAX_FIXED_AT_START);
}
// Un hasard prévisible (parcours E2E) ne fait jamais boucler le mélange.
for (const random of [() => 0, (max) => max - 1]) assert.ok(placedCount(scramble(35, random)) <= MAX_FIXED_AT_START);
});
test("two pieces swap only in the same row or the same column", () => {
const { cols } = MIRROR_MODES.hard;
assert.ok(aligned(cols, 0, 4));
assert.ok(aligned(cols, 2, 32));
assert.ok(!aligned(cols, 0, 6));
assert.ok(!aligned(cols, 7, 7));
const pos = [1, 0, 2, 3];
assert.deepEqual(swapCells(pos, 0, 1), [0, 1, 2, 3]);
assert.deepEqual(pieceAt([2, 0, 1]), [1, 2, 0]);
});
test("the computer finds a legal solution that holds its announced length", () => {
const random = seeded(2);
for (const mode of Object.keys(MIRROR_MODES)) {
const { cols } = MIRROR_MODES[mode];
const count = cellCount(mode);
for (let round = 0; round < (mode === "normal" ? 20 : 2); round += 1) {
const start = scramble(count, random);
const { length, first } = solve(start, cols);
// Rejouer la solution coup par coup : chaque premier coup est légal et la longueur annoncée est tenue.
let pos = start, steps = 0;
while (!isSolved(pos)) {
const next = solve(pos, cols).first;
assert.ok(next && aligned(cols, next[0], next[1]));
pos = swapCells(pos, next[0], next[1]);
steps += 1;
assert.ok(steps <= length + 2, `${mode} ${steps} > ${length}`);
}
assert.ok(first && length >= (count - placedCount(start)) / 2 && length <= 2 * count);
assert.deepEqual(solve(start, cols), { length, first }, "déterministe");
}
}
});
test("a reward is a base plus a share per swap left, and a balanced companion has its own help", () => {
assert.equal(mirrorReward({ base: 10, perSwap: 1 }, 3), 13);
assert.equal(mirrorReward({ base: 20, perSwap: 2 }, -1), 20);
assert.equal(swapLimit(15, 3), 18);
assert.deepEqual(helpsOf([]), [BALANCED_HELP]);
assert.deepEqual(helpsOf(["bravoure", "endurance"]), ["bravoure", "endurance"]);
});
// --- Illustrations ---------------------------------------------------------------------------------------------------------
test("every illustration has its measure, and the uniform ones are left out", () => {
for (const card of baseCatalog.cards) {
if (card.image) assert.ok(measures.square[card.id], `mesure carrée manquante : ${card.id} (node scripts/mirror-illustrations.mjs)`);
if (card.fullImage) assert.ok(measures.portrait[card.id], `mesure portrait manquante : ${card.id} (node scripts/mirror-illustrations.mjs)`);
}
const hard = mirrorCandidates(catalog, measures, "hard").map((card) => card.id);
const normal = mirrorCandidates(catalog, measures, "normal").map((card) => card.id);
assert.ok(hard.length >= 30 && normal.length >= 200, `${hard.length} / ${normal.length}`);
assert.ok(!hard.includes("great-void") && !normal.includes("great-void"));
assert.ok(hard.includes("starvoid-dragon") && normal.includes("pale-moon-owl"));
for (const id of hard) assert.ok(measures.portrait[id].ambiguous / measures.portrait[id].pieces <= MAX_AMBIGUOUS_SHARE);
// Une collection fermée n'est jamais dévoilée, et une carte sans mesure n'est pas jouable.
const nebula = mirrorCandidates(published((id) => id === "primordial-nebula"), measures, "normal");
assert.ok(nebula.length > 0 && nebula.every((card) => card.collectionId === "primordial-nebula"));
assert.deepEqual(mirrorCandidates(catalog, { square: {}, portrait: {} }, "normal"), []);
assert.equal(drawIllustration([{ id: "a" }, { id: "b" }], new Set(["a"]), () => 0), "b");
assert.equal(drawIllustration([{ id: "a" }], new Set(["a"]), () => 0), "a");
});
// --- Réglages --------------------------------------------------------------------------------------------------------------
test("mirror settings are closed by default and read tolerantly", () => {
assert.equal(DEFAULT_MIRROR_SETTINGS.enabled, false);
assert.equal(mirrorSettingsError(DEFAULT_MIRROR_SETTINGS), null);
assert.ok(mirrorSettingsError({ ...DEFAULT_MIRROR_SETTINGS, margins: { normal: -1, hard: 6 } }));
assert.ok(mirrorSettingsError({ ...DEFAULT_MIRROR_SETTINGS, rewards: { normal: { base: 1 }, hard: { base: 1, perSwap: 1 } } }));
const read = readMirrorSettings({ enabled: true, margins: { normal: "x" } });
assert.equal(read.enabled, true);
assert.equal(read.margins.normal, DEFAULT_MIRROR_SETTINGS.margins.normal);
assert.deepEqual(readMirrorSettings({ rewards: { hard: { base: 50 } } }).rewards.hard, { base: 50, perSwap: 2 });
});
// --- Service ---------------------------------------------------------------------------------------------------------------
const NOON = Date.parse("2026-11-28T11:00:00Z");
const DAY = "2026-11-28";
const DAY_MS = 24 * 3_600_000;
const refuses = (code, callback) => assert.throws(callback, (error) => error.code === code);
function game(t, { enabled = true, team = false, seed = 5 } = {}) {
const database = new CardsDatabase(":memory:");
t.after(() => database.close());
const clock = { now: NOON };
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random: seeded(seed) });
database.db.prepare("UPDATE collection_states SET active = 1").run();
service.reloadCatalog();
const player = service.upsertPlayer({ discordId: "1", displayName: "Léa", avatarUrl: "" });
const admin = service.upsertPlayer({ discordId: "2", displayName: "Admin", avatarUrl: "", isAdmin: true });
if (enabled) service.mirror.updateSettings(admin.id, { ...DEFAULT_MIRROR_SETTINGS, enabled: true });
if (team) service.team.updateSettings(admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS, enabled: true });
return { database, db: database.db, clock, service, player, admin, mirror: service.mirror };
}
const stored = (db, playerId, mode, day = DAY) => JSON.parse(db.prepare("SELECT state_json FROM mirror_games WHERE player_id = ? AND day = ? AND mode = ?").get(playerId, day, mode).state_json);
// Joue jusqu'à la fin, ou `limit` échanges : en Facile, chaque morceau directement à sa place ; sinon la solution de l'ordinateur.
function nextMove(pos, mode) {
if (!MIRROR_MODES[mode].freeSwaps) return solve(pos, MIRROR_MODES[mode].cols).first;
const piece = pos.findIndex((cell, index) => cell !== index);
return [pos[piece], piece];
}
function play({ mirror, db, player }, mode, limit = Infinity) {
let view = mirror.view(player.id).games[mode];
for (let count = 0; view.status === "playing" && count < limit; count += 1) {
const [from, to] = nextMove(stored(db, player.id, mode).pos, mode);
view = mirror.swap(player.id, { day: DAY, mode, from, to, moves: view.moves }).mirror.games[mode];
}
return view;
}
// Échange légal qui ne pose aucun morceau, pour épuiser les échanges.
function wasteSwap({ mirror, db, player }, mode) {
const { pos } = stored(db, player.id, mode);
const { cols } = MIRROR_MODES[mode];
const at = pieceAt(pos);
for (let x = 0; x < pos.length; x += 1) for (let y = 0; y < pos.length; y += 1) {
if (aligned(cols, x, y) && at[x] !== y && at[y] !== x && at[x] !== x && at[y] !== y) {
return mirror.swap(player.id, { day: DAY, mode, from: x, to: y, moves: mirror.view(player.id).games[mode].moves }).mirror.games[mode];
}
}
throw new Error("aucun échange neutre");
}
// Termine le Facile (et le Normal pour `upTo = "hard"`), pour ouvrir le mode suivant.
function unlock(context, upTo = "normal", player = context.player) {
for (let mode = "easy"; mode !== upTo; mode = MIRROR_MODES_ORDER[MIRROR_MODES_ORDER.indexOf(mode) + 1]) {
context.mirror.start(player.id, { day: DAY, mode });
play({ ...context, player }, mode);
}
}
const MIRROR_MODES_ORDER = ["easy", "normal", "hard"];
function readyTeam({ service, player }) {
service.team.startRecruitment(player.id, { day: DAY });
let view = service.team.view(player.id);
while (view.status === "recruiting") {
const { cardId } = view.recruitment.current ?? view.recruitment.offer[0];
if (!view.recruitment.current) service.team.chooseCharacter(player.id, { cardId });
view = service.team.keepCompanion(player.id, { cardId }).team;
}
return view;
}
test("the mirror is closed by default and only an administrator opens it", (t) => {
const { mirror, player, admin, db } = game(t, { enabled: false });
assert.equal(mirror.view(player.id).enabled, false);
assert.deepEqual(mirror.summary(player.id), { enabled: false, easy: "none", normal: "none", hard: "none", locks: { easy: null, normal: "easy", hard: "normal" } });
refuses("MIRROR_CLOSED", () => mirror.start(player.id, { day: DAY, mode: "normal" }));
assert.throws(() => mirror.updateSettings(player.id, { ...DEFAULT_MIRROR_SETTINGS, enabled: true }), (error) => error.status === 403);
refuses("MIRROR_SETTINGS_INVALID", () => mirror.updateSettings(admin.id, { ...DEFAULT_MIRROR_SETTINGS, margins: { normal: 99, hard: 6 } }));
refuses("MIRROR_SETTINGS_UNCHANGED", () => mirror.updateSettings(admin.id, { ...DEFAULT_MIRROR_SETTINGS }));
assert.equal(mirror.updateSettings(admin.id, { ...DEFAULT_MIRROR_SETTINGS, enabled: true, unknown: 1 }).mirrorSettings.settings.enabled, true);
assert.equal(JSON.parse(db.prepare("SELECT settings_json FROM mirror_settings").get().settings_json).unknown, undefined);
});
// Marges élargies le 29 novembre 2026 : des réglages restés sur les anciennes valeurs par défaut prennent les nouvelles.
test("saved settings on the old default margins move to the wider ones, other margins stay", (t) => {
const { database, db, mirror } = game(t);
const version = MIGRATIONS.findIndex((migration) => typeof migration === "string" && migration.includes("'$.margins.hard', 14")) + 1;
assert.ok(version > 0);
const rerun = (margins) => {
db.prepare("UPDATE mirror_settings SET settings_json = ?").run(JSON.stringify({ ...DEFAULT_MIRROR_SETTINGS, enabled: true, margins }));
db.prepare("DELETE FROM schema_migrations WHERE version = ?").run(version);
database.migrate();
return mirror.settings.margins;
};
assert.deepEqual(rerun({ easy: 4, normal: 3, hard: 6 }), { easy: 4, normal: 6, hard: 14 });
assert.deepEqual(rerun({ easy: 4, normal: 5, hard: 9 }), { easy: 4, normal: 5, hard: 9 });
});
test("the easy picture swaps any two pieces, against the free minimum, and opens the normal one", (t) => {
const context = game(t);
const { mirror, player, db, service } = context;
assert.equal(previousMode("easy"), null);
assert.equal(previousMode("hard"), "normal");
const easy = mirror.start(player.id, { day: DAY, mode: "easy" }).mirror.games.easy;
const state = stored(db, player.id, "easy");
assert.equal(easy.freeSwap, true);
assert.equal(state.par, minSwaps(state.start));
assert.equal(easy.limit, state.par + DEFAULT_MIRROR_SETTINGS.margins.easy);
// Deux morceaux éloignés s'échangent.
assert.equal(mirror.swap(player.id, { day: DAY, mode: "easy", from: 0, to: 5, moves: 0 }).mirror.games.easy.swaps, 1);
assert.equal(mirror.view(player.id).locks.normal, "easy");
const before = service.getState(player.id).wallet.stardust;
const won = play(context, "easy");
assert.equal(won.status, "won");
assert.equal(won.reward, DEFAULT_MIRROR_SETTINGS.rewards.easy.base + won.left * DEFAULT_MIRROR_SETTINGS.rewards.easy.perSwap);
assert.equal(service.getState(player.id).wallet.stardust, before + won.reward);
assert.equal(mirror.view(player.id).locks.normal, null);
});
test("a normal game keeps its secret, refuses illegal swaps and pays once when the picture is whole", (t) => {
const context = game(t);
const { mirror, player, db, service } = context;
unlock(context);
const before = service.getState(player.id).wallet.stardust;
const view = mirror.start(player.id, { day: DAY, mode: "normal" }).mirror;
const normal = view.games.normal;
assert.deepEqual([normal.status, normal.cols, normal.rows, normal.swaps], ["playing", 4, 4, 0]);
// Ni l'illustration, ni la place des morceaux, ni la référence ne sortent avant la fin.
assert.equal(normal.cardId, null);
assert.equal(normal.par, null);
assert.ok(!JSON.stringify(view).includes('"pos"') && !JSON.stringify(view).includes('"start"'));
const state = stored(db, player.id, "normal");
assert.equal(normal.limit, state.par + DEFAULT_MIRROR_SETTINGS.margins.normal);
// Le contour vert du Normal : les cases déjà justes.
assert.deepEqual(normal.placed, state.pos.flatMap((cell, piece) => (cell === piece ? [cell] : [])));
assert.deepEqual(mirror.image(player.id, "normal").at, pieceAt(state.pos));
// Commencer deux fois rend la même partie.
assert.deepEqual(mirror.start(player.id, { day: DAY, mode: "normal" }).mirror.games.normal, normal);
refuses("MIRROR_SWAP_INVALID", () => mirror.swap(player.id, { day: DAY, mode: "normal", from: 0, to: 5, moves: 0 }));
refuses("MIRROR_INVALID", () => mirror.swap(player.id, { day: DAY, mode: "normal", from: 0, to: 16, moves: 0 }));
refuses("MIRROR_EXPIRED", () => mirror.swap(player.id, { day: "2026-11-27", mode: "normal", from: 0, to: 1, moves: 0 }));
// Un envoi en double (double clic) ne joue pas deux fois.
const once = mirror.swap(player.id, { day: DAY, mode: "normal", from: 0, to: 1, moves: 0 }).mirror.games.normal;
assert.equal(mirror.swap(player.id, { day: DAY, mode: "normal", from: 0, to: 1, moves: 0 }).mirror.games.normal.swaps, once.swaps);
assert.deepEqual(once.lastMove, [0, 1]);
const won = play(context, "normal");
assert.equal(won.status, "won");
assert.equal(won.reward, DEFAULT_MIRROR_SETTINGS.rewards.normal.base + won.left * DEFAULT_MIRROR_SETTINGS.rewards.normal.perSwap);
assert.ok(won.cardId && Number.isInteger(won.par) && won.placedCount === 16);
assert.equal(service.getState(player.id).wallet.stardust, before + won.reward);
refuses("MIRROR_FINISHED", () => mirror.swap(player.id, { day: DAY, mode: "normal", from: 0, to: 1, moves: won.moves }));
const history = service.getState(player.id).history.find((entry) => entry.type === "mirror_finished" && entry.details.mode === "normal");
assert.equal(history.details.stardust, won.reward);
assert.equal(mirror.summary(player.id).normal, "won");
});
test("the hard picture opens after the normal one and is the same for everyone", (t) => {
const context = game(t);
const { mirror, player, service, db } = context;
refuses("MIRROR_LOCKED", () => mirror.start(player.id, { day: DAY, mode: "hard" }));
refuses("MIRROR_LOCKED", () => mirror.start(player.id, { day: DAY, mode: "normal" }));
unlock(context, "hard");
const hard = mirror.start(player.id, { day: DAY, mode: "hard" }).mirror;
assert.deepEqual([hard.games.hard.cols, hard.games.hard.rows, hard.games.hard.placedOnHover], [5, 7, true]);
assert.deepEqual(hard.games.hard.placed, placedCells(stored(db, player.id, "hard").pos));
assert.equal(hard.number, 1);
const other = service.upsertPlayer({ discordId: "3", displayName: "Noé", avatarUrl: "" });
unlock(context, "hard", other);
mirror.start(other.id, { day: DAY, mode: "hard" });
assert.deepEqual(stored(db, other.id, "hard").start, stored(db, player.id, "hard").start);
assert.equal(db.prepare("SELECT COUNT(DISTINCT card_id) AS count FROM mirror_games WHERE mode = 'hard'").get().count, 1);
// Le Normal ne reprend jamais l'illustration du Difficile du jour.
const hardCard = db.prepare("SELECT card_id FROM mirror_days").get().card_id;
assert.ok(db.prepare("SELECT card_id FROM mirror_games WHERE mode = 'normal'").all().every((row) => row.card_id !== hardCard));
const summary = mirror.adminSummary();
assert.equal(summary.games.normal.won, 2);
assert.equal(summary.games.hard.started, 2);
assert.ok(summary.hard.cardId && summary.hard.par > 0);
});
test("a hard picture that shows the player's daily card waits for the daily card", (t) => {
const context = game(t);
const { mirror, player, service, db } = context;
service.todayPuzzle(player.id);
const hardCard = mirror.cards.database.transaction(() => mirror.ensureHardDay(DAY)).cardId;
db.prepare("UPDATE daily_attempts SET card_id = ? WHERE player_id = ?").run(hardCard, player.id);
unlock(context, "hard");
// Ni le Facile ni le Normal ne tirent la Carte du jour en cours, et pas deux fois la même illustration.
const cards = db.prepare("SELECT card_id FROM mirror_games WHERE mode IN ('easy', 'normal')").all().map((row) => row.card_id);
assert.ok(!cards.includes(hardCard) && new Set(cards).size === 2);
assert.equal(mirror.view(player.id).locks.hard, "daily");
refuses("MIRROR_DAILY_FIRST", () => mirror.start(player.id, { day: DAY, mode: "hard" }));
db.prepare("UPDATE daily_attempts SET status = 'lost' WHERE player_id = ?").run(player.id);
assert.equal(mirror.view(player.id).locks.hard, null);
});
test("a game without swaps left is lost and pays nothing", (t) => {
const context = game(t);
const { mirror, player, service } = context;
unlock(context);
const before = service.getState(player.id).wallet.stardust;
mirror.start(player.id, { day: DAY, mode: "normal" });
let view = mirror.view(player.id).games.normal;
while (view.status === "playing") view = wasteSwap(context, "normal");
assert.equal(view.status, "lost");
assert.equal(view.left, 0);
assert.ok(view.cardId && view.placedCount < 16);
assert.equal(service.getState(player.id).wallet.stardust, before);
// Une partie perdue ouvre quand même le Difficile.
assert.equal(mirror.view(player.id).locks.hard, null);
});
test("any companion of a ready daily team can help, once each, up to five per game", (t) => {
const context = game(t, { team: true });
const { mirror, player, db, service } = context;
unlock(context);
mirror.start(player.id, { day: DAY, mode: "normal" });
assert.deepEqual(mirror.view(player.id).team, []);
const team = readyTeam(context);
const helpers = mirror.view(player.id).team;
assert.equal(helpers.length, team.companions.length);
assert.equal(mirror.view(player.id).games.normal.helpsLeft, HELPERS_PER_GAME);
// Le modèle se voit jusqu'au premier mouvement.
assert.equal(mirror.view(player.id).games.normal.modelOpen, true);
assert.deepEqual(mirror.image(player.id, "normal", { model: true }).at, Array.from({ length: 16 }, (_, piece) => piece));
// Coups de main forcés pour l'essai : l'équipe affichée donne les compagnons ; leurs coups de main sont remplacés ici.
const ids = helpers.map((helper) => helper.cardId);
const withHelps = (list) => { mirror.teamHelpers = () => list.map((helps, index) => ({ cardId: ids[index], helps })); };
const reset = () => {
const state = stored(db, player.id, "normal");
state.used = {};
db.prepare("UPDATE mirror_games SET state_json = ? WHERE player_id = ? AND mode = 'normal'").run(JSON.stringify(state), player.id);
};
const moves = () => mirror.view(player.id).games.normal.moves;
const use = (cardId, help, cell) => mirror.useHelp(player.id, { day: DAY, mode: "normal", cardId, help, moves: moves(), cell }).mirror.games.normal;
const swapNormal = (from, to) => mirror.swap(player.id, { day: DAY, mode: "normal", from, to, moves: moves() }).mirror.games.normal;
refuses("MIRROR_HELPER_INVALID", () => use("starvoid-dragon-unknown", "bravoure"));
// Bravoure : un morceau mal placé va à sa place, sans compter de mouvement. Deux coups de main au plus par partie.
withHelps([["bravoure"], ["endurance"], ["fortune"]]);
const placedBefore = placedCount(stored(db, player.id, "normal").pos);
const placedOne = use(ids[0], "bravoure");
assert.ok(placedOne.placed.length > placedBefore && placedOne.swaps === 0 && placedOne.lastMove);
refuses("MIRROR_HELP_USED", () => use(ids[0], "bravoure"));
refuses("MIRROR_HELPER_INVALID", () => use(ids[1], "fortune"));
refuses("MIRROR_SWAP_INVALID", () => swapNormal(0, 5));
const free = swapNormal(0, 1);
// Après le premier mouvement, le modèle ne sort plus du serveur.
assert.equal(free.modelOpen, false);
refuses("MIRROR_MODEL_HIDDEN", () => mirror.image(player.id, "normal", { model: true }));
// Endurance : reprend le dernier mouvement, remet les morceaux et le rend.
const before = stored(db, player.id, "normal").pos;
const undone = use(ids[1], "endurance");
assert.equal(undone.swaps, free.swaps - 1);
assert.deepEqual(undone.lastMove, [0, 1]);
assert.deepEqual(stored(db, player.id, "normal").pos, swapCells(before, 0, 1));
assert.equal(undone.helpsLeft, HELPERS_PER_GAME - 2);
// Un coup de main par compagnon, jusqu'à HELPERS_PER_GAME par partie.
const full = stored(db, player.id, "normal");
full.used = Object.fromEntries(Array.from({ length: HELPERS_PER_GAME }, (_, index) => [`compagnon-${index}`, "fortune"]));
db.prepare("UPDATE mirror_games SET state_json = ? WHERE player_id = ? AND mode = 'normal'").run(JSON.stringify(full), player.id);
refuses("MIRROR_HELPS_EXHAUSTED", () => use(ids[2], "fortune"));
// Orientation : la vraie case du morceau choisi ; Équilibré : EXTRA_MOVES mouvements de plus.
reset();
withHelps([["orientation"], ["balanced"]]);
refuses("MIRROR_INVALID", () => use(ids[0], "orientation"));
const { pos } = stored(db, player.id, "normal");
assert.deepEqual(use(ids[0], "orientation", 6).hint, [6, pieceAt(pos)[6]]);
const ahead = mirror.view(player.id).games.normal;
const extra = use(ids[1], "balanced");
assert.deepEqual([extra.limit, extra.left], [ahead.limit + EXTRA_MOVES, ahead.left + EXTRA_MOVES]);
refuses("MIRROR_MODEL_HIDDEN", () => mirror.image(player.id, "normal", { model: true }));
// Fortune : le Trésor double le gain d'une image reconstituée.
reset();
withHelps([["fortune"]]);
assert.equal(use(ids[0], "fortune").treasure, true);
const before2 = service.getState(player.id).wallet.stardust;
const won = play(context, "normal");
assert.equal(won.status, "won");
const { base, perSwap } = DEFAULT_MIRROR_SETTINGS.rewards.normal;
assert.equal(won.reward, 2 * (base + perSwap * won.left));
assert.equal(service.getState(player.id).wallet.stardust, before2 + won.reward);
assert.equal(won.modelOpen, true);
});
test("a closed daily team gives no helper, and a deleted account leaves no game", (t) => {
const context = game(t);
const { mirror, player, db } = context;
mirror.start(player.id, { day: DAY, mode: "easy" });
assert.deepEqual(mirror.view(player.id).team, []);
mirror.forgetPlayer(player.id);
assert.equal(db.prepare("SELECT COUNT(*) AS count FROM mirror_games").get().count, 0);
});
test("a new day brings a new hard picture and a new normal game", (t) => {
const context = game(t);
const { mirror, player, clock, db } = context;
mirror.start(player.id, { day: DAY, mode: "easy" });
clock.now += DAY_MS;
const next = mirror.view(player.id);
assert.equal(next.day, "2026-11-29");
assert.equal(next.games.easy, null);
mirror.cards.database.transaction(() => { mirror.ensureHardDay(DAY); mirror.ensureHardDay("2026-11-29"); });
const cards = db.prepare("SELECT card_id FROM mirror_days ORDER BY day").all().map((row) => row.card_id);
assert.notEqual(cards[0], cards[1]);
});
test("only the development server resets the mirror games", (t) => {
const { mirror, player } = game(t);
refuses("NOT_FOUND", () => mirror.resetForTests(player.id));
});
test("the mirror API requires a session", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
t.after(() => handler.close?.());
for (const [method, path] of [["GET", ""], ["GET", "/image?mode=normal"], ["POST", "/start"], ["POST", "/swap"], ["POST", "/help"]]) {
const req = Readable.from(method === "POST" ? [Buffer.from("{}")] : []);
Object.assign(req, { method, url: `/api/cards/mirror${path}`, headers: { host: "localhost", origin: "http://localhost", "content-type": "application/json" }, socket: { remoteAddress: "127.0.0.1" } });
let status = 0;
await handler(req, { setHeader() {}, writeHead(code) { status = code; }, end() {} });
assert.equal(status, 401, path);
}
});