First commit

This commit is contained in:
2026-10-27 12:42:57 +01:00
commit 7dd9f4b14d
74 changed files with 33018 additions and 0 deletions

6
backend/.dockerignore Normal file
View File

@@ -0,0 +1,6 @@
node_modules
dist
.env
Dockerfile
.dockerignore
data/images

9
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
node_modules
dist
.env
data/cards.json
data/card-effects.json
data/card-effects.pseudo.txt
data/images/
data/playmats/
data/*.tmp

23
backend/Dockerfile Normal file
View File

@@ -0,0 +1,23 @@
FROM node:24-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM base AS dev
COPY . .
EXPOSE 4000
CMD ["npm", "run", "dev"]
FROM base AS build
COPY . .
RUN npm run build
FROM node:24-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
COPY --from=build /app/data ./data
EXPOSE 4000
CMD ["node", "dist/server.js"]

0
backend/data/.gitkeep Normal file
View File

View File

@@ -0,0 +1,4 @@
# Miirym, Sentinel Wyrm [supported]
keywords Flying, Ward {2}
on enters(each other nontoken dragon you control):
create_token(you, 1, copy of the triggering object, not legendary)

View File

@@ -0,0 +1,260 @@
# Card effect compiler
The card database from Scryfall is English prose. The game engine cannot execute
prose, so `backend/src/effects/` compiles every oracle-text line into a small
JSON AST. The AST is the canonical form for the engine. A pretty-printer renders
the same AST as readable pseudocode, and a matching parser reads that pseudocode
back, so a human can replace the generated implementation of a card without
touching JSON.
This is deliberately **not** a rules engine. It answers "what does the card
say?" in machine-readable form. "What happens when it resolves?" belongs to the
engine that consumes these nodes.
## Pipeline
```text
Scryfall oracle text
-> normalize (card name, "this creature", contractions, reminder text)
-> classify (keyword / triggered / activated / static / spell effect)
-> parse targets, values, costs, conditions, durations
-> JSON AST + pseudocode rendering
data/card-overrides/<oracle_id>.pseudo.txt
-> pseudocode parser
-> JSON AST used instead of the generated one
```
Every line is parsed as a whole. If any part of a line is not understood, the
line becomes `{ "kind": "unsupported", "reason": ..., "text": ... }` instead of
a guessed effect. A wrong effect is worse than a missing one.
## Commands
From `backend/`:
```bash
npm run compile:cards # writes data/card-effects.json and .pseudo.txt
npm test # compiler, pseudocode parser, and engine tests
npm run dev # API for the frontend editor
```
Current output over the imported Commander pool (32,116 cards):
```text
Cards: 14,141 supported, 10,119 partial, 7,856 unsupported
Ability lines: 37,983/60,470 parsed (62.8%)
```
- **supported** — every ability line parsed.
- **partial** — at least one line parsed, at least one unsupported.
- **unsupported** — no line parsed.
The unsupported lines are the work queue. Re-running the compiler after adding
patterns updates the numbers.
## Output files
| File | Contents |
| ---- | -------- |
| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card |
| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode |
| `data/card-overrides/<oracle_id>.pseudo.txt` | Human-authored implementations, one file per card |
The two generated files are git-ignored. Overrides are ordinary source files and
should be committed.
## Pseudocode
```text
# Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
# Llanowar Elves [supported]
activate {T}:
add_mana(you, {G})
# Krenko, Mob Boss [supported]
activate {T}:
create_token(you, count(creature goblin you control), 1/1 red goblin creature)
```
Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads
it back into the same AST the compiler produces. Blocks are indented two spaces.
A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a
new section for a multi-face card. Use `(no abilities)` when a face has none.
## Manual implementations
The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a
card, edit its pseudocode, and save. The editor toggles between the text view and a
node canvas where sockets are wired to define effect order and nested bodies; both
edit the same source. The API validates the source before writing it, so a typo
never replaces a working file. Overrides take precedence during
`npm run compile:cards`; invalid override files stop the compile with the line
number.
| Method | Path | Purpose |
| ------ | ---- | ------- |
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag |
| `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` |
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output |
| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text |
| `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent |
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
`CARD_OVERRIDES_DIR` changes the storage directory (useful for tests).
### AI drafts
The editor's **Draft with AI** button calls
`POST /cards/:oracleId/translate`. The backend sends the card's oracle text to
an [OpenRouter](https://openrouter.ai/) model and returns pseudocode, without
saving it. The response is parsed before it reaches the browser, so prose or a
non-parseable guess is reported as an error instead of replacing the editor.
Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL`
defaults to `google/gemini-2.5-flash-lite`.
The system prompt contains the syntax reference and a strict output contract:
pseudocode only, no explanations, Markdown, code fences or card header, and no
invented operations. Output is capped at 700 tokens. A fenced answer is
unwrapped defensively, but an invalid answer is not retried (that would spend
more tokens). The translator uses the default model only; there is no per-request
model picker.
## AST
The types live in `src/effects/types.ts`. A card contains one or more abilities:
```jsonc
{
"oracle_id": "...",
"name": "Soul Warden",
"status": "supported",
"abilities": [
{
"kind": "triggered",
"event": {
"kind": "enters",
"subject": {
"kind": "object",
"selector": { "other": true, "types": ["creature"] },
"mode": "each"
}
},
"effects": [
{ "op": "life", "player": "you", "amount": { "kind": "number", "value": 1 }, "mode": "gain" }
],
"optional": false,
"text": "Whenever another creature enters, you gain 1 life."
}
]
}
```
### Ability kinds
| Kind | Meaning | Example |
| ---- | ------- | ------- |
| `keyword` | One parameterless or parameterized keyword | `Flying`, `Ward {2}`, `Crew 3` |
| `keywords` | Several keywords on one oracle line | `Flying, vigilance` |
| `triggered` | `When`/`Whenever`/`At` ability | `When this enters, draw a card.` |
| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` |
| `unsupported` | Preserved text plus a reason | `Choose one —` |
### Effects
| `op` | Payload |
| ---- | ------- |
| `damage` | `target`, `amount`, optional `source` |
| `draw`, `discard`, `mill` | `player`, `amount` |
| `life` | `player`, `amount`, `mode: gain \| lose` |
| `pump` | `target`, `power`, `toughness`, `duration` |
| `grant` | `target`, `keyword`, optional `value`, `duration` |
| `put_counters`, `remove_counters` | `target`, `counter`, `amount` |
| `create_token` | `player`, `amount`, `token` |
| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` |
| `sacrifice` | `player`, `target`, optional `unless` cost |
| `counter` | `what`, `target`, optional `unless` cost |
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` |
| `search`, `shuffle` | player, selector, destination |
| `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
| `scry`, `surveil` | `player`, `amount` |
| `fight` | two targets |
| `energy` | `player`, `amount` |
| `attach` | target to attach this/trigger object to |
| `restriction` | target, rule, duration |
| `keyword_action` | `action`, optional `amount`, `detail`, `target` |
| `proliferate` | no payload |
### Targets, values, costs
- **Targets** are `self`, `trigger_subject`, `any`, `player`, `spell`, `ability`,
or `object` with an `ObjectSelector` and mode `target` / `each` / `choose`.
- **Selectors** carry types, subtypes, controller, colors, zone, tapped/attacking
state, `other`, `attached: equipped|enchanted`, and `includeSelf`.
- **Values** are `number`, `x`, `count(selector)`, `source_power`,
`source_toughness`, `cards_in_hand`, or `event_amount`.
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
- **Conditions** cover controlling permanents, turn ownership, tapped source,
life totals, and graveyard size.
- **Durations** cover permanent, end of turn, your next turn, the end of your
next turn, end of combat, controller's next untap step, and while the source
remains.
## How a line is parsed
1. Reminder text in parentheses is removed. Card names and "this creature" /
"this permanent" become `this`.
2. Pure keyword lines are recognized from Scryfall's keyword list plus the
parameterized keyword table.
3. Trigger prefixes (`When this enters`, `Whenever this attacks`, `At the
beginning of your upkeep`, ...) become a `TriggerEvent`.
4. A colon splits an activated ability into costs and effects.
5. A leading duration (`Until end of turn, ...`) moves to the end of the
effect, where the duration parser expects it.
6. Otherwise a static effect is attempted.
7. Instant/sorcery lines fall back to a one-shot effect (`kind: "spell"`).
8. Anything left over is `unsupported`.
Effects are split on sentences, `, then`, and `and` only when both sides parse.
`When you do, ...` becomes a reflexive `if you do` condition. `it` becomes the
trigger subject only when no explicit target/`that` appears in the same effect;
ambiguous pronouns stay unsupported.
## Adding support
For a single card, open the frontend editor, edit the pseudocode, and save; no
compiler change is needed. For a whole class of cards:
1. Run `npm run compile:cards` and pick a frequent unsupported pattern.
2. Add a regex + AST builder in `src/effects/compile.ts` (or a target/value
parser in `src/effects/parse.ts`).
3. Add a focused test in `test/effects.test.ts`.
4. Run `npm test` and `npm run compile:cards`.
Prefer narrow, anchored patterns. A broad pattern that misreads one card is a
game bug that is hard to find later.
## Known gaps
The remaining unsupported lines are mostly:
- modal abilities (`Choose one —` and bullets)
- replacement effects (`If ... instead`, `As ... enters, ...`)
- continuous-effect layers and dependency rules
- copy, control-change, and type-change effects
- alternative/additional costs and cost modifiers
- level/class/saga structures and chapter abilities
- quoted token abilities and copying tokens
- complex pronoun/context resolution and "for each" scaling beyond simple counts
- dice, stickers, attractions, dungeons, and other supplemental mechanics
None of these are blocked by the AST; each needs a parser pattern and an engine
implementation.

158
backend/docs/game-engine.md Normal file
View File

@@ -0,0 +1,158 @@
# Game engine
`backend/src/game/` is a small but real Magic rules engine. It consumes the compiled
effect AST from `backend/src/effects/types.ts` directly — there is no second card
language. Card definitions are immutable input; a `GameObject` is the per-game
instance that moves between zones.
## Quick start
Run the data imports first (see the root README), then:
```ts
import { Game } from './src/game/game.js'
import { deckFromOracleIds } from './src/game/catalog.js'
const game = new Game({
seed: 1,
startingLife: 40,
startingHandSize: 7,
commander: true,
players: [
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 },
],
})
game.start()
```
`commander: true` creates each supplied commander in that player's command zone. The
`deck` should contain the other 99 cards; `validateCommanderDeck(commander, cards)`
in `commander.ts` checks size, singleton, color identity, and the commander type.
`catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds
intrinsic mana abilities for basic lands, because Scryfall's oracle text only has
reminder text for them and the compiler produces no ability.
For tests or hand-authored cards, build a `CardDefinition` yourself:
```ts
const bolt: CardDefinition = {
oracleId: 'lightning-bolt',
name: 'Lightning Bolt',
typeLine: 'Instant',
manaCost: '{R}',
manaValue: 1,
abilities: [{
kind: 'spell',
optional: false,
text: 'Lightning Bolt deals 3 damage to any target.',
effects: [{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }],
}],
}
```
## Actions
| Method | Purpose |
| ------ | ------- |
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. |
| `castSpell(playerId, cardId, { targets, x, mode })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. |
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. |
| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. |
| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. |
| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. |
| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. |
| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. |
| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. |
| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. |
| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. |
| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. |
| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. |
| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. |
Actions that use the stack move priority to the next living player. Non-instant,
non-flash spells can only be cast in the active player's main phase with an empty
stack. Targets may be supplied explicitly; if omitted, the first legal target is
chosen automatically, which keeps scripted games short. A search effect that matches
several cards pauses instead: other actions are refused until its controller calls
`chooseSearchCard` (the match API uses the `choose_search` action).
## Turn structure
```text
untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers
-> declare blockers -> combat damage -> end combat -> postcombat main
-> end step -> cleanup -> next player's turn
```
The starting player skips their first draw. Cleanup discards down to seven cards,
clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn`
effects, and empties mana pools. The engine advances phases when every living
player passes in turn; it does not stop at every rules-defined priority window.
The match manager calls `autoAdvance()` after each action, so priority is only
shown to players who can actually do something.
## Supported
- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
cease to exist when they leave the battlefield.
- Commander: command-zone casting, `{2}` tax per previous cast from the command
zone, return to the command zone instead of graveyard/exile/hand/library, and a
loss at 21 combat damage from one commander. Deck construction is validated by
`validateCommanderDeck`.
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
abilities plus automatic tapping of untapped mana sources when paying.
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
putting/removing counters, mill, energy, and choice costs.
- Abilities: spell effects, activated abilities, triggered abilities (enters,
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static
effects, and basic replacement effects for entering tapped/with counters.
- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability,
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy,
attach, restrictions, conditional and modal effects, dig, and divided damage.
- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
lifelink, vigilance, haste, indestructible. Regeneration shields replace
destruction.
- State-based actions: life at or below zero, ten poison counters, 21 commander
damage from one commander, lethal or deathtouch damage, zero toughness, and
drawing from an empty library.
## Known limitations
- Some effect nodes are accepted but intentionally do nothing yet:
`prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`,
`put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`.
Unsupported oracle lines are already marked by the compiler and never reach here.
- Commander support covers single commanders. Partner, backgrounds, companions,
and "choose a commander" variants are not modelled. The engine always takes the
command-zone replacement instead of asking.
- The legend rule, planeswalker loyalty abilities, attacking planeswalkers, and
protection/menace/defender are not implemented unless expressed as a compiled
restriction.
- Modal spells choose a mode by index (`options.mode`); optional "you may" choices
are not modelled. An optional `pay` is simply not paid when unaffordable. Search
effects with several matching cards do pause for the player's pick.
- Opening hands are kept automatically; there is no mulligan flow.
- Replacement/prevention effects, layers, and dependency ordering are simplified.
Continuous effects apply in creation order rather than in full rules order.
- The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory
multiplayer matches, validates decks, and sends each player a personalized view
(own hand only, libraries as counts) over SSE.
- There is no persistence, account system, or reconnect grace period; a server
restart drops all matches.
## Tests
```bash
cd backend
npx tsx --test test/game.test.ts test/commander.test.ts
```
The tests cover turn flow, priority, spell resolution, triggers, mana and summoning
sickness, static and temporary pumps, combat, counterspells, tokens, searching,
entering tapped/with counters, decking, lethal damage, commander tax and damage,
decklist import, and multi-defender combat.

1809
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

24
backend/package.json Normal file
View File

@@ -0,0 +1,24 @@
{
"name": "commander-backend",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js",
"import:cards": "tsx scripts/import-cards.ts",
"compile:cards": "tsx scripts/compile-cards.ts",
"test": "tsx --test test/*.test.ts"
},
"dependencies": {
"@fastify/cors": "^11.3.1",
"fastify": "^5.12.7",
"mongoose": "^9.11.4"
},
"devDependencies": {
"@types/node": "^24.19.2",
"tsx": "^4.23.15",
"typescript": "^7.0.2"
}
}

View File

@@ -0,0 +1,103 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { Card } from '../src/cards.js'
import { compileCard } from '../src/effects/compile.js'
import { formatCard } from '../src/effects/format.js'
import { compileImplementation, readAllOverrides } from '../src/effects/implementations.js'
import { PseudoParseError } from '../src/effects/pseudo.js'
import type { Ability, CompiledCard } from '../src/effects/types.js'
const DATA_DIR = join(process.cwd(), 'data')
const CARDS_FILE = join(DATA_DIR, 'cards.json')
const AST_FILE = join(DATA_DIR, 'card-effects.json')
const PSEUDO_FILE = join(DATA_DIR, 'card-effects.pseudo.txt')
function formatBytes(bytes: number): string {
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
let cards: Card[]
try {
cards = JSON.parse(await readFile(CARDS_FILE, 'utf8')) as Card[]
} catch {
console.error(`Card data not found at ${CARDS_FILE}. Run "npm run import:cards" first.`)
process.exit(1)
}
const overrides = await readAllOverrides()
const cardsById = new Map(cards.map(card => [card.oracle_id, card]))
for (const oracleId of overrides.keys()) {
if (!cardsById.has(oracleId)) {
console.warn(`Ignoring override for unknown oracle id: ${oracleId}`)
}
}
const compiled: CompiledCard[] = []
const cardCounts = { supported: 0, partial: 0, unsupported: 0 }
const reasons = new Map<string, number>()
const samples: string[] = []
let abilityCount = 0
let manualCount = 0
let parsedCount = 0
function abilitiesOf(card: CompiledCard): Ability[] {
return card.faces ? card.faces.flatMap(face => face.abilities) : card.abilities
}
function sourceLines(ability: Ability): number {
if (ability.kind === 'keyword' || ability.kind === 'keywords') return 1
return ability.text.split('\n').length
}
for (const card of cards) {
const source = overrides.get(card.oracle_id)
let result: CompiledCard
try {
result = source === undefined ? compileCard(card) : compileImplementation(card, source)
} catch (error) {
if (error instanceof PseudoParseError) {
console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`)
console.error(` ${error.message}`)
process.exit(1)
}
throw error
}
if (result.manual) manualCount++
compiled.push(result)
cardCounts[result.status]++
for (const ability of abilitiesOf(result)) {
const lines = sourceLines(ability)
abilityCount += lines
if (ability.kind === 'unsupported') {
reasons.set(ability.reason, (reasons.get(ability.reason) ?? 0) + lines)
if (samples.length < 10 && ability.reason === 'unmatched line') samples.push(ability.text)
} else {
parsedCount += lines
}
}
}
await mkdir(DATA_DIR, { recursive: true })
const astOutput = JSON.stringify(compiled)
const pseudoOutput = compiled.map(formatCard).join('\n\n')
await writeFile(AST_FILE, astOutput)
await writeFile(PSEUDO_FILE, pseudoOutput)
console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`)
console.log(
`Cards: ${cardCounts.supported} supported, ${cardCounts.partial} partial, ${cardCounts.unsupported} unsupported.`,
)
console.log(
`Ability lines: ${parsedCount}/${abilityCount} parsed (${((100 * parsedCount) / abilityCount).toFixed(1)}%).`,
)
console.log('Unsupported reasons:')
for (const [reason, count] of [...reasons.entries()].sort((a, b) => b[1] - a[1])) {
console.log(` ${reason}: ${count}`)
}
if (samples.length) {
console.log('Sample unsupported lines:')
for (const sample of samples) console.log(` - ${sample}`)
}
console.log(`Wrote ${formatBytes(Buffer.byteLength(astOutput))} to ${AST_FILE}`)
console.log(`Wrote ${formatBytes(Buffer.byteLength(pseudoOutput))} to ${PSEUDO_FILE}`)

View File

@@ -0,0 +1,166 @@
import { mkdir, rename, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { createInterface } from 'node:readline'
import { Readable } from 'node:stream'
import { createGunzip } from 'node:zlib'
import type { Card, CardFace } from '../src/cards.js'
const BULK_API = 'https://api.scryfall.com/bulk-data'
const OUT_FILE = join(process.cwd(), 'data', 'cards.json')
const HEADERS = {
'User-Agent': 'commander-import/0.1',
Accept: 'application/json',
}
interface BulkData {
type: string
name: string
updated_at: string
compressed_size: number
jsonl_download_uri?: string
}
interface RawFace {
name: string
mana_cost?: string
type_line?: string
oracle_text?: string
colors?: string[]
power?: string
toughness?: string
loyalty?: string
defense?: string
image_uris?: { normal?: string }
}
interface RawCard {
oracle_id: string
name: string
layout?: string
mana_cost?: string
cmc?: number
type_line?: string
oracle_text?: string
colors?: string[]
color_identity?: string[]
keywords?: string[]
rarity?: string
power?: string
toughness?: string
loyalty?: string
defense?: string
image_uris?: { normal?: string }
card_faces?: RawFace[]
legalities?: Record<string, string>
}
function toFace(face: RawFace): CardFace {
return {
name: face.name,
mana_cost: face.mana_cost,
type_line: face.type_line,
oracle_text: face.oracle_text,
colors: face.colors ?? [],
power: face.power,
toughness: face.toughness,
loyalty: face.loyalty,
defense: face.defense,
image_uri: face.image_uris?.normal,
}
}
function toCard(raw: RawCard): Card {
return {
oracle_id: raw.oracle_id,
name: raw.name,
layout: raw.layout ?? 'normal',
cmc: raw.cmc ?? 0,
type_line: raw.type_line ?? '',
colors: raw.colors ?? [],
color_identity: raw.color_identity ?? [],
keywords: raw.keywords ?? [],
rarity: raw.rarity,
legal_formats: Object.entries(raw.legalities ?? {})
.filter(([, status]) => status === 'legal' || status === 'restricted')
.map(([format]) => format),
mana_cost: raw.mana_cost,
oracle_text: raw.oracle_text,
power: raw.power,
toughness: raw.toughness,
loyalty: raw.loyalty,
defense: raw.defense,
image_uri: raw.image_uris?.normal ?? raw.card_faces?.[0]?.image_uris?.normal,
card_faces: raw.card_faces?.map(toFace),
}
}
function formatBytes(bytes: number): string {
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
const metaResponse = await fetch(BULK_API, { headers: HEADERS })
if (!metaResponse.ok) {
throw new Error(`Scryfall bulk-data request failed: ${metaResponse.status}`)
}
const meta = (await metaResponse.json()) as { data: BulkData[] }
const bulk = meta.data.find(entry => entry.type === 'oracle_cards')
if (!bulk?.jsonl_download_uri) {
throw new Error('Scryfall oracle_cards bulk export not found')
}
console.log(
`Downloading ${bulk.name} (${formatBytes(bulk.compressed_size)}, updated ${bulk.updated_at})...`,
)
const response = await fetch(bulk.jsonl_download_uri, { headers: HEADERS })
if (!response.ok || !response.body) {
throw new Error(`Scryfall card download failed: ${response.status}`)
}
const body = response.body as Parameters<typeof Readable.fromWeb>[0]
const lines = createInterface({
input: Readable.fromWeb(body).pipe(createGunzip()),
crlfDelay: Infinity,
})
const cards: Card[] = []
const seen = new Set<string>()
let skipped = 0
for await (const line of lines) {
if (!line.trim()) continue
const raw = JSON.parse(line) as RawCard
if (!raw.oracle_id || !raw.name) {
throw new Error(`Scryfall card is missing oracle_id or name: ${line.slice(0, 120)}`)
}
if (seen.has(raw.oracle_id)) {
throw new Error(`Duplicate oracle_id in Scryfall export: ${raw.oracle_id}`)
}
seen.add(raw.oracle_id)
if (raw.legalities?.commander !== 'legal') {
skipped++
continue
}
cards.push(toCard(raw))
}
if (cards.length < 15_000) {
throw new Error(`Imported only ${cards.length} cards, expected at least 15000`)
}
cards.sort((a, b) => a.name.localeCompare(b.name) || a.oracle_id.localeCompare(b.oracle_id))
const output = JSON.stringify(cards)
const tmpFile = `${OUT_FILE}.tmp`
await mkdir(dirname(OUT_FILE), { recursive: true })
await writeFile(tmpFile, output)
await rename(tmpFile, OUT_FILE)
console.log(
`Imported ${cards.length} Commander-legal cards (skipped ${skipped} other cards, ${seen.size} total).`,
)
console.log(`Wrote ${formatBytes(Buffer.byteLength(output))} to ${OUT_FILE}`)

336
backend/src/accounts.ts Normal file
View File

@@ -0,0 +1,336 @@
import { createHash, randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util'
import mongoose, { Schema } from 'mongoose'
import type { FastifyInstance, FastifyRequest } from 'fastify'
import { implementationIndex, type ImplementationSummary } from './effects/implementations.js'
const scrypt = promisify(scryptCallback)
const USERNAME = /^[a-zA-Z0-9_.-]{3,32}$/
const JPEG_DATA_URL = /^data:image\/jpeg;base64,[A-Za-z0-9+/]+={0,2}$/
const MAX_PLAYMAT_LENGTH = 4_500_000
const MAX_CARD_BACK_LENGTH = 1_500_000
export class AuthError extends Error {
constructor(message: string, readonly status = 401) {
super(message)
}
}
export interface DeckCardInput {
oracleId: string
name: string
manaCost?: string
typeLine: string
colorIdentity: string[]
oracleText?: string
imageUri?: string
}
export interface DeckInput {
name: string
commander: DeckCardInput
cards: DeckCardInput[]
cardBack?: string | null
}
export type PlaymatInput =
| { kind: 'card'; oracleId: string }
| { kind: 'upload'; data: string }
const userSchema = new Schema({
username: { type: String, required: true, trim: true },
salt: { type: String, required: true },
passwordHash: { type: String, required: true },
playmat: { type: Schema.Types.Mixed, default: null, select: false },
cardBack: { type: String, default: null, select: false },
}, { timestamps: true })
userSchema.index({ username: 1 }, { unique: true, collation: { locale: 'en', strength: 2 } })
const sessionSchema = new Schema({
tokenHash: { type: String, required: true, unique: true },
userId: { type: Schema.Types.ObjectId, required: true, index: true },
createdAt: { type: Date, default: Date.now, expires: '30d' },
})
const deckCardSchema = new Schema({
oracleId: { type: String, required: true },
name: { type: String, required: true },
manaCost: String,
typeLine: { type: String, required: true },
colorIdentity: [String],
oracleText: String,
imageUri: String,
}, { _id: false })
const deckSchema = new Schema({
owner: { type: Schema.Types.ObjectId, required: true, index: true },
deckId: { type: String, required: true },
name: { type: String, required: true },
commander: { type: deckCardSchema, required: true },
cards: { type: [deckCardSchema], default: [] },
cardBack: { type: String, default: null },
updatedAt: { type: Number, required: true },
})
deckSchema.index({ owner: 1, deckId: 1 }, { unique: true })
const User = mongoose.models.User ?? mongoose.model('User', userSchema)
const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema)
const Deck = mongoose.models.Deck ?? mongoose.model('Deck', deckSchema)
interface DeckRow {
deckId: string
name: string
commander: DeckCardInput
cards: DeckCardInput[]
cardBack?: string | null
updatedAt: number
}
export async function connectDatabase(
uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/commander',
): Promise<void> {
await mongoose.connect(uri)
await Promise.all([User.init(), Session.init(), Deck.init()])
}
export async function closeDatabase(): Promise<void> {
await mongoose.disconnect()
}
export async function hashPassword(password: string): Promise<{ salt: string; hash: string }> {
const salt = randomBytes(16).toString('hex')
const hash = (await scrypt(password, salt, 64)) as Buffer
return { salt, hash: hash.toString('hex') }
}
export async function verifyPassword(password: string, salt: string, hash: string): Promise<boolean> {
const actual = (await scrypt(password, salt, 64)) as Buffer
const expected = Buffer.from(hash, 'hex')
return actual.length === expected.length && timingSafeEqual(actual, expected)
}
function tokenHash(token: string): string {
return createHash('sha256').update(token).digest('hex')
}
function bearerToken(request: FastifyRequest): string | undefined {
const header = request.headers.authorization
return header?.startsWith('Bearer ') ? header.slice(7).trim() || undefined : undefined
}
async function startSession(userId: string): Promise<string> {
const token = randomBytes(32).toString('hex')
await Session.create({ tokenHash: tokenHash(token), userId })
return token
}
async function authenticate(request: FastifyRequest): Promise<{ id: string; username: string }> {
const token = bearerToken(request)
if (!token) throw new AuthError('Sign in required')
const session = await Session.findOne({ tokenHash: tokenHash(token) }).lean()
if (!session) throw new AuthError('Your session has expired; sign in again')
const user = await User.findById(session.userId).select('_id username').lean()
if (!user) throw new AuthError('User not found')
return { id: String(user._id), username: user.username }
}
function credentials(body: unknown): { username: string; password: string } {
const input = body as { username?: unknown; password?: unknown } | null | undefined
if (typeof input?.username !== 'string' || typeof input?.password !== 'string') {
throw new AuthError('Send a username and a password', 400)
}
const username = input.username.trim()
if (!USERNAME.test(username)) {
throw new AuthError('Username must be 3-32 letters, numbers, dots, dashes or underscores', 400)
}
if (input.password.length < 8 || input.password.length > 200) {
throw new AuthError('Password must be 8-200 characters', 400)
}
return { username, password: input.password }
}
function limitedText(value: unknown, max: number): string | undefined {
return typeof value === 'string' && value.length <= max ? value : undefined
}
function parseDeckCard(value: unknown): DeckCardInput | null {
if (!value || typeof value !== 'object') return null
const card = value as Record<string, unknown>
const oracleId = limitedText(card.oracleId, 100)
const name = limitedText(card.name, 200)
const typeLine = limitedText(card.typeLine, 300)
if (!oracleId || !name || !typeLine) return null
return {
oracleId,
name,
manaCost: limitedText(card.manaCost, 100),
typeLine,
colorIdentity: Array.isArray(card.colorIdentity)
? card.colorIdentity.filter((color): color is string => typeof color === 'string' && color.length <= 2).slice(0, 8)
: [],
oracleText: limitedText(card.oracleText, 5_000),
imageUri: limitedText(card.imageUri, 500),
}
}
function parseDeck(value: unknown): DeckInput | null {
if (!value || typeof value !== 'object') return null
const deck = value as Record<string, unknown>
const name = limitedText(deck.name, 60)
const commander = parseDeckCard(deck.commander)
if (!name || !commander || !Array.isArray(deck.cards) || deck.cards.length > 250) return null
const cards = deck.cards.map(parseDeckCard)
if (cards.some(card => !card)) return null
const cardBack = 'cardBack' in deck ? parseCardBack(deck.cardBack) : undefined
if ('cardBack' in deck && cardBack === undefined) return null
return { name, commander, cards: cards as DeckCardInput[], cardBack }
}
function parsePlaymat(value: unknown): PlaymatInput | null | undefined {
if (value === null) return null
if (!value || typeof value !== 'object') return undefined
const choice = value as Record<string, unknown>
if (choice.kind === 'card' && typeof choice.oracleId === 'string' && choice.oracleId.length <= 100) {
return { kind: 'card', oracleId: choice.oracleId }
}
if (choice.kind === 'upload' && typeof choice.data === 'string'
&& choice.data.length <= MAX_PLAYMAT_LENGTH && JPEG_DATA_URL.test(choice.data)) {
return { kind: 'upload', data: choice.data }
}
return undefined
}
function parseCardBack(value: unknown): string | null | undefined {
if (value === null) return null
if (typeof value !== 'string' || value.length > MAX_CARD_BACK_LENGTH) return undefined
if (/^#[0-9a-fA-F]{3,8}$/.test(value)) return value
if (JPEG_DATA_URL.test(value)) return value
return undefined
}
function toDeck(row: DeckRow, index?: Map<string, ImplementationSummary>) {
const enrich = (card: DeckCardInput) => {
const implementation = index?.get(card.oracleId)
return implementation ? { ...card, implementation } : card
}
return {
id: row.deckId,
name: row.name,
commander: enrich(row.commander),
cards: row.cards.map(enrich),
cardBack: row.cardBack ?? null,
updatedAt: row.updatedAt,
}
}
async function preferences(userId: string) {
const user = await User.findById(userId)
.select('+playmat +cardBack')
.lean<{ playmat?: PlaymatInput | null; cardBack?: string | null }>()
if (!user) throw new AuthError('User not found')
return { playmat: user.playmat ?? null, cardBack: user.cardBack ?? null }
}
export function registerAccountRoutes(app: FastifyInstance): void {
app.post<{ Body: { username?: unknown; password?: unknown } }>('/auth/register', async (request, reply) => {
const { username, password } = credentials(request.body)
const existing = await User.findOne({ username }).collation({ locale: 'en', strength: 2 }).select('_id').lean()
if (existing) return reply.code(409).send({ error: 'That username is taken' })
const { salt, hash } = await hashPassword(password)
try {
const user = await User.create({ username, salt, passwordHash: hash })
const token = await startSession(String(user._id))
return reply.code(201).send({ token, username: user.username })
} catch (error) {
if ((error as { code?: number }).code === 11000) {
return reply.code(409).send({ error: 'That username is taken' })
}
throw error
}
})
app.post<{ Body: { username?: unknown; password?: unknown } }>('/auth/login', async (request, reply) => {
const { username, password } = credentials(request.body)
const user = await User.findOne({ username }).collation({ locale: 'en', strength: 2 })
if (!user || !(await verifyPassword(password, user.salt, user.passwordHash))) {
return reply.code(401).send({ error: 'Wrong username or password' })
}
return { token: await startSession(String(user._id)), username: user.username }
})
app.post('/auth/logout', async request => {
const token = bearerToken(request)
if (token) await Session.deleteOne({ tokenHash: tokenHash(token) })
return { ok: true }
})
app.get('/auth/me', async request => {
const user = await authenticate(request)
return { username: user.username }
})
app.get('/me/decks', async request => {
const user = await authenticate(request)
const decks = await Deck.find({ owner: user.id }).sort({ updatedAt: -1 }).lean<DeckRow[]>()
const index = await implementationIndex()
return { decks: decks.map(deck => toDeck(deck, index)) }
})
app.put<{ Params: { id: string } }>(
'/me/decks/:id',
{ bodyLimit: 6_500_000 },
async (request, reply) => {
const user = await authenticate(request)
const deckId = request.params.id
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(deckId)) {
return reply.code(400).send({ error: 'Invalid deck id' })
}
const deck = parseDeck(request.body)
if (!deck) return reply.code(400).send({ error: 'Invalid deck' })
const row = await Deck.findOneAndUpdate(
{ owner: user.id, deckId },
{ ...deck, updatedAt: Date.now() },
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).lean<DeckRow>()
if (!row) throw new AuthError('Could not save the deck', 500)
return { deck: toDeck(row) }
},
)
app.delete<{ Params: { id: string } }>('/me/decks/:id', async request => {
const user = await authenticate(request)
await Deck.deleteOne({ owner: user.id, deckId: request.params.id })
return { ok: true }
})
app.get('/me/preferences', async request => {
const user = await authenticate(request)
return preferences(user.id)
})
app.put<{ Body: Record<string, unknown> }>(
'/me/preferences',
{ bodyLimit: 6_500_000 },
async (request, reply) => {
const user = await authenticate(request)
const body = request.body ?? {}
const update: Record<string, unknown> = {}
if ('playmat' in body) {
const playmat = parsePlaymat(body.playmat)
if (playmat === undefined) return reply.code(400).send({ error: 'Invalid playmat' })
update.playmat = playmat
}
if ('cardBack' in body) {
const cardBack = parseCardBack(body.cardBack)
if (cardBack === undefined) return reply.code(400).send({ error: 'Invalid card back' })
update.cardBack = cardBack
}
if (Object.keys(update).length) await User.updateOne({ _id: user.id }, { $set: update })
return preferences(user.id)
},
)
}

139
backend/src/cards.ts Normal file
View File

@@ -0,0 +1,139 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
export interface CardFace {
name: string
mana_cost?: string
type_line?: string
oracle_text?: string
colors: string[]
power?: string
toughness?: string
loyalty?: string
defense?: string
image_uri?: string
}
export interface Card {
oracle_id: string
name: string
layout: string
cmc: number
type_line: string
colors: string[]
color_identity: string[]
keywords: string[]
rarity?: string
legal_formats?: string[]
mana_cost?: string
oracle_text?: string
power?: string
toughness?: string
loyalty?: string
defense?: string
image_uri?: string
card_faces?: CardFace[]
}
export interface CardFilters {
format?: string
color?: string
type?: string
rarity?: string
cmcMin?: number
cmcMax?: number
}
/** Color filter matches color identity: C is colorless, M is more than one color. */
export function matchesCardFilters(card: Card, filters: CardFilters): boolean {
if (filters.format && !card.legal_formats?.includes(filters.format)) return false
if (filters.color) {
const identity = card.color_identity
const matches = filters.color === 'C'
? identity.length === 0
: filters.color === 'M'
? identity.length > 1
: identity.includes(filters.color)
if (!matches) return false
}
const type = filters.type
if (type) {
const typeLines = [card.type_line, ...(card.card_faces?.map(face => face.type_line ?? '') ?? [])]
if (!typeLines.some(line => line.toLowerCase().includes(type))) return false
}
if (filters.rarity && card.rarity !== filters.rarity) return false
if (filters.cmcMin !== undefined && card.cmc < filters.cmcMin) return false
if (filters.cmcMax !== undefined && card.cmc > filters.cmcMax) return false
return true
}
export class CardsUnavailableError extends Error {}
const DATA_FILE = join(import.meta.dirname, '..', 'data', 'cards.json')
let data: { cards: Card[]; byId: Map<string, Card>; byName: Map<string, Card> } | undefined
function namesOf(card: Card): string[] {
const names = new Set([card.name, ...(card.card_faces?.map(face => face.name) ?? [])])
for (const name of [...names]) {
const front = name.split(' // ')[0]
if (front) names.add(front)
}
return [...names]
}
function load() {
if (data) return data
let raw: string
try {
raw = readFileSync(DATA_FILE, 'utf8')
} catch {
throw new CardsUnavailableError(
`Card data not found at ${DATA_FILE}. Run "npm run import:cards" in backend/.`,
)
}
const cards = JSON.parse(raw) as Card[]
if (!Array.isArray(cards)) throw new Error(`Invalid card data at ${DATA_FILE}`)
const byName = new Map<string, Card>()
for (const card of cards) {
for (const name of namesOf(card)) {
const key = name.toLowerCase()
if (!byName.has(key)) byName.set(key, card)
}
}
data = { cards, byId: new Map(cards.map(card => [card.oracle_id, card])), byName }
return data
}
export function getCard(oracleId: string): Card | undefined {
return load().byId.get(oracleId)
}
/** Case-insensitive exact lookup; also accepts a split card's front face. */
export function findCardByName(name: string): Card | undefined {
return load().byName.get(name.trim().toLowerCase())
}
export function allCards(): Card[] {
return load().cards
}
export function searchCards(
query: string,
limit: number,
offset = 0,
filter?: (card: Card) => boolean,
): { total: number; cards: Card[] } {
const { cards } = load()
const needle = query.trim().toLowerCase()
const matches = cards.filter(card =>
(!needle || card.name.toLowerCase().includes(needle)) && (!filter || filter(card)),
)
return { total: matches.length, cards: matches.slice(offset, offset + limit) }
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,603 @@
import type {
Ability,
CompiledCard,
Condition,
Cost,
Duration,
Effect,
ManaSpec,
ObjectSelector,
StaticEffect,
Target,
TokenSpec,
TriggerEvent,
Value,
} from './types.js'
const COLOR_NAMES: Record<string, string> = { W: 'white', U: 'blue', B: 'black', R: 'red', G: 'green', C: 'colorless' }
function formatValue(value: Value): string {
switch (value.kind) {
case 'number':
return String(value.value)
case 'x':
return 'X'
case 'count':
return `count(${formatSelector(value.selector)})`
case 'source_power':
return 'its power'
case 'source_toughness':
return 'its toughness'
case 'cards_in_hand':
return `cards in ${value.player === 'you' ? 'your' : "that player's"} hand`
case 'max_cards_in_hand':
return 'cards in the hand of the opponent with the most cards'
case 'max_opponent_count':
return `greatest number of ${formatSelector(value.selector)} an opponent controls`
case 'total_mana_value':
return `total mana value of ${formatSelector(value.selector)}`
case 'total_power':
return `total power of ${formatSelector(value.selector)}`
case 'any_number':
return 'any number'
case 'event_amount':
return 'that much'
}
}
function isBareSelector(selector: ObjectSelector): boolean {
return selector.types?.length === 0 && Object.keys(selector).every(key => key === 'types')
}
function formatSelector(selector: ObjectSelector): string {
const parts: string[] = []
if (selector.other) parts.push('other')
if (selector.tapped === true) parts.push('tapped')
if (selector.tapped === false) parts.push('untapped')
if (selector.attacking) parts.push('attacking')
if (selector.token) parts.push('token')
if (selector.token === false) parts.push('nontoken')
if (selector.attached) parts.push(selector.attached)
if (selector.colors?.length) {
parts.push(selector.colors.map(color => COLOR_NAMES[color] ?? color).join(' and '))
}
if (selector.supertypes?.length) parts.push(...selector.supertypes)
if (selector.subtypes?.length) parts.push(selector.subtypes.join(' '))
if (selector.types?.length) {
parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' '))
}
if (selector.excludeTypes?.length) parts.push(`non-${selector.excludeTypes.join('/')}`)
if (selector.counters) parts.push(`with ${selector.counters.atLeast}+ ${selector.counters.counter} counters`)
if (selector.keywords?.length) parts.push(`with ${selector.keywords.join(' and ')}`)
if (selector.excludeKeywords?.length) parts.push(`without ${selector.excludeKeywords.join(' and ')}`)
if (selector.power?.atLeast !== undefined) parts.push(`power ${selector.power.atLeast}+`)
if (selector.power?.atMost !== undefined) parts.push(`power ${selector.power.atMost} or less`)
if (selector.toughness?.atLeast !== undefined) parts.push(`toughness ${selector.toughness.atLeast}+`)
if (selector.toughness?.atMost !== undefined) parts.push(`toughness ${selector.toughness.atMost} or less`)
if (selector.manaValue?.atLeast !== undefined) parts.push(`mana value ${selector.manaValue.atLeast}+`)
if (selector.manaValue?.atMost !== undefined) parts.push(`mana value ${selector.manaValue.atMost} or less`)
if (selector.name) parts.push(`named ${selector.name}`)
let text = parts.filter(Boolean).join(' ')
if (selector.controller === 'you') text += ' you control'
else if (selector.controller === 'opponent') text += ' an opponent controls'
if (selector.owner === 'you') text += ' you own'
else if (selector.owner === 'opponent') text += " you don't own"
if (!text) text = 'card'
if (selector.zone === 'graveyard') text += ' from a graveyard'
else if (selector.zone === 'library') text += ' from a library'
else if (selector.zone === 'hand') text += ' from a hand'
else if (selector.zone === 'exile') text += ' in exile'
return text
}
export function formatTarget(target: Target): string {
switch (target.kind) {
case 'self':
return 'this'
case 'trigger_subject':
return 'the triggering object'
case 'previous_target':
return 'the chosen target'
case 'any':
return 'any target'
case 'player':
if (target.mode === 'each') {
if (target.who === 'each_opponent') return 'each opponent'
if (target.who === 'each_player') return 'each player'
}
if (target.who === 'you') return 'you'
if (target.who === 'target_player') return 'target player'
if (target.who === 'that_player') return 'that player'
if (target.who === 'opponent') return 'target opponent'
if (target.who === 'its_controller') return 'its controller'
if (target.who === 'its_owner') return 'its owner'
return target.who
case 'player_or_planeswalker':
return 'target player or planeswalker'
case 'object': {
const prefix = target.mode === 'target' ? 'target ' : target.mode === 'each' ? 'each ' : ''
const count = target.count ? `${target.upTo ? 'up to ' : ''}${target.count} ` : ''
const includeSelf = target.includeSelf ? 'this or ' : ''
return `${prefix}${count}${includeSelf}${formatSelector(target.selector)}`
}
case 'spell':
return isBareSelector(target.selector) ? 'target spell' : `target ${formatSelector(target.selector)} spell`
case 'ability':
return 'target ability'
case 'divided':
return `divided(${target.max === 'any' ? 'any number' : target.max}${target.selector ? `, ${formatSelector(target.selector)}` : ''})`
}
}
function formatMana(mana: ManaSpec): string {
if (mana.kind === 'symbols') {
return `${mana.symbols.join('')}${mana.restriction ? ` (only ${mana.restriction})` : ''}`
}
return `${formatValue(mana.amount)} mana of any${mana.oneColor ? ' one' : ''} color${mana.restriction ? ` (only ${mana.restriction})` : ''}`
}
function formatCost(cost: Cost): string {
switch (cost.kind) {
case 'mana':
return cost.symbols
case 'tap':
return '{T}'
case 'untap':
return '{Q}'
case 'tap_other':
return `tap ${formatSelector(cost.selector)}`
case 'energy':
return `{E} x${cost.amount}`
case 'loyalty':
return `${cost.amount > 0 ? '+' : ''}${cost.amount} loyalty`
case 'pay_life':
return `pay ${formatValue(cost.amount)} life`
case 'discard':
if (cost.amount.kind === 'cards_in_hand' && cost.amount.player === 'you') {
return `discard your hand${cost.random ? ' at random' : ''}`
}
return `discard ${formatValue(cost.amount)} card(s)${cost.random ? ' at random' : ''}`
case 'sacrifice':
return `sacrifice ${formatSelector(cost.selector)}`
case 'sacrifice_self':
return 'sacrifice this'
case 'exile_self':
return 'exile this from a graveyard'
case 'exile_from_graveyard':
return `exile ${cost.amount ? `${formatValue(cost.amount)} ` : ''}${formatSelector(cost.selector)} from your graveyard`
case 'reveal':
return `reveal ${formatSelector(cost.selector)} from your hand`
case 'choice':
return `(${cost.options.map(option => option.map(formatCost).join(' + ')).join(' or ')})`
case 'return_to_hand':
return `return ${formatSelector(cost.selector)} to its owner's hand`
case 'behold':
return `behold ${formatSelector(cost.selector)}`
case 'waterbend':
return `waterbend ${formatValue(cost.amount)}`
case 'blight':
return `blight ${formatValue(cost.amount)}`
case 'choose':
return `choose ${cost.what}`
case 'put_counter':
return `put ${cost.counter} counter on ${formatSelector(cost.selector)}`
case 'remove_counters':
return `remove ${formatValue(cost.amount)} ${cost.counter} counter(s) from ${cost.selector ? formatSelector(cost.selector) : 'this'}`
case 'forage':
return 'forage'
case 'collect_evidence':
return `collect evidence ${cost.amount}`
case 'mill':
return `mill ${formatValue(cost.amount)} card(s)`
}
}
function formatDuration(duration: Duration): string {
switch (duration) {
case 'permanent':
return ''
case 'until_end_of_turn':
return ', until end of turn'
case 'until_your_next_turn':
return ', until your next turn'
case 'until_end_of_your_next_turn':
return ', until the end of your next turn'
case 'until_end_of_combat':
return ', until end of combat'
case 'until_controllers_next_untap_step':
return ", until its controller's next untap step"
case 'while_source_on_battlefield':
return ', for as long as this remains on the battlefield'
}
}
function formatToken(token: TokenSpec): string {
const parts: string[] = []
if (token.tapped) parts.push('tapped')
if (token.power && token.toughness) parts.push(`${formatValue(token.power)}/${formatValue(token.toughness)}`)
if (token.colors?.length) parts.push(token.colors.map(color => COLOR_NAMES[color] ?? color).join(' and '))
if (token.subtypes.length) parts.push(...token.subtypes)
if (token.types.length) parts.push(...token.types)
if (token.keywords?.length) parts.push(`with ${token.keywords.join(', ')}`)
return parts.join(' ')
}
export function formatEffect(effect: Effect): string {
switch (effect.op) {
case 'damage':
return `damage(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.source ? `, from ${formatTarget(effect.source)}` : ''})`
case 'draw':
return `draw(${effect.player}, ${formatValue(effect.amount)})`
case 'discard':
return `discard(${effect.player}, ${formatValue(effect.amount)}${effect.random ? ', at random' : ''})`
case 'mill':
return `mill(${effect.player}, ${formatValue(effect.amount)})`
case 'life':
return `${effect.mode === 'gain' ? 'gain_life' : 'lose_life'}(${effect.player}, ${formatValue(effect.amount)})`
case 'pump':
return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})`
case 'grant':
return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''}${formatDuration(effect.duration)})`
case 'put_counters':
return `put_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
case 'remove_counters':
return `remove_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
case 'proliferate':
return 'proliferate()'
case 'create_token':
return effect.copyOf
? `create_token(${effect.player}, ${formatValue(effect.amount)}, copy of ${formatTarget(effect.copyOf)}${effect.notLegendary ? ', not legendary' : ''})`
: `create_token(${effect.player}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})`
case 'destroy':
return `destroy(${formatTarget(effect.target)})`
case 'exile':
return `exile(${formatTarget(effect.target)})`
case 'sacrifice':
return `sacrifice(${effect.player}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})`
case 'counter':
return `counter(${effect.what}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})`
case 'return_to_hand':
return `return_to_hand(${formatTarget(effect.target)})`
case 'return_to_battlefield': {
const counters = effect.counters
? `, ${effect.counters.amount.kind === 'number' ? effect.counters.amount.value : formatValue(effect.counters.amount)} ${effect.counters.counter} counters`
: ''
return `return_to_battlefield(${formatTarget(effect.target)}${effect.tapped ? ', tapped' : ''}${effect.transformed ? ', transformed' : ''}${counters})`
}
case 'set_pt':
return `set_pt(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})`
case 'put_on_top':
return `put_on_top(${formatTarget(effect.target)})`
case 'tap':
return `tap(${formatTarget(effect.target)})`
case 'untap':
return `untap(${formatTarget(effect.target)})`
case 'scry':
return `scry(${effect.player}, ${formatValue(effect.amount)})`
case 'surveil':
return `surveil(${effect.player}, ${formatValue(effect.amount)})`
case 'search':
return `search(${effect.player}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}, to ${effect.destination}${effect.zones?.length === 2 ? ', library+graveyard' : ''}${effect.tapped ? ', tapped' : ''}${effect.shuffle ? ', shuffle' : ''})`
case 'shuffle':
return `shuffle(${effect.player})`
case 'add_mana':
return `add_mana(${effect.player}, ${formatMana(effect.mana)})`
case 'fight':
return `fight(${formatTarget(effect.a)}, ${formatTarget(effect.b)})`
case 'regenerate':
return `regenerate(${formatTarget(effect.target)})`
case 'energy':
return `energy(${effect.player}, ${formatValue(effect.amount)})`
case 'attach':
return `attach(this, ${formatTarget(effect.target)})`
case 'restriction':
return `restrict(${formatTarget(effect.target)}, ${effect.rule}${formatDuration(effect.duration)})`
case 'keyword_action':
return `${effect.action.replace(/ /g, '_')}(${effect.target ? formatTarget(effect.target) : ''}${effect.amount ? `${effect.target ? ', ' : ''}${formatValue(effect.amount)}` : ''}${effect.detail ? `, ${effect.detail}` : ''})`
case 'level_up':
return `level_up(${effect.level})`
case 'put_from_among':
return `put_from_among(${formatValue(effect.amount)}${effect.selector ? `, ${formatSelector(effect.selector)}` : ''}, to ${effect.destination})`
case 'dig':
return `dig(${formatValue(effect.amount)}, ${effect.upTo ? 'up to ' : ''}${formatValue(effect.pick)}${effect.pickSelector ? ` ${formatSelector(effect.pickSelector)}` : ''} to ${effect.to}${effect.tapped ? ' tapped' : ''}, rest ${effect.rest}${effect.order ? ` ${effect.order}` : ''}${effect.optional ? ', optional' : ''})`
case 'prevent_damage':
return `prevent_${effect.combatOnly ? 'combat_' : ''}damage(${formatTarget(effect.target)}, ${effect.amount === 'all' ? 'all' : formatValue(effect.amount)}${formatDuration(effect.duration)})`
case 'gain_control':
return `gain_control(${formatTarget(effect.target)}${formatDuration(effect.duration)})`
case 'emblem':
return `emblem("${effect.text}")`
case 'transform':
return `transform(${formatTarget(effect.target)})`
case 'pay':
return `pay(${effect.costs.map(formatCost).join(', ')})`
case 'conditional':
return `if ${formatCondition(effect.condition)}:\n${indent(effect.effects.map(formatEffect).join('\n'))}`
case 'modal': {
const choose = effect.min === effect.max ? String(effect.min) : `${effect.min}-${effect.max}`
const body = effect.modes
.map((mode, index) => `${index + 1}. ${mode.map(formatEffect).join('; ')}`)
.join('\n')
return `choose ${choose}:\n${indent(body)}`
}
case 'look_top':
return `look_top(${effect.player}, ${formatValue(effect.amount)}${effect.reorder ? ', reorder' : ''})`
case 'schedule':
return `schedule(${effect.when}):\n${indent(effect.effects.map(formatEffect).join('\n'))}`
case 'damage_divided':
return `damage_divided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})`
}
}
function formatCondition(condition: Condition): string {
switch (condition.kind) {
case 'you_control':
return `you control ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}${formatSelector(condition.selector)}`
case 'opponent_controls':
return `an opponent controls ${formatSelector(condition.selector)}`
case 'your_turn':
return 'it is your turn'
case 'not_your_turn':
return "it isn't your turn"
case 'source_tapped':
return 'this is tapped'
case 'life_at_least':
return `${condition.player} has at least ${condition.amount} life`
case 'life_at_most':
return `${condition.player} has at most ${condition.amount} life`
case 'cards_in_graveyard':
return `${condition.player} has ${condition.atLeast}+ cards in their graveyard`
case 'source_untapped':
return 'this is untapped'
case 'source_attacking':
return 'this is attacking'
case 'life_above_starting':
return `${condition.player} has at least ${condition.amount} life more than their starting life total`
case 'hand_empty':
return `${condition.player} has no cards in hand`
case 'creature_died_this_turn':
return `${condition.controller === 'you' ? 'a creature you control' : condition.controller === 'opponent' ? 'a creature an opponent controls' : 'a creature'} died this turn`
case 'you_gained_life_this_turn':
return `you gained ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}life this turn`
case 'you_drew_cards_this_turn':
return `you drew ${condition.atLeast ? `${condition.atLeast}+ ` : 'a '}cards this turn`
case 'spells_cast_last_turn':
return `${condition.who} cast ${condition.atLeast}+ spells last turn`
case 'no_spells_last_turn':
return 'no spells were cast last turn'
case 'attacked_this_turn':
return 'this attacked this turn'
case 'you_attacked_this_turn':
return 'you attacked this turn'
case 'defending_player_controls':
return `defending player controls ${formatSelector(condition.selector)}`
case 'targets':
return `it targets ${formatSelector(condition.selector)}`
case 'was_kicked':
return 'this was kicked'
case 'cast':
return condition.fromHand ? 'you cast it from your hand' : 'you cast it'
case 'in_graveyard':
return 'this is in your graveyard'
case 'on_battlefield':
return 'this is on the battlefield'
case 'monarch':
return "you're the monarch"
case 'initiative':
return 'you have the initiative'
case 'citys_blessing':
return "you have the city's blessing"
case 'suspended':
return 'this is suspended'
case 'bargained':
return 'it was bargained'
case 'was_creature':
return 'it was a creature'
case 'opponent_lost_life_this_turn':
return 'an opponent lost life this turn'
case 'life_changed_this_turn':
return 'you gained or lost life this turn'
case 'descended_this_turn':
return 'you descended this turn'
case 'permanent_left_battlefield_this_turn':
return 'a permanent you controlled left the battlefield this turn'
case 'nonland_permanents_entered_this_turn':
return `${condition.atLeast}+ nonland permanents entered the battlefield under your control this turn`
case 'attacked_with_total_power':
return `you attacked with total power ${condition.atLeast}+ this combat`
case 'total_power':
return `creatures you control have total power ${condition.atLeast}+`
case 'opponent_controls_more_lands':
return 'an opponent controls more lands than you'
case 'distinct_powers':
return `you control ${condition.atLeast}+ creatures with different powers`
case 'graveyard_card_types':
return `there are ${condition.atLeast}+ card types in your graveyard`
case 'no_objects':
return `no ${formatSelector(condition.selector)} on the battlefield`
case 'cards_in_hand_at_most':
return `${condition.who} has ${condition.atMost} or fewer cards in hand`
case 'not_their_turn':
return 'it is not their turn'
case 'no_attackers':
return 'no creatures attacked this turn'
case 'opponent_poison':
return `an opponent has ${condition.atLeast}+ poison counters`
case 'tribute_not_paid':
return "tribute wasn't paid"
case 'had_counters':
return condition.counter ? `it had a ${condition.counter} counter on it` : 'it had counters on it'
case 'mana_from_treasure':
return 'mana from a Treasure was spent to cast it'
case 'mana_spent':
return `at least ${condition.atLeast} mana was spent to cast it`
case 'no_mana_spent':
return 'no mana was spent to cast it'
case 'mana_symbol_spent':
return `${condition.symbols} was spent to cast it`
case 'kicked_with':
return `it was kicked with ${condition.cost}`
case 'more_cards_than_each_opponent':
return 'you have more cards in hand than each opponent'
case 'first_combat_phase':
return 'it is the first combat phase of the turn'
case 'not_token':
return 'it is not a token'
case 'cast_spell_this_turn':
return `you've cast ${condition.noncreature ? 'a noncreature ' : 'a '}spell this turn`
case 'full_party':
return 'you have a full party'
case 'graveyard_count':
return `there are ${condition.atLeast}+ ${formatSelector(condition.selector)} in your graveyard`
case 'creature_power_greater_than_base':
return `you control a creature with ${condition.stat} greater than its base ${condition.stat}`
case 'if_you_do':
return 'you do'
case 'if_you_dont':
return "you don't"
case 'otherwise':
return 'otherwise'
}
}
function formatTrigger(event: TriggerEvent): string {
switch (event.kind) {
case 'enters':
return `enters(${formatTarget(event.subject)})`
case 'dies':
return `dies(${formatTarget(event.subject)})`
case 'attacks':
return `attacks(${formatTarget(event.subject)})`
case 'blocks':
return `blocks(${formatTarget(event.subject)})`
case 'attacks_or_blocks':
return `attacks_or_blocks(${formatTarget(event.subject)})`
case 'enters_or_attacks':
return `enters_or_attacks(${formatTarget(event.subject)})`
case 'enters_or_dies':
return `enters_or_dies(${formatTarget(event.subject)})`
case 'leaves_battlefield':
return `leaves_battlefield(${formatTarget(event.subject)})`
case 'deals_damage':
return `deals_${event.combat ? 'combat_' : ''}damage(${formatTarget(event.subject)}, ${event.recipient})`
case 'upkeep':
return `upkeep(${event.who})`
case 'end_step':
return `end_step(${event.who})`
case 'begin_combat':
return `begin_combat(${event.who})`
case 'main_phase':
return `${event.phase}_main_phase(${event.who})`
case 'cast':
return `cast(${event.who}, ${isBareSelector(event.spell) ? 'any spell' : formatSelector(event.spell)}${event.targetsSelf ? ', targets this' : ''}${event.orCopy ? ', or copy' : ''}${event.ordinal ? `, #${event.ordinal} each turn` : ''})`
case 'becomes_level':
return `becomes_level(${event.level})`
case 'draw':
return `draw(${event.who}${event.ordinal ? `, #${event.ordinal} each turn` : ''})`
case 'counter_placed':
return `counter_placed(${formatTarget(event.subject)}${event.counter ? `, ${event.counter}` : ''})`
case 'becomes_target':
return `becomes_target(${formatTarget(event.subject)})`
case 'life':
return `${event.mode}_life(${event.who})`
}
}
function formatStaticEffect(effect: StaticEffect): string {
switch (effect.op) {
case 'pump':
return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)})`
case 'grant':
return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''})`
case 'restriction': {
const extra = [
effect.value ? formatValue(effect.value) : '',
effect.comparison ? effect.comparison.replace(/_/g, ' ') : '',
effect.detail ?? '',
effect.condition ? `if ${formatCondition(effect.condition)}` : '',
].filter(Boolean).join(' ')
return `restrict(${formatTarget(effect.target)}, ${effect.rule}${extra ? ` ${extra}` : ''})`
}
case 'enters_tapped':
return `enters_tapped(${formatTarget(effect.target)}${effect.unless ? `, unless ${formatCondition(effect.unless)}` : ''})`
case 'enters_with_counters':
return `enters_with_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})`
case 'grant_ability':
return `grant_ability(${formatTarget(effect.target)}):\n${indent(formatAbility(effect.ability))}`
case 'set_pt':
return `set_pt(${formatTarget(effect.target)}${effect.base ? ', base' : ''}, ${effect.power ? formatValue(effect.power) : '?'}/${effect.toughness ? formatValue(effect.toughness) : '?'})`
case 'control':
return `control(${formatTarget(effect.target)})`
case 'choose':
return `choose(${effect.what})`
case 'replacement':
return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})`
case 'cost_reduction':
return `cost_reduction(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.condition ? `, if ${formatCondition(effect.condition)}` : ''})`
}
}
function indent(text: string, spaces = 2): string {
const pad = ' '.repeat(spaces)
return text
.split('\n')
.map(line => `${pad}${line}`)
.join('\n')
}
export function formatAbility(ability: Ability): string {
switch (ability.kind) {
case 'keyword':
return `keyword ${ability.keyword}${ability.value ? ` ${ability.value}` : ''}`
case 'keywords':
return `keywords ${ability.keywords.map(keyword => `${keyword.keyword}${keyword.value ? ` ${keyword.value}` : ''}`).join(', ')}`
case 'triggered': {
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
const body = ability.effects.map(formatEffect).join('\n')
return `on ${formatTrigger(ability.event)}${condition}${ability.optional ? ' (may)' : ''}:\n${indent(body)}`
}
case 'activated': {
const costs = ability.costs.map(formatCost).join(', ')
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
const limit = ability.activationsPerTurn ? ` (${ability.activationsPerTurn}/turn)` : ''
const timing = ability.timing === 'sorcery' ? ' (sorcery speed)' : ''
const body = ability.effects.map(formatEffect).join('\n')
return `activate ${costs}${condition}${limit}${timing}${ability.optional ? ' (may)' : ''}:\n${indent(body)}`
}
case 'static': {
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
return `static${condition}:\n${indent(ability.effects.map(formatStaticEffect).join('\n'))}`
}
case 'spell':
return `spell${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'additional_cost':
return `additional cost${ability.optional ? ' (may)' : ''}: ${ability.costs.map(formatCost).join(', ')}`
case 'chapter':
return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'level_band': {
const band = ability.max !== undefined ? `${ability.min}-${ability.max}` : `${ability.min}+`
const pt = ability.power ? `: ${formatValue(ability.power)}/${formatValue(ability.toughness!)}` : ''
return `level ${band}${pt}`
}
case 'level_pt':
return `level_pt(${formatValue(ability.power)}/${formatValue(ability.toughness)})`
case 'unsupported':
return `unsupported (${ability.reason}): ${ability.text.replace(/\n/g, '\n ')}`
}
}
export function formatCard(card: CompiledCard): string {
const lines = [`# ${card.name} [${card.status}]`]
if (card.faces?.length) {
for (const face of card.faces) {
lines.push('', `## ${face.name} [${face.status}]`)
lines.push(face.abilities.map(formatAbility).join('\n') || '(no abilities)')
}
} else {
lines.push(card.abilities.map(formatAbility).join('\n') || '(no abilities)')
}
return lines.join('\n')
}

