sokko-g/tests/nebula-cards-expeditions.test.mjs
Shinuwa 3720fd01f7 Rebuild the Expeditions page around one guided journey: one card, no roles, leave alone or open to a group, follow the trip, keep a Journal
An expedition now opens with a single card. Its creator leaves alone right away, or opens it to the Guild board with an invite link and launches it whenever they want; at the end of recruitment it leaves by itself, alone or as a group, and is never dissolved for lack of players. Stars no longer depend on the number of players, a player has one expedition at a time, and roles are gone: each card brings its stats and a team adds them up, so every requirement is its per-slot share times the number of slots.

The page follows the player's path: the offered destination card is revealed once in a modal, then Préparer shows the destinations (stat requirements, condition and dangers coloured for the chosen card, loot effects), a frame with the sent card in large size, its equipment slots and stats, and the duration and departure. Cards and commons are chosen in modals with sorts and highlighted current picks; tags get matching colours on the card and on equipment synergies. Once gone, the trip is shown with a progress bar and moving cards, the loot opens in a modal, and finished expeditions move to a Journal tab with the Grimoire.

Power commons get short power names of their own and show their exact effects on hover, a card holds one power at a time, and Coup de folie now draws the real requirements between 80 % and 130 % of the shown ones, revealed on return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:10:56 +01:00

