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

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',
})