View File

@@ -0,0 +1,236 @@
// Human-authored card implementations live in one plain-text file per oracle
// id under data/card-overrides/. The file is pseudocode in the same syntax the
// formatter prints, so it stays readable and can be re-compiled by the engine.
import { readFileSync, statSync } from 'node:fs'
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { allCards } from '../cards.js'
import type { Card } from '../cards.js'
import { compileCard, statusOf } from './compile.js'
import { formatCard } from './format.js'
import { parsePseudoCard, PseudoParseError } from './pseudo.js'
import type { CompiledCard, CompiledFace } from './types.js'
export type ImplementationStatus = 'supported' | 'partial' | 'unsupported'
export interface ImplementationSummary {
status: ImplementationStatus
manual: boolean
}
export interface Implementation {
compiled: CompiledCard
source: string
manual: boolean
updatedAt?: string
error?: string
}
const DEFAULT_DIR = join(import.meta.dirname, '..', '..', 'data', 'card-overrides')
const COMPILED_FILE = join(import.meta.dirname, '..', '..', 'data', 'card-effects.json')
const ORACLE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export function overridesDir(): string {
return process.env.CARD_OVERRIDES_DIR ?? DEFAULT_DIR
}
function overrideFile(oracleId: string): string {
if (!ORACLE_ID.test(oracleId)) throw new Error(`Invalid oracle id: ${oracleId}`)
return join(overridesDir(), `${oracleId}.pseudo.txt`)
}
function isMissing(error: unknown): boolean {
return (error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'
}
export async function readOverride(oracleId: string): Promise<{ source: string; updatedAt: string } | undefined> {
if (!ORACLE_ID.test(oracleId)) return undefined
const file = overrideFile(oracleId)
try {
const [source, info] = await Promise.all([readFile(file, 'utf8'), stat(file)])
return { source, updatedAt: info.mtime.toISOString() }
} catch (error) {
if (isMissing(error)) return undefined
throw error
}
}
export async function readAllOverrides(): Promise<Map<string, string>> {
const result = new Map<string, string>()
let names: string[]
try {
names = await readdir(overridesDir())
} catch (error) {
if (isMissing(error)) return result
throw error
}
for (const name of names) {
const oracleId = name.replace(/\.pseudo\.txt$/, '')
if (name === oracleId || !ORACLE_ID.test(oracleId)) continue
const override = await readOverride(oracleId)
if (override) result.set(oracleId, override.source)
}
return result
}
export async function writeOverride(oracleId: string, source: string): Promise<void> {
const file = overrideFile(oracleId)
await mkdir(overridesDir(), { recursive: true })
const tmp = `${file}.tmp`
await writeFile(tmp, source.endsWith('\n') ? source : `${source}\n`, 'utf8')
await rename(tmp, file)
}
export async function deleteOverride(oracleId: string): Promise<void> {
const file = overrideFile(oracleId)
try {
await unlink(file)
} catch (error) {
if (!isMissing(error)) throw error
}
}
function facesStatus(faces: CompiledFace[]): ImplementationStatus {
if (faces.some(face => face.status === 'unsupported')) {
return faces.every(face => face.status === 'unsupported') ? 'unsupported' : 'partial'
}
return faces.some(face => face.status === 'partial') ? 'partial' : 'supported'
}
/** Parses manual pseudocode and turns it into the same AST the compiler emits. */
export function compileImplementation(card: Card, source: string): CompiledCard {
const parsed = parsePseudoCard(source)
if (card.card_faces?.length) {
if (!parsed.faces?.length) {
throw new PseudoParseError(
`this card has ${card.card_faces.length} faces; add "## <face name>" sections`,
1,
)
}
if (parsed.faces.length !== card.card_faces.length) {
throw new PseudoParseError(
`expected ${card.card_faces.length} faces, found ${parsed.faces.length}`,
1,
)
}
const faces: CompiledFace[] = card.card_faces.map((face, index) => {
const manualFace = parsed.faces![index]
if (manualFace.name.toLowerCase() !== face.name.toLowerCase()) {
throw new PseudoParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1)
}
return {
name: face.name,
status: statusOf(manualFace.abilities),
abilities: manualFace.abilities,
}
})
return {
oracle_id: card.oracle_id,
name: card.name,
status: facesStatus(faces),
abilities: [],
faces,
manual: true,
}
}
if (parsed.faces?.length) {
throw new PseudoParseError('this card has no faces; remove the "##" sections', 1)
}
return {
oracle_id: card.oracle_id,
name: card.name,
status: statusOf(parsed.abilities),
abilities: parsed.abilities,
manual: true,
}
}
export async function getImplementation(card: Card): Promise<Implementation> {
const override = await readOverride(card.oracle_id)
if (!override) {
const compiled = compileCard(card)
return { compiled, source: formatCard(compiled), manual: false }
}
try {
return {
compiled: compileImplementation(card, override.source),
source: override.source,
manual: true,
updatedAt: override.updatedAt,
}
} catch (error) {
return {
compiled: compileCard(card),
source: override.source,
manual: true,
updatedAt: override.updatedAt,
error: error instanceof Error ? error.message : String(error),
}
}
}
interface CompiledIndex {
byId: Map<string, CompiledCard>
mtimeMs: number
}
let compiledIndex: CompiledIndex | undefined
function loadCompiledIndex(): CompiledIndex {
try {
const info = statSync(COMPILED_FILE)
if (compiledIndex?.mtimeMs === info.mtimeMs) return compiledIndex
const cards = JSON.parse(readFileSync(COMPILED_FILE, 'utf8')) as CompiledCard[]
compiledIndex = {
byId: new Map(cards.map(card => [card.oracle_id, card])),
mtimeMs: info.mtimeMs,
}
} catch {
compiledIndex = { byId: new Map(), mtimeMs: 0 }
}
return compiledIndex
}
async function buildStatusIndex(): Promise<Map<string, ImplementationSummary>> {
const cards = allCards()
const auto = loadCompiledIndex().byId
const overrides = await readAllOverrides()
const result = new Map<string, ImplementationSummary>()
for (const card of cards) {
const source = overrides.get(card.oracle_id)
if (source !== undefined) {
try {
const compiled = compileImplementation(card, source)
result.set(card.oracle_id, { status: compiled.status, manual: true })
} catch {
result.set(card.oracle_id, { status: auto.get(card.oracle_id)?.status ?? compileCard(card).status, manual: true })
}
continue
}
const compiled = auto.get(card.oracle_id) ?? compileCard(card)
result.set(card.oracle_id, { status: compiled.status, manual: Boolean(compiled.manual) })
}
return result
}
let statusIndex: Promise<Map<string, ImplementationSummary>> | undefined
export function implementationIndex(): Promise<Map<string, ImplementationSummary>> {
statusIndex ??= buildStatusIndex()
return statusIndex
}
export function invalidateImplementationIndex(): void {
statusIndex = undefined
}

