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

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
}