Keep a pending opening's cards out of the home highlight and collection until they are revealed, and refuse transfers meanwhile. Odds now ignore rarities a pack cannot give. Stable files gain an ETag so card images revalidate instead of downloading again, and logging out clears the local collection copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
328 lines
20 KiB
JavaScript
328 lines
20 KiB
JavaScript
// Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG.
|
||
import { readFileSync } from "node:fs";
|
||
|
||
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
|
||
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
|
||
const PACK_CATEGORIES = new Set(["permanent", "event", "shop"]);
|
||
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$/;
|
||
|
||
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;
|
||
}
|
||
|
||
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");
|
||
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}.`);
|
||
}
|
||
}
|
||
|
||
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.`);
|
||
}
|
||
|
||
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 (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.`);
|
||
}
|
||
}
|
||
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))
|
||
};
|
||
}
|
||
|
||
// Raretés qu'un paquet peut réellement donner, quels que soient ses taux.
|
||
export function drawableRarities(catalog, collection) {
|
||
const pools = collection.packCategory === "shop" ? shopPackPools(catalog, collection.id) : null;
|
||
const editions = pools ? [...pools.others, ...pools.featured] : collectionDrawableEditions(catalog, collection.id);
|
||
return catalog.rarities.map((rarity) => rarity.id).filter((rarity) => editions.some((edition) => edition.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, drawableRarities: drawableRarities(published, collection) }));
|
||
return published;
|
||
}
|