1142
backend/src/effects/parse.ts Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,269 @@
// Natural language -> card pseudocode through an OpenRouter-hosted model.
// The model is told to emit pseudocode only, and the answer is parsed before
// it reaches the editor, so prose or a guess never becomes an implementation.
import type { Card } from '../cards.js'
import { compileImplementation } from './implementations.js'
export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite'
const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions'
const MAX_TOKENS = 700
export class TranslationError extends Error {
readonly status: number
constructor(message: string, status = 502) {
super(message)
this.name = 'TranslationError'
this.status = status
}
}
// Kept compact: it is both the model's only context and the format contract.
// Anything not listed here is rejected by the parser, so the model must not
// invent operations.
export const PSEUDO_GUIDE = `Pseudocode is line-oriented. Ability headers sit at column 0 and end with a colon. Their effects are indented two spaces, one call per line. Semicolons separate multiple effects on one line.
Multi-face cards use "## <exact face name>" lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed.
Ability headers:
on <trigger>[ if <condition>][ (may)]:
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]:
static[ if <condition>]:
spell[(may)]:
keyword <Keyword>[ value]
keywords <Keyword>, <Keyword>
additional cost[(may)]: <cost>
chapter <I>, <II>[(may)]:
level <min>-<max>[: <power>/<toughness>]
level <min>+[: <power>/<toughness>]
level_pt(<power>/<toughness>)
Triggers:
enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target),
enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target),
deals_damage(target, player|creature|permanent|any), deals_combat_damage(...),
upkeep(you|opponent|each_player), end_step(...), begin_combat(...),
first_main_phase(...), postcombat_main_phase(...), becomes_level(N),
cast(you|opponent|each_player, <spell selector>|any spell[, targets this][, or copy][, #N each turn]),
draw(you|opponent|each_player[, #N each turn]), counter_placed(target[, counter]),
becomes_target(target), gain_life(you|opponent|each_player), lose_life(...)
Targets:
this, the triggering object, the chosen target, any target, target player,
target opponent, each opponent, each player, target player or planeswalker,
target spell, target ability, target <selector>, each <selector>,
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>])
Selectors begin with optional state words: other, tapped, untapped, attacking, token,
equipped, enchanted. Then optional colors (white blue black red green colorless),
supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls",
"you own", "you don't own", "with <keyword>", "without <keyword>",
"power N+" / "power N or less", "toughness N+" / "toughness N or less",
"mana value N+" / "mana value N or less", "named <name>",
"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack".
Values: a number, X, count(<selector>), its power, its toughness,
cards in your hand, cards in that player's hand, total power of <selector>,
total mana value of <selector>, greatest number of <selector> an opponent controls,
that much, any number.
Costs: {T}, {Q}, {2}{G}, {E} xN, +1 loyalty, -2 loyalty, pay N life,
discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice <selector>,
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard,
reveal <selector> from your hand, return <selector> to its owner's hand,
behold <selector>, waterbend <value>, blight <value>, choose <text>,
put <counter> counter on <selector>, forage, collect evidence N, mill N card(s).
A choice is written (cost or cost) or (cost + cost).
Effects, one call per line:
damage(target, amount[, from source])
damage_divided(amount, target)
draw(player, amount)
discard(player, amount[, at random])
mill(player, amount)
gain_life(player, amount)
lose_life(player, amount)
pump(target, power/toughness[, duration])
set_pt(target, power/toughness[, duration])
grant(target, Keyword[ value][, duration])
put_counters(target, counter, amount)
remove_counters(target, counter, amount)
proliferate()
create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword])
destroy(target), exile(target), tap(target), untap(target), regenerate(target)
sacrifice(player, target[, unless cost])
counter(spell|ability, target[, unless cost])
return_to_hand(target), put_on_top(target)
return_to_battlefield(target[, tapped][, transformed][, amount counter counters])
scry(player, amount), surveil(player, amount)
search(player, selector, amount, to hand|battlefield|graveyard|top|bottom[, tapped][, shuffle])
shuffle(player)
add_mana(player, {G}{G} | amount mana of any color)
fight(a, b)
energy(player, amount)
attach(this, target)
restrict(target, cant_attack|cant_block|doesnt_untap[, duration])
prevent_damage(target, amount|all[, duration])
prevent_combat_damage(target, amount|all[, duration])
gain_control(target[, duration])
emblem("text")
transform(target)
pay(cost)
look_top(player, amount[, reorder])
level_up(N)
put_from_among(amount[, selector], to hand|graveyard|battlefield|top|bottom)
dig(amount, up to? pick [selector] to hand|battlefield[ tapped], rest bottom|graveyard|top[ any|random][, optional])
Other keyword actions: action_name(target) or action_name(amount, detail)
Nested blocks:
if <condition>:
<effects>
choose <min>[-<max>]:
1. <effects separated by ;>
2. <effects separated by ;>
schedule(next_upkeep|next_end_step):
<effects>
Static effects:
pump(target, power/toughness)
grant(target, Keyword[ value])
restrict(target, rule[ detail][ if <condition>])
enters_tapped(target[, unless <condition>])
enters_with_counters(target, counter, amount)
grant_ability(target):
<one ability block>
set_pt(target[, base], power/toughness|?)
control(target)
choose(creature_type|color|card_name|player|opponent|number)
replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent)
cost_reduction(target, amount[, if <condition>])
Common conditions: you control <selector>, you control at least N <selector>,
an opponent controls <selector>, it is your turn, it isn't your turn,
this is tapped, this is untapped, this is attacking, <player> has at least N life,
<player> has at most N life, <player> has N+ cards in their graveyard,
<player> has no cards in hand, a creature died this turn,
you gained at least N life this turn, you drew N+ cards this turn,
you cast it from your hand, this is in your graveyard, this is on the battlefield,
you're the monarch, you have the initiative, it was kicked,
you've cast a spell this turn, you've cast a noncreature spell this turn,
no creatures attacked this turn, you do, you don't, otherwise.
Durations: permanent (default), until end of turn, until your next turn,
until end of combat, until its controller's next untap step,
for as long as this remains on the battlefield.
Players: you, opponent, each_opponent, each_player, target_player, that_player,
its_controller, its_owner.
Example:
on enters(this):
gain_life(you, 1)
activate {T}:
add_mana(you, {G})
spell:
draw(you, 2)`
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
Output rules:
- Answer with pseudocode only. No explanation, no code fences, no card header, no comments.
- Use only the syntax below. Never invent an operation or a keyword argument.
- If an ability cannot be expressed, use: unsupported (<short reason>): <original oracle text>
- For multi-face cards, output only the "## <face name>" sections in the given order.
${PSEUDO_GUIDE}`
function describeCard(card: Card): string {
if (card.card_faces?.length) {
const faces = card.card_faces.map(face => [
`## ${face.name}`,
face.type_line ? `Type: ${face.type_line}` : '',
face.oracle_text || '(no abilities)',
].filter(Boolean).join('\n'))
return [`Card: ${card.name}`, `Layout: ${card.layout}`, ...faces].join('\n\n')
}
return [
`Card: ${card.name}`,
`Type: ${card.type_line}`,
`Oracle text:\n${card.oracle_text || '(no abilities)'}`,
].join('\n')
}
/** Removes the code fence models add out of habit. Everything else is kept. */
export function cleanTranslation(text: string): string {
const trimmed = text.trim()
const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/)
return (fenced ? fenced[1] : trimmed).trim()
}
interface ChatResponse {
choices?: Array<{ message?: { content?: unknown } }>
error?: { message?: string }
}
export interface TranslateOptions {
apiKey?: string
model?: string
fetch?: typeof fetch
}
export async function translateCard(card: Card, options: TranslateOptions = {}): Promise<string> {
const apiKey = options.apiKey ?? process.env.OPENROUTER_API_KEY
if (!apiKey) {
throw new TranslationError('OPENROUTER_API_KEY is not set on the backend.', 503)
}
const fetchImpl = options.fetch ?? fetch
let response: Response
try {
response = await fetchImpl(ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-Title': 'Commander card pseudocode translator',
},
body: JSON.stringify({
model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: describeCard(card) },
],
temperature: 0,
max_tokens: MAX_TOKENS,
}),
signal: AbortSignal.timeout(60_000),
})
} catch (error) {
throw new TranslationError(`Could not reach OpenRouter: ${error instanceof Error ? error.message : String(error)}`)
}
const data = await response.json().catch(() => undefined) as ChatResponse | undefined
if (!response.ok) {
const detail = data?.error?.message ? `: ${data.error.message}` : ''
throw new TranslationError(`OpenRouter returned ${response.status}${detail}`)
}
const content = data?.choices?.[0]?.message?.content
if (typeof content !== 'string') {
throw new TranslationError('OpenRouter returned no text.')
}
const source = cleanTranslation(content)
if (!source) throw new TranslationError('OpenRouter returned an empty answer.')
try {
compileImplementation(card, source)
} catch (error) {
throw new TranslationError(
`The model did not return valid pseudocode: ${error instanceof Error ? error.message : String(error)}`,
)
}
return source
}

