sokko-g/services/cards/catalog.js
Shinuwa ea5f5c9a51 Give the Primordials distinct weaknesses, emblems that build their specialty and constellations that guide their weakness
- Each Primordial has a 45 % specialty and its own 10 % weakness; its emblematic common raises its two strengths with the synergy on its specialty, and its constellation gives Orientation plus its weakness, without penalties.
- Commons declare the stat their synergy raises when stats tie and for power commons, so the bonus no longer falls on Bravoure by field order.
- Expertise is measured against the solo requirement, so it stays within reach when the group raises each place's requirement.
- Missing lore links become playable: the Dragon, Panda and Capybara own their emblems, Turtles and the Reindeer share an identity, and the Bat, the light-current Otters and the Aurora Wolf are recognised at their destinations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:23:43 +01:00

430 lines
28 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 : charge et valide le catalogue public, ses finitions et effets Sokko TCG.
import { readFileSync } from "node:fs";
import { POWER_IDS, STAT_IDS } from "./expedition-rules.js";
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
// `expedition` : collection qui ne s'obtient qu'en expédition (jamais en paquet, en boutique ni par un code).
const PACK_CATEGORIES = new Set(["permanent", "event", "shop", "expedition"]);
const PACK_BACK_SYMBOLS = new Set(["star", "rift", "orbit"]);
const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
// Formats d'une variation mythique : le premier est le format de référence ; `full-art` utilise `card.fullImage` sur toute la carte.
const STANDARD_FORMAT = "standard";
export const FULL_ART_FORMAT = "full-art";
// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation.
export const MATCH_HOLO_PALETTE_ID = "match-holo";
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
// Étiquettes d'expédition : vocabulaire fermé, par famille (personnage, lieu, thème, objet).
export const EXPEDITION_TAG_PATTERN = /^(personnage|lieu|theme|objet):[a-z0-9-]+$/;
const MAX_CARD_TAGS = 8;
// Équipement d'une commune : un budget fixe de 6 points, réparti selon l'une de ces formes (valeurs triées).
export const EQUIPMENT_BUDGET = 6;
const EQUIPMENT_FORMS = new Set(["6", "3,3", "2,2,2", "8,-2"]);
// Chaque carte rare ou mieux doit partager une étiquette avec au moins ce nombre de communes (ses équipements en synergie).
export const MIN_COMPATIBLE_COMMONS = 3;
// Carte de destination : elle débloque une destination des Expéditions. Toujours rare, elle ne part jamais en équipe
// (ni étiquettes, ni profil, ni équipement) et s'affiche en pleine illustration.
export const DESTINATION_CARD_KIND = "destination";
const DESTINATION_ID_PATTERN = /^[a-z0-9-]+$/;
export const isDestinationCard = (card) => card?.kind === DESTINATION_CARD_KIND;
function requireUnique(items, label) {
const ids = new Set();
for (const item of items) {
if (!item?.id || typeof item.id !== "string") throw new TypeError(`${label}: every item needs a string id.`);
if (ids.has(item.id)) throw new TypeError(`${label}: duplicate id ${item.id}.`);
ids.add(item.id);
}
return ids;
}
// Profil d'expédition : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100.
export function validExpeditionProfile(profile) {
if (!profile || typeof profile !== "object" || Array.isArray(profile) || Object.keys(profile).length !== STAT_IDS.length) return false;
if (STAT_IDS.some((stat) => !Number.isInteger(profile[stat]) || profile[stat] < 0 || profile[stat] > 100)) return false;
return STAT_IDS.reduce((sum, stat) => sum + profile[stat], 0) === 100;
}
function validateExpeditionTags(tags) {
if (!Array.isArray(tags) || !tags.length) throw new TypeError("Cards catalog expeditionTags must be a non-empty array.");
const ids = requireUnique(tags, "expeditionTags");
for (const tag of tags) {
if (!EXPEDITION_TAG_PATTERN.test(tag.id) || typeof tag.label !== "string" || !tag.label || tag.label.length > 40) {
throw new TypeError(`Invalid expedition tag ${tag.id}: family:name id and a 1 to 40 character label.`);
}
}
return ids;
}
function validateCardExpedition(card, tagIds) {
const expedition = card.expedition;
if (!expedition || !Array.isArray(expedition.tags) || !expedition.tags.length || expedition.tags.length > MAX_CARD_TAGS) {
throw new TypeError(`Card ${card.id} needs 1 to ${MAX_CARD_TAGS} expedition tags.`);
}
if (new Set(expedition.tags).size !== expedition.tags.length) throw new TypeError(`Card ${card.id} repeats an expedition tag.`);
const unknown = expedition.tags.find((tag) => !tagIds.has(tag));
if (unknown) throw new TypeError(`Card ${card.id} uses unknown expedition tag ${unknown}.`);
if (expedition.profile != null && !validExpeditionProfile(expedition.profile)) throw new TypeError(`Card ${card.id} expedition profile must give integer shares of the four stats summing to 100.`);
const synergyStat = expedition.equipment?.synergyStat;
if (synergyStat != null && !STAT_IDS.includes(synergyStat)) throw new TypeError(`Card ${card.id} synergyStat must be one of the four stats.`);
if (expedition.equipment?.power != null) {
if (!POWER_IDS.includes(expedition.equipment.power) || expedition.equipment.stats != null) throw new TypeError(`Card ${card.id} power equipment must name a known power and carry no stats.`);
if (synergyStat == null) throw new TypeError(`Card ${card.id} power equipment needs a synergyStat: it has no stats to choose from.`);
} else if (expedition.equipment != null) {
const stats = expedition.equipment.stats;
const values = stats && typeof stats === "object" && !Array.isArray(stats) ? Object.entries(stats) : null;
if (!values?.length || values.some(([stat, value]) => !STAT_IDS.includes(stat) || !Number.isInteger(value) || value === 0)
|| !EQUIPMENT_FORMS.has(values.map(([, value]) => value).sort((a, b) => b - a).join(","))) {
throw new TypeError(`Card ${card.id} equipment must spread ${EQUIPMENT_BUDGET} points as +6, +3/+3, +2/+2/+2 or +8/−2.`);
}
// La synergie renforce une stat que l'objet apporte ; à égalité, elle est choisie, jamais laissée à l'ordre des stats.
const top = Math.max(...values.map(([, value]) => value));
if (synergyStat != null && !(stats[synergyStat] > 0)) throw new TypeError(`Card ${card.id} synergyStat must be a stat its equipment raises.`);
if (synergyStat == null && values.filter(([, value]) => value === top).length > 1) throw new TypeError(`Card ${card.id} equipment ties on its best stat and needs a synergyStat.`);
}
}
// Les communes sont les équipements, les autres cartes ne le sont pas ; chaque carte rare ou mieux a des équipements en synergie.
function validateEquipmentCoverage(catalog) {
const rarityOf = new Map(catalog.editions.filter((edition) => !edition.promotional && edition.rarity !== "mythic").map((edition) => [edition.cardId, edition.rarity]));
const commons = [];
for (const card of catalog.cards.filter((item) => !isDestinationCard(item))) {
const common = rarityOf.get(card.id) === "common";
if (common && !card.expedition.equipment) throw new TypeError(`Common card ${card.id} needs equipment stats.`);
if (!common && card.expedition.equipment) throw new TypeError(`Card ${card.id} is not a common and cannot be equipment.`);
if (common) commons.push(card);
}
for (const card of catalog.cards) {
if (isDestinationCard(card) || !rarityOf.get(card.id) || rarityOf.get(card.id) === "common") continue;
const compatible = commons.filter((common) => common.expedition.tags.some((tag) => card.expedition.tags.includes(tag))).length;
if (compatible < MIN_COMPATIBLE_COMMONS) throw new TypeError(`Card ${card.id} shares a tag with only ${compatible} commons (at least ${MIN_COMPATIBLE_COMMONS} needed for equipment synergies).`);
}
}
export function validateCardsCatalog(catalog) {
if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1.");
for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) {
if (!Array.isArray(catalog[key]) || !catalog[key].length) throw new TypeError(`Cards catalog ${key} must be a non-empty array.`);
}
const rarityIds = requireUnique(catalog.rarities, "rarities");
const effectPresetIds = requireUnique(catalog.effectPresets, "effectPresets");
const effectPaletteIds = requireUnique(catalog.effectPalettes, "effectPalettes");
const particleShapeIds = requireUnique(catalog.particleShapes, "particleShapes");
const particlePaletteIds = requireUnique(catalog.particlePalettes, "particlePalettes");
const particlePresetIds = requireUnique(catalog.particlePresets, "particlePresets");
requireUnique(catalog.openingEffects, "openingEffects");
const finishIds = requireUnique(catalog.finishes, "finishes");
const collectionIds = requireUnique(catalog.collections, "collections");
const cardIds = requireUnique(catalog.cards, "cards");
requireUnique(catalog.editions, "editions");
const expeditionTagIds = validateExpeditionTags(catalog.expeditionTags);
if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities.");
// Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet.
validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights");
for (const preset of catalog.effectPresets) {
if (!preset.label || preset.kind !== "holographic") throw new TypeError(`Invalid holographic effect preset ${preset.id}.`);
}
if (catalog.cardFormats?.[0]?.id !== STANDARD_FORMAT || catalog.cardFormats.some((format) => !format.label) || !catalog.cardFormats.some((format) => format.id === FULL_ART_FORMAT)) {
throw new TypeError("Cards catalog must declare the standard and full-art formats.");
}
for (const palette of catalog.effectPalettes) {
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length !== 7
|| new Set(palette.colors).size !== 7
|| palette.colors.some((color) => !COLOR_PATTERN.test(color)) || !COLOR_PATTERN.test(palette.highlight)) {
throw new TypeError(`Invalid effect palette ${palette.id}.`);
}
}
for (const shape of catalog.particleShapes) {
if (!shape.label || !PARTICLE_SHAPE_KINDS.has(shape.kind)) throw new TypeError(`Invalid particle shape ${shape.id}.`);
}
for (const palette of catalog.particlePalettes) {
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length < 1 || palette.colors.length > 7
|| palette.colors.some((color) => !COLOR_PATTERN.test(color))) {
throw new TypeError(`Invalid particle palette ${palette.id}.`);
}
}
for (const preset of catalog.particlePresets) {
if (!preset.label || !particleShapeIds.has(preset.shapeId) || !particlePaletteIds.has(preset.paletteId)
|| !Number.isInteger(preset.count) || preset.count < 1 || preset.count > 64) {
throw new TypeError(`Invalid particle preset ${preset.id}.`);
}
}
// Un seul effet d'ouverture par rareté ; les variantes mythiques passent par les réglages d'ouverture.
const openingEffectRarities = new Set();
for (const effect of catalog.openingEffects) {
if (!effect.label || !RARITY_IDS.has(effect.rarity) || effect.rarity === "common"
|| !Array.isArray(effect.auraColors) || effect.auraColors.length < 1 || effect.auraColors.length > 7
|| effect.auraColors.some((color) => !COLOR_PATTERN.test(color))
|| Object.hasOwn(effect, "collectionId")
|| !Number.isInteger(effect.auraDurationMs) || effect.auraDurationMs < 0 || effect.auraDurationMs > 2_000
|| !Number.isInteger(effect.particleDurationMs) || effect.particleDurationMs < 0 || effect.particleDurationMs > 2_000) {
throw new TypeError(`Invalid opening effect ${effect.id}.`);
}
if (effect.particlePresetId != null && !particlePresetIds.has(effect.particlePresetId)) throw new TypeError(`Opening effect ${effect.id} needs a known particle preset.`);
if (effect.particlePresetId == null && effect.particleDurationMs !== 0) throw new TypeError(`Opening effect ${effect.id} cannot animate missing particles.`);
if (openingEffectRarities.has(effect.rarity)) throw new TypeError(`Duplicate opening effect for rarity ${effect.rarity}.`);
openingEffectRarities.add(effect.rarity);
}
for (const rarity of ["rare", "epic", "legendary", "mythic"]) {
if (!openingEffectRarities.has(rarity)) throw new TypeError(`Cards catalog needs an opening effect for rarity ${rarity}.`);
}
const defaultMythicOpening = catalog.openingEffects.find((effect) => effect.rarity === "mythic");
if (!particlePresetIds.has(defaultMythicOpening.particlePresetId)) throw new TypeError("The default mythic opening effect needs particles.");
for (const finish of catalog.finishes) {
if (!finish.label
|| !Object.hasOwn(finish, "effectPresetId")
|| !Object.hasOwn(finish, "paletteId")) {
throw new TypeError(`Invalid finish ${finish.id}.`);
}
const hasEffect = finish.effectPresetId != null;
if (hasEffect && !effectPresetIds.has(finish.effectPresetId)) throw new TypeError(`Finish ${finish.id} needs a known holographic effect.`);
if (hasEffect && !effectPaletteIds.has(finish.paletteId)) throw new TypeError(`Holographic finish ${finish.id} needs a known palette.`);
if (!hasEffect && finish.paletteId != null) throw new TypeError(`Finish ${finish.id} cannot use a palette without a holographic effect.`);
}
for (const collection of catalog.collections) {
if (!collection.name || !collection.systemName || !collection.description || (collection.active != null && typeof collection.active !== "boolean") || typeof collection.promotional !== "boolean") {
throw new TypeError(`Invalid collection ${collection.id}.`);
}
if (!PACK_CATEGORIES.has(collection.packCategory)
|| !PACK_BACK_SYMBOLS.has(collection.back?.symbol)
|| !PACK_BACK_IMAGE_PATTERN.test(collection.back?.image)
|| !COLOR_PATTERN.test(collection.back?.primary)
|| !COLOR_PATTERN.test(collection.back?.secondary)) {
throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`);
}
if (!validExpeditionProfile(collection.expedition?.profile)) throw new TypeError(`Collection ${collection.id} needs an expedition profile giving integer shares of the four stats summing to 100.`);
}
for (const card of catalog.cards) {
if (!collectionIds.has(card.collectionId)) throw new TypeError(`Unknown collection for card ${card.id}.`);
if (!card.name || card.name.length > 40) throw new TypeError(`Card ${card.id} name must contain 1 to 40 characters.`);
if (!card.description || card.description.length > 200) throw new TypeError(`Card ${card.id} description must contain 1 to 200 characters.`);
if (card.image != null && !CARD_IMAGE_PATTERN.test(card.image)) throw new TypeError(`Card ${card.id} image must use a canonical WebP path.`);
if (card.fullImage != null && !CARD_IMAGE_PATTERN.test(card.fullImage)) throw new TypeError(`Card ${card.id} full image must use a canonical WebP path.`);
// Illustrations à zones vides : même fichier que l'illustration de leur format, suffixé `__cutout`, pour les effets à sous-couche.
for (const [cutoutKey, imageKey, label] of [["cutoutImage", "image", "image"], ["fullCutoutImage", "fullImage", "full image"]]) {
if (card[cutoutKey] != null && (!card[imageKey] || card[cutoutKey] !== card[imageKey].replace(/\.webp$/, "__cutout.webp"))) {
throw new TypeError(`Card ${card.id} ${cutoutKey === "cutoutImage" ? "cutout" : "full cutout"} image must be its ${label} suffixed with __cutout.`);
}
}
if (card.kind != null && card.kind !== DESTINATION_CARD_KIND) throw new TypeError(`Card ${card.id} has an unknown kind.`);
if (isDestinationCard(card)) {
if (!DESTINATION_ID_PATTERN.test(card.destinationId ?? "")) throw new TypeError(`Destination card ${card.id} needs a destinationId.`);
if (card.expedition != null) throw new TypeError(`Destination card ${card.id} never joins a team and takes no expedition data.`);
} else {
if (card.destinationId != null) throw new TypeError(`Card ${card.id} is not a destination card and cannot name a destination.`);
validateCardExpedition(card, expeditionTagIds);
}
}
const destinationCards = catalog.cards.filter(isDestinationCard);
requireUnique(destinationCards.map((card) => ({ id: card.destinationId })), "destination cards");
for (const edition of catalog.editions) {
if (!cardIds.has(edition.cardId)) throw new TypeError(`Unknown card for edition ${edition.id}.`);
if (!RARITY_IDS.has(edition.rarity)) throw new TypeError(`Unknown rarity for edition ${edition.id}.`);
if (!Array.isArray(edition.finishIds) || edition.finishIds.some((id) => !finishIds.has(id))) throw new TypeError(`Unknown finish for edition ${edition.id}.`);
if (edition.retired != null && typeof edition.retired !== "boolean") throw new TypeError(`Edition ${edition.id} retired flag must be a boolean.`);
if (destinationCards.some((card) => card.id === edition.cardId) && edition.rarity !== "rare") throw new TypeError(`Destination card edition ${edition.id} must be rare.`);
if (edition.promotional && edition.legendaryEditionId) throw new TypeError(`Promotional edition ${edition.id} cannot require a legendary parent.`);
if (edition.rarity === "mythic" && !edition.promotional) {
const parent = catalog.editions.find((candidate) => candidate.id === edition.legendaryEditionId);
if (!parent || parent.cardId !== edition.cardId || parent.rarity !== "legendary") throw new TypeError(`Mythic edition ${edition.id} needs a legendary edition of the same card.`);
}
}
validateEquipmentCoverage(catalog);
if (catalog.mythicOpeningSettings != null) {
if (!Array.isArray(catalog.mythicOpeningSettings)) throw new TypeError("Cards catalog mythicOpeningSettings must be an array.");
const settingKeys = new Set();
for (const setting of catalog.mythicOpeningSettings) {
const targets = setting?.scope === "collection" ? collectionIds : setting?.scope === "card" ? cardIds : null;
if (!targets?.has(setting.targetId)
|| (setting.particleShapeId != null && !particleShapeIds.has(setting.particleShapeId))
|| (setting.particlePaletteId != null && setting.particlePaletteId !== MATCH_HOLO_PALETTE_ID && !particlePaletteIds.has(setting.particlePaletteId))) {
throw new TypeError(`Invalid mythic opening setting ${setting?.scope}:${setting?.targetId}.`);
}
const key = `${setting.scope}:${setting.targetId}`;
if (settingKeys.has(key)) throw new TypeError(`Duplicate mythic opening setting ${key}.`);
settingKeys.add(key);
}
}
// Les taux de tirage n'existent que dans le catalogue publié (ils viennent de la base).
for (const collection of catalog.collections) {
if (collection.dropWeights != null) validateRarityWeights(collection.dropWeights, rarityIds, collection.id);
}
return catalog;
}
export const MAX_RARITY_WEIGHT = 1_000_000;
// Poids entiers, positifs ou nuls, une entrée par rareté connue, total strictement positif.
export function validateRarityWeights(weights, rarityIds, label = "drop weights") {
if (!weights || typeof weights !== "object" || Array.isArray(weights)) throw new TypeError(`Invalid drop weights in ${label}.`);
const entries = Object.entries(weights);
if (entries.length !== rarityIds.size || entries.some(([rarity, weight]) => !rarityIds.has(rarity) || !Number.isInteger(weight) || weight < 0 || weight > MAX_RARITY_WEIGHT)) {
throw new TypeError(`Invalid drop weight in ${label}.`);
}
if (entries.reduce((sum, [, weight]) => sum + weight, 0) <= 0) throw new TypeError(`Drop weights in ${label} must have a positive total.`);
return weights;
}
export const STANDARD_FINISH_ID = "standard";
// Les finitions ne sont pas déclarées : « standard » plus une finition par combinaison effet holographique × palette.
export function withGeneratedFinishes(catalog) {
const finishes = [{ id: STANDARD_FINISH_ID, label: "Standard", effectPresetId: null, paletteId: null, formatId: STANDARD_FORMAT }];
for (const format of catalog.cardFormats || []) {
for (const effect of catalog.effectPresets || []) {
for (const palette of catalog.effectPalettes || []) {
// Le format de référence garde des identifiants courts ; les autres sont préfixés par leur format.
const standard = format.id === STANDARD_FORMAT;
finishes.push({
id: `${standard ? "" : `${format.id}-`}${effect.id}-${palette.id}`,
label: `${standard ? "" : `${format.label} · `}${effect.label} — ${palette.label}`,
effectPresetId: effect.id,
paletteId: palette.id,
formatId: format.id
});
}
}
}
return { ...catalog, finishes };
}
// catalog.json ne déclare ni finitions (générées) ni contenu géré en base depuis l'administration :
// variations mythiques, activation des paquets et taux de tirage.
export function assertVersionedCatalogScope(catalog) {
if (catalog.finishes) throw new TypeError("Finishes are generated from effect presets and palettes: remove finishes from catalog.json.");
if (catalog.dropTables) throw new TypeError("Drop rates are managed from the admin database: remove dropTables from catalog.json.");
const withRates = catalog.collections?.find((collection) => Object.hasOwn(collection, "dropWeights"));
if (withRates) throw new TypeError(`Collection ${withRates.id} drop rates are managed from the admin database: remove dropWeights from catalog.json.`);
const withState = catalog.collections?.find((collection) => Object.hasOwn(collection, "active"));
if (withState) throw new TypeError(`Collection ${withState.id} availability is managed from the admin database: remove active from catalog.json.`);
const mythic = catalog.editions?.find((edition) => edition.rarity === "mythic" && !edition.promotional);
if (mythic) throw new TypeError(`Mythic edition ${mythic.id} must be managed from the admin database, not catalog.json.`);
return catalog;
}
// Prépare le catalogue versionné tel qu'il est lu depuis catalog.json.
export function prepareVersionedCatalog(raw) {
return validateCardsCatalog(withGeneratedFinishes(assertVersionedCatalogScope(raw)));
}
export function loadCardsCatalog(path) {
return prepareVersionedCatalog(JSON.parse(readFileSync(path, "utf8")));
}
export function createCatalogIndex(catalog) {
return {
collections: new Map(catalog.collections.map((item) => [item.id, item])),
cards: new Map(catalog.cards.map((item) => [item.id, item])),
editions: new Map(catalog.editions.map((item) => [item.id, item])),
finishes: new Map(catalog.finishes.map((item) => [item.id, item])),
effectPresets: new Map(catalog.effectPresets.map((item) => [item.id, item])),
effectPalettes: new Map(catalog.effectPalettes.map((item) => [item.id, item])),
particleShapes: new Map(catalog.particleShapes.map((item) => [item.id, item])),
particlePalettes: new Map(catalog.particlePalettes.map((item) => [item.id, item])),
particlePresets: new Map(catalog.particlePresets.map((item) => [item.id, item])),
openingEffects: new Map(catalog.openingEffects.map((item) => [item.id, item]))
};
}
export function isDrawableEdition(edition) {
return !edition.promotional && !edition.retired;
}
// Éditions tirables d'une collection.
export function collectionDrawableEditions(catalog, collectionId) {
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
return catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
}
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
const SHOP_FEATURED_RARITIES = new Set(["legendary", "mythic"]);
export function shopPackPools(catalog, collectionId) {
const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
const drawable = catalog.editions.filter(isDrawableEdition);
return {
others: drawable.filter((edition) => activeIds.has(sourceOf.get(edition.cardId))),
featured: drawable.filter((edition) => sourceOf.get(edition.cardId) === collectionId && SHOP_FEATURED_RARITIES.has(edition.rarity))
};
}
// Nombre d'éditions qu'un paquet peut réellement donner par rareté, quels que soient ses taux.
export function drawableCounts(catalog, collection) {
const pools = collection.packCategory === "shop" ? shopPackPools(catalog, collection.id) : null;
const editions = pools ? [...pools.others, ...pools.featured] : collectionDrawableEditions(catalog, collection.id);
return Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, editions.filter((edition) => edition.rarity === rarity.id).length]));
}
export function drawableRarities(catalog, collection) {
return Object.entries(drawableCounts(catalog, collection)).filter(([, count]) => count > 0).map(([rarity]) => rarity);
}
export function holographicFinishIds(catalog) {
return new Set(catalog.finishes.filter((finish) => finish.effectPresetId != null).map((finish) => finish.id));
}
export function legendaryParentEdition(catalog, cardId) {
return catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity === "legendary" && !edition.promotional) || null;
}
export function mythicEditionId(cardId, finishId) {
return `${cardId}-${finishId}`;
}
// Construit le catalogue publié : catalogue versionné + variations mythiques et réglages d'ouverture enregistrés en base.
// `variations` : [{ editionId, cardId, finishId, status: "active" | "retired" }]
// `openingSettings` : [{ scope: "collection" | "card", targetId, particleShapeId | null, particlePaletteId | null }]
// `collectionStates` : [{ collectionId, active }] ; une collection sans état est inactive.
// `dropRates` : [{ collectionId, rarityWeights }] ; publiés sur chaque collection dans `dropWeights`.
export function buildPublishedCatalog(versionedCatalog, { variations = [], openingSettings = [], collectionStates = [], dropRates = [] } = {}) {
const catalog = structuredClone(versionedCatalog);
const states = new Map(collectionStates.map((state) => [state.collectionId, Boolean(state.active)]));
const rates = new Map(dropRates.map((rate) => [rate.collectionId, rate.rarityWeights]));
catalog.collections = catalog.collections.map((collection) => {
const dropWeights = rates.get(collection.id);
return { ...collection, active: states.get(collection.id) ?? false, ...(dropWeights ? { dropWeights: { ...dropWeights } } : {}) };
});
for (const collection of catalog.collections.filter((item) => item.active)) {
if (!collection.dropWeights) throw new TypeError(`Active collection ${collection.id} needs drop rates.`);
}
const holographic = holographicFinishIds(catalog);
const knownIds = new Set(catalog.editions.map((edition) => edition.id));
const mythics = variations.map((variation) => {
const parent = legendaryParentEdition(catalog, variation.cardId);
if (!parent || !holographic.has(variation.finishId) || variation.editionId !== mythicEditionId(variation.cardId, variation.finishId) || knownIds.has(variation.editionId)) {
throw new TypeError(`Mythic variation ${variation.editionId} needs a legendary card and a holographic finish.`);
}
knownIds.add(variation.editionId);
return {
id: variation.editionId,
cardId: variation.cardId,
rarity: "mythic",
finishIds: [variation.finishId],
promotional: false,
legendaryEditionId: parent.id,
...(variation.status === "retired" ? { retired: true } : {})
};
});
// Chaque variation suit sa carte légendaire, dans l'ordre des finitions.
const finishOrder = new Map(catalog.finishes.map((finish, index) => [finish.id, index]));
mythics.sort((left, right) => finishOrder.get(left.finishIds[0]) - finishOrder.get(right.finishIds[0]));
catalog.editions = catalog.editions.flatMap((edition) => edition.rarity === "legendary" && !edition.promotional
? [edition, ...mythics.filter((mythic) => mythic.legendaryEditionId === edition.id)]
: [edition]);
catalog.mythicOpeningSettings = openingSettings
.map(({ scope, targetId, particleShapeId = null, particlePaletteId = null }) => ({ scope, targetId, particleShapeId, particlePaletteId }))
.filter((setting) => setting.particleShapeId || setting.particlePaletteId);
return validateCardsCatalog(catalog);
}
export function publicCatalog(catalog) {
const published = JSON.parse(JSON.stringify(catalog));
published.collections = published.collections.map((collection) => ({ ...collection, drawableCounts: drawableCounts(published, collection), drawableRarities: drawableRarities(published, collection) }));
return published;
}