483 lines
38 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : vérifie les données, les réglages et les règles pures des Expéditions Sokko TCG.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { test } from "node:test";
import { prepareVersionedCatalog } from "../services/cards/catalog.js";
import { DESTINATION_SPECIALTIES, loadExpeditionDestinations, validateExpeditionDestinations } from "../services/cards/expedition-content.js";
import {
applyHazards, cardPower, drawExpeditionDay, editionExpeditionData, efficiency, evaluateTeam, expectedLoot, maxLevel,
requirementsFor, resolveDayEntry, rollLoot, roundStochastic, scoreExpedition, splitPower, STAT_IDS, teamStats, upgradeCost, gainProgress,
equipmentBonus, LINEAGES, resonancesOf, teamSynergy, unlockedSlots, bonusLootPct, pickItems, HIDDEN_ITEMS, teamPowers, travelHours, rollRequirementFactor,
bonusLevel, levelCount, starsForLevel, planStats, vocationProfile, clampAllocation, allocationError, levelPoints, maxStatPoints
} from "../services/cards/expedition-rules.js";
import { drawCollectionCard } from "../services/cards/game-rules.js";
import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, readPath, validateExpeditionSettings
} from "../services/cards/expedition-settings.js";
import { EXPEDITION_SETTING_GROUPS, expeditionSettingLabel } from "../website/src/features/cards/admin/expeditionSettingFields.js";
import { expeditionsPending, guildQuests } from "../website/src/features/cards/guildQuests.js";
const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"));
const catalog = prepareVersionedCatalog(rawCatalog);
const destinationsPath = "services/cards/content/expedition-destinations.json";
const destinations = loadExpeditionDestinations(destinationsPath, catalog);
const destinationIds = destinations.map((destination) => destination.id);
const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinationIds);
const profile = (bravoure, endurance, fortune, orientation) => ({ bravoure, endurance, fortune, orientation });
// La Collection affiche les cartes dans l'ordre du catalogue : chaque collection va de la plus rare à la plus commune.
test("every collection lists its cards from the rarest to the most common", () => {
const rank = new Map(rawCatalog.rarities.map((rarity, index) => [rarity.id, index]));
const rarityOf = new Map(rawCatalog.editions.map((edition) => [edition.cardId, edition.rarity]));
for (const collection of rawCatalog.collections) {
const ranks = rawCatalog.cards.filter((card) => card.collectionId === collection.id).map((card) => rank.get(rarityOf.get(card.id)));
assert.ok(ranks.every((value, index) => index === 0 || value <= ranks[index - 1]), `${collection.id} : cartes de la plus rare à la plus commune`);
}
});
test("every catalog card carries expedition tags and every collection a profile", () => {
const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id));
const teamCards = rawCatalog.cards.filter((card) => card.kind !== "destination");
assert.ok(teamCards.every((card) => card.expedition.tags.length >= 1 && card.expedition.tags.every((tag) => tagIds.has(tag))));
assert.ok(rawCatalog.collections.every((collection) => STAT_IDS.reduce((sum, stat) => sum + collection.expedition.profile[stat], 0) === 100));
// Aucune étiquette inutilisée : le vocabulaire reste celui des cartes.
const used = new Set(teamCards.flatMap((card) => card.expedition.tags));
assert.deepEqual(rawCatalog.expeditionTags.filter((tag) => !used.has(tag.id)), []);
});
// Carte de destination : rare, sans données d'expédition, liée à une destination existante ; elle ne part jamais en équipe.
test("a destination card is a rare that unlocks a destination and never joins a team", () => {
// Les Courants de Lumière perdent leur carte du catalogue, remplacée par celle du test.
const freeDestination = "light-currents";
const withCard = (card, rarity = "rare") => {
const copy = structuredClone(rawCatalog);
copy.cards = copy.cards.filter((item) => item.destinationId !== freeDestination);
copy.editions = copy.editions.filter((edition) => copy.cards.some((item) => item.id === edition.cardId));
copy.cards.push({ id: "card-light-currents", collectionId: "watchers-logbooks", name: "Une destination", description: "Une destination.", kind: "destination", destinationId: freeDestination, ...card });
copy.editions.push({ id: "card-light-currents-standard", cardId: "card-light-currents", rarity, finishIds: ["standard"], promotional: false });
return copy;
};
const prepared = prepareVersionedCatalog(withCard({}));
assert.equal(editionExpeditionData(prepared, "card-light-currents-standard", 0, settings), null);
assert.ok(validateExpeditionDestinations(JSON.parse(JSON.stringify(destinations.map(({ ...item }) => item))), prepared));
assert.throws(() => prepareVersionedCatalog(withCard({}, "epic")), /must be rare/);
assert.throws(() => prepareVersionedCatalog(withCard({ expedition: { tags: ["theme:voyage"] } })), /never joins a team/);
assert.throws(() => prepareVersionedCatalog(withCard({ destinationId: undefined })), /needs a destinationId/);
assert.throws(() => validateExpeditionDestinations(destinations, prepareVersionedCatalog(withCard({ destinationId: "nowhere" }))), /unknown destination nowhere/);
});
test("catalog validation refuses broken expedition data", () => {
const unknownTag = structuredClone(rawCatalog);
unknownTag.cards[0].expedition.tags = ["theme:inconnu"];
assert.throws(() => prepareVersionedCatalog(unknownTag), /unknown expedition tag theme:inconnu/);
const noTags = structuredClone(rawCatalog);
delete noTags.cards[0].expedition;
assert.throws(() => prepareVersionedCatalog(noTags), /needs 1 to 8 expedition tags/);
const repeated = structuredClone(rawCatalog);
repeated.cards[0].expedition.tags = ["theme:voyage", "theme:voyage"];
assert.throws(() => prepareVersionedCatalog(repeated), /repeats an expedition tag/);
const badProfile = structuredClone(rawCatalog);
badProfile.cards[0].expedition.profile = profile(50, 50, 10, 0);
assert.throws(() => prepareVersionedCatalog(badProfile), /summing to 100/);
const noCollectionProfile = structuredClone(rawCatalog);
delete noCollectionProfile.collections[0].expedition;
assert.throws(() => prepareVersionedCatalog(noCollectionProfile), /needs an expedition profile/);
const badTagId = structuredClone(rawCatalog);
badTagId.expeditionTags.push({ id: "Voyage", label: "Voyage" });
assert.throws(() => prepareVersionedCatalog(badTagId), /family:name id/);
});
test("destinations order the four stats and stay satisfiable by rare or better cards", () => {
const visible = destinations.filter((destination) => !destination.hidden);
assert.equal(visible.length, 14);
assert.deepEqual(destinations.filter((destination) => destination.hidden).map((destination) => destination.id), ["crimson-passage", "lost-observatory"]);
// Chaque couple (stat principale, seconde stat) a au moins une destination : les profils restent variés.
assert.equal(new Set(visible.map((destination) => destination.stats.slice(0, 2).join("+"))).size, 12);
const broken = (change) => {
const copy = structuredClone(destinations);
change(copy[0]);
return () => validateExpeditionDestinations(copy, catalog);
};
assert.throws(broken((destination) => { destination.stats = ["bravoure", "bravoure", "fortune", "orientation"]; }), /order the four stats/);
assert.throws(broken((destination) => { destination.conditions = [{ type: "tag", tag: "personnage:ours" }]; }), /fewer than 3/);
assert.throws(broken((destination) => { destination.dangers[0].unlessTags = ["theme:inconnu"]; }), /known counter tags/);
assert.throws(broken((destination) => { destination.coverCardId = "missing"; }), /unknown cover card/);
assert.throws(() => validateExpeditionDestinations(destinations.map((destination) => ({ ...destination, hidden: true })), catalog), /visible destination/);
});
test("expedition settings merge stored values with defaults and validate bounds and cross rules", () => {
assert.equal(validateExpeditionSettings(settings, destinationIds), null);
assert.equal(settings.enabled, false);
assert.deepEqual(settings.destinations[destinationIds[0]], { active: true, weight: 1 });
// Champ manquant ou invalide : valeur par défaut, signalée ; clé inconnue : supprimée.
const invalid = [];
const merged = mergeExpeditionSettings({ power: { rare: 45, cap: "x" }, extra: 1, destinations: { [destinationIds[0]]: { active: false, weight: 3 }, gone: { active: true, weight: 1 } } }, destinationIds, (path) => invalid.push(path));
assert.equal(merged.power.rare, 45);
assert.equal(merged.power.cap, 100);
assert.deepEqual(invalid, ["power.cap"]);
assert.equal("extra" in merged, false);
assert.equal("gone" in merged.destinations, false);
assert.deepEqual(merged.destinations[destinationIds[0]], { active: false, weight: 3 });
// Chaque champ du schéma a une valeur par défaut valide.
for (const field of EXPEDITION_SETTINGS_SCHEMA) assert.notEqual(readPath(DEFAULT_EXPEDITION_SETTINGS, field.path), undefined, field.path);
const withChange = (path, value) => {
const copy = structuredClone(settings);
const keys = path.split(".");
keys.slice(0, -1).reduce((node, key) => node[key], copy)[keys.at(-1)] = value;
return copy;
};
assert.match(validateExpeditionSettings(withChange("day.destinationsPerDay", 0), destinationIds), /day\.destinationsPerDay/);
assert.match(validateExpeditionSettings(withChange("durations.hours", [6, 2, 12]), destinationIds), /croissantes/);
assert.match(validateExpeditionSettings(withChange("requirements.star3", [1, 2]), destinationIds), /3 entiers/);
assert.match(validateExpeditionSettings(withChange("score.successPct", 130), destinationIds), /Réussite < Triomphe/);
assert.match(validateExpeditionSettings(withChange("stars", { min: 4, max: 2 }), destinationIds), /étoile minimale/);
assert.match(validateExpeditionSettings(withChange("power.rare", 120), destinationIds), /plafond/);
assert.match(validateExpeditionSettings(withChange("destinations", { unknown: { active: true, weight: 1 } }), destinationIds), /inconnue/);
const next = withChange("loot.eclatsPerHourCents", 300);
next.destinations[destinationIds[1]].weight = 4;
assert.deepEqual(diffExpeditionSettings(settings, next), [
{ path: "loot.eclatsPerHourCents", previous: 200, next: 300 },
{ path: `destinations.${destinationIds[1]}.weight`, previous: 1, next: 4 }
]);
});
test("power grows with levels up to the shared cap and splits exactly by profile", () => {
assert.equal(cardPower("rare", 0, settings), 40);
assert.equal(cardPower("rare", 4, settings), 60);
assert.equal(cardPower("rare", 99, settings), 100);
assert.equal(cardPower("common", 3, settings), 0);
assert.deepEqual(["rare", "epic", "legendary", "mythic"].map((rarity) => maxLevel(rarity, settings)), [12, 9, 6, 3]);
assert.deepEqual(splitPower(40, profile(25, 25, 20, 30)), { bravoure: 10, endurance: 10, fortune: 8, orientation: 12 });
const odd = splitPower(55, profile(33, 33, 17, 17));
assert.equal(Object.values(odd).reduce((sum, value) => sum + value, 0), 55);
// Une mythique garde sa propre rareté, mais le profil et les étiquettes de sa carte.
const legendary = editionExpeditionData(catalog, "starvoid-dragon-standard", 0, settings);
assert.equal(legendary.power, 70);
assert.deepEqual(legendary.tags, ["personnage:dragon", "lieu:nebuleuse", "lieu:soleil"]);
assert.equal(editionExpeditionData(catalog, "dragon-constellation-standard", 0, settings), null);
});
test("requirements scale per slot, cards add their stats, hazards and conditions weigh on the score", () => {
const destination = destinations.find((item) => item.id === "light-currents");
// Une carte seule : la part d'une place ; un groupe : une part par place, Veilleur de la Guilde compris.
assert.deepEqual(requirementsFor(destination, 2, 1, settings), [
{ stat: "orientation", main: true, value: 11 },
{ stat: "bravoure", main: false, value: 10 }
]);
assert.deepEqual(requirementsFor(destination, 2, 4, settings).map((item) => item.value), [44, 40]);
// Pas de rôle : chaque carte apporte ses stats telles quelles.
const slot = { stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 12 }, tags: [], collectionId: "primordial-nebula" };
assert.deepEqual(teamStats([slot, slot]), { bravoure: 20, endurance: 20, fortune: 20, orientation: 24 });
// 12 h sans Endurance : −15 % ; Endurance suffisante : aucun malus. Danger non paré : −20 %, moins le bouclier.
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 0.85);
assert.equal(applyHazards({ bravoure: 10, endurance: 24, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 1);
const danger = { id: "d", label: "D", stat: "bravoure", unlessTags: ["theme:hiver"] };
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 8);
assert.equal(applyHazards({ bravoure: 10, endurance: 28, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 9);
assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: true }] }, settings).stats.bravoure, 10);
assert.equal(efficiency(0.5, settings), 0.5);
assert.equal(efficiency(1.5, settings), 1.25);
assert.equal(efficiency(3, settings), 1.5);
const requirements = [{ stat: "bravoure", main: true, value: 10 }, { stat: "fortune", main: false, value: 10 }];
const full = scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 } }, settings);
assert.equal(full.scorePct, 100);
assert.equal(full.tier, "success");
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 }, conditionMet: false }, settings).scorePct, 75);
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 40, fortune: 40 } }, settings).tier, "triumph");
assert.equal(scoreExpedition({ requirements, stats: { bravoure: 5, fortune: 5 } }, settings).tier, "struggle");
});
test("one more star never raises the score of the same team", () => {
const destination = destinations[0];
const entry = { condition: destination.conditions[0], dangers: destination.dangers };
// Équipe faible sur la stat principale, forte sur la seconde : sans la règle, 2 ★ ferait mieux que 1 ★.
const slots = [
{ stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, tags: [], collectionId: "primordial-nebula" },
{ stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, tags: [], collectionId: "primordial-nebula" }
];
const scores = [1, 2, 3, 4].map((stars) => evaluateTeam({ destination, entry, stars, durationIndex: 0, slots }, settings));
for (let index = 1; index < scores.length; index += 1) assert.ok(scores[index].scorePct <= scores[index - 1].scorePct);
assert.equal(scores[1].limitedByStars, 1);
});
test("loot is proportional to the chosen duration and rounds without changing its average", () => {
const short = expectedLoot({ hours: 2, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings);
const long = expectedLoot({ hours: 12, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings);
assert.equal(long.eclats / 12, short.eclats / 2);
assert.equal(short.eclats, 5.2);
// Fortune : +2 % par point moyen par place, plafonné ; destinations bonus : multiplicateur propre.
assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 20, slotCount: 2 }, settings).fortuneBonusPct, 20);
assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 200, slotCount: 2 }, settings).fortuneBonusPct, 50);
assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: 6 }, settings).eclats, 10);
assert.equal(roundStochastic(2.3, () => 0), 3);
assert.equal(roundStochastic(2.3, (max) => max - 1), 2);
assert.equal(roundStochastic(4, () => 0), 4);
assert.deepEqual(rollLoot({ eclats: 1.5, stardust: 0.2, cards: 5 }, settings, () => 0), { eclats: 2, stardust: 1, cards: settings.loot.maxCards });
});
// Paysage d'une destination : facultatif, toujours un WebP du dossier des destinations, et présent sur le disque.
test("destination landscapes point to existing images of their folder", async () => {
for (const destination of destinations.filter((item) => item.image)) await readFile(`website/public${destination.image}`);
await readFile("website/public/static/img/expeditions/brush-mask.webp");
const raw = JSON.parse(await readFile(destinationsPath, "utf8"));
assert.throws(() => validateExpeditionDestinations([{ ...raw[0], image: "/static/img/cards/other.webp" }, ...raw.slice(1)], catalog), /image must be/);
const linked = raw.findIndex((destination) => destination.rewardCollectionId);
const withSpecialty = raw.map((destination, index) => (index === linked ? { ...destination, specialty: ["eclats", "cards"] } : destination));
assert.throws(() => validateExpeditionDestinations(withSpecialty, catalog), /cannot have a specialty/);
const free = raw.findIndex((destination) => !destination.rewardCollectionId && !destination.hidden);
for (const specialty of ["eclats", [], ["eclats", "eclats"], ["eclats", "gold"], ["eclats", "stardust", "cards"]]) {
assert.throws(() => validateExpeditionDestinations(raw.map((destination, index) => (index === free ? { ...destination, specialty } : destination)), catalog), /one or two different values/);
}
// Une destination liée par collection : celle de sa carte de destination des paquets.
assert.deepEqual(raw.filter((destination) => destination.rewardCollectionId).map((destination) => [destination.id, destination.rewardCollectionId]).sort(),
[["cosmic-cloud-heart", "primordial-nebula"], ["level-isles", "dream-arcade"], ["reunited-isles-feast", "long-night"]]);
const crater = raw.findIndex((destination) => destination.id === "scale-crater");
assert.throws(() => validateExpeditionDestinations(raw.map((destination, index) => (index === crater ? { ...destination, specialty: undefined, rewardCollectionId: "long-night" } : destination)), catalog), /collection of the destination card/);
// Destinations non liées : chaque profil de butin possible une fois et une seule (chaque spécialité simple, chaque paire, une neutre).
const unlinked = raw.filter((destination) => !destination.hidden && !destination.rewardCollectionId);
const profiles = unlinked.map((destination) => (destination.specialty ? [...destination.specialty].sort().join("+") : "neutre")).sort();
const kinds = [...DESTINATION_SPECIALTIES].sort();
const pairs = kinds.flatMap((kind, index) => kinds.slice(index + 1).map((other) => `${kind}+${other}`));
assert.deepEqual(profiles, [...kinds, ...pairs, "neutre"].sort());
});
// Spécialités de butin : une récompense favorisée ×boostPct (les autres ×otherPct), ou deux ×pairBoostPct (les deux autres
// ×pairOtherPct), cartes de collection comprises ; rien sans spécialité. Une carte de collection suit les taux de rareté, puis
// favorise les manquantes.
test("destination specialties raise one or two rewards and lower the others", () => {
const loot = (specialty) => expectedLoot({ hours: 6, stars: 2, tier: "success", fortune: 0, slotCount: 2, specialty }, settings);
const neutral = loot(null);
const { boostPct, otherPct, pairBoostPct, pairOtherPct } = settings.specialty;
const ratio = (value, reference, pct) => Math.abs(value - reference * pct / 100) < 1e-9;
const single = loot(["eclats"]);
assert.ok(ratio(single.eclats, neutral.eclats, boostPct) && ratio(single.stardust, neutral.stardust, otherPct));
assert.ok(ratio(single.cards, neutral.cards, otherPct) && ratio(single.objects, neutral.objects, otherPct));
const pair = loot(["cards", "items"]);
assert.ok(ratio(pair.cards, neutral.cards, pairBoostPct) && ratio(pair.objects, neutral.objects, pairBoostPct));
assert.ok(ratio(pair.eclats, neutral.eclats, pairOtherPct) && ratio(pair.stardust, neutral.stardust, pairOtherPct));
// Une rareté tirée avec les taux de la collection, puis une carte pondérée : la manquante (b) pèse 200, la possédée (a) 100.
const mini = { collections: [{ id: "c", active: true, dropWeights: { rare: 1 } }], cards: [{ id: "a", collectionId: "c" }, { id: "b", collectionId: "c" }], editions: [{ id: "a1", cardId: "a", rarity: "rare" }, { id: "b1", cardId: "b", rarity: "rare" }] };
const weightOf = (edition) => (edition.id === "a1" ? 100 : 200);
assert.equal(drawCollectionCard(mini, "c", (max) => (max === 300 ? 99 : 0), { weightOf }), "a1");
assert.equal(drawCollectionCard(mini, "c", (max) => (max === 300 ? 100 : 0), { weightOf }), "b1");
assert.equal(drawCollectionCard({ ...mini, collections: [{ ...mini.collections[0], active: false }] }, "c", () => 0), null);
});
// La difficulté se tire avec les destinations : un niveau de chaque, puis la suite recommence. Un niveau donne les mêmes étoiles,
// qu'on parte seul ou en groupe.
test("each daily destination draws a difficulty level, one of each", () => {
assert.equal(levelCount(settings), 5);
assert.deepEqual([0, 1, 2, 3, 4].map((level) => starsForLevel(level, settings)), [1, 2, 3, 4, 5]);
assert.equal(starsForLevel(9, settings), settings.stars.max);
for (const random of [() => 0, (max) => max - 1, (max) => Math.floor(max / 2)]) {
assert.deepEqual(drawExpeditionDay(destinations, settings, [], random).map((entry) => entry.level).sort(), [0, 1, 2, 3]);
}
// Limité aux destinations débloquées : avec deux destinations, seulement les deux premiers niveaux.
const two = drawExpeditionDay(destinations, settings, [], (max) => max - 1, new Set(["light-currents", "great-void"]));
assert.deepEqual(two.map((entry) => entry.destinationId).sort(), ["great-void", "light-currents"]);
assert.deepEqual(two.map((entry) => entry.level).sort(), [0, 1]);
assert.deepEqual(drawExpeditionDay(destinations, settings, [], () => 0, new Set()), []);
const six = drawExpeditionDay(destinations, { ...settings, day: { ...settings.day, destinationsPerDay: 6 } }, [], () => 0).map((entry) => entry.level);
assert.deepEqual(six.slice(0, 5).sort(), [0, 1, 2, 3, 4]);
assert.deepEqual(six.slice(5), six.slice(0, 1));
// Une destination bonus garde son niveau toute la journée ; un tirage d'avant les niveaux prend celui de sa place.
assert.equal(bonusLevel("player:2026-11-15:5:great-void", settings), bonusLevel("player:2026-11-15:5:great-void", settings));
assert.ok(bonusLevel("player:2026-11-15:5:great-void", settings) < 5);
assert.equal(resolveDayEntry(destinations, { destinationId: destinations[0].id, conditionIndex: 0, dangerIndexes: [0, 0] }, 2).level, 2);
});
test("the day draw picks active visible destinations and avoids yesterday's when it can", () => {
const draw = drawExpeditionDay(destinations, settings, [], () => 0);
assert.equal(draw.length, 4);
assert.equal(new Set(draw.map((entry) => entry.destinationId)).size, 4);
const recent = draw.map((entry) => entry.destinationId);
const next = drawExpeditionDay(destinations, settings, recent, () => 0);
assert.ok(next.every((entry) => !recent.includes(entry.destinationId)));
// Destinations retirées ou de poids nul : jamais tirées.
const closed = structuredClone(settings);
for (const id of destinationIds.slice(1)) closed.destinations[id].active = false;
assert.deepEqual(drawExpeditionDay(destinations, closed, [destinationIds[0]], () => 0).map((entry) => entry.destinationId), [destinationIds[0]]);
// Le second danger diffère du premier quand la destination en a deux.
assert.ok(draw.every((entry) => entry.dangerIndexes[0] !== entry.dangerIndexes[1]));
const resolved = resolveDayEntry(destinations, draw[0]);
assert.equal(resolved.entry.dangers.length, 2);
assert.equal(resolveDayEntry(destinations, { destinationId: "missing", conditionIndex: 0, dangerIndexes: [0, 0] }), null);
});
test("every server setting has its label in the administration, and nothing else", () => {
const labelled = EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => field.path));
assert.deepEqual([...labelled].sort(), EXPEDITION_SETTINGS_SCHEMA.map((field) => field.path).sort());
assert.equal(expeditionSettingLabel(`destinations.${destinations[0].id}.weight`, destinations), `${destinations[0].name} · poids`);
});
test("the guild shows expeditions when open and flags them once a day or when one is back", () => {
const now = Date.parse("2026-11-15T10:00:00Z");
const summary = { enabled: true, running: 0, returned: 0, nextReturnAt: null, launchedToday: false, eligible: 3, busyEditions: [] };
assert.equal(expeditionsPending(summary, now), true);
assert.equal(expeditionsPending({ ...summary, launchedToday: true }, now), false);
// Une carte jouable suffit pour partir.
assert.equal(expeditionsPending({ ...summary, eligible: 1 }, now), true);
assert.equal(expeditionsPending({ ...summary, eligible: 0 }, now), false);
assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now + 1000 }, now), false);
assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now - 1000 }, now), true);
// Un groupe à rejoindre attend le joueur ; son propre groupe en formation ne déclenche pas le rappel quotidien.
assert.equal(expeditionsPending({ ...summary, launchedToday: true, joinableGroups: 1 }, now), true);
assert.equal(expeditionsPending({ ...summary, forming: 1 }, now), false);
// Fermées : la tuile disparaît, sauf tant qu'une expédition du joueur n'est pas terminée.
assert.deepEqual(guildQuests({ expeditions: { ...summary, enabled: false } }, now), []);
assert.equal(guildQuests({ expeditions: { ...summary, enabled: false, returned: 1 } }, now)[0].pending, true);
});
test("a level costs Éclats by current power, so a rare pays the longer road to the same cap", () => {
const total = (rarity) => {
let sum = 0;
for (let level = 0; upgradeCost(rarity, level, settings) != null; level += 1) sum += upgradeCost(rarity, level, settings);
return sum;
};
assert.equal(upgradeCost("rare", 0, settings), 10);
assert.equal(upgradeCost("mythic", 0, settings), 100);
assert.equal(upgradeCost("rare", 12, settings), null);
assert.deepEqual(["rare", "epic", "legendary", "mythic"].map(total), [780, 720, 570, 330]);
// Expérience de terrain : 10 % par retour, un niveau tous les 100 %, rien au-delà du plafond.
assert.deepEqual(gainProgress({ level: 0, fieldXp: 95 }, "rare", { xpPct: 10 }, settings), { level: 1, fieldXp: 5 });
assert.deepEqual(gainProgress({ level: 2, fieldXp: 50 }, "mythic", { levels: 1, xpPct: 60 }, settings), { level: 3, fieldXp: 0 });
assert.deepEqual(gainProgress({ level: 11, fieldXp: 0 }, "rare", { levels: 5 }, settings), { level: 12, fieldXp: 0 });
});
test("commons carry equipment spread over a fixed budget, and every card has synergy partners", () => {
const commons = rawCatalog.cards.filter((card) => card.expedition?.equipment?.stats);
assert.equal(commons.length, 68);
for (const card of commons) assert.equal(Object.values(card.expedition.equipment.stats).reduce((sum, value) => sum + value, 0), 6, card.id);
// Les communes des Carnets des Veilleurs portent chacune un pouvoir, et aucune stat.
assert.deepEqual(rawCatalog.cards.filter((card) => card.expedition?.equipment?.power).map((card) => card.expedition.equipment.power).sort(), ["fogBell", "longsight", "madCompass", "rations", "starNet", "stormLantern", "talisman", "treasureMap"]);
assert.throws(() => prepareVersionedCatalog({ ...structuredClone(rawCatalog), cards: rawCatalog.cards.map((card) => (card.id === "mad-compass" ? { ...card, expedition: { ...card.expedition, equipment: { power: "flying" } } } : card)) }), /known power/);
const broken = (change) => {
const copy = structuredClone(rawCatalog);
change(copy);
return () => prepareVersionedCatalog(copy);
};
const common = (copy) => copy.cards.find((card) => card.id === "star-compass");
assert.throws(broken((copy) => { common(copy).expedition.equipment.stats = { orientation: 7 }; }), /must spread 6 points/);
assert.throws(broken((copy) => { common(copy).expedition.equipment.stats = { orientation: 4, fortune: 2 }; }), /must spread 6 points/);
assert.throws(broken((copy) => { delete common(copy).expedition.equipment; }), /needs equipment stats/);
assert.throws(broken((copy) => { copy.cards[0].expedition.equipment = { stats: { bravoure: 6 } }; }), /cannot be equipment/);
assert.throws(broken((copy) => { copy.cards.find((card) => card.id === "cosmic-water-axolotl").expedition.tags = ["personnage:axolotl"]; }), /shares a tag with only/);
// Lignées : chaque étiquette citée existe dans le vocabulaire.
const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id));
for (const [primordial, tags] of Object.entries(LINEAGES)) for (const tag of [primordial, ...tags]) assert.ok(tagIds.has(tag), tag);
assert.ok(destinations.every((destination) => destination.themeTags.length > 0));
});
test("equipment opens with power, shared tags add synergy points, and teams earn affinity and resonances", () => {
assert.deepEqual([40, 70, 99, 100].map((power) => unlockedSlots(power, settings)), [1, 2, 2, 3]);
const bonus = equipmentBonus([
{ stats: { orientation: 4, fortune: 2 }, tags: ["theme:voyage"] },
{ stats: { bravoure: 8, endurance: -2 }, tags: ["theme:fete"] }
], ["theme:voyage", "personnage:loup"], settings);
assert.deepEqual(bonus.stats, { bravoure: 8, endurance: -2, fortune: 2, orientation: 6 });
assert.deepEqual(bonus.pairs, ["theme:voyage", null]);
const card = (cardId, collectionId, tags) => ({ cardId, collectionId, tags });
// Écho : le même personnage dans deux collections ; Lignée : un Primordial et une carte de son thème ; Étoiles sœurs : deux cartes d'un thème.
assert.deepEqual(resonancesOf([card("a", "primordial-nebula", ["personnage:hamster"]), card("b", "dream-arcade", ["personnage:hamster"])], settings), [{ type: "echo", key: "personnage:hamster" }]);
assert.deepEqual(resonancesOf([card("a", "primordial-nebula", ["personnage:loup"]), card("b", "primordial-nebula", ["theme:aurores"])], settings), [{ type: "lineage", key: "personnage:loup" }]);
assert.deepEqual(resonancesOf([card("a", "x", ["theme:hiver"]), card("b", "x", ["theme:hiver"])], settings), [{ type: "sisters", key: "theme:hiver" }]);
// Une même carte ne forme pas seule une Lignée ; deux Résonances au plus.
assert.deepEqual(resonancesOf([card("a", "x", ["personnage:loup", "theme:aurores"]), card("b", "y", ["theme:nuit"])], settings), []);
const all = [card("a", "primordial-nebula", ["personnage:loup", "theme:hiver"]), card("b", "dream-arcade", ["personnage:loup", "theme:aurores", "theme:hiver"])];
assert.deepEqual(resonancesOf(all, settings).map((item) => item.type), ["echo", "lineage"]);
const destination = { themeTags: ["theme:hiver"] };
const synergy = teamSynergy({ destination, slots: all, cohesionPct: 10 }, settings);
assert.equal(synergy.affinity, "theme:hiver");
// Affinité 10 + deux Résonances 20 + cohésion 10 = 40, plafonné à 25.
assert.equal(synergy.totalPct, 25);
assert.equal(teamSynergy({ destination: { themeTags: ["lieu:vide"] }, slots: [card("a", "x", ["theme:nuit"])] }, settings).totalPct, 0);
});
test("objects come by weight, hidden ones only with enough Orientation, and bonus destinations multiply the loot", () => {
const counts = (orientationPerSlot, excluded = []) => {
const seen = new Set();
let step = 0;
// Hasard parcourant tout l'intervalle : chaque objet permis finit par sortir.
for (let index = 0; index < 200; index += 1) pickItems(1, { orientationPerSlot, excluded }, settings, (max) => (step++ * 7) % max).forEach((id) => seen.add(id));
return seen;
};
const closed = counts(0);
assert.ok(HIDDEN_ITEMS.every((id) => !closed.has(id)));
assert.ok(["anchor", "guideStar", "skyChart"].every((id) => closed.has(id)));
const open = counts(15, ["plan"]);
assert.ok(open.has("fragment") && open.has("engraving") && !open.has("plan"));
assert.deepEqual([null, "5", "6", "hidden"].map((slot) => bonusLootPct(slot, settings)), [100, 100, 125, 150]);
assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: "hidden" }, settings).eclats, 12);
assert.equal(expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2 }, settings).objects, 0.5);
});
test("powers trade an advantage for a cost and count once per team", () => {
const destination = destinations[0];
const entry = { condition: destination.conditions[0], dangers: destination.dangers };
const slot = (powers = []) => ({ stats: { bravoure: 30, endurance: 30, fortune: 30, orientation: 30 }, tags: [], collectionId: "x", cardId: `c${powers.join()}`, powers });
assert.deepEqual(teamPowers([slot(["talisman"]), slot(["talisman", "starNet"])]), ["talisman", "starNet"]);
const evaluate = (powers, stats) => evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(), stats }, { ...slot(), stats }], powers }, settings);
const weak = { bravoure: 1, endurance: 1, fortune: 1, orientation: 1 };
const strong = { bravoure: 90, endurance: 90, fortune: 90, orientation: 90 };
// Talisman : ni échec ni triomphe.
assert.equal(evaluate([], weak).tier, "struggle");
assert.equal(evaluate(["talisman"], weak).tier, "success");
assert.equal(evaluate(["talisman"], strong).tier, "success");
// Carte au trésor : une part du score en moins ; Filet : un peu de Fortune en moins.
const plain = evaluate([], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 });
assert.ok(Math.abs(evaluate(["treasureMap"], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }).scorePct - plain.scorePct * 0.9) < 1e-9);
assert.equal(evaluate(["starNet"], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }).stats.fortune, plain.stats.fortune - 2);
// Butin et trajet : la Boussole folle et les Provisions changent le butin, la Longue-vue et les Provisions le temps de trajet.
const loot = (powers) => expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2, powers }, settings);
assert.equal(loot(["madCompass"]).eclats, loot([]).eclats * 1.3);
// Coup de folie : les exigences réelles sont tirées entre 80 % et 130 % de celles affichées ; sans lui, elles ne changent pas.
assert.equal(rollRequirementFactor([], settings, () => 0), 100);
assert.deepEqual([rollRequirementFactor(["madCompass"], settings, () => 0), rollRequirementFactor(["madCompass"], settings, (max) => max - 1)], [80, 130]);
const tenStats = { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 };
const scaled = (pct) => evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(), stats: tenStats }], requirementFactorPct: pct }, settings).perRequirement.map((item) => item.value);
const shown = requirementsFor(destination, 2, 1, settings).map((item) => item.value);
assert.deepEqual(scaled(100), shown);
assert.deepEqual(scaled(130), shown.map((value) => Math.round(value * 1.3)));
assert.equal(loot(["rations"]).eclats, loot([]).eclats * 0.85);
assert.equal(loot(["longsight"]).cards, loot([]).cards * 1.25);
assert.deepEqual([travelHours(6, [], settings), travelHours(6, ["longsight"], settings), travelHours(8, ["rations"], settings)], [6, 8, 6]);
// Lanterne de tempête : un danger subi pèse moitié moins, mais le trajet dure une heure de plus.
const exposed = { bravoure: 10, endurance: 0, fortune: 10, orientation: 10 };
const danger = { id: "storm", stat: "bravoure", countered: false };
const struck = applyHazards(exposed, { slotCount: 2, durationIndex: 0, dangers: [danger] }, settings).dangers[0];
const sheltered = applyHazards(exposed, { slotCount: 2, durationIndex: 0, dangers: [danger], dangerReliefPct: settings.powers.stormLanternDangerPct }, settings).dangers[0];
assert.ok(struck.factor < 1);
assert.ok(Math.abs((1 - sheltered.factor) - (1 - struck.factor) * 0.5) < 1e-9);
const stars5 = (powers) => evaluateTeam({ destination, entry, stars: 5, durationIndex: 0, slots: [{ ...slot(), stats: exposed }, { ...slot(), stats: exposed }], powers }, settings);
assert.ok(stars5(["stormLantern"]).scorePct >= stars5([]).scorePct);
assert.equal(travelHours(6, ["stormLantern"], settings), 7);
// Cloche de brume : du butin en moins en solo, rien en groupe ; en groupe, un bonus de synergie.
assert.ok(Math.abs(loot(["fogBell"]).eclats - loot([]).eclats * 0.8) < 1e-9);
const groupLoot = (powers) => expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2, powers, group: true }, settings);
assert.equal(groupLoot(["fogBell"]).eclats, groupLoot([]).eclats);
assert.equal(teamSynergy({ destination, slots: [], bellPct: settings.powers.fogBellSynergyPct }, settings).totalPct, 10);
});
test("progression plans: the default keeps today's stats, vocations reach the cap and free points stay within the rules", () => {
const profile = { bravoure: 25, endurance: 25, fortune: 20, orientation: 30 };
for (const level of [0, 3, 12]) assert.deepEqual(planStats("rare", level, profile, null, settings), splitPower(cardPower("rare", level, settings), profile));
assert.deepEqual([levelPoints("rare", 4, settings), levelPoints("legendary", 6, settings), levelPoints("legendary", 9, settings), maxStatPoints(25, settings)], [20, 30, 30, 15]);
assert.deepEqual(vocationProfile("navigator", settings), { bravoure: 0, endurance: 20, fortune: 20, orientation: 60 });
assert.deepEqual(vocationProfile("leader", { ...settings, plans: { maxStatPct: 45 } }), { bravoure: 45, endurance: 28, fortune: 0, orientation: 27 });
// Rare de niveau 4 : base 40 selon le profil, puis 20 points en vocation de Gardien (12 / 4 / 4).
assert.deepEqual(planStats("rare", 4, profile, { plan: "guardian" }, settings), { bravoure: 14, endurance: 22, fortune: 8, orientation: 16 });
assert.deepEqual(planStats("rare", 4, profile, { plan: "free", allocation: { fortune: 7 } }, settings), { bravoure: 10, endurance: 10, fortune: 15, orientation: 12 });
// Une répartition qui ne respecte plus les règles (réglage abaissé) est ramenée dedans, sans erreur.
assert.deepEqual(clampAllocation({ bravoure: 20, endurance: 9 }, 20, settings), { bravoure: 11, endurance: 9, fortune: 0, orientation: 0 });
assert.equal(allocationError({ bravoure: 12, fortune: 8 }, 20, settings), null);
assert.match(allocationError({ bravoure: 13 }, 20, settings), /12 points/);
assert.match(allocationError({ bravoure: 10, fortune: 11 }, 20, settings), /20 points/);
assert.ok(allocationError({ magic: 1 }, 20, settings));
});