View File

@@ -0,0 +1,336 @@
// Canonical card-effect AST. The oracle-text compiler emits these nodes and the
// game engine consumes them. Keep this file free of parsing logic.
export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command'
export type PlayerRef =
| 'you'
| 'opponent'
| 'each_opponent'
| 'each_player'
| 'target_player'
| 'that_player'
| 'its_controller'
| 'its_owner'
export interface ObjectSelector {
/** Type-line words that must all match unless `match` is 'any'. */
types?: string[]
match?: 'all' | 'any'
excludeTypes?: string[]
supertypes?: string[]
subtypes?: string[]
controller?: 'you' | 'opponent' | 'any'
owner?: 'you' | 'opponent'
colors?: string[]
other?: boolean
attached?: 'equipped' | 'enchanted'
zone?: Zone
tapped?: boolean
attacking?: boolean
token?: boolean
name?: string
counters?: { counter: string; atLeast: number }
power?: { atLeast?: number; atMost?: number }
toughness?: { atLeast?: number; atMost?: number }
manaValue?: { atLeast?: number; atMost?: number }
keywords?: string[]
excludeKeywords?: string[]
}
export type Target =
| { kind: 'self' }
| { kind: 'trigger_subject' }
| { kind: 'previous_target' }
| { kind: 'object'; selector: ObjectSelector; mode: 'target' | 'each' | 'choose'; count?: number; upTo?: boolean; includeSelf?: boolean }
| { kind: 'player'; who: PlayerRef; mode: 'target' | 'each' }
| { kind: 'player_or_planeswalker'; mode: 'target' }
| { kind: 'any' }
| { kind: 'spell'; selector: ObjectSelector; mode: 'target' | 'each' }
| { kind: 'ability'; selector?: ObjectSelector; mode: 'target' }
| { kind: 'divided'; max: number | 'any'; selector?: ObjectSelector }
export type Value =
| { kind: 'number'; value: number }
| { kind: 'x' }
| { kind: 'count'; selector: ObjectSelector }
| { kind: 'source_power' }
| { kind: 'source_toughness' }
| { kind: 'cards_in_hand'; player: PlayerRef }
| { kind: 'max_cards_in_hand' }
| { kind: 'max_opponent_count'; selector: ObjectSelector }
| { kind: 'total_mana_value'; selector: ObjectSelector }
| { kind: 'total_power'; selector: ObjectSelector }
| { kind: 'any_number' }
| { kind: 'event_amount' }
export type ManaSpec =
| { kind: 'symbols'; symbols: string[]; restriction?: string }
| { kind: 'any_color'; amount: Value; oneColor: boolean; restriction?: string }
export interface TokenSpec {
name?: string
types: string[]
subtypes: string[]
colors: string[]
power?: Value
toughness?: Value
keywords?: string[]
tapped?: boolean
}
export type Duration =
| 'permanent'
| 'until_end_of_turn'
| 'until_your_next_turn'
| 'until_end_of_your_next_turn'
| 'until_end_of_combat'
| 'until_controllers_next_untap_step'
| 'while_source_on_battlefield'
export interface KeywordAbility {
kind: 'keyword'
keyword: string
value?: string
}
export type Cost =
| { kind: 'mana'; symbols: string }
| { kind: 'tap' }
| { kind: 'untap' }
| { kind: 'tap_other'; selector: ObjectSelector }
| { kind: 'energy'; amount: number }
| { kind: 'loyalty'; amount: number }
| { kind: 'pay_life'; amount: Value }
| { kind: 'discard'; amount: Value; player: PlayerRef; random?: boolean }
| { kind: 'sacrifice'; selector: ObjectSelector }
| { kind: 'sacrifice_self' }
| { kind: 'exile_self' }
| { kind: 'exile_from_graveyard'; selector: ObjectSelector; amount?: Value }
| { kind: 'reveal'; selector: ObjectSelector }
| { kind: 'choice'; options: Cost[][] }
| { kind: 'return_to_hand'; selector: ObjectSelector }
| { kind: 'behold'; selector: ObjectSelector }
| { kind: 'waterbend'; amount: Value }
| { kind: 'blight'; amount: Value }
| { kind: 'choose'; what: string }
| { kind: 'put_counter'; counter: string; selector: ObjectSelector }
| { kind: 'remove_counters'; counter: string; amount: Value; selector?: ObjectSelector }
| { kind: 'forage' }
| { kind: 'collect_evidence'; amount: number }
| { kind: 'mill'; amount: Value }
export type Condition =
| { kind: 'you_control'; selector: ObjectSelector; atLeast?: number }
| { kind: 'opponent_controls'; selector: ObjectSelector; atLeast?: number }
| { kind: 'your_turn' }
| { kind: 'not_your_turn' }
| { kind: 'source_tapped' }
| { kind: 'source_untapped' }
| { kind: 'source_attacking' }
| { kind: 'life_at_least'; player: PlayerRef; amount: number }
| { kind: 'life_at_most'; player: PlayerRef; amount: number }
| { kind: 'life_above_starting'; player: PlayerRef; amount: number }
| { kind: 'cards_in_graveyard'; player: PlayerRef; atLeast: number }
| { kind: 'hand_empty'; player: PlayerRef }
| { kind: 'creature_died_this_turn'; controller?: 'you' | 'opponent' }
| { kind: 'you_gained_life_this_turn'; atLeast?: number }
| { kind: 'you_drew_cards_this_turn'; atLeast?: number }
| { kind: 'spells_cast_last_turn'; who: 'you' | 'opponent' | 'each_player' | 'a_player'; atLeast: number }
| { kind: 'no_spells_last_turn' }
| { kind: 'attacked_this_turn' }
| { kind: 'you_attacked_this_turn' }
| { kind: 'defending_player_controls'; selector: ObjectSelector }
| { kind: 'targets'; selector: ObjectSelector }
| { kind: 'was_kicked' }
| { kind: 'cast'; fromHand?: boolean }
| { kind: 'in_graveyard' }
| { kind: 'on_battlefield' }
| { kind: 'monarch' }
| { kind: 'initiative' }
| { kind: 'citys_blessing' }
| { kind: 'suspended' }
| { kind: 'bargained' }
| { kind: 'was_creature' }
| { kind: 'opponent_lost_life_this_turn' }
| { kind: 'life_changed_this_turn' }
| { kind: 'descended_this_turn' }
| { kind: 'permanent_left_battlefield_this_turn'; controller: 'you' }
| { kind: 'nonland_permanents_entered_this_turn'; atLeast: number }
| { kind: 'attacked_with_total_power'; atLeast: number }
| { kind: 'total_power'; controller: 'you'; atLeast: number }
| { kind: 'opponent_controls_more_lands' }
| { kind: 'distinct_powers'; atLeast: number }
| { kind: 'graveyard_card_types'; atLeast: number }
| { kind: 'no_objects'; selector: ObjectSelector }
| { kind: 'cards_in_hand_at_most'; who: PlayerRef; atMost: number }
| { kind: 'not_their_turn' }
| { kind: 'no_attackers' }
| { kind: 'opponent_poison'; atLeast: number }
| { kind: 'tribute_not_paid' }
| { kind: 'had_counters'; counter?: string }
| { kind: 'mana_from_treasure' }
| { kind: 'mana_spent'; atLeast: number }
| { kind: 'no_mana_spent' }
| { kind: 'mana_symbol_spent'; symbols: string }
| { kind: 'kicked_with'; cost: string }
| { kind: 'more_cards_than_each_opponent' }
| { kind: 'first_combat_phase' }
| { kind: 'not_token' }
| { kind: 'cast_spell_this_turn'; noncreature?: boolean }
| { kind: 'full_party' }
| { kind: 'graveyard_count'; selector: ObjectSelector; atLeast: number }
| { kind: 'creature_power_greater_than_base'; controller: 'you'; stat: 'power' | 'toughness' }
| { kind: 'if_you_do' }
| { kind: 'if_you_dont' }
| { kind: 'otherwise' }
export type TriggerEvent =
| { kind: 'enters'; subject: Target }
| { kind: 'dies'; subject: Target }
| { kind: 'attacks'; subject: Target }
| { kind: 'blocks'; subject: Target }
| { kind: 'attacks_or_blocks'; subject: Target }
| { kind: 'enters_or_attacks'; subject: Target }
| { kind: 'enters_or_dies'; subject: Target }
| { kind: 'leaves_battlefield'; subject: Target }
| { kind: 'deals_damage'; subject: Target; recipient: 'player' | 'creature' | 'permanent' | 'any'; combat: boolean }
| { kind: 'upkeep'; who: 'you' | 'opponent' | 'each_player' }
| { kind: 'end_step'; who: 'you' | 'opponent' | 'each_player' }
| { kind: 'begin_combat'; who: 'you' | 'opponent' | 'each_player' }
| { kind: 'main_phase'; who: 'you' | 'opponent' | 'each_player'; phase: 'first' | 'postcombat' }
| { kind: 'cast'; who: 'you' | 'opponent' | 'each_player'; spell: ObjectSelector; targetsSelf?: boolean; ordinal?: number; orCopy?: boolean }
| { kind: 'becomes_level'; level: number }
| { kind: 'draw'; who: 'you' | 'opponent' | 'each_player'; ordinal?: number }
| { kind: 'counter_placed'; subject: Target; counter?: string }
| { kind: 'becomes_target'; subject: Target }
| { kind: 'life'; who: 'you' | 'opponent' | 'each_player'; mode: 'gain' | 'lose' }
export type Effect =
| { op: 'damage'; target: Target; amount: Value; source?: Target }
| { op: 'draw'; player: PlayerRef; amount: Value }
| { op: 'discard'; player: PlayerRef; amount: Value; random?: boolean }
| { op: 'mill'; player: PlayerRef; amount: Value }
| { op: 'life'; player: PlayerRef; amount: Value; mode: 'gain' | 'lose' }
| { op: 'pump'; target: Target; power: Value; toughness: Value; duration: Duration }
| { op: 'set_pt'; target: Target; power: Value; toughness: Value; duration: Duration }
| { op: 'grant'; target: Target; keyword: string; value?: string; duration: Duration }
| { op: 'put_counters'; target: Target; counter: string; amount: Value }
| { op: 'remove_counters'; target: Target; counter: string; amount: Value }
| { op: 'proliferate' }
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean }
| { op: 'destroy'; target: Target }
| { op: 'exile'; target: Target }
| { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost }
| { op: 'counter'; what: 'spell' | 'ability'; target: Target; unless?: Cost }
| { op: 'return_to_hand'; target: Target }
| { op: 'return_to_battlefield'; target: Target; tapped: boolean; transformed?: boolean; counters?: { counter: string; amount: Value } }
| { op: 'put_on_top'; target: Target }
| { op: 'tap'; target: Target }
| { op: 'untap'; target: Target }
| { op: 'scry'; player: PlayerRef; amount: Value }
| { op: 'surveil'; player: PlayerRef; amount: Value }
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[] }
| { op: 'shuffle'; player: PlayerRef }
| { op: 'add_mana'; player: PlayerRef; mana: ManaSpec }
| { op: 'fight'; a: Target; b: Target }
| { op: 'regenerate'; target: Target }
| { op: 'energy'; player: PlayerRef; amount: Value }
| { op: 'attach'; target: Target }
| { op: 'restriction'; target: Target; rule: 'cant_attack' | 'cant_block' | 'doesnt_untap'; duration: Duration }
| { op: 'keyword_action'; action: string; amount?: Value; detail?: string; target?: Target }
| { op: 'prevent_damage'; target: Target; amount: Value | 'all'; combatOnly?: boolean; duration: Duration }
| { op: 'gain_control'; target: Target; duration: Duration }
| { op: 'emblem'; text: string }
| { op: 'transform'; target: Target }
| { op: 'pay'; costs: Cost[] }
| { op: 'conditional'; condition: Condition; effects: Effect[] }
| { op: 'modal'; min: number; max: number; modes: Effect[][] }
| { op: 'look_top'; player: PlayerRef; amount: Value; reorder?: boolean }
| { op: 'schedule'; when: 'next_upkeep' | 'next_end_step'; effects: Effect[] }
| { op: 'level_up'; level: number }
| { op: 'put_from_among'; player: PlayerRef; selector?: ObjectSelector; amount: Value; destination: 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' }
| { op: 'dig'; player: PlayerRef; amount: Value; pick: Value; upTo?: boolean; pickSelector?: ObjectSelector; to: 'hand' | 'battlefield'; rest: 'bottom' | 'graveyard' | 'top'; order?: 'any' | 'random'; optional?: boolean; tapped?: boolean }
| { op: 'damage_divided'; amount: Value; target: Target }
export type StaticEffect =
| { op: 'pump'; target: Target; power: Value; toughness: Value }
| { op: 'grant'; target: Target; keyword: string; value?: string }
| { op: 'grant_ability'; target: Target; ability: Ability }
| { op: 'restriction'; target: Target; rule: string; value?: Value; comparison?: 'or_greater' | 'or_less'; detail?: string; condition?: Condition }
| { op: 'enters_tapped'; target: Target; unless?: Condition }
| { op: 'enters_with_counters'; target: Target; counter: string; amount: Value }
| { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean }
| { op: 'control'; target: Target }
| { op: 'choose'; what: 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' }
| { op: 'replacement'; what: 'dies' | 'leaves_battlefield' | 'discard' | 'draw'; instead: 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent'; target?: Target }
| { op: 'cost_reduction'; target: Target; amount: Value; condition?: Condition }
export type Ability =
| KeywordAbility
| {
kind: 'keywords'
keywords: KeywordAbility[]
}
| {
kind: 'triggered'
event: TriggerEvent
condition?: Condition
effects: Effect[]
optional: boolean
text: string
}
| {
kind: 'activated'
costs: Cost[]
effects: Effect[]
condition?: Condition
timing?: 'instant' | 'sorcery'
activationsPerTurn?: number
optional: boolean
text: string
}
| {
kind: 'static'
effects: StaticEffect[]
condition?: Condition
text: string
}
| {
kind: 'spell'
effects: Effect[]
optional: boolean
text: string
}
| {
kind: 'additional_cost'
costs: Cost[]
optional: boolean
text: string
}
| {
kind: 'chapter'
chapters: string[]
effects: Effect[]
optional: boolean
text: string
}
| { kind: 'level_band'; min: number; max?: number; power?: Value; toughness?: Value; text: string }
| { kind: 'level_pt'; power: Value; toughness: Value; text: string }
| { kind: 'unsupported'; reason: string; text: string }
export interface CompiledFace {
name: string
status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[]
}
export interface CompiledCard {
oracle_id: string
name: string
status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[]
faces?: CompiledFace[]
/** True when a human edited the implementation instead of the oracle parser. */
manual?: boolean
}

110
backend/src/game/catalog.ts Normal file
View File

@@ -0,0 +1,110 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import type { Card, CardFace } from '../cards.js'
import { CardsUnavailableError } from '../cards.js'
import type { Ability, CompiledCard } from '../effects/types.js'
import type { CardDefinition } from './types.js'
const DATA_DIR = join(import.meta.dirname, '..', '..', 'data')
const CARDS_FILE = join(DATA_DIR, 'cards.json')
const EFFECTS_FILE = join(DATA_DIR, 'card-effects.json')
const BASIC_MANA: Record<string, string> = {
plains: 'W',
island: 'U',
swamp: 'B',
mountain: 'R',
forest: 'G',
}
let catalog: Map<string, CardDefinition> | undefined
function numberOrUndefined(value: string | undefined): number | undefined {
if (value === undefined || value === '') return undefined
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : undefined
}
function basicLandAbility(typeLine: string): Ability[] {
if (!/basic land/i.test(typeLine)) return []
const subtype = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/)[0] ?? ''
const color = BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined)
if (!color) return []
return [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
optional: false,
text: `{T}: Add {${color}}.`,
}]
}
function definitionFrom(
card: Card,
compiled: CompiledCard | undefined,
face?: CardFace,
faceAbilities?: Ability[],
): CardDefinition {
const typeLine = face?.type_line ?? card.type_line
return {
oracleId: card.oracle_id,
name: face?.name ?? card.name,
typeLine,
manaCost: face?.mana_cost ?? card.mana_cost,
manaValue: card.cmc,
colors: face?.colors ?? card.colors,
colorIdentity: card.color_identity,
power: numberOrUndefined(face?.power ?? card.power),
toughness: numberOrUndefined(face?.toughness ?? card.toughness),
loyalty: numberOrUndefined(face?.loyalty ?? card.loyalty),
oracleText: face?.oracle_text ?? card.oracle_text,
abilities: [...(faceAbilities ?? compiled?.abilities ?? []), ...basicLandAbility(typeLine)],
}
}
export function cardDefinitionFromCard(card: Card, compiled?: CompiledCard): CardDefinition {
const face = card.card_faces?.[0]
const compiledFace = compiled?.faces?.[0]
return definitionFrom(card, compiled, face, compiledFace?.abilities)
}
function load(): Map<string, CardDefinition> {
if (catalog) return catalog
let cards: Card[]
let compiled: CompiledCard[]
try {
cards = JSON.parse(readFileSync(CARDS_FILE, 'utf8')) as Card[]
} catch {
throw new CardsUnavailableError(
`Card data not found at ${CARDS_FILE}. Run "npm run import:cards" in backend/.`,
)
}
try {
compiled = JSON.parse(readFileSync(EFFECTS_FILE, 'utf8')) as CompiledCard[]
} catch {
throw new CardsUnavailableError(
`Compiled card effects not found at ${EFFECTS_FILE}. Run "npm run compile:cards" in backend/.`,
)
}
const effects = new Map(compiled.map(card => [card.oracle_id, card]))
catalog = new Map(cards.map(card => [card.oracle_id, cardDefinitionFromCard(card, effects.get(card.oracle_id))]))
return catalog
}
export function getCardDefinition(oracleId: string): CardDefinition | undefined {
return load().get(oracleId)
}
/** Resolves a list of oracle ids into deck definitions, rejecting unknown cards. */
export function deckFromOracleIds(oracleIds: string[]): CardDefinition[] {
const missing: string[] = []
const deck: CardDefinition[] = []
for (const oracleId of oracleIds) {
const definition = getCardDefinition(oracleId)
if (definition) deck.push(definition)
else missing.push(oracleId)
}
if (missing.length) throw new Error(`Unknown oracle ids: ${missing.join(', ')}`)
return deck
}

