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>
447 lines
30 KiB
JavaScript
447 lines
30 KiB
JavaScript
/**
|
||
* @file Vérifie les règles, le service et l'API de la Carte du jour de Sokko TCG.
|
||
*/
|
||
|
||
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 sharp from "sharp";
|
||
import { createCardsApiHandler } from "../services/cards/api.js";
|
||
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
|
||
import { computeStreak, dailyCandidates, dailyCrop, dailyDayKey, dailyZoom, drawDailyPuzzle, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "../services/cards/daily.js";
|
||
import { answerClues, canUseDailyHint, compareClues, DAILY_HINTS, dailyCluesIssues, dailyHintCredits, loadDailyClues, nameShape, partialDescription, prepareDailyClues } from "../services/cards/daily-clues.js";
|
||
import { CardsDatabase } from "../services/cards/database.js";
|
||
import { CardsService } from "../services/cards/service.js";
|
||
import { dailyKnowledge, dailyVerdict } from "../website/src/features/cards/dailyKnowledge.js";
|
||
|
||
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
|
||
const ACTIVE_STATES = [{ collectionId: "primordial-nebula", active: true }, { collectionId: "dream-arcade", active: false }];
|
||
const catalog = buildPublishedCatalog(baseCatalog, { variations: [], collectionStates: ACTIVE_STATES, dropRates: [{ collectionId: "primordial-nebula", rarityWeights: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 } }] });
|
||
|
||
test("the daily day changes at midnight in Paris, in winter and in summer", () => {
|
||
assert.equal(dailyDayKey(Date.parse("2026-11-13T22:59:59Z")), "2026-11-13");
|
||
assert.equal(dailyDayKey(Date.parse("2026-11-13T23:00:00Z")), "2026-11-14");
|
||
assert.equal(dailyDayKey(Date.parse("2026-07-01T21:59:59Z")), "2026-07-01");
|
||
assert.equal(dailyDayKey(Date.parse("2026-07-01T22:00:00Z")), "2026-07-02");
|
||
assert.equal(nextDailyAt(Date.parse("2026-11-13T12:00:00Z")), Date.parse("2026-11-13T23:00:00Z"));
|
||
// Passage à l'heure d'été le 29 mars 2026 : le minuit suivant est à 22 h UTC.
|
||
assert.equal(nextDailyAt(Date.parse("2026-03-29T12:00:00Z")), Date.parse("2026-03-29T22:00:00Z"));
|
||
assert.equal(nextDailyAt(Date.parse("2026-10-25T12:00:00Z")), Date.parse("2026-10-25T23:00:00Z"));
|
||
assert.equal(shiftDayKey("2026-03-01", -1), "2026-02-28");
|
||
assert.equal(shiftDayKey("2026-12-31", 1), "2027-01-01");
|
||
});
|
||
|
||
test("the daily streak counts consecutive won days up to today or yesterday", () => {
|
||
assert.equal(computeStreak([], "2026-11-13"), 0);
|
||
assert.equal(computeStreak(["2026-11-11", "2026-11-12", "2026-11-13"], "2026-11-13"), 3);
|
||
assert.equal(computeStreak(["2026-11-11", "2026-11-12"], "2026-11-13"), 2);
|
||
assert.equal(computeStreak(["2026-11-10", "2026-11-12"], "2026-11-13"), 1);
|
||
assert.equal(computeStreak(["2026-11-11"], "2026-11-13"), 0);
|
||
});
|
||
|
||
test("the daily card comes from an open collection and avoids recent cards", () => {
|
||
const candidates = dailyCandidates(catalog);
|
||
assert.ok(candidates.length > 0);
|
||
assert.ok(candidates.every((item) => item.collectionId === "primordial-nebula"));
|
||
const first = drawDailyPuzzle(catalog, [], () => 0);
|
||
assert.equal(first.cardId, candidates[0].id);
|
||
assert.deepEqual([first.focusX, first.focusY], [20, 20]);
|
||
const last = drawDailyPuzzle(catalog, [], (max) => max - 1);
|
||
assert.deepEqual([last.focusX, last.focusY], [80, 80]);
|
||
assert.equal(drawDailyPuzzle(catalog, [candidates[0].id], () => 0).cardId, candidates[1].id);
|
||
// Quand toutes les cartes sont récentes, le tirage reprend sur toute la liste.
|
||
assert.equal(drawDailyPuzzle(catalog, candidates.map((item) => item.id), () => 0).cardId, candidates[0].id);
|
||
assert.equal(drawDailyPuzzle({ ...catalog, collections: catalog.collections.map((item) => ({ ...item, active: false })) }, [], () => 0), null);
|
||
// Une carte encore sans illustration n'est jamais tirée.
|
||
const withoutImage = { ...catalog, cards: catalog.cards.map((item) => item.id === candidates[0].id ? { ...item, image: null } : item) };
|
||
assert.ok(!dailyCandidates(withoutImage).some((item) => item.id === candidates[0].id));
|
||
});
|
||
|
||
test("the daily zoom loosens with each wrong guess", () => {
|
||
assert.equal(dailyZoom(0, false), 6);
|
||
assert.equal(dailyZoom(5, false), 1.15);
|
||
assert.equal(dailyZoom(9, false), 1.15);
|
||
assert.equal(dailyZoom(2, true), 1);
|
||
});
|
||
|
||
const clues = loadDailyClues();
|
||
const cardNamed = (name) => baseCatalog.cards.find((item) => item.name === name);
|
||
const shown = (parts) => parts.map((part) => (part.hidden ? "▒" : part.text)).join("");
|
||
|
||
test("every card of the catalog has a daily subject and a theme, and no subject holds too many cards", () => {
|
||
assert.deepEqual(dailyCluesIssues(baseCatalog, clues), []);
|
||
const incomplete = dailyCluesIssues({ cards: [...baseCatalog.cards, { id: "new-card", name: "Chose Inconnue" }] }, clues);
|
||
assert.deepEqual(incomplete, ["new-card: no subject", "new-card: no theme for « Chose Inconnue »"]);
|
||
assert.deepEqual(dailyCluesIssues({ cards: baseCatalog.cards.slice(1) }, clues), [`${baseCatalog.cards[0].id}: unknown card`]);
|
||
});
|
||
|
||
test("a daily theme comes from the words of the name, the subject only by default", () => {
|
||
const theme = (name) => clues.themeLabels.get(clues.themeOf(name));
|
||
assert.equal(theme("Renardeau des Congères"), "Hiver");
|
||
assert.equal(theme("Renardeau des Neiges Astrales"), "Hiver");
|
||
// « Voie lactée » et « Îles réunies » se lisent en entier ; « Astral » cède devant un mot plus parlant.
|
||
assert.equal(theme("Panda de la Voie Lactée"), "Cosmos");
|
||
assert.equal(theme("Sapin des Îles Réunies"), "Fête");
|
||
assert.equal(theme("Encrier Astral"), "Cosmos");
|
||
assert.equal(theme("Constellation du Loup"), "Lumière");
|
||
assert.equal(theme("Premier Croissant"), "Lune");
|
||
const content = { subjects: [{ id: "animal", label: "Animal", phrase: "un animal" }], themes: [{ id: "one", label: "Un", words: ["lune"] }, { id: "two", label: "Deux", words: ["Lune"] }], compoundSubjects: [], cards: {} };
|
||
assert.throws(() => prepareDailyClues(content), /already belongs to one/);
|
||
assert.throws(() => prepareDailyClues({ ...content, themes: [], subjects: [{ id: "animal/oiseau", label: "Oiseau" }] }), /has no parent animal/);
|
||
assert.throws(() => prepareDailyClues({ ...content, themes: [], cards: { card: { subject: "objet" } } }), /unknown subject objet/);
|
||
const subject = (extra) => prepareDailyClues({ ...content, themes: [], subjects: [{ id: "animal", label: "Animal", ...extra }] });
|
||
assert.throws(() => subject({ phrase: "animal" }), /needs a phrase/);
|
||
assert.throws(() => subject({ phrase: "un animal", sentences: { same: "C’est {subject}" } }), /needs sentences/);
|
||
});
|
||
|
||
test("a daily guess shows the common part of the subject and the theme, never the rest of the answer", () => {
|
||
const answer = cardNamed("Renardeau des Congères");
|
||
const compare = (name) => {
|
||
const { subject, theme } = compareClues(clues, answer, cardNamed(name));
|
||
return { subject: { common: subject.common.map((step) => step.label), different: subject.different?.label ?? null }, theme };
|
||
};
|
||
assert.deepEqual(compare("Épée du Socle Ancien"), { subject: { common: [], different: "Objet" }, theme: { label: "Combat", span: [0, 4], same: false } });
|
||
assert.deepEqual(compare("Loutre Pilote du Bateau du Ciel").subject, { common: ["Animal", "Mammifère"], different: "Mustélidé" });
|
||
assert.deepEqual(compare("Loup des Aurores").subject, { common: ["Animal", "Mammifère", "Canidé"], different: null });
|
||
// Une espèce sans branche s'arrête à « Mammifère » : rien ne dit que la réponse va plus loin.
|
||
assert.deepEqual(compare("Phoque des Glaces Lunaires"), { subject: { common: ["Animal", "Mammifère"], different: null }, theme: { label: "Hiver", span: [11, 17], same: true } });
|
||
// Une carte sans indices reste jouable, sans comparaison.
|
||
assert.deepEqual(compareClues(clues, answer, { id: "new-card", name: "Chose Inconnue" }), { subject: { common: [], different: null }, theme: null });
|
||
});
|
||
|
||
test("the partial description and the name shape hide words without sending them", () => {
|
||
const hedgehog = cardNamed("Hérisson à la Guirlande");
|
||
assert.equal(shown(partialDescription(hedgehog)), "En voulant aider à décorer le sapin, il s'est emmêlé dans la ▒.");
|
||
assert.equal(shown(nameShape("Renardeau des Neiges Astrales")), "▒ des ▒ ▒");
|
||
assert.equal(shown(nameShape("L'Échange de l'Aube")), "L'▒ de l'▒");
|
||
assert.ok(nameShape(hedgehog.name).filter((part) => part.hidden).every((part) => Object.keys(part).join() === "hidden"));
|
||
for (const card of baseCatalog.cards) assert.ok(partialDescription(card).some((part) => part.text) && nameShape(card.name).some((part) => part.hidden), card.id);
|
||
});
|
||
|
||
test("what a player learned adds up, whatever the order of the guesses", async () => {
|
||
const content = JSON.parse(await readFile("website/public/data/site.json", "utf8")).cards.daily;
|
||
const answer = cardNamed("Petit Tsuchinoko des Herbes Rouges");
|
||
const guesses = (...names) => names.map((name) => compareClues(clues, answer, cardNamed(name)));
|
||
const verdict = (...names) => dailyVerdict(guesses(...names), content).map((part) => part.text).join("");
|
||
const umbrella = "Parapluie à l'Œil Rieur";
|
||
// Un essai moins bon n'efface rien : la famille écartée n'apprend plus rien une fois la bonne connue.
|
||
assert.deepEqual(dailyKnowledge(guesses(umbrella, "Loup des Aurores")), { path: ["Créature fantastique", "Yokai"], ruledOut: [], theme: null, ruledOutThemes: ["Mystère", "Lumière"] });
|
||
assert.deepEqual(dailyKnowledge(guesses("Loup des Aurores", "Dragon du Néant Étoilé")).ruledOut, ["Dragon"]);
|
||
assert.equal(dailyKnowledge(guesses("Loup des Aurores"), "Plante").theme, "Plante");
|
||
assert.equal(dailyKnowledge(guesses("Esprit du Cèdre Creux")).theme, "Plante");
|
||
assert.equal(verdict(umbrella), "C’est bien un yokai.");
|
||
assert.equal(verdict("Dragon du Néant Étoilé"), "C’est bien une créature fantastique, mais pas un dragon.");
|
||
assert.equal(verdict("Loup des Aurores"), "Sa famille n’est pas inspirée d’un animal réel.");
|
||
assert.equal(verdict(umbrella, "Loup des Aurores"), "Sa famille n’est pas inspirée d’un animal réel : vous le saviez déjà.");
|
||
assert.equal(verdict("Épée du Socle Ancien", "Dragon du Néant Étoilé", umbrella), "C’est bien un yokai.");
|
||
const fox = compareClues(clues, cardNamed("Renardeau des Congères"), cardNamed("Manchot des Glaces Étoilées"));
|
||
assert.equal(dailyVerdict([fox], content).map((part) => part.text).join(""), "Sa famille est bien inspirée d’un animal réel, mais pas d’un oiseau.");
|
||
assert.deepEqual(dailyVerdict([{ subject: { common: [], different: null }, theme: null }], content), []);
|
||
});
|
||
|
||
test("a wrong daily guess earns one hint of the player's choice", () => {
|
||
assert.equal(dailyHintCredits(0, 0), 0);
|
||
assert.equal(dailyHintCredits(3, 1), 2);
|
||
assert.equal(dailyHintCredits(6, 0), DAILY_HINTS.length);
|
||
assert.equal(canUseDailyHint("album", 0, []), false);
|
||
assert.equal(canUseDailyHint("album", 1, []), true);
|
||
assert.equal(canUseDailyHint("album", 2, ["album"]), false);
|
||
assert.equal(canUseDailyHint("collection", 1, ["album"]), false);
|
||
// Chaque indice est ouvert dès le premier essai raté : le joueur choisit l'ordre.
|
||
for (const hint of DAILY_HINTS) assert.equal(canUseDailyHint(hint, 1, []), true, hint);
|
||
// Un thème déjà trouvé par un essai n'est plus un indice.
|
||
assert.equal(canUseDailyHint("theme", 3, [], ["theme"]), false);
|
||
assert.equal(canUseDailyHint("rarity", 6, []), false);
|
||
assert.equal(canUseDailyHint("unknown", 6, []), false);
|
||
});
|
||
|
||
function dailyService(start = Date.parse("2026-11-13T09:00:00Z"), random = () => 0) {
|
||
const clock = { now: start };
|
||
const database = new CardsDatabase(":memory:");
|
||
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random });
|
||
const admin = service.upsertPlayer({ discordId: "daily-admin", displayName: "Admin", isAdmin: true });
|
||
const player = service.upsertPlayer({ discordId: "daily-player", displayName: "Player" });
|
||
const wrongCards = () => {
|
||
const answer = service.todayPuzzle(player.id).cardId;
|
||
return service.catalog.cards.filter((item) => item.collectionId === "primordial-nebula" && item.id !== answer).map((item) => item.id);
|
||
};
|
||
return { clock, database, service, admin, player, wrongCards };
|
||
}
|
||
|
||
test("the daily crop keeps the visible part of the illustration around the focus point", () => {
|
||
assert.deepEqual(dailyCrop(800, 800, { x: 20, y: 20 }, 6), { left: 133, top: 133, width: 133, height: 133 });
|
||
assert.deepEqual(dailyCrop(800, 800, { x: 100, y: 0 }, 4.2), { left: 610, top: 0, width: 190, height: 190 });
|
||
assert.deepEqual(dailyCrop(640, 640, { x: 50, y: 80 }, 1.15), { left: 42, top: 66, width: 557, height: 557 });
|
||
assert.deepEqual(dailyCrop(800, 800, { x: 20, y: 20 }, 1), { left: 0, top: 0, width: 800, height: 800 });
|
||
});
|
||
|
||
test("each player draws a daily card on the first visit and the answer stays hidden while playing", () => {
|
||
const { service, admin, player, database } = dailyService();
|
||
// Le tableau de bord résume la quête sans tirer de carte : seul le passage par la Carte du jour en tire une.
|
||
assert.equal(service.getState(player.id).daily.status, "playing");
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts").get().count, 0);
|
||
const daily = service.getDaily(player.id);
|
||
assert.equal(daily.day, "2026-11-13");
|
||
assert.equal(daily.number, 1);
|
||
assert.equal(daily.status, "playing");
|
||
assert.equal(daily.zoom, 6);
|
||
assert.equal(daily.maxGuesses, MAX_DAILY_GUESSES);
|
||
assert.equal(daily.reward, 10);
|
||
assert.equal(daily.answerCardId, null);
|
||
// Les mots de recherche couvrent toutes les cartes proposables : ils ne désignent pas la réponse.
|
||
const { searchWords, ...hiddenAnswer } = daily;
|
||
assert.deepEqual(searchWords["starlit-ice-penguin"], ["pingouin", "oiseau"]);
|
||
assert.equal(Object.keys(searchWords).some((cardId) => service.index.cards.get(cardId).collectionId === "dream-arcade"), false);
|
||
assert.ok(!JSON.stringify(hiddenAnswer).includes(service.todayPuzzle(player.id).cardId));
|
||
assert.deepEqual(daily.hints, []);
|
||
assert.equal(daily.hintCredits, 0);
|
||
assert.deepEqual(daily.hintChoices.map((choice) => choice.available), [false, false, false, false, false]);
|
||
// Le point de zoom reste au serveur, qui n'envoie que la zone visible de l'illustration.
|
||
assert.equal(daily.focus, undefined);
|
||
assert.deepEqual(service.dailyImage(player.id).focus, { x: 20, y: 20 });
|
||
assert.equal(daily.nextAt, Date.parse("2026-11-13T23:00:00Z"));
|
||
assert.ok(daily.collectionIds.includes("primordial-nebula"));
|
||
assert.ok(!daily.collectionIds.includes("dream-arcade"));
|
||
assert.equal(service.getDaily(admin.id).day, daily.day);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_days").get().count, 1);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts").get().count, 2);
|
||
// Ouvrir la page tire une carte sans jouer : l'administration ne compte que les joueurs qui ont proposé une carte.
|
||
assert.deepEqual(service.getAdminDashboard(admin.id).daily, { day: "2026-11-13", number: 1, players: 0, winners: 0 });
|
||
assert.equal(service.getState(player.id).daily.status, "playing");
|
||
});
|
||
|
||
test("players get different daily cards, so a shared answer does not help", () => {
|
||
let draw = 0;
|
||
const { service, admin, player } = dailyService(undefined, (max) => (draw++ * 7) % max);
|
||
const mine = service.todayPuzzle(player.id).cardId;
|
||
const theirs = service.todayPuzzle(admin.id).cardId;
|
||
assert.notEqual(mine, theirs);
|
||
assert.equal(service.todayPuzzle(player.id).cardId, mine);
|
||
assert.equal(service.guessDaily(player.id, { day: "2026-11-13", cardId: theirs }).daily.status, "playing");
|
||
});
|
||
|
||
test("wrong daily guesses unzoom the card until the player runs out of guesses", () => {
|
||
const { service, player, wrongCards } = dailyService();
|
||
const [first, ...others] = wrongCards();
|
||
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: first });
|
||
assert.deepEqual({ status: state.daily.status, guessCount: state.daily.guessCount }, { status: "playing", guessCount: 1 });
|
||
assert.equal(daily.guesses.length, 1);
|
||
assert.equal(daily.guesses[0].correct, false);
|
||
assert.ok(Array.isArray(daily.guesses[0].subject.common));
|
||
assert.equal(typeof daily.guesses[0].theme.same, "boolean");
|
||
assert.equal(daily.zoom, 4.2);
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: first }), (error) => error.code === "DAILY_GUESS_REPEATED");
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: "unknown-card" }), (error) => error.code === "DAILY_GUESS_INVALID");
|
||
const closedCard = service.catalog.cards.find((item) => item.collectionId === "dream-arcade");
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: closedCard.id }), (error) => error.code === "DAILY_GUESS_INVALID");
|
||
assert.throws(() => service.guessDaily(player.id, { day: "13/11/2026", cardId: others[0] }), (error) => error.code === "DAILY_GUESS_INVALID");
|
||
let last;
|
||
for (const cardId of others.slice(0, MAX_DAILY_GUESSES - 1)) last = service.guessDaily(player.id, { day: "2026-11-13", cardId }).daily;
|
||
assert.equal(last.status, "lost");
|
||
assert.equal(last.zoom, 1);
|
||
assert.equal(last.earned, 0);
|
||
assert.equal(last.answerCardId, service.todayPuzzle(player.id).cardId);
|
||
// La réponse détaillée n'arrive qu'avec la fin de partie.
|
||
assert.equal(daily.answerClues, null);
|
||
assert.deepEqual(last.answerClues, answerClues(clues, service.index.cards.get(last.answerCardId)));
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: others.at(-1) }), (error) => error.code === "DAILY_FINISHED");
|
||
assert.equal(service.getState(player.id).wallet.stardust, 0);
|
||
});
|
||
|
||
test("a player flips the daily hints in the order of their choice, for free", () => {
|
||
const { clock, service, player, wrongCards } = dailyService();
|
||
const day = "2026-11-13";
|
||
const flip = (hint) => service.useDailyHint(player.id, { day, hint });
|
||
const others = wrongCards();
|
||
const puzzle = service.todayPuzzle(player.id);
|
||
const answer = service.index.cards.get(puzzle.cardId);
|
||
assert.throws(() => flip("album"), (error) => error.code === "DAILY_HINT_LOCKED");
|
||
assert.throws(() => flip("answer"), (error) => error.code === "DAILY_HINT_INVALID");
|
||
assert.throws(() => service.useDailyHint(player.id, { day: "demain", hint: "album" }), (error) => error.code === "DAILY_HINT_INVALID");
|
||
assert.deepEqual(service.guessDaily(player.id, { day, cardId: others[0] }).daily.hintChoices.filter((choice) => choice.available).map((choice) => choice.id).filter((id) => id !== "theme"), ["album", "collection", "shape", "page"]);
|
||
// La possession est celle du tirage : une carte reçue pendant la partie ne change pas l'indice.
|
||
const edition = service.catalog.editions.find((item) => item.cardId === answer.id);
|
||
service.db.prepare("INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, 0)").run(player.id, edition.id);
|
||
const album = flip("album");
|
||
assert.deepEqual(album.hints, [{ id: "album", value: false }]);
|
||
assert.equal(album.hintCredits, 0);
|
||
assert.equal(album.guesses.length, 1);
|
||
assert.deepEqual(flip("album").hints, album.hints);
|
||
assert.throws(() => flip("collection"), (error) => error.code === "DAILY_HINT_LOCKED");
|
||
for (const cardId of others.slice(1, 4)) service.guessDaily(player.id, { day, cardId });
|
||
assert.equal(service.getDaily(player.id).hintCredits, 3);
|
||
flip("shape");
|
||
flip("page");
|
||
const view = flip("collection");
|
||
assert.deepEqual(view.hints.map((hint) => hint.id), ["album", "shape", "page", "collection"]);
|
||
assert.equal(view.hints.at(-1).value, answer.collectionId);
|
||
assert.deepEqual(view.hints[1].value, nameShape(answer.name));
|
||
assert.ok(!JSON.stringify(view).includes(answer.id));
|
||
const won = service.guessDaily(player.id, { day, cardId: answer.id }).daily;
|
||
assert.equal(won.hints.length, 4);
|
||
assert.equal(won.earned, 10);
|
||
assert.equal(won.hintCredits, 0);
|
||
assert.throws(() => flip("theme"), (error) => error.code === "DAILY_FINISHED");
|
||
clock.now = Date.parse("2026-11-13T23:00:00Z");
|
||
assert.throws(() => flip("theme"), (error) => error.code === "DAILY_EXPIRED");
|
||
});
|
||
|
||
test("the theme hint names the theme of the answer, unless a guess already found it", () => {
|
||
const day = "2026-11-13";
|
||
const play = (sameTheme) => {
|
||
const { service, player, wrongCards } = dailyService();
|
||
const themeOf = (cardId) => clues.themeOf(service.index.cards.get(cardId).name);
|
||
const theme = themeOf(service.todayPuzzle(player.id).cardId);
|
||
const others = wrongCards().filter((cardId) => themeOf(cardId) !== theme);
|
||
const guesses = sameTheme ? [wrongCards().find((cardId) => themeOf(cardId) === theme), ...others] : others;
|
||
let daily;
|
||
for (const cardId of guesses.slice(0, 3)) daily = service.guessDaily(player.id, { day, cardId }).daily;
|
||
return { service, player, others, choice: daily.hintChoices.find((item) => item.id === "theme"), flip: () => service.useDailyHint(player.id, { day, hint: "theme" }), label: clues.themeLabels.get(theme) };
|
||
};
|
||
const unknown = play(false);
|
||
assert.deepEqual(unknown.choice, { id: "theme", known: false, available: true });
|
||
assert.deepEqual(unknown.flip().hints, [{ id: "theme", value: unknown.label }]);
|
||
const found = play(true);
|
||
assert.deepEqual(found.choice, { id: "theme", known: true, available: false });
|
||
assert.throws(found.flip, (error) => error.code === "DAILY_HINT_LOCKED");
|
||
// Le crédit que le thème aurait pris n'est pas annoncé quand il ne reste rien à retourner.
|
||
for (const cardId of found.others.slice(2, 4)) found.service.guessDaily(found.player.id, { day, cardId });
|
||
for (const hint of ["album", "collection", "page", "shape"]) found.service.useDailyHint(found.player.id, { day, hint });
|
||
assert.equal(found.service.getDaily(found.player.id).hintCredits, 0);
|
||
});
|
||
|
||
test("games that had flipped the former rarity hint get their hint back", () => {
|
||
const { service, player, database } = dailyService();
|
||
service.todayPuzzle(player.id);
|
||
database.db.prepare("UPDATE daily_attempts SET hints_json = '[\"album\",\"rarity\",\"page\"]'").run();
|
||
database.db.prepare("DELETE FROM schema_migrations WHERE version = 27").run();
|
||
database.migrate();
|
||
assert.equal(database.db.prepare("SELECT hints_json FROM daily_attempts").get().hints_json, '["album","page"]');
|
||
});
|
||
|
||
test("a daily game drawn before the hints reads the ownership in the collection", () => {
|
||
const { service, player, wrongCards } = dailyService();
|
||
const answer = service.todayPuzzle(player.id).cardId;
|
||
service.db.prepare("UPDATE daily_attempts SET owned = NULL").run();
|
||
const edition = service.catalog.editions.find((item) => item.cardId === answer);
|
||
service.db.prepare("INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, 0)").run(player.id, edition.id);
|
||
service.guessDaily(player.id, { day: "2026-11-13", cardId: wrongCards()[0] });
|
||
assert.deepEqual(service.useDailyHint(player.id, { day: "2026-11-13", hint: "album" }).hints, [{ id: "album", value: true }]);
|
||
});
|
||
|
||
test("finding the daily card credits the reward once and records it in the player history", () => {
|
||
const { service, admin, player, wrongCards } = dailyService();
|
||
service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: 25 });
|
||
const answer = service.todayPuzzle(player.id).cardId;
|
||
service.guessDaily(player.id, { day: "2026-11-13", cardId: wrongCards()[0] });
|
||
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: answer });
|
||
assert.equal(daily.status, "won");
|
||
assert.equal(daily.earned, 25);
|
||
assert.equal(daily.streak, 1);
|
||
assert.equal(daily.zoom, 1);
|
||
assert.equal(daily.answerCardId, answer);
|
||
assert.equal(state.wallet.stardust, 25);
|
||
assert.deepEqual(state.history.find((entry) => entry.type === "daily_won"), { type: "daily_won", entityId: "2026-11-13", details: { number: 1, cardId: answer, guesses: 2, stardust: 25 }, createdAt: Date.parse("2026-11-13T09:00:00Z") });
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: answer }), (error) => error.code === "DAILY_FINISHED");
|
||
assert.equal(service.getState(player.id).wallet.stardust, 25);
|
||
assert.deepEqual(service.getAdminDashboard(admin.id).daily, { day: "2026-11-13", number: 1, players: 1, winners: 1 });
|
||
// La récompense de la Carte du jour n'est pas une action d'administration.
|
||
assert.ok(!service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "daily_won"));
|
||
assert.throws(() => service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: -1 }), /Carte du jour/);
|
||
});
|
||
|
||
test("a new daily card arrives at midnight in Paris and the streak continues", () => {
|
||
const { clock, service, player } = dailyService();
|
||
const firstAnswer = service.todayPuzzle(player.id).cardId;
|
||
service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer });
|
||
clock.now = Date.parse("2026-11-13T23:00:00Z");
|
||
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer }), (error) => error.code === "DAILY_EXPIRED");
|
||
const daily = service.getDaily(player.id);
|
||
assert.equal(daily.day, "2026-11-14");
|
||
assert.equal(daily.number, 2);
|
||
assert.equal(daily.status, "playing");
|
||
assert.equal(daily.streak, 1);
|
||
const secondAnswer = service.todayPuzzle(player.id).cardId;
|
||
assert.notEqual(secondAnswer, firstAnswer);
|
||
assert.equal(service.guessDaily(player.id, { day: "2026-11-14", cardId: secondAnswer }).daily.streak, 2);
|
||
});
|
||
|
||
test("deleting an account erases its daily games", () => {
|
||
const { service, player, database } = dailyService();
|
||
service.guessDaily(player.id, { day: "2026-11-13", cardId: service.todayPuzzle(player.id).cardId });
|
||
service.deleteAccount(player.id);
|
||
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts WHERE player_id = ?").get(player.id).count, 0);
|
||
});
|
||
|
||
function mockRequest({ method = "GET", path, body, headers = {} }) {
|
||
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
|
||
req.method = method;
|
||
req.url = path;
|
||
req.headers = { host: "localhost:5173", ...headers };
|
||
req.socket = { remoteAddress: "127.0.0.1" };
|
||
return req;
|
||
}
|
||
|
||
async function call(handler, options) {
|
||
const response = { status: 0, headers: {}, chunks: [] };
|
||
const res = {
|
||
setHeader(name, value) { response.headers[name.toLowerCase()] = value; },
|
||
writeHead(status, headers = {}) {
|
||
response.status = status;
|
||
for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value;
|
||
},
|
||
end(value = "") { response.chunks.push(Buffer.from(value)); }
|
||
};
|
||
await handler(mockRequest(options), res);
|
||
response.raw = Buffer.concat(response.chunks);
|
||
response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null;
|
||
return response;
|
||
}
|
||
|
||
test("the daily API requires a session, protects guesses and serves only the visible part of the image while playing", 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 path of ["/api/cards/daily", "/api/cards/daily/image"]) assert.equal((await call(handler, { path })).status, 401);
|
||
for (const path of ["/api/cards/daily/guesses", "/api/cards/daily/hints"]) assert.equal((await call(handler, { method: "POST", path, body: {} })).status, 401);
|
||
|
||
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
||
const cookie = login.headers["set-cookie"].split(";")[0];
|
||
const csrf = login.json.csrfToken;
|
||
const daily = await call(handler, { path: "/api/cards/daily", headers: { cookie } });
|
||
assert.equal(daily.status, 200);
|
||
assert.equal(daily.json.answerCardId, null);
|
||
|
||
const image = await call(handler, { path: "/api/cards/daily/image", headers: { cookie } });
|
||
assert.equal(image.status, 200);
|
||
assert.equal(image.headers["content-type"], "image/webp");
|
||
assert.equal(image.headers["cache-control"], "private, no-store");
|
||
assert.equal(image.headers["content-disposition"], undefined);
|
||
assert.equal(image.raw.subarray(8, 12).toString("ascii"), "WEBP");
|
||
const player = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get();
|
||
const answer = handler.service.todayPuzzle(player.id).cardId;
|
||
assert.ok(!JSON.stringify(image.headers).includes(answer));
|
||
// Pendant la partie, un morceau recadré de 720 px, jamais le fichier de l'illustration.
|
||
const original = await readFile(resolve("website/public", `.${handler.service.index.cards.get(answer).image}`));
|
||
assert.notDeepEqual(image.raw, original);
|
||
assert.equal((await sharp(image.raw).metadata()).width, 720);
|
||
|
||
const unprotected = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie }, body: { day: daily.json.day, cardId: answer } });
|
||
assert.equal(unprotected.status, 403);
|
||
const wrong = handler.service.catalog.cards.find((item) => item.id !== answer && daily.json.collectionIds.includes(item.collectionId)).id;
|
||
await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: wrong } });
|
||
assert.equal((await call(handler, { method: "POST", path: "/api/cards/daily/hints", headers: { cookie }, body: { day: daily.json.day, hint: "collection" } })).status, 403);
|
||
const hint = await call(handler, { method: "POST", path: "/api/cards/daily/hints", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, hint: "collection" } });
|
||
assert.equal(hint.status, 200);
|
||
assert.deepEqual(hint.json.daily.hints, [{ id: "collection", value: handler.service.index.cards.get(answer).collectionId }]);
|
||
const won = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
|
||
assert.equal(won.status, 200);
|
||
assert.equal(won.json.daily.status, "won");
|
||
assert.ok(won.json.state.history.some((entry) => entry.type === "daily_won"));
|
||
// La partie finie, l'illustration entière.
|
||
assert.deepEqual((await call(handler, { path: "/api/cards/daily/image", headers: { cookie } })).raw, original);
|
||
const again = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
|
||
assert.equal(again.status, 409);
|
||
assert.equal(again.json.error.code, "DAILY_FINISHED");
|
||
});
|