/** * Loads the campaign/character/monster/scenario data the menus read, from * the same JSON files the engine uses (served at `/data/` by the Dart * server). The reference app ships these as bundled assets; here the * server is the single source and the client fetches on demand and caches. */ import type { GraphicPositional, MonsterAbilityCard } from '../protocol/types'; // --- Raw JSON shapes (the subset the UI needs) ---------------------------- interface RawClass { name: string; edition: string; health: number[]; hidden?: boolean; color: string | string[]; colorSecondary?: string | string[]; /** `adds`/`removes` per perk slot (the reference `PerkModel`). */ perks?: { text?: string; adds?: string[]; removes?: string[] }[]; perksFH?: { text?: string; adds?: string[]; removes?: string[] }[]; } interface RawMonsterStats { health: number | string; [ key: string ]: unknown; } interface RawMonsterLevel { level: number; normal?: RawMonsterStats; elite?: RawMonsterStats; boss?: RawMonsterStats; } interface RawMonster { deck: string; count: number; levels: RawMonsterLevel[]; display?: string; gfx?: string; hidden?: boolean; flying?: boolean; } interface RawScenario { monsters?: string[]; lootDeck?: Record; special?: unknown[]; initialMessage?: string; } interface RawEdition { edition: string; classes: RawClass[]; monsters: Record; scenarios: Record; /** Monster ability-card decks (the reference `MonsterAbilityDeckModel`). */ monsterAbilities?: RawMonsterAbilityDeck[]; } interface RawMonsterAbilityDeck { name: string; edition: string; cards: unknown[]; } // --- UI-facing types ------------------------------------------------------- export interface ClassData { id: string; name: string; edition: string; hidden: boolean; health: number[]; color: string; colorSecondary: string; /** `/images/class-icons/.png` */ icon: string; /** The `adds` graphic list per perk slot (the reference `perks`). */ perks: string[][]; perksFH: string[][]; /** The full perk-slot data (text + adds + removes) for the perks menu. */ perkDetails: PerkDetail[]; perkDetailsFH: PerkDetail[]; } /** One perk slot (the reference `PerkModel`). */ export interface PerkDetail { text: string; adds: string[]; removes: string[]; } export interface MonsterData { name: string; display: string; gfx: string; deck: string; count: number; hidden: boolean; flying: boolean; levels: RawMonsterLevel[]; maxLevel: number; /** The first level has a boss block. */ isBoss: boolean; edition: string; /** `/images/monsters/.png` */ portrait: string; } export interface ScenarioData { name: string; monsters: string[]; } export interface CampaignData { edition: string; classes: ClassData[]; monsters: MonsterData[]; /** Scenario names in file order. */ scenarios: ScenarioData[]; /** * Monster ability-card decks, keyed by deck name (the reference * `MonsterAbilityDeckModel`). The client reconstructs full cards from * these when state references a card by `{nr, deck}`. */ abilityDecks: Record; } export function firstColor(value: string | string[] | undefined, fallback = '000000') { const v = Array.isArray(value) ? value[0] : value; return v ?? fallback; } function escapePathSegment(value: string): string { return encodeURIComponent(value); } /** * Parse one ability-card raw entry into a full {@link MonsterAbilityCard}. * Mirrors the reference `MonsterAbilityDeckModel.fromJson`: the card is a * JSON array of `[optionalTitle, nr, shuffle, initiative, optionalGraphics, * ...lines]` where the title (a leading string) and the graphics list (at * index 3, a list of `{gfx,x,y,scale?,angle?}`) are both optional. */ function parseAbilityCard(raw: unknown[], deckName: string): MonsterAbilityCard { let title = deckName; let arr = raw; if (typeof arr[0] === 'string') { title = arr[0] as string; arr = arr.slice(1); } const nr = arr[0] as number; const shuffle = arr[1] as boolean; const initiative = arr[2] as number; let rest = arr.slice(3); let graphics: GraphicPositional[] = []; if (Array.isArray(rest[0])) { graphics = (rest[0] as Array>).map((g) => ({ gfx: g.gfx as string, x: g.x as number, y: g.y as number, scale: (g.scale as number | undefined) ?? 1, angle: (g.angle as number | undefined) ?? 0 })); rest = rest.slice(1); } return { title, nr, shuffle, initiative, lines: rest as string[], deck: deckName, graphics }; } // --- The loader ------------------------------------------------------------ export class GameDataClient { private campaignsPromise: Promise | null = null; private campaignsCache: string[] | null = null; private readonly cache = new Map>(); /** Resolved campaign data (populated as each fetch lands) for sync lookups. */ private readonly loaded = new Map(); private readonly roomsCache = new Map[]> | null>>(); constructor(private readonly base = '/data') {} /** The list of campaign/edition names (order from `editions.json`). */ campaigns(): Promise { if (this.campaignsCache) return Promise.resolve(this.campaignsCache); if (this.campaignsPromise) return this.campaignsPromise; this.campaignsPromise = fetch(`${this.base}/editions/editions.json`) .then((r) => r.json()) .then((d: { editions: string[] }) => { this.campaignsCache = d.editions; return d.editions; }); return this.campaignsPromise; } /** Character classes, monsters, and scenario names for a campaign. */ loadCampaign(campaign: string): Promise { const cached = this.cache.get(campaign); if (cached) return cached; const promise = fetch( `${this.base}/editions/${escapePathSegment(campaign)}.json` ) .then((r) => { if (!r.ok) throw new Error(`failed to load campaign ${campaign}`); return r.json(); }) .then((raw: RawEdition) => { const abilityDecks: Record = {}; for (const deck of raw.monsterAbilities ?? []) { abilityDecks[deck.name] = deck.cards.map((c) => parseAbilityCard(c as unknown[], deck.name) ); } const data: CampaignData = { edition: raw.edition, classes: raw.classes.map((c) => this.toClass(c)), monsters: Object.entries(raw.monsters).map(([name, m]) => this.toMonster(name, m, raw.edition) ), scenarios: Object.entries(raw.scenarios).map(([name, s]) => ({ name, monsters: s.monsters ?? [] })), abilityDecks }; this.loaded.set(campaign, data); return data; }); this.cache.set(campaign, promise); return promise; } /** * The monster model for [name] in [campaign] (by name or display name), * or null when the campaign data is not yet loaded. Used to resolve a * state monster (keyed by model name) to its stats, deck, and art. */ findMonster(campaign: string, name: string): MonsterData | null { const data = this.loaded.get(campaign); if (!data) return null; return ( data.monsters.find((m) => m.name === name || m.display === name) ?? null ); } /** The ability cards for a monster-ability [deck] in [campaign]. */ abilityCards(campaign: string, deck: string): MonsterAbilityCard[] { return this.loaded.get(campaign)?.abilityDecks[deck] ?? []; } /** * The full ability card for a state reference `{deck, nr}` in [campaign] — * the client reconstructs it from the edition data (state carries only the * reference). Null when the campaign is not loaded or the card is unknown. */ abilityCard( campaign: string, deck: string, nr: number ): MonsterAbilityCard | null { const cards = this.loaded.get(campaign)?.abilityDecks[deck]; if (!cards) return null; return cards.find((c) => c.nr === nr) ?? null; } /** * The addable section names for a scenario, mirroring the server's * `ScenarioModel`: the rooms file is keyed by the scenario number (the * `#` and name stripped — `"#0 Howling in the Snow"` → `"0"`); the first * room is the scenario start (skipped) and each remaining room's name is * an addable section. Names containing "spawn" are excluded. */ sections(campaign: string, scenario: string): Promise { const key = `${campaign}::${scenario}`; const cached = this.roomsCache.get(campaign); const roomsPromise = cached ?? fetch(`${this.base}/rooms/${escapePathSegment(campaign)}.json`) .then((r) => (r.ok ? r.json() : null)) .then( (rooms: Record[]> | null) => { this.roomsCache.set(campaign, Promise.resolve(rooms)); return rooms; } ); const promise = roomsPromise.then((rooms) => { if (!rooms) return []; // The rooms key is the scenario number after `#` (first token): // `"#1 A Town in Flames"` → `"1"`, `"#4A …"` → `"4A"`. const nr = scenario.startsWith('#') ? scenario.slice(1).split(/\s/)[0] : scenario; const entry = rooms[nr] ?? rooms[scenario] ?? null; if (!Array.isArray(entry)) return []; return entry .slice(1) // skip the scenario start room .map((room) => Object.keys(room)[0] ?? '') .filter((name) => name && !name.toLowerCase().includes('spawn')); }); this.roomsCache.set(campaign, roomsPromise); void key; // (cache key kept for a possible per-scenario variant) return promise; } private toClass(c: RawClass): ClassData { const name = c.name; const toDetails = ( perks: RawClass['perks'] ): PerkDetail[] => (perks ?? []).map((p) => ({ text: p.text ?? '', adds: p.adds ?? [], removes: p.removes ?? [] })); return { id: name, name, edition: c.edition, hidden: c.hidden ?? false, health: c.health, color: firstColor(c.color), colorSecondary: firstColor(c.colorSecondary, firstColor(c.color)), icon: `/images/class-icons/${escapePathSegment(name)}.png`, perks: (c.perks ?? []).map((p) => p.adds ?? []), perksFH: (c.perksFH ?? []).map((p) => p.adds ?? []), perkDetails: toDetails(c.perks), perkDetailsFH: toDetails(c.perksFH) }; } /** * The character class for [name] in [campaign] (by name or display * name), or null when the campaign data is not yet loaded. Used by the * modifier-card gfx resolver for perk (`P`) graphics. */ classByName(campaign: string, name: string): ClassData | null { const data = this.loaded.get(campaign); if (!data) return null; return ( data.classes.find((c) => c.name === name || c.id === name) ?? null ); } private toMonster(name: string, m: RawMonster, edition: string): MonsterData { const display = m.display ?? name; const gfx = m.gfx ?? display; const levels = m.levels ?? []; const maxLevel = levels.reduce( (max, l) => Math.max(max, l.level), levels.length ? 0 : 1 ); return { name, display, gfx, deck: m.deck, count: m.count, hidden: m.hidden ?? false, flying: m.flying ?? false, levels, maxLevel, isBoss: levels.some((l) => l.boss != null), edition, portrait: `/images/monsters/${escapePathSegment(gfx)}.png` }; } } /** The default shared client. */ export const gameData = new GameDataClient();