View File

@@ -0,0 +1,174 @@
import { findCardByName, type Card } from '../cards.js'
export interface ImportedDeck {
commander?: Card
cards: Card[]
errors: string[]
}
export function isBasicLand(card: Card): boolean {
return /\bbasic\b/i.test(card.type_line) && /\bland\b/i.test(card.type_line)
}
export function canBeCommander(card: Card): boolean {
const text = [card.oracle_text, ...(card.card_faces?.map(face => face.oracle_text) ?? [])]
.filter(Boolean)
.join(' ')
return (/\blegendary\b/i.test(card.type_line) && /\bcreature\b/i.test(card.type_line))
|| /can be your commander/i.test(text)
}
/** Checks the Commander deck-construction rules the engine can enforce. */
export function validateCommanderDeck(commander: Card, cards: Card[]): string[] {
const errors: string[] = []
if (!canBeCommander(commander)) errors.push(`${commander.name} cannot be a commander.`)
if (cards.length + 1 !== 100) {
errors.push(`Deck has ${cards.length + 1} cards; Commander decks need exactly 100 including the commander.`)
}
const identity = new Set(commander.color_identity)
const counts = new Map<string, number>()
for (const card of cards) {
counts.set(card.oracle_id, (counts.get(card.oracle_id) ?? 0) + 1)
if (card.oracle_id === commander.oracle_id) {
errors.push(`${card.name} cannot be both the commander and a deck card.`)
}
const outside = card.color_identity.filter(color => !identity.has(color))
if (outside.length) errors.push(`${card.name} is outside the commander's color identity.`)
}
for (const [oracleId, count] of counts) {
if (count < 2) continue
const card = cards.find(entry => entry.oracle_id === oracleId)
if (card && !isBasicLand(card)) {
errors.push(`${card.name} appears ${count} times; only basic lands may repeat.`)
}
}
return [...new Set(errors)]
}
const SECTION_HEADERS = new Set([
'commander', 'commanders', 'deck', 'mainboard', 'main', 'main deck',
'sideboard', 'maybeboard', 'tokens', 'creatures', 'instants', 'sorceries',
'artifacts', 'enchantments', 'planeswalkers', 'lands', 'battle', 'other',
])
interface Entry {
quantity: number
name: string
section: 'commander' | 'deck' | 'ignore'
}
function cleanName(raw: string): string {
return raw
.replace(/\s*\*[fF]\*\s*$/, '')
.replace(/\s+\([A-Z0-9]{2,8}\)\s+[A-Z0-9-]+.*$/, '')
.replace(/\s+\[[A-Z0-9]{2,8}\].*$/, '')
.trim()
}
function parseEntries(
text: string,
resolve: (name: string) => Card | undefined,
): { entries: Entry[]; unresolved: string[] } {
const entries: Entry[] = []
const unresolved: string[] = []
let section: Entry['section'] = 'deck'
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line || line.startsWith('//') || line.startsWith('#')) continue
const header = line.replace(/:$/, '').replace(/\s*\(\d+\)$/, '').toLowerCase()
if (SECTION_HEADERS.has(header)) {
section = header.startsWith('commander') ? 'commander'
: header === 'sideboard' || header === 'maybeboard' || header === 'tokens' ? 'ignore'
: 'deck'
continue
}
const match = line.match(/^(\d+)\s*[xX]?\s*(.+)$/) ?? line.match(/^()(.+)$/)
if (!match) continue
const quantity = Number(match[1] || 1)
if (!Number.isFinite(quantity) || quantity <= 0) continue
const name = cleanName(match[2])
if (!name) continue
const card = resolve(name)
if (!card) {
unresolved.push(name)
continue
}
entries.push({ quantity, name: card.name, section })
}
return { entries, unresolved }
}
/**
* Parses common decklist exports (Moxfield, Archidekt, Arena, plain text):
*
* Commander
* 1 Atraxa, Praetors' Voice
*
* Deck
* 1 Sol Ring
* 10 Forest
*
* Without a Commander section, a single legendary creature in the list is
* inferred as the commander.
*/
export function importDeckText(
text: string,
resolve: (name: string) => Card | undefined = findCardByName,
): ImportedDeck {
const { entries, unresolved } = parseEntries(text, resolve)
const errors: string[] = []
if (unresolved.length) {
errors.push(`Unrecognized cards: ${[...new Set(unresolved)].join(', ')}`)
}
const commanderEntries = entries.filter(entry => entry.section === 'commander')
const deckEntries = entries.filter(entry => entry.section === 'deck')
let commander = commanderEntries[0] ? resolve(commanderEntries[0].name) : undefined
if (commanderEntries.length > 1 || commanderEntries.some(entry => entry.quantity > 1)) {
errors.push('A deck can only have one commander.')
}
if (!commander) {
const candidates = new Map<string, Card>()
for (const entry of deckEntries) {
const card = resolve(entry.name)
if (card && entry.quantity === 1 && canBeCommander(card)) candidates.set(card.oracle_id, card)
}
if (candidates.size === 1) {
commander = [...candidates.values()][0]
} else if (candidates.size > 1 && deckEntries.length) {
errors.push('Multiple possible commanders found; put the commander in a Commander section.')
}
}
const cards: Card[] = []
let commanderRemoved = false
for (const entry of deckEntries) {
const card = resolve(entry.name)
if (!card) continue
for (let index = 0; index < entry.quantity; index++) {
if (!commanderRemoved && commander && card.oracle_id === commander.oracle_id) {
commanderRemoved = true
continue
}
cards.push(card)
}
}
if (!commander) {
errors.push('No commander found. Add a "Commander" section with one legendary creature.')
} else {
errors.push(...validateCommanderDeck(commander, cards))
}
return { commander, cards, errors: [...new Set(errors)] }
}

2999
backend/src/game/game.ts Normal file

File diff suppressed because it is too large Load Diff

602
backend/src/game/rooms.ts Normal file
View File

@@ -0,0 +1,602 @@
import { randomUUID } from 'node:crypto'
import { getCard, type Card } from '../cards.js'
import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js'
import { getCardDefinition } from './catalog.js'
import { validateCommanderDeck } from './commander.js'
import { Game, GameError } from './game.js'
import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js'
export class MatchError extends Error {
constructor(message: string, readonly status = 400) {
super(message)
}
}
export interface DeckSubmission {
commander: string
cards: string[]
}
export interface ActionPayload {
type: string
cardId?: string
sourceId?: string
abilityIndex?: number
targets?: TargetChoice[]
x?: number
mode?: number
position?: { x?: unknown; y?: unknown }
attackers?: { attackerId: string; defenderId: string }[]
blocks?: { blockerId: string; attackerId: string }[]
}
export interface CardView {
id: string
oracleId: string
name: string
typeLine: string
manaCost?: string
manaValue?: number
colors: string[]
colorIdentity: string[]
oracleText?: string
power?: number
toughness?: number
tapped: boolean
damage: number
counters: Record<string, number>
isToken: boolean
isCommander: boolean
zone: string
controller: string
owner: string
position?: { x: number; y: number }
attacking?: string
blockedBy: string[]
blocking?: string
abilities: { index: number; kind: string; text?: string }[]
/** Viewer-specific: can this card be played from hand right now? */
playable?: boolean
}
export type Playmat =
| { kind: 'card'; oracleId: string }
| { kind: 'upload'; id: string }
export interface PlaymatSubmission {
kind?: unknown
oracleId?: unknown
data?: unknown
}
export interface PlayerView {
id: string
name: string
/** Present while the match is in the lobby. */
commander?: { oracleId: string; name: string }
playmat?: Playmat
life?: number
lost?: boolean
handCount?: number
libraryCount?: number
battlefield?: CardView[]
graveyard?: CardView[]
exile?: CardView[]
command?: CardView[]
commanderId?: string
commanderDamage?: { commanderId: string; commanderName: string; amount: number }[]
commanderCasts?: Record<string, number>
landPlayedThisTurn?: boolean
}
export interface MatchView {
id: string
status: 'lobby' | 'active' | 'finished'
version: number
viewerId: string
hostId: string
maxPlayers: number
players: PlayerView[]
game?: {
turn: number
activePlayer: string
phase: string
step: string
priority: string
status: string
winner?: string
stack: { id: string; kind: string; label: string; controller: string }[]
log: string[]
hand: CardView[]
manaPool: ManaPool
/** Present while a search waits for a pick; `cards` is populated only for its chooser. */
pendingSearch?: {
player: string
remaining: number
destination: string
cards: CardView[]
}
}
}
export interface MatchSummary {
id: string
hostName: string
status: 'lobby' | 'active' | 'finished'
playerCount: number
maxPlayers: number
players: string[]
createdAt: number
}
interface Seat {
playerId: string
token: string
name: string
commander: CardDefinition
cards: CardDefinition[]
playmat?: Playmat
}
interface Match {
id: string
hostId: string
maxPlayers: number
status: 'lobby' | 'active' | 'finished'
seats: Seat[]
game?: Game
version: number
createdAt: number
listeners: Map<string, Set<(state: MatchView) => void>>
}
const matches = new Map<string, Match>()
function requireMatch(matchId: string): Match {
const match = matches.get(matchId)
if (!match) throw new MatchError('Game not found', 404)
return match
}
function requireSeat(match: Match, token: string | undefined): Seat {
const seat = match.seats.find(entry => entry.token === token)
if (!seat) throw new MatchError('You are not seated in this game', 403)
return seat
}
function playerName(name: unknown): string {
const clean = typeof name === 'string' ? name.trim().slice(0, 30) : ''
return clean || 'Player'
}
function resolveDeck(deck: DeckSubmission | undefined): { commander: CardDefinition; cards: CardDefinition[] } {
if (!deck || typeof deck.commander !== 'string' || !Array.isArray(deck.cards)) {
throw new MatchError('A commander deck is required')
}
if (deck.cards.length > 250 || deck.cards.some(id => typeof id !== 'string')) {
throw new MatchError('Invalid deck')
}
const commander = getCard(deck.commander)
if (!commander) throw new MatchError('Commander not found')
const cards: Card[] = []
const missing: string[] = []
for (const oracleId of deck.cards) {
const card = getCard(oracleId)
if (card) cards.push(card)
else missing.push(oracleId)
}
if (missing.length) {
throw new MatchError(`Unknown cards: ${[...new Set(missing)].join(', ')}`)
}
const errors = validateCommanderDeck(commander, cards)
if (errors.length) throw new MatchError(errors.join('\n'))
const commanderDefinition = getCardDefinition(deck.commander)
if (!commanderDefinition) throw new MatchError('Commander effects are unavailable')
const definitions = deck.cards.map(id => {
const definition = getCardDefinition(id)
if (!definition) throw new MatchError(`Effects are unavailable for ${id}`)
return definition
})
return { commander: commanderDefinition, cards: definitions }
}
function makeSeat(name: unknown, deck: DeckSubmission | undefined): Seat {
const resolved = resolveDeck(deck)
return {
playerId: randomUUID(),
token: randomUUID(),
name: playerName(name),
commander: resolved.commander,
cards: resolved.cards,
}
}
export function listMatches(): MatchSummary[] {
return [...matches.values()]
.filter(match => match.status !== 'finished')
.sort((a, b) => b.createdAt - a.createdAt)
.slice(0, 50)
.map(match => ({
id: match.id,
hostName: match.seats.find(seat => seat.playerId === match.hostId)?.name ?? 'Unknown',
status: match.status,
playerCount: match.seats.length,
maxPlayers: match.maxPlayers,
players: match.seats.map(seat => seat.name),
createdAt: match.createdAt,
}))
}
export function createMatch(
name: unknown,
deck: DeckSubmission | undefined,
maxPlayers: unknown,
): { matchId: string; playerId: string; token: string } {
const limit = Math.min(4, Math.max(2, Number(maxPlayers) || 4))
const seat = makeSeat(name, deck)
const match: Match = {
id: randomUUID(),
hostId: seat.playerId,
maxPlayers: limit,
status: 'lobby',
seats: [seat],
version: 0,
createdAt: Date.now(),
listeners: new Map(),
}
matches.set(match.id, match)
return { matchId: match.id, playerId: seat.playerId, token: seat.token }
}
export function joinMatch(
matchId: string,
name: unknown,
deck: DeckSubmission | undefined,
): { matchId: string; playerId: string; token: string } {
const match = requireMatch(matchId)
if (match.status !== 'lobby') throw new MatchError('This game has already started')
if (match.seats.length >= match.maxPlayers) throw new MatchError('This game is full')
const seat = makeSeat(name, deck)
match.seats.push(seat)
broadcast(match)
return { matchId: match.id, playerId: seat.playerId, token: seat.token }
}
export function leaveMatch(matchId: string, token: string | undefined): void {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
// A started game can't drop the seat without breaking its state: forfeit instead.
if (match.status === 'active' && match.game) {
match.game.concede(seat.playerId)
match.game.autoAdvance()
if (match.game.status === 'finished') match.status = 'finished'
broadcast(match)
return
}
match.seats = match.seats.filter(entry => entry !== seat)
if (!match.seats.length) {
matches.delete(match.id)
return
}
if (match.hostId === seat.playerId) match.hostId = match.seats[0].playerId
broadcast(match)
}
export function setDeck(matchId: string, token: string | undefined, deck: DeckSubmission | undefined): void {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
if (match.status !== 'lobby') throw new MatchError('You can only change your deck in the lobby')
const resolved = resolveDeck(deck)
seat.commander = resolved.commander
seat.cards = resolved.cards
broadcast(match)
}
export async function setPlaymat(
matchId: string,
token: string | undefined,
submission: PlaymatSubmission | undefined,
): Promise<Playmat | undefined> {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
if (!submission) throw new MatchError('Invalid playmat selection')
const kind = submission.kind
let next: Playmat | undefined
if (kind === 'none') {
next = undefined
} else if (kind === 'card') {
if (typeof submission.oracleId !== 'string') throw new MatchError('Missing card id')
const card = getCard(submission.oracleId)
if (!card || !scryfallArtUrl(card.image_uri)) throw new MatchError('Card art not found')
next = { kind: 'card', oracleId: card.oracle_id }
} else if (kind === 'upload') {
if (typeof submission.data !== 'string') throw new MatchError('Missing playmat image')
try {
next = { kind: 'upload', id: await storePlaymatImage(submission.data) }
} catch (error) {
if (error instanceof PlaymatError) throw new MatchError(error.message)
throw error
}
} else {
throw new MatchError('Invalid playmat selection')
}
const previous = seat.playmat
seat.playmat = next
broadcast(match)
if (previous?.kind === 'upload' && previous.id !== (next?.kind === 'upload' ? next.id : '')) {
await deletePlaymatImage(previous.id)
}
return next
}
export function startMatch(matchId: string, token: string | undefined): void {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
if (seat.playerId !== match.hostId) throw new MatchError('Only the host can start the game')
if (match.status !== 'lobby') throw new MatchError('This game has already started')
if (match.seats.length < 2) throw new MatchError('At least two players are needed')
const game = new Game({
seed: Date.now(),
startingLife: 40,
startingHandSize: 7,
firstPlayer: match.seats[0].playerId,
commander: true,
players: match.seats.map(entry => ({
id: entry.playerId,
name: entry.name,
deck: entry.cards,
commander: entry.commander,
})),
})
game.start()
game.autoAdvance()
match.game = game
match.status = game.status === 'finished' ? 'finished' : 'active'
broadcast(match)
}
export function getMatchView(matchId: string, token: string | undefined): MatchView {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
return serialize(match, seat.playerId)
}
export function subscribe(
matchId: string,
token: string | undefined,
send: (state: MatchView) => void,
): () => void {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
let listeners = match.listeners.get(seat.playerId)
if (!listeners) {
listeners = new Set()
match.listeners.set(seat.playerId, listeners)
}
listeners.add(send)
send(serialize(match, seat.playerId))
return () => {
listeners?.delete(send)
if (listeners && listeners.size === 0) match.listeners.delete(seat.playerId)
}
}
export function performAction(matchId: string, token: string | undefined, action: ActionPayload): void {
const match = requireMatch(matchId)
const seat = requireSeat(match, token)
const game = match.game
if (match.status !== 'active' || !game) throw new MatchError('This game is not active')
const targets = Array.isArray(action.targets)
? action.targets.filter((target): target is TargetChoice => Boolean(target)
&& typeof target.id === 'string'
&& (target.kind === 'player' || target.kind === 'object' || target.kind === 'spell'))
: []
const options = {
targets,
x: Number.isFinite(action.x) ? Number(action.x) : 0,
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
}
try {
switch (action.type) {
case 'play_land':
game.playLand(seat.playerId, requireId(action.cardId))
break
case 'cast':
game.castSpell(seat.playerId, requireId(action.cardId), options)
break
case 'activate':
if (!Number.isInteger(action.abilityIndex)) throw new MatchError('Invalid ability')
game.activateAbility(seat.playerId, requireId(action.sourceId), Number(action.abilityIndex), options)
break
case 'move_permanent':
game.movePermanent(seat.playerId, requireId(action.cardId), Number(action.position?.x), Number(action.position?.y))
// Layout only: skip autoAdvance so dragging never passes priority.
broadcast(match)
return
case 'choose_search':
game.chooseSearchCard(seat.playerId, requireId(action.cardId))
break
case 'attack':
if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers')
game.declareAttackers(seat.playerId, action.attackers.map(entry => ({
attackerId: requireId(entry?.attackerId),
defenderId: requireId(entry?.defenderId),
})))
break
case 'block':
if (!Array.isArray(action.blocks)) throw new MatchError('Invalid blocks')
game.declareBlockers(seat.playerId, action.blocks.map(entry => ({
blockerId: requireId(entry?.blockerId),
attackerId: requireId(entry?.attackerId),
})))
break
case 'pass':
game.pass(seat.playerId)
break
case 'end_turn':
game.endTurn(seat.playerId)
break
default:
throw new MatchError(`Unknown action: ${action.type}`)
}
} catch (error) {
if (error instanceof GameError) throw new MatchError(error.message)
throw error
}
game.autoAdvance()
if (game.status === 'finished') match.status = 'finished'
broadcast(match)
}
function requireId(id: unknown): string {
if (typeof id !== 'string' || !id) throw new MatchError('Missing card or player id')
return id
}
function cardView(game: Game, object: GameObject, abilities = true): CardView {
const definition = object.definition
const creature = /creature/i.test(definition.typeLine)
return {
id: object.id,
oracleId: definition.oracleId,
name: definition.name,
typeLine: definition.typeLine,
manaCost: definition.manaCost,
manaValue: definition.manaValue,
colors: definition.colors ?? [],
colorIdentity: definition.colorIdentity ?? [],
oracleText: definition.oracleText,
power: creature ? game.getPower(object) : undefined,
toughness: creature ? game.getToughness(object) : undefined,
tapped: object.tapped,
damage: object.damage,
counters: { ...object.counters },
isToken: object.isToken,
isCommander: Boolean(object.isCommander),
zone: object.zone,
controller: object.controller,
owner: object.owner,
position: object.position ? { ...object.position } : undefined,
attacking: object.attacking,
blockedBy: [...object.blockedBy],
blocking: object.blocking,
abilities: abilities
? (definition.abilities ?? []).map((ability, index) => ({
index,
kind: ability.kind,
text: 'text' in ability ? ability.text : undefined,
}))
: [],
}
}
function serialize(match: Match, viewerId: string): MatchView {
const view: MatchView = {
id: match.id,
status: match.status,
version: match.version,
viewerId,
hostId: match.hostId,
maxPlayers: match.maxPlayers,
players: match.seats.map(seat => ({
id: seat.playerId,
name: seat.name,
commander: { oracleId: seat.commander.oracleId, name: seat.commander.name },
playmat: seat.playmat,
})),
}
const game = match.game
if (!game) return view
view.players = match.seats.map(seat => {
const player = game.getPlayer(seat.playerId)
return {
id: player.id,
name: player.name,
playmat: seat.playmat,
life: player.life,
lost: player.lost,
handCount: player.hand.length,
libraryCount: player.library.length,
battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))),
graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)),
exile: player.exile.map(id => cardView(game, game.getObject(id), false)),
command: player.command.map(id => cardView(game, game.getObject(id), false)),
commanderId: player.commanderId,
commanderDamage: Object.entries(player.commanderDamage)
.filter(([, amount]) => amount > 0)
.map(([commanderId, amount]) => ({
commanderId,
commanderName: game.objects.get(commanderId)?.definition.name ?? 'Commander',
amount,
})),
commanderCasts: { ...player.commanderCasts },
landPlayedThisTurn: player.landPlayedThisTurn,
}
})
const viewer = game.getPlayer(viewerId)
const search = game.pendingSearch
view.game = {
turn: game.turn,
activePlayer: game.activePlayer,
phase: game.phase,
step: game.step,
priority: game.priority,
status: game.status,
winner: game.winner,
stack: game.stack.map(item => ({
id: item.id,
kind: item.kind,
label: item.label,
controller: item.controller,
})),
log: game.log.slice(-80),
hand: viewer.hand.map(id => ({
...cardView(game, game.getObject(id)),
playable: game.canPlayCard(viewerId, id),
})),
manaPool: { ...viewer.manaPool },
pendingSearch: search
? {
player: search.playerId,
remaining: search.remaining,
destination: search.destination,
cards: search.playerId === viewerId
? game.searchCandidates(viewerId).map(object => cardView(game, object, false))
: [],
}
: undefined,
}
return view
}
function broadcast(match: Match): void {
match.version++
for (const [playerId, listeners] of match.listeners) {
let state: MatchView
try {
state = serialize(match, playerId)
} catch {
continue
}
for (const send of [...listeners]) {
try {
send(state)
} catch {
listeners.delete(send)
}
}
}
}

156
backend/src/game/types.ts Normal file
View File

@@ -0,0 +1,156 @@
// The runtime game model. Card definitions are immutable input; objects are the
// per-game instances that move between zones.
import type { Ability, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js'
export type ManaColor = 'W' | 'U' | 'B' | 'R' | 'G' | 'C'
export type ManaPool = Record<ManaColor, number>
export interface CardDefinition {
oracleId: string
name: string
typeLine: string
manaCost?: string
manaValue?: number
colors?: string[]
colorIdentity?: string[]
power?: number
toughness?: number
loyalty?: number
oracleText?: string
/** Compiled oracle-text abilities, or hand-written abilities in tests. */
abilities?: Ability[]
}
export interface PlayerConfig {
id: string
name?: string
deck: CardDefinition[]
/** Creates this card in the command zone when the game uses commander rules. */
commander?: CardDefinition
life?: number
}
export interface GameConfig {
players: PlayerConfig[]
startingLife?: number
startingHandSize?: number
seed?: number
firstPlayer?: string
/** Enables command-zone casting, commander tax, and commander damage. */
commander?: boolean
}
export interface PlayerState {
id: string
name: string
life: number
lost: boolean
manaPool: ManaPool
library: string[]
hand: string[]
graveyard: string[]
exile: string[]
battlefield: string[]
command: string[]
commanderId?: string
/** Damage received from each commander, keyed by the commander's object id. */
commanderDamage: Record<string, number>
/** Times each commander has been cast from the command zone. */
commanderCasts: Record<string, number>
landPlayedThisTurn: boolean
cardsDrawnThisTurn: number
lifeGainedThisTurn: number
spellsCastThisTurn: number
creaturesDiedThisTurn: number
nonlandPermanentsEnteredThisTurn: number
attackedThisTurn: boolean
energy: number
poison: number
}
export interface GameObject {
id: string
definition: CardDefinition
owner: string
controller: string
zone: Zone
tapped: boolean
damage: number
/** Set when this object has been dealt damage by a source with deathtouch. */
deathtouched: boolean
counters: Record<string, number>
isToken: boolean
token?: TokenSpec
isCommander?: boolean
enteredTurn: number
/** Normalized center on the controller's mat; absent means auto-arranged. */
position?: { x: number; y: number }
attacking?: string
blockedBy: string[]
blocking?: string
attachments: string[]
attachedTo?: string
regenerationShields: number
activations: Record<number, number>
}
export type TargetChoice =
| { kind: 'player'; id: string }
| { kind: 'object'; id: string }
| { kind: 'spell'; id: string }
export interface StackItem {
id: string
kind: 'spell' | 'ability'
source: GameObject
controller: string
label: string
effects: Effect[]
targets: TargetChoice[]
x: number
mode: number
triggerSubject?: GameObject
eventPlayer?: string
eventAmount?: number
}
export interface ActionOptions {
targets?: TargetChoice[]
x?: number
mode?: number
}
/** A search that is waiting for its player to pick one of several matching cards. */
export interface PendingSearch {
playerId: string
selector: ObjectSelector
remaining: number
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'
tapped: boolean
shuffle: boolean
zones?: ('library' | 'graveyard')[]
}
export interface CombatAttack {
attackerId: string
defenderId: string
}
export interface CombatBlock {
blockerId: string
attackerId: string
}
export type Phase = 'beginning' | 'precombat_main' | 'combat' | 'postcombat_main' | 'ending'
export type Step =
| 'untap'
| 'upkeep'
| 'draw'
| 'main'
| 'begin_combat'
| 'declare_attackers'
| 'declare_blockers'
| 'combat_damage'
| 'end_combat'
| 'end_step'
| 'cleanup'

108
backend/src/images.ts Normal file
View File

@@ -0,0 +1,108 @@
import { randomUUID } from 'node:crypto'
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
export const IMAGE_DIR = join(import.meta.dirname, '..', 'data', 'images')
export const PLAYMAT_DIR = join(import.meta.dirname, '..', 'data', 'playmats')
const MAX_PLAYMAT_BYTES = 3_000_000
const PLAYMAT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
const PLAYMAT_DATA_URL = /^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/
const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])
export class PlaymatError extends Error {}
const downloads = new Map<string, Promise<Buffer>>()
/** Only accept art from Scryfall's image host, never an arbitrary URL from the data file. */
export function scryfallImageUrl(uri: string | undefined): string | undefined {
if (!uri) return undefined
try {
const url = new URL(uri)
const scryfall = url.hostname === 'scryfall.io' || url.hostname.endsWith('.scryfall.io')
return url.protocol === 'https:' && scryfall ? url.href : undefined
} catch {
return undefined
}
}
/** Scryfall serves the same art wider for playmats; swap the size segment of a normal image URL. */
export function scryfallArtUrl(uri: string | undefined): string | undefined {
const source = scryfallImageUrl(uri)
if (!source) return undefined
return scryfallImageUrl(source.replace('/normal/', '/art_crop/'))
}
async function cachedImage(key: string, source: string, dir: string): Promise<Buffer> {
const file = join(dir, `${key}.jpg`)
try {
return await readFile(file)
} catch {
// Not cached yet.
}
let download = downloads.get(file)
if (!download) {
download = (async () => {
const response = await fetch(source, {
headers: { 'User-Agent': 'commander-api/0.1', Accept: 'image/jpeg,image/*' },
})
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/')) {
throw new Error(`Scryfall image request failed: ${response.status}`)
}
const data = Buffer.from(await response.arrayBuffer())
await mkdir(dir, { recursive: true })
const temp = `${file}.tmp`
await writeFile(temp, data)
await rename(temp, file)
return data
})().finally(() => downloads.delete(file))
downloads.set(file, download)
}
return download
}
/** Return a card's face, downloading it from Scryfall once and keeping a copy on disk. */
export function cardImage(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
return cachedImage(encodeURIComponent(oracleId), source, dir)
}
/** Wide art crop used as a playmat. Cached separately from the card face. */
export function cardArt(oracleId: string, source: string, dir = IMAGE_DIR): Promise<Buffer> {
return cachedImage(`art-${encodeURIComponent(oracleId)}`, source, dir)
}
/** Validate and store an uploaded playmat, returning the id used in its URL. */
export async function storePlaymatImage(dataUrl: string, dir = PLAYMAT_DIR): Promise<string> {
const match = PLAYMAT_DATA_URL.exec(dataUrl)
if (!match) throw new PlaymatError('Playmat must be a base64 JPEG image')
const data = Buffer.from(match[1], 'base64')
if (!data.length || data.length > MAX_PLAYMAT_BYTES) {
throw new PlaymatError('Playmat image must be under 3 MB')
}
if (!data.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) {
throw new PlaymatError('Playmat image is not a JPEG')
}
const id = randomUUID()
await mkdir(dir, { recursive: true })
await writeFile(join(dir, `${id}.jpg`), data)
return id
}
export async function playmatImage(id: string, dir = PLAYMAT_DIR): Promise<Buffer | undefined> {
if (!PLAYMAT_ID.test(id)) return undefined
try {
return await readFile(join(dir, `${id}.jpg`))
} catch {
return undefined
}
}
export async function deletePlaymatImage(id: string, dir = PLAYMAT_DIR): Promise<void> {
if (!PLAYMAT_ID.test(id)) return
await rm(join(dir, `${id}.jpg`), { force: true })
}

458
backend/src/server.ts Normal file
View File

@@ -0,0 +1,458 @@
import Fastify from 'fastify'
import cors from '@fastify/cors'
import {
AuthError,
closeDatabase,
connectDatabase,
registerAccountRoutes,
} from './accounts.js'
import {
CardsUnavailableError,
findCardByName,
getCard,
matchesCardFilters,
searchCards,
} from './cards.js'
import {
compileImplementation,
deleteOverride,
getImplementation,
implementationIndex,
invalidateImplementationIndex,
readOverride,
writeOverride,
type ImplementationStatus,
} from './effects/implementations.js'
import { PseudoParseError } from './effects/pseudo.js'
import { translateCard, TranslationError } from './effects/translate.js'
import { importDeckText } from './game/commander.js'
import { cardArt, cardImage, playmatImage, scryfallArtUrl, scryfallImageUrl } from './images.js'
import {
MatchError,
createMatch,
getMatchView,
joinMatch,
leaveMatch,
listMatches,
performAction,
setDeck,
setPlaymat,
startMatch,
subscribe,
type ActionPayload,
type DeckSubmission,
type MatchView,
type PlaymatSubmission,
} from './game/rooms.js'
const app = Fastify({ logger: true })
const STATUS_FILTERS = new Set<ImplementationStatus | 'needs-work' | 'manual' | 'all'>([
'supported',
'partial',
'unsupported',
'needs-work',
'manual',
'all',
])
const COLOR_FILTERS = new Set(['W', 'U', 'B', 'R', 'G', 'C', 'M'])
const TYPE_FILTERS = new Set([
'artifact', 'battle', 'creature', 'enchantment', 'instant', 'kindred', 'land',
'planeswalker', 'sorcery', 'legendary',
])
const RARITY_FILTERS = new Set(['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus'])
function parseCmc(value: string | undefined): number | undefined | null {
if (value === undefined || value === '') return undefined
const parsed = Number(value)
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null
}
await app.register(cors, {
origin: process.env.CORS_ORIGIN?.split(',').map(origin => origin.trim())
?? ['http://localhost:3000'],
// @fastify/cors defaults to GET,HEAD,POST; decks and preferences are saved with PUT.
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
})
app.setErrorHandler((error, request, reply) => {
if (error instanceof CardsUnavailableError) {
return reply.code(503).send({ error: error.message })
}
if (error instanceof PseudoParseError) {
return reply.code(400).send({ error: error.message, line: error.line })
}
if (error instanceof TranslationError || error instanceof MatchError || error instanceof AuthError) {
return reply.code(error.status).send({ error: error.message })
}
request.log.error(error)
return reply.code(500).send({ error: 'Internal server error' })
})
registerAccountRoutes(app)
app.get('/health', async () => ({ status: 'ok', service: 'commander-api' }))
app.get<{
Querystring: {
q?: string
limit?: string
offset?: string
status?: string
format?: string
color?: string
type?: string
rarity?: string
cmcMin?: string
cmcMax?: string
}
}>(
'/cards',
async (request, reply) => {
const { q = '', limit, offset, status = 'all' } = request.query
if (!STATUS_FILTERS.has(status as ImplementationStatus | 'needs-work' | 'manual' | 'all')) {
return reply.code(400).send({ error: `Unknown status filter: ${status}` })
}
const format = request.query.format?.trim().toLowerCase() || undefined
if (format && !/^[a-z][a-z0-9_]{0,31}$/.test(format)) {
return reply.code(400).send({ error: `Invalid format filter: ${format}` })
}
const color = request.query.color?.trim().toUpperCase() || undefined
if (color && !COLOR_FILTERS.has(color)) {
return reply.code(400).send({ error: `Unknown color filter: ${color}` })
}
const type = request.query.type?.trim().toLowerCase() || undefined
if (type && !TYPE_FILTERS.has(type)) {
return reply.code(400).send({ error: `Unknown type filter: ${type}` })
}
const rarity = request.query.rarity?.trim().toLowerCase() || undefined
if (rarity && !RARITY_FILTERS.has(rarity)) {
return reply.code(400).send({ error: `Unknown rarity filter: ${rarity}` })
}
const cmcMin = parseCmc(request.query.cmcMin)
const cmcMax = parseCmc(request.query.cmcMax)
if (cmcMin === null || cmcMax === null) {
return reply.code(400).send({ error: 'Mana value filters must be non-negative numbers' })
}
const parsedLimit = Number.parseInt(limit ?? '50', 10)
const pageSize = Number.isFinite(parsedLimit) ? Math.min(Math.max(parsedLimit, 1), 200) : 50
const parsedOffset = Number.parseInt(offset ?? '0', 10)
const start = Number.isFinite(parsedOffset) ? Math.max(parsedOffset, 0) : 0
const index = await implementationIndex()
const result = searchCards(q, pageSize, start, card => {
const summary = index.get(card.oracle_id)
if (status === 'manual' && !summary?.manual) return false
if (status === 'needs-work' && summary?.status === 'supported') return false
if (status !== 'all' && status !== 'manual' && status !== 'needs-work' && summary?.status !== status) {
return false
}
return matchesCardFilters(card, { format, color, type, rarity, cmcMin, cmcMax })
})
return {
total: result.total,
cards: result.cards.map(card => ({
...card,
implementation: index.get(card.oracle_id) ?? null,
})),
}
},
)
app.get('/stats', async () => {
const index = await implementationIndex()
const stats = { supported: 0, partial: 0, unsupported: 0, manual: 0 }
for (const summary of index.values()) {
stats[summary.status]++
if (summary.manual) stats.manual++
}
return stats
})
app.get<{ Params: { id: string } }>('/cards/:id', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
return card
})
/** Only fetch art from Scryfall's image host, never an arbitrary URL from the data file. */
app.get<{ Params: { id: string } }>('/cards/:id/image', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
const source = scryfallImageUrl(card.image_uri)
if (!source) return reply.code(404).send({ error: 'Card image not available' })
try {
const image = await cardImage(card.oracle_id, source)
return reply
.header('Cache-Control', 'public, max-age=31536000, immutable')
.type('image/jpeg')
.send(image)
} catch (error) {
request.log.warn({ err: error, card: card.oracle_id }, 'Card image download failed')
return reply.code(502).send({ error: 'Card image unavailable' })
}
})
app.get<{ Params: { id: string } }>('/cards/:id/art', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
const source = scryfallArtUrl(card.image_uri)
if (!source) return reply.code(404).send({ error: 'Card art not available' })
try {
const image = await cardArt(card.oracle_id, source)
return reply
.header('Cache-Control', 'public, max-age=31536000, immutable')
.type('image/jpeg')
.send(image)
} catch (error) {
request.log.warn({ err: error, card: card.oracle_id }, 'Card art download failed')
return reply.code(502).send({ error: 'Card art unavailable' })
}
})
app.get<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
return { card, ...(await getImplementation(card)) }
})
app.put<{ Params: { id: string }; Body: { source?: unknown } }>(
'/cards/:id/implementation',
async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
const source = request.body?.source
if (typeof source !== 'string') {
return reply.code(400).send({ error: 'Body must be JSON with a "source" string' })
}
if (source.length > 1_000_000) {
return reply.code(413).send({ error: 'Implementation is too large' })
}
// Validate before touching the existing file, so a typo cannot lose work.
compileImplementation(card, source)
await writeOverride(card.oracle_id, source)
invalidateImplementationIndex()
return { card, ...(await getImplementation(card)) }
},
)
app.post<{ Params: { id: string } }>('/cards/:id/translate', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
return { source: await translateCard(card) }
})
app.delete<{ Params: { id: string } }>('/cards/:id/implementation', async (request, reply) => {
const card = getCard(request.params.id)
if (!card) return reply.code(404).send({ error: 'Card not found' })
await deleteOverride(card.oracle_id)
invalidateImplementationIndex()
return { card, ...(await getImplementation(card)) }
})
// Kept for scripts and debugging: a card has an override even if nobody asked
// for the whole implementation payload.
app.get<{ Params: { id: string } }>('/cards/:id/override', async (request, reply) => {
const override = await readOverride(request.params.id)
if (!override) return reply.code(404).send({ error: 'No manual implementation' })
return override
})
// ---------------------------------------------------------------------------
// Decks and Commander games
// ---------------------------------------------------------------------------
app.post<{ Body: { text?: unknown } }>('/decks/import', async (request, reply) => {
const text = request.body?.text
if (typeof text !== 'string') {
return reply.code(400).send({ error: 'Body must be JSON with a "text" string' })
}
if (text.length > 200_000) {
return reply.code(413).send({ error: 'Decklist is too large' })
}
return importDeckText(text)
})
app.post<{ Body: { names?: unknown } }>('/cards/resolve', async (request, reply) => {
const names = request.body?.names
if (!Array.isArray(names) || names.some(name => typeof name !== 'string')) {
return reply.code(400).send({ error: 'Body must be JSON with a "names" string array' })
}
return { cards: names.slice(0, 100).map(name => findCardByName(String(name)) ?? null) }
})
app.get('/games', async () => ({ games: listMatches() }))
/** A stale or invalid browser preference must never block creating or joining a game. */
async function applyPlaymat(
match: { matchId: string; token: string },
playmat: PlaymatSubmission | undefined,
): Promise<void> {
if (!playmat) return
try {
await setPlaymat(match.matchId, match.token, playmat)
} catch (error) {
if (!(error instanceof MatchError)) throw error
}
}
app.post<{
Body: { name?: unknown; deck?: DeckSubmission; maxPlayers?: unknown; playmat?: PlaymatSubmission }
}>(
'/games',
{ bodyLimit: 4_500_000 },
async (request, reply) => {
try {
const match = createMatch(request.body?.name, request.body?.deck, request.body?.maxPlayers)
await applyPlaymat(match, request.body?.playmat)
return match
} catch (error) {
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
throw error
}
},
)
app.post<{
Params: { id: string }
Body: { name?: unknown; deck?: DeckSubmission; playmat?: PlaymatSubmission }
}>(
'/games/:id/join',
{ bodyLimit: 4_500_000 },
async (request, reply) => {
try {
const match = joinMatch(request.params.id, request.body?.name, request.body?.deck)
await applyPlaymat(match, request.body?.playmat)
return match
} catch (error) {
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
throw error
}
},
)
app.post<{ Params: { id: string }; Body: { token?: string } }>(
'/games/:id/leave',
async (request, reply) => {
leaveMatch(request.params.id, request.body?.token)
return { ok: true }
},
)
app.post<{ Params: { id: string }; Body: { token?: string } }>(
'/games/:id/start',
async (request, reply) => {
startMatch(request.params.id, request.body?.token)
return { ok: true }
},
)
app.post<{ Params: { id: string }; Body: { token?: string; action?: ActionPayload } }>(
'/games/:id/actions',
async (request, reply) => {
if (!request.body?.action) {
return reply.code(400).send({ error: 'Body must include an action' })
}
performAction(request.params.id, request.body.token, request.body.action)
return { ok: true }
},
)
app.post<{ Params: { id: string }; Body: { token?: string; deck?: DeckSubmission } }>(
'/games/:id/deck',
async (request, reply) => {
setDeck(request.params.id, request.body?.token, request.body?.deck)
return { ok: true }
},
)
app.post<{ Params: { id: string }; Body: { token?: string; playmat?: PlaymatSubmission } }>(
'/games/:id/playmat',
{ bodyLimit: 4_500_000 },
async (request, reply) => {
try {
const playmat = await setPlaymat(request.params.id, request.body?.token, request.body?.playmat)
return { playmat }
} catch (error) {
if (error instanceof MatchError) return reply.code(error.status).send({ error: error.message })
throw error
}
},
)
app.get<{ Params: { id: string } }>('/playmats/:id', async (request, reply) => {
const image = await playmatImage(request.params.id)
if (!image) return reply.code(404).send({ error: 'Playmat not found' })
return reply
.header('Cache-Control', 'public, max-age=31536000, immutable')
.header('X-Content-Type-Options', 'nosniff')
.type('image/jpeg')
.send(image)
})
app.get<{ Params: { id: string }; Querystring: { token?: string } }>(
'/games/:id/state',
async request => getMatchView(request.params.id, request.query.token),
)
app.get<{ Params: { id: string }; Querystring: { token?: string } }>(
'/games/:id/events',
(request, reply) => {
const token = request.query.token
// Validate before hijacking so errors keep their status codes.
getMatchView(request.params.id, token)
const origin = request.headers.origin
const allowed = process.env.CORS_ORIGIN?.split(',').map(entry => entry.trim())
?? ['http://localhost:3000']
const allowOrigin = origin && allowed.includes(origin) ? origin : allowed[0]
reply.hijack()
reply.raw.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
'Access-Control-Allow-Origin': allowOrigin,
})
reply.raw.write(': connected\n\n')
const send = (state: MatchView): void => {
reply.raw.write(`data: ${JSON.stringify(state)}\n\n`)
}
const unsubscribe = subscribe(request.params.id, token, send)
const ping = setInterval(() => reply.raw.write(': ping\n\n'), 25_000)
request.raw.on('close', () => {
clearInterval(ping)
unsubscribe()
})
},
)
await connectDatabase()
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, async () => {
await app.close()
await closeDatabase()
process.exit(0)
})
}
await app.listen({
port: Number(process.env.PORT ?? 4000),
host: '0.0.0.0',
})

View File

@@ -0,0 +1,13 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { hashPassword, verifyPassword } from '../src/accounts.js'
test('passwords are salted and verified', async () => {
const first = await hashPassword('correct horse battery staple')
const second = await hashPassword('correct horse battery staple')
assert.notEqual(first.salt, second.salt)
assert.notEqual(first.hash, second.hash)
assert.equal(await verifyPassword('correct horse battery staple', first.salt, first.hash), true)
assert.equal(await verifyPassword('wrong password', first.salt, first.hash), false)
})

View File

@@ -0,0 +1,53 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { matchesCardFilters } from '../src/cards.js'
function card(overrides: Partial<Card> = {}): Card {
return {
oracle_id: 'test',
name: 'Test Card',
layout: 'normal',
cmc: 3,
type_line: 'Legendary Creature — Human',
colors: ['G', 'U'],
color_identity: ['G', 'U'],
keywords: [],
rarity: 'rare',
legal_formats: ['commander', 'legacy'],
...overrides,
}
}
const cardByIdentity = card({ color_identity: ['G', 'U'] })
test('card filters match format legality, color identity, type, rarity, and mana value', () => {
assert.equal(matchesCardFilters(cardByIdentity, { format: 'legacy' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { format: 'standard' }), false)
assert.equal(matchesCardFilters(cardByIdentity, {}), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'U' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'M' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { color: 'C' }), false)
assert.equal(matchesCardFilters(card({ color_identity: [] }), { color: 'C' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'legendary' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'creature' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { type: 'land' }), false)
const modalCard = card({
type_line: 'Sorcery',
card_faces: [
{ name: 'Front', type_line: 'Sorcery', colors: [] },
{ name: 'Back', type_line: 'Land', colors: [] },
],
})
assert.equal(matchesCardFilters(modalCard, { type: 'land' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'rare' }), true)
assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'common' }), false)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 3, cmcMax: 3 }), true)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false)
})

View File

@@ -0,0 +1,159 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { canBeCommander, importDeckText, validateCommanderDeck } from '../src/game/commander.js'
import { Game } from '../src/game/game.js'
import type { CardDefinition } from '../src/game/types.js'
function card(name: string, overrides: Partial<Card> = {}): Card {
return {
oracle_id: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
layout: 'normal',
cmc: 0,
type_line: 'Creature — Test',
colors: [],
color_identity: [],
keywords: [],
...overrides,
}
}
function commanderCard(name: string, overrides: Partial<Card> = {}): Card {
return card(name, {
type_line: 'Legendary Creature — Test',
color_identity: ['G'],
...overrides,
})
}
function basicLand(name: string): Card {
return card(name, { type_line: 'Basic Land — Forest', color_identity: ['G'] })
}
function commanderDefinition(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
return {
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
typeLine: 'Legendary Creature — Test',
manaCost: '{1}',
manaValue: 1,
colors: ['G'],
colorIdentity: ['G'],
power: 2,
toughness: 2,
abilities: [],
...overrides,
}
}
test('commander deck validation enforces size, singleton, identity, and commander type', () => {
const commander = commanderCard('Test Commander')
const legal = Array.from({ length: 99 }, () => basicLand('Forest'))
assert.deepEqual(validateCommanderDeck(commander, legal), [])
assert.match(validateCommanderDeck(commander, legal.slice(1)).join(' '), /exactly 100/)
const duplicate = [...legal.slice(1), card('Sol Ring', { color_identity: [] }), card('Sol Ring', { color_identity: [] })]
assert.match(validateCommanderDeck(commander, duplicate).join(' '), /only basic lands may repeat/)
const offColor = [...legal.slice(1), card('Counterspell', { color_identity: ['U'] })]
assert.match(validateCommanderDeck(commander, offColor).join(' '), /outside the commander's color identity/)
assert.match(validateCommanderDeck(card('Not Legendary'), legal).join(' '), /cannot be a commander/)
assert.equal(canBeCommander(card('Planeswalker Commander', { oracle_text: 'This can be your commander.' })), true)
})
test('decklist import reads sections, quantities, and set suffixes', () => {
const known = new Map<string, Card>([
['Test Commander', commanderCard('Test Commander')],
['Sol Ring', card('Sol Ring')],
['Forest', basicLand('Forest')],
])
const result = importDeckText(`
Commander
1 Test Commander (TST) 1
Deck
1 Sol Ring (TST) 2
2 Forest (TST) 3 *F*
`, name => known.get(name))
assert.equal(result.commander?.name, 'Test Commander')
assert.equal(result.cards.length, 3)
assert.equal(result.cards.filter(entry => entry.name === 'Forest').length, 2)
assert.match(result.errors.join(' '), /exactly 100/)
})
test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => {
const commander = commanderDefinition('Test Commander')
const game = new Game({
seed: 1,
startingHandSize: 0,
commander: true,
players: [
{ id: 'p1', deck: [], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
],
})
game.start()
const forest = {
oracleId: 'forest',
name: 'Forest',
typeLine: 'Basic Land — Forest',
abilities: [{
kind: 'activated' as const,
costs: [{ kind: 'tap' as const }],
effects: [{ op: 'add_mana' as const, player: 'you' as const, mana: { kind: 'symbols' as const, symbols: ['{G}'] } }],
optional: false,
text: '{T}: Add {G}.',
}],
}
const player = game.getPlayer('p1')
assert.equal(player.command.length, 1)
const object = game.getObject(player.command[0])
assert.equal(object.isCommander, true)
for (let index = 0; index < 4; index++) game.addCard('p1', forest, 'battlefield')
game.castSpell('p1', object.id)
game.resolveStack()
assert.equal(object.zone, 'battlefield')
assert.equal(player.commanderCasts[object.id], 1)
game.moveToZone(object, 'graveyard')
assert.equal(object.zone, 'command')
assert.equal(player.graveyard.length, 0)
game.castSpell('p1', object.id)
game.resolveStack()
assert.equal(object.zone, 'battlefield')
assert.equal(player.commanderCasts[object.id], 2)
assert.equal(player.battlefield.map(id => game.getObject(id)).filter(land => land.tapped).length, 4)
})
test('twenty-one commander damage loses the game', () => {
const commander = commanderDefinition('Big Commander', { power: 21, manaCost: '{0}', manaValue: 0 })
const game = new Game({
seed: 1,
startingHandSize: 0,
commander: true,
players: [
{ id: 'p1', deck: [], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
],
})
game.start()
const object = game.getObject(game.getPlayer('p1').command[0])
game.castSpell('p1', object.id)
game.resolveStack()
object.enteredTurn = 0
game.declareAttackers('p1', [{ attackerId: object.id, defenderId: 'p2' }])
game.declareBlockers('p2', [])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').commanderDamage[object.id], 21)
assert.equal(game.getPlayer('p2').lost, true)
assert.equal(game.winner, 'p1')
})

View File

@@ -0,0 +1,297 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { compileText } from '../src/effects/compile.js'
import { formatAbility } from '../src/effects/format.js'
import { parsePseudoCard } from '../src/effects/pseudo.js'
import type { Ability, Effect, Target } from '../src/effects/types.js'
function creature(text: string, keywords: string[] = []): Ability[] {
return compileText(text, 'Test Creature', keywords, 'Creature — Human')
}
function spell(text: string): Ability[] {
return compileText(text, 'Test Spell', [], 'Instant')
}
test('keyword lines become keyword abilities', () => {
const [ability] = creature('Flying, vigilance, lifelink')
assert.equal(ability.kind, 'keywords')
if (ability.kind !== 'keywords') return
assert.deepEqual(ability.keywords.map(keyword => keyword.keyword), ['Flying', 'Vigilance', 'Lifelink'])
})
test('enters trigger with a draw effect', () => {
const [ability] = creature('When this creature enters, draw a card.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.event, { kind: 'enters', subject: { kind: 'self' } })
assert.equal(ability.effects.length, 1)
assert.equal(ability.effects[0].op, 'draw')
})
test('activated mana ability', () => {
const [ability] = creature('{T}: Add {G}.')
assert.equal(ability.kind, 'activated')
if (ability.kind !== 'activated') return
assert.deepEqual(ability.costs, [{ kind: 'tap' }])
assert.deepEqual(ability.effects[0], {
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{G}'] },
})
})
test('search effect keeps destination, tapped, and shuffle', () => {
const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
assert.deepEqual(ability.effects[0], {
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
})
})
test('"it" refers to the triggering object when unambiguous', () => {
const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
const effect = ability.effects[0]
assert.equal(effect.op, 'put_counters')
if (effect.op !== 'put_counters') return
assert.deepEqual(effect.target, { kind: 'trigger_subject' })
})
test('ambiguous "it" is left unsupported instead of guessed', () => {
const [ability] = creature(
'When this creature enters, tap target creature an opponent controls and put a stun counter on it.',
)
assert.equal(ability.kind, 'unsupported')
})
test('modal text is unsupported', () => {
const [ability] = creature('Choose one —')
assert.equal(ability.kind, 'unsupported')
if (ability.kind !== 'unsupported') return
assert.equal(ability.reason, 'modal')
})
test('static anthem', () => {
const [ability] = creature('Creatures you control get +1/+1.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.equal(ability.effects[0].op, 'pump')
if (ability.effects[0].op !== 'pump') return
assert.equal(ability.effects[0].power.kind, 'number')
const target = ability.effects[0].target as Extract<Target, { kind: 'object' }>
assert.equal(target.mode, 'each')
assert.equal(target.selector.controller, 'you')
})
test('enters-with-counters is a static replacement effect', () => {
const [ability] = creature('This creature enters with X +1/+1 counters on it.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.effects[0], {
op: 'enters_with_counters',
target: { kind: 'self' },
counter: '+1/+1',
amount: { kind: 'x' },
})
})
test('trigger condition cards in graveyard', () => {
const [ability] = creature(
'Threshold — As long as there are seven or more cards in your graveyard, this creature gets +1/+1 and has first strike.',
)
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 })
})
test('formatter renders pseudocode', () => {
const [ability] = creature('When this creature enters, draw a card.')
const text = formatAbility(ability)
assert.match(text, /on enters\(this\)/)
assert.match(text, /draw\(you, 1\)/)
})
test('token copy of the triggering nontoken Dragon loses legendary', () => {
const [ability] = creature(
"Whenever another nontoken Dragon you control enters, create a token that's a copy of it, except the token isn't legendary.",
)
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.event, {
kind: 'enters',
subject: {
kind: 'object',
selector: {
other: true,
controller: 'you',
token: false,
types: ['creature'],
subtypes: ['dragon'],
},
mode: 'each',
},
})
const effect = ability.effects[0]
assert.equal(effect.op, 'create_token')
if (effect.op !== 'create_token') return
assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' })
assert.equal(effect.notLegendary, true)
assert.equal(formatAbility(ability), 'on enters(each other nontoken dragon creature you control):\n create_token(you, 1, copy of the triggering object, not legendary)')
})
test('all effects are typed', () => {
const [ability] = spell('Draw two cards, then discard a card.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const effects: Effect[] = ability.effects
assert.deepEqual(effects.map(effect => effect.op), ['draw', 'discard'])
})
test('a leading duration applies to the effect', () => {
const [ability] = spell('Until end of turn, target creature gets +2/+0 and gains first strike.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const [pump, grant] = ability.effects
assert.equal(pump.op, 'pump')
assert.equal(grant.op, 'grant')
if (pump.op !== 'pump' || grant.op !== 'grant') return
assert.equal(pump.duration, 'until_end_of_turn')
assert.equal(grant.duration, 'until_end_of_turn')
})
test('"When you do" becomes a reflexive condition and energy costs are payable', () => {
const [ability] = creature(
'Whenever a creature attacks, you may pay {3}. When you do, put a +1/+1 counter on that creature.',
)
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
const conditional = ability.effects[1]
assert.equal(conditional.op, 'conditional')
if (conditional.op !== 'conditional') return
assert.deepEqual(conditional.condition, { kind: 'if_you_do' })
const [activated] = creature('{T}, Pay {E}{E}: This creature deals 1 damage to target creature.')
assert.equal(activated.kind, 'activated')
if (activated.kind !== 'activated') return
assert.deepEqual(activated.costs, [
{ kind: 'tap' },
{ kind: 'energy', amount: 2 },
])
})
test('for-each pump keeps the zero stat', () => {
const [ability] = creature('This creature gets +1/+0 for each artifact you control.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
const effect = ability.effects[0]
assert.equal(effect.op, 'pump')
if (effect.op !== 'pump') return
assert.deepEqual(effect.power, { kind: 'count', selector: { types: ['artifact'], controller: 'you' } })
assert.deepEqual(effect.toughness, { kind: 'number', value: 0 })
})
test('"When <subject>" triggers and bare "gain life" effects parse', () => {
const [dies] = creature('When enchanted creature dies, return this to its owner\'s hand.')
assert.equal(dies.kind, 'triggered')
if (dies.kind !== 'triggered') return
assert.deepEqual(dies.event, {
kind: 'dies',
subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
})
const [upkeep] = creature('At the beginning of your upkeep, you may gain 1 life.')
assert.equal(upkeep.kind, 'triggered')
if (upkeep.kind !== 'triggered') return
assert.equal(upkeep.optional, true)
assert.deepEqual(upkeep.effects[0], {
op: 'life',
player: 'you',
amount: { kind: 'number', value: 1 },
mode: 'gain',
})
})
test('a trailing condition becomes a static condition', () => {
const [ability] = creature('This creature cannot attack if defending player controls an untapped land.')
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.condition, {
kind: 'defending_player_controls',
selector: { tapped: false, types: ['land'] },
})
})
test('"until the end of your next turn" gets its own duration', () => {
for (const text of [
'Target creature gets +2/+2 until the end of your next turn.',
'Until the end of your next turn, target creature gets +2/+2.',
]) {
const [ability] = spell(text)
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const effect = ability.effects[0]
assert.equal(effect.op, 'pump')
if (effect.op !== 'pump') return
assert.equal(effect.duration, 'until_end_of_your_next_turn')
const pseudo = formatAbility(ability)
assert.match(pseudo, /until the end of your next turn/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
}
})
test('parameterized keywords accept an em dash', () => {
const [escape] = creature('Escape—{2}{R}, Exile three other cards from your graveyard.')
assert.equal(escape.kind, 'keyword')
if (escape.kind !== 'keyword') return
assert.equal(escape.keyword, 'Escape')
const [fabricate] = creature('Fabricate 1')
assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' })
})
test('counter-removal costs parse and round-trip through pseudocode', () => {
const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.')
assert.equal(self.kind, 'activated')
if (self.kind !== 'activated') return
assert.deepEqual(self.costs, [
{ kind: 'mana', symbols: '{2}{u}' },
{ kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } },
])
const pseudo = formatAbility(self)
assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.')
assert.equal(other.kind, 'activated')
if (other.kind !== 'activated') return
assert.deepEqual(other.costs, [{
kind: 'remove_counters',
counter: 'spore',
amount: { kind: 'number', value: 3 },
selector: { controller: 'you', types: ['creature'] },
}])
})
test('a trigger returns its own card from the graveyard', () => {
const [ability] = creature('When this dies, return this from your graveyard to the battlefield with a finality counter on it.')
assert.equal(ability.kind, 'triggered')
if (ability.kind !== 'triggered') return
assert.deepEqual(ability.effects, [{
op: 'return_to_battlefield',
target: { kind: 'self' },
tapped: false,
transformed: undefined,
counters: { counter: 'finality', amount: { kind: 'number', value: 1 } },
}])
})

647
backend/test/game.test.ts Normal file
View File

@@ -0,0 +1,647 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { Game, GameError } from '../src/game/game.js'
import type { Ability, Effect } from '../src/effects/types.js'
import type { CardDefinition } from '../src/game/types.js'
function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
return {
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
name,
typeLine: 'Creature — Test',
manaValue: 0,
colors: [],
abilities: [],
...overrides,
}
}
function creature(name: string, power: number, toughness: number, abilities: Ability[] = []): CardDefinition {
return card(name, { typeLine: 'Creature — Test', power, toughness, abilities })
}
function spell(name: string, effects: Effect[], manaCost = ''): CardDefinition {
return card(name, { typeLine: 'Instant', manaCost, manaValue: 0, abilities: [{ kind: 'spell', effects, optional: false, text: name }] })
}
function land(name: string, color: string): CardDefinition {
return card(name, {
typeLine: `Basic Land — ${name}`,
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
optional: false,
text: `{T}: Add {${color}}.`,
}],
})
}
function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
const game = new Game({
seed: 7,
startingHandSize: 0,
players: players.map(player => ({ id: player.id, life: player.life, deck: player.deck ?? [card('Filler')] })),
})
return game
}
test('turns start at the first main phase, draw opening hands, and pass to the next player', () => {
const forest = land('Forest', 'G')
const game = new Game({
seed: 1,
startingHandSize: 7,
players: [
{ id: 'p1', deck: Array.from({ length: 10 }, () => forest) },
{ id: 'p2', deck: Array.from({ length: 10 }, () => forest) },
],
})
game.start()
assert.equal(game.turn, 1)
assert.equal(game.activePlayer, 'p1')
assert.equal(game.phase, 'precombat_main')
assert.equal(game.step, 'main')
assert.equal(game.priority, 'p1')
assert.equal(game.getPlayer('p1').life, 40)
assert.equal(game.getPlayer('p1').hand.length, 7)
assert.equal(game.getPlayer('p1').library.length, 3)
game.endTurn('p1')
assert.equal(game.turn, 2)
assert.equal(game.activePlayer, 'p2')
assert.equal(game.getPlayer('p2').hand.length, 8)
assert.equal(game.getPlayer('p1').hand.length, 7)
})
test('passing priority twice advances from the main phase into combat', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.pass('p1')
assert.equal(game.priority, 'p2')
game.pass('p2')
assert.equal(game.phase, 'combat')
assert.equal(game.step, 'declare_attackers')
assert.equal(game.priority, 'p1')
})
test('a spell goes on the stack, auto-taps mana, and resolves its compiled effect', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
assert.equal(game.stack.length, 1)
assert.equal(mountain.tapped, true)
assert.equal(game.priority, 'p2')
game.resolveStack()
assert.equal(game.stack.length, 0)
assert.equal(game.getPlayer('p2').life, 37)
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
})
test('permanents can be repositioned by their controller and positions are cleared on zone changes', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
game.movePermanent('p1', bear.id, 0.25, 0.75)
assert.deepEqual(bear.position, { x: 0.25, y: 0.75 })
game.movePermanent('p1', bear.id, -1, 2)
assert.deepEqual(bear.position, { x: 0, y: 1 })
assert.throws(() => game.movePermanent('p2', bear.id, 0.5, 0.5), /control/)
game.moveToZone(bear, 'graveyard')
assert.equal(bear.position, undefined)
})
test('enters triggers from compiled card code fire and resolve through the stack', () => {
const soulWarden = card('Soul Warden', {
typeLine: 'Creature — Human Cleric',
power: 1,
toughness: 1,
colors: ['W'],
abilities: [{
kind: 'triggered',
event: {
kind: 'enters',
subject: { kind: 'object', selector: { other: true, types: ['creature'] }, mode: 'each' },
},
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'gain' }],
optional: false,
text: 'Whenever another creature enters, you gain 1 life.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', soulWarden, 'battlefield')
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1), 'hand')
game.castSpell('p1', elves.id)
game.resolveStack()
assert.equal(game.getPlayer('p1').life, 41)
assert.ok(game.getPlayer('p1').battlefield.includes(elves.id))
})
test('activated mana abilities produce mana and creatures have summoning sickness', () => {
const solRing = card('Sol Ring', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{C}', '{C}'] } }],
optional: false,
text: '{T}: Add {C}{C}.',
}],
})
const game = setup([{ id: 'p1', deck: Array.from({ length: 5 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 5 }, () => card('Filler')) }])
game.start()
const ring = game.addCard('p1', solRing, 'battlefield')
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1, [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{G}'] } }],
optional: false,
text: '{T}: Add {G}.',
}]), 'battlefield')
game.activateAbility('p1', ring.id, 0)
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 2 })
assert.equal(ring.tapped, true)
assert.throws(() => game.activateAbility('p1', elves.id, 0), GameError)
game.endTurn('p1')
game.endTurn('p2')
assert.equal(elves.tapped, false)
game.activateAbility('p1', elves.id, 0)
assert.equal(game.getPlayer('p1').manaPool.G, 1)
})
test('static pump effects apply to matching creatures only', () => {
const anthem = card('Glorious Anthem', {
typeLine: 'Enchantment',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'static',
effects: [{
op: 'pump',
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
}],
text: 'Creatures you control get +1/+1.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const anthemObject = game.addCard('p1', anthem, 'battlefield')
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const enemy = game.addCard('p2', creature('Enemy Bear', 2, 2), 'battlefield')
assert.equal(game.getPower(bear), 3)
assert.equal(game.getToughness(bear), 3)
assert.equal(game.getPower(enemy), 2)
assert.equal(game.getPower(anthemObject), 0)
})
test('temporary pump effects expire at end of turn', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const growth = game.addCard('p1', spell('Giant Growth', [{
op: 'pump',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
power: { kind: 'number', value: 3 },
toughness: { kind: 'number', value: 3 },
duration: 'until_end_of_turn',
}]), 'hand')
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
assert.equal(game.getPower(bear), 5)
assert.equal(game.getToughness(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 2)
})
test('"until the end of your next turn" lasts through the controller next turn', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
const growth = game.addCard('p1', spell('Growth', [{
op: 'pump',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
power: { kind: 'number', value: 3 },
toughness: { kind: 'number', value: 3 },
duration: 'until_end_of_your_next_turn',
}]), 'hand')
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
assert.equal(game.getPower(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 5)
game.endTurn('p2')
assert.equal(game.getPower(bear), 5)
game.endTurn('p1')
assert.equal(game.getPower(bear), 2)
})
test('combat damage kills creatures and moves them to the graveyard', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
const attacker = game.addCard('p1', creature('Attacker', 2, 2), 'battlefield')
const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield')
game.start()
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
assert.equal(game.step, 'declare_blockers')
assert.equal(game.priority, 'p2')
assert.equal(attacker.tapped, true)
game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 40)
assert.equal(game.step, 'end_combat')
assert.ok(game.getPlayer('p1').graveyard.includes(attacker.id))
assert.ok(game.getPlayer('p2').graveyard.includes(blocker.id))
})
test('unblocked attackers deal damage to the defending player', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
const attacker = game.addCard('p1', creature('Attacker', 3, 3), 'battlefield')
game.start()
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
game.declareBlockers('p2', [])
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 37)
})
test('counterspell counters a spell on the stack', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
game.addCard('p2', land('Island', 'U'), 'battlefield')
game.addCard('p2', land('Island', 'U'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
const counterspell = game.addCard('p2', spell('Counterspell', [
{ op: 'counter', what: 'spell', target: { kind: 'spell', selector: { types: [] }, mode: 'target' } },
], '{U}{U}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
game.castSpell('p2', counterspell.id)
assert.equal(game.stack.length, 2)
game.resolveStack()
assert.equal(game.getPlayer('p2').life, 40)
assert.equal(game.stack.length, 0)
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
assert.ok(game.getPlayer('p2').graveyard.includes(counterspell.id))
})
test('activated abilities create tokens that enter the battlefield', () => {
const maker = card('Goblin Maker', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'create_token',
player: 'you',
amount: { kind: 'number', value: 1 },
token: { name: 'Goblin', types: ['creature'], subtypes: ['goblin'], colors: ['R'], power: { kind: 'number', value: 1 }, toughness: { kind: 'number', value: 1 } },
}],
optional: false,
text: '{T}: Create a 1/1 Goblin.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const source = game.addCard('p1', maker, 'battlefield')
game.activateAbility('p1', source.id, 0)
assert.equal(game.stack.length, 1)
game.resolveStack()
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
assert.equal(tokens.length, 1)
assert.equal(tokens[0].definition.name, 'Goblin')
assert.equal(game.getPower(tokens[0]), 1)
})
test('search effects find cards in the library and put them onto the battlefield tapped', () => {
const forest = land('Forest', 'G')
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const found = game.addCard('p1', forest, 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.resolveStack()
assert.ok(game.getPlayer('p1').battlefield.includes(found.id))
assert.equal(found.tapped, true)
})
test('search effects let the player pick among multiple matching cards', () => {
const forest = land('Forest', 'G')
const island = land('Island', 'U')
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const forestObject = game.addCard('p1', forest, 'library')
const islandObject = game.addCard('p1', island, 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.resolveStack()
assert.equal(game.pendingSearch?.playerId, 'p1')
assert.deepEqual(
game.searchCandidates('p1').map(object => object.id).sort(),
[forestObject.id, islandObject.id].sort(),
)
assert.equal(forestObject.zone, 'library')
assert.throws(() => game.pass('p1'), GameError)
game.chooseSearchCard('p1', islandObject.id)
assert.equal(game.pendingSearch, undefined)
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
assert.equal(islandObject.tapped, true)
assert.ok(game.getPlayer('p1').library.includes(forestObject.id))
})
test('autoAdvance stops instead of passing while a search needs a pick', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
game.addCard('p1', land('Forest', 'G'), 'library')
game.addCard('p1', land('Island', 'U'), 'library')
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
op: 'search',
player: 'you',
selector: { types: ['land'], supertypes: ['basic'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}]), 'hand')
game.castSpell('p1', rampantGrowth.id)
game.autoAdvance()
assert.equal(game.pendingSearch?.playerId, 'p1')
assert.equal(game.priority, 'p1')
})
test('static replacement effects make permanents enter tapped with counters', () => {
const slow = creature('Slow Bear', 2, 2, [{
kind: 'static',
effects: [{ op: 'enters_tapped', target: { kind: 'self' } }],
text: 'This enters tapped.',
}, {
kind: 'static',
effects: [{
op: 'enters_with_counters',
target: { kind: 'self' },
counter: '+1/+1',
amount: { kind: 'number', value: 1 },
}],
text: 'This enters with a +1/+1 counter.',
}])
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p1', slow, 'hand')
game.castSpell('p1', bear.id)
game.resolveStack()
assert.equal(bear.tapped, true)
assert.equal(bear.counters['+1/+1'], 1)
assert.equal(game.getPower(bear), 3)
assert.equal(game.getToughness(bear), 3)
})
test('a player who runs out of cards loses and the last player wins', () => {
const game = new Game({
seed: 3,
startingHandSize: 0,
players: [
{ id: 'p1', deck: [card('Filler')] },
{ id: 'p2', deck: [] },
],
})
game.start()
game.endTurn('p1')
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p1')
assert.equal(game.getPlayer('p2').lost, true)
})
test('lethal damage to a player ends the game', () => {
const game = setup([{ id: 'p1' }, { id: 'p2', life: 3 }])
game.start()
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const bolt = game.addCard('p1', spell('Lightning Bolt', [
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
], '{R}'), 'hand')
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
game.resolveStack()
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p1')
assert.equal(game.getPlayer('p2').life, 0)
})
test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
const expensive = game.addCard('p1', spell('Expensive Spell', [], '{R}{R}'), 'hand')
assert.throws(() => game.castSpell('p1', expensive.id), GameError)
assert.equal(mountain.tapped, false)
assert.equal(game.getPlayer('p1').manaPool.R, 0)
assert.ok(game.getPlayer('p1').hand.includes(expensive.id))
})
test('phyrexian mana can be paid with exactly enough life', () => {
const game = setup([{ id: 'p1', life: 2 }, { id: 'p2' }])
game.start()
const spellCard = game.addCard('p1', spell('Gitaxian Probe', [], '{W/P}'), 'hand')
assert.doesNotThrow(() => game.castSpell('p1', spellCard.id))
assert.equal(game.getPlayer('p1').life, 0)
assert.equal(game.status, 'finished')
assert.equal(game.winner, 'p2')
})
test('an unless cost auto-taps the mana sources of the payer', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
const forests = [
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
]
const edict = game.addCard('p1', spell('Edict', [{
op: 'sacrifice',
player: 'opponent',
target: { kind: 'object', selector: { types: ['creature'] } },
unless: { kind: 'mana', symbols: '{2}' },
}]), 'hand')
game.castSpell('p1', edict.id, {
targets: [{ kind: 'player', id: 'p2' }, { kind: 'object', id: bear.id }],
})
game.resolveStack()
assert.equal(bear.zone, 'battlefield')
assert.ok(forests.every(forest => forest.tapped))
assert.equal(game.getPlayer('p2').manaPool.G, 0)
})
test('canPlayCard reports legal lands and spells for the player with priority', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
const bear = game.addCard('p1', card('Grizzly Bears', {
typeLine: 'Creature — Bear',
power: 2,
toughness: 2,
manaCost: '{G}',
}), 'hand')
assert.equal(game.canPlayCard('p1', forest.id), true)
assert.equal(game.canPlayCard('p1', bear.id), false)
assert.equal(game.canPlayCard('p2', forest.id), false)
game.playLand('p1', forest.id)
assert.equal(game.canPlayCard('p1', bear.id), true)
})
test('autoAdvance skips empty phases and stops when someone can act', () => {
const expensive = card('Expensive', { manaCost: '{5}' })
const game = new Game({
seed: 3,
startingHandSize: 0,
players: [
{ id: 'p1', deck: [expensive] },
{ id: 'p2', deck: [expensive] },
],
})
game.start()
game.addCard('p1', land('Forest', 'G'), 'battlefield')
// The only action is a mana ability, which should not hold the phase open.
game.autoAdvance()
assert.equal(game.turn, 2)
assert.equal(game.activePlayer, 'p2')
assert.equal(game.phase, 'precombat_main')
assert.equal(game.priority, 'p2')
const hasty = creature('Hasty', 2, 2, [{ kind: 'keyword', keyword: 'Haste' }])
game.addCard('p2', hasty, 'battlefield')
game.autoAdvance()
assert.equal(game.turn, 2)
assert.equal(game.phase, 'combat')
assert.equal(game.step, 'declare_attackers')
assert.equal(game.priority, 'p2')
})
test('every defending player declares blocks before combat damage in multiplayer', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }])
game.start()
const first = game.addCard('p1', creature('First Attacker', 2, 2), 'battlefield')
const second = game.addCard('p1', creature('Second Attacker', 3, 3), 'battlefield')
first.enteredTurn = 0
second.enteredTurn = 0
game.declareAttackers('p1', [
{ attackerId: first.id, defenderId: 'p2' },
{ attackerId: second.id, defenderId: 'p3' },
])
assert.equal(game.step, 'declare_blockers')
game.declareBlockers('p2', [])
assert.equal(game.step, 'declare_blockers')
assert.equal(game.priority, 'p3')
game.declareBlockers('p3', [])
assert.equal(game.step, 'combat_damage')
game.resolveCombatDamage()
assert.equal(game.getPlayer('p2').life, 38)
assert.equal(game.getPlayer('p3').life, 37)
})
test('counter-removal costs are paid and fail when counters run out', () => {
const vessel = card('Spore Vessel', {
typeLine: 'Artifact',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'remove_counters', counter: 'spore', amount: { kind: 'number', value: 2 } }],
effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }],
optional: false,
text: 'Remove two spore counters from this: Draw a card.',
}],
})
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2' }])
game.start()
const source = game.addCard('p1', vessel, 'battlefield')
source.counters.spore = 3
game.activateAbility('p1', source.id, 0)
game.resolveStack()
assert.equal(source.counters.spore, 1)
assert.equal(game.getPlayer('p1').hand.length, 1)
assert.throws(() => game.activateAbility('p1', source.id, 0), GameError)
assert.equal(source.counters.spore, 1)
})

View File

@@ -0,0 +1,89 @@
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import {
PlaymatError,
cardImage,
deletePlaymatImage,
playmatImage,
scryfallArtUrl,
scryfallImageUrl,
storePlaymatImage,
} from '../src/images.js'
const ART = Buffer.from([0xff, 0xd8, 0xff, 0xd9])
test('only https URLs on the Scryfall image host are accepted', () => {
assert.equal(
scryfallImageUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'),
'https://cards.scryfall.io/normal/front/a/b/art.jpg?123',
)
assert.equal(scryfallImageUrl('http://cards.scryfall.io/art.jpg'), undefined)
assert.equal(scryfallImageUrl('https://example.com/art.jpg'), undefined)
assert.equal(scryfallImageUrl('not a url'), undefined)
assert.equal(scryfallImageUrl(undefined), undefined)
})
test('playmat art swaps the card image for the wide Scryfall crop', () => {
assert.equal(
scryfallArtUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'),
'https://cards.scryfall.io/art_crop/front/a/b/art.jpg?123',
)
assert.equal(scryfallArtUrl(undefined), undefined)
assert.equal(scryfallArtUrl('https://example.com/normal/art.jpg'), undefined)
})
test('uploaded playmats are stored, served and deleted', async () => {
const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-'))
const jpeg = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.from('pixels')])
try {
const id = await storePlaymatImage(`data:image/jpeg;base64,${jpeg.toString('base64')}`, dir)
assert.deepEqual(await playmatImage(id, dir), jpeg)
await deletePlaymatImage(id, dir)
assert.equal(await playmatImage(id, dir), undefined)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('uploaded playmats must be JPEG data URLs with a JPEG signature', async () => {
const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-'))
try {
await assert.rejects(storePlaymatImage('data:image/png;base64,AAAA', dir), PlaymatError)
await assert.rejects(storePlaymatImage('data:image/jpeg;base64,AAAA', dir), PlaymatError)
await assert.rejects(storePlaymatImage('not an image', dir), PlaymatError)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('card art is downloaded once and then served from the disk cache', async () => {
let requests = 0
const server = createServer((_request, response) => {
requests++
response.writeHead(200, { 'Content-Type': 'image/jpeg' })
response.end(ART)
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const dir = await mkdtemp(join(tmpdir(), 'commander-images-'))
try {
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/art.jpg`
assert.deepEqual(await cardImage('card-id', url, dir), ART)
assert.deepEqual(await readFile(join(dir, 'card-id.jpg')), ART)
assert.deepEqual(await cardImage('card-id', url, dir), ART)
assert.equal(requests, 1)
} finally {
await new Promise(resolve => server.close(resolve))
await rm(dir, { recursive: true, force: true })
}
})

View File

@@ -0,0 +1,92 @@
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { formatCard } from '../src/effects/format.js'
import {
compileImplementation,
deleteOverride,
readAllOverrides,
readOverride,
writeOverride,
} from '../src/effects/implementations.js'
import { parsePseudoCard, PseudoParseError } from '../src/effects/pseudo.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000001',
name: 'Test Card',
layout: 'normal',
cmc: 1,
type_line: 'Creature — Human',
colors: [],
color_identity: [],
keywords: [],
}
const SOURCE = `on enters(this):
choose 1:
1. exile(target other creature you own); schedule(next_end_step):
return_to_battlefield(the chosen target)
static:
grant_ability(each enchanted land):
on upkeep(you) (may):
pay({W}{W})
if you do:
gain_life(you, 1)`
test('pseudocode round-trips through the compiler and formatter', () => {
const compiled = compileImplementation(CARD, SOURCE)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
const rendered = formatCard(compiled)
const reparsed = compileImplementation(CARD, rendered)
assert.equal(formatCard(reparsed), rendered)
assert.equal(reparsed.abilities.length, 2)
const [triggered] = reparsed.abilities
assert.equal(triggered.kind, 'triggered')
if (triggered.kind !== 'triggered') return
assert.equal(triggered.effects[0].op, 'modal')
if (triggered.effects[0].op !== 'modal') return
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
const staticAbility = reparsed.abilities[1]
assert.equal(staticAbility.kind, 'static')
if (staticAbility.kind !== 'static') return
assert.equal(staticAbility.effects[0].op, 'grant_ability')
if (staticAbility.effects[0].op !== 'grant_ability') return
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
})
test('invalid pseudocode reports its line', () => {
assert.throws(
() => parsePseudoCard('spell:\n draw(you)'),
(error: unknown) => error instanceof PseudoParseError && error.line === 2,
)
})
test('manual implementations persist one file per card', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
const previous = process.env.CARD_OVERRIDES_DIR
process.env.CARD_OVERRIDES_DIR = dir
t.after(async () => {
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
else process.env.CARD_OVERRIDES_DIR = previous
await rm(dir, { recursive: true, force: true })
})
await writeOverride(CARD.oracle_id, SOURCE)
const stored = await readOverride(CARD.oracle_id)
assert.equal(stored?.source, `${SOURCE}\n`)
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
const compiled = compileImplementation(CARD, stored!.source)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
await deleteOverride(CARD.oracle_id)
assert.equal(await readOverride(CARD.oracle_id), undefined)
})

View File

@@ -0,0 +1,38 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { findCardByName } from '../src/cards.js'
import { createMatch, getMatchView, joinMatch, leaveMatch, setDeck, startMatch } from '../src/game/rooms.js'
function deck(commanderName: string) {
const commander = findCardByName(commanderName)
const forest = findCardByName('Forest')
assert.ok(commander && forest)
return {
commander: commander.oracle_id,
cards: Array.from({ length: 99 }, () => forest.oracle_id),
}
}
test('lobby decks can be swapped and invalid decks are rejected', () => {
const first = deck("Atraxa, Praetors' Voice")
const second = deck('Kenrith, the Returned King')
const { matchId, token } = createMatch('Host', first, 2)
setDeck(matchId, token, second)
assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King')
assert.throws(() => setDeck(matchId, token, { ...second, cards: [] }), /100/)
assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King')
})
test('leaving a started game forfeits the seat instead of erroring', () => {
const host = createMatch('Host', deck("Atraxa, Praetors' Voice"), 2)
const guest = joinMatch(host.matchId, 'Guest', deck('Kenrith, the Returned King'))
startMatch(host.matchId, host.token)
leaveMatch(host.matchId, host.token)
const view = getMatchView(host.matchId, guest.token)
assert.equal(view.status, 'finished')
assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true)
})

View File

@@ -0,0 +1,117 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { cleanTranslation, TranslationError, translateCard } from '../src/effects/translate.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000002',
name: 'Test Spell',
layout: 'normal',
cmc: 2,
type_line: 'Sorcery',
colors: ['U'],
color_identity: ['U'],
keywords: [],
oracle_text: 'Draw two cards.',
}
interface RequestBody {
model: string
messages: Array<{ role: string; content: string }>
temperature: number
max_tokens: number
}
function fakeOpenRouter(content: string) {
let body: RequestBody | undefined
let headers: Record<string, string> | undefined
const fetchImpl = async (_input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
body = JSON.parse(String(init?.body)) as RequestBody
headers = init?.headers as Record<string, string>
return new Response(JSON.stringify({ choices: [{ message: { content } }] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return {
fetchImpl: fetchImpl as typeof fetch,
get body() {
assert.ok(body)
return body
},
get headers() {
assert.ok(headers)
return headers
},
}
}
test('translation asks for pseudocode only and validates the answer', async () => {
const fake = fakeOpenRouter('spell:\n draw(you, 2)')
const source = await translateCard(CARD, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, 'spell:\n draw(you, 2)')
assert.equal(fake.body.model, 'test/model')
assert.equal(fake.body.temperature, 0)
assert.equal(fake.body.max_tokens, 700)
assert.equal(fake.headers.Authorization, 'Bearer test-key')
assert.match(fake.body.messages[0].content, /pseudocode only/i)
assert.match(fake.body.messages[0].content, /Never invent an operation/)
assert.match(fake.body.messages[1].content, /Draw two cards\./)
})
test('a model code fence is removed before saving', async () => {
const fake = fakeOpenRouter('```\nspell:\n draw(you, 2)\n```')
const source = await translateCard(CARD, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, 'spell:\n draw(you, 2)')
assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)')
})
test('prose instead of pseudocode is rejected', async () => {
const fake = fakeOpenRouter('Here is the translated card. It draws two cards.')
await assert.rejects(
translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }),
(error: unknown) => error instanceof TranslationError && /valid pseudocode/.test(error.message),
)
})
test('missing API key is reported before any request', async () => {
let called = false
const fetchImpl = async () => {
called = true
return new Response('{}')
}
await assert.rejects(
translateCard(CARD, { apiKey: '', fetch: fetchImpl as typeof fetch }),
(error: unknown) => error instanceof TranslationError && error.status === 503,
)
assert.equal(called, false)
})
test('multi-face cards receive their face names in the prompt', async () => {
const faces: Card = {
...CARD,
layout: 'transform',
card_faces: [
{ name: 'Front', type_line: 'Creature', oracle_text: 'When this enters, draw a card.', colors: [] },
{ name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] },
],
}
const fake = fakeOpenRouter('## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
const source = await translateCard(faces, {
apiKey: 'test-key',
model: 'test/model',
fetch: fake.fetchImpl,
})
assert.equal(source, '## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
assert.match(fake.body.messages[1].content, /## Front/)
assert.match(fake.body.messages[1].content, /## Back/)
})

13
backend/tsconfig.json Normal file
View File

@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}