This commit is contained in:
2026-11-04 17:10:22 +01:00
parent 9ec486274f
commit c742d0cfa8
40 changed files with 12394 additions and 9414 deletions

View File

@@ -0,0 +1,470 @@
// Safe JavaScript card source. A card implementation is a module-shaped
// expression that calls the builder API below:
//
// export default [
// triggered(when.enters(permanents.withType('creature')), () => {
// gainLife(you, 1)
// }),
// ]
//
// The source is tokenized, parsed and evaluated against that API only. It is
// never passed to eval or new Function, so a saved override cannot run code.
import { singularize } from './parse.js'
import type {
Ability,
Condition,
Cost,
Duration,
Effect,
KeywordAbility,
ManaSpec,
ObjectSelector,
PlayerRef,
SearchDestination,
StaticEffect,
Target,
TokenSpec,
TriggerEvent,
Value,
Zone,
} from './types.js'
export const PLAYER_REFS = new Set<PlayerRef>([
'you',
'opponent',
'each_opponent',
'each_player',
'target_player',
'that_player',
'its_controller',
'its_owner',
])
export const DURATIONS = new Set<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 const ZONES = new Set<Zone>(['battlefield', 'hand', 'graveyard', 'library', 'exile', 'stack', 'command'])
export const SEARCH_DESTINATIONS = new Set<SearchDestination>(['hand', 'battlefield', 'graveyard', 'top', 'bottom'])
export const COLOR_CODES: Record<string, string> = {
white: 'W',
blue: 'U',
black: 'B',
red: 'R',
green: 'G',
colorless: 'C',
}
export const CHOICES = new Set(['creature_type', 'color', 'card_name', 'player', 'opponent', 'number'])
export const RESTRICTION_RULES = new Set(['cant_attack', 'cant_block', 'doesnt_untap'])
export const REPLACEMENT_WHATS = new Set(['dies', 'leaves_battlefield', 'discard', 'draw'])
export const REPLACEMENT_RESULTS = new Set(['exile', 'return_to_hand', 'return_to_library', 'prevent'])
export const TRIGGER_PLAYERS = new Set(['you', 'opponent', 'each_player'])
export const VALUE_KINDS = new Set([
'number', 'x', 'count', 'source_power', 'source_toughness', 'cards_in_hand',
'max_cards_in_hand', 'max_opponent_count', 'total_mana_value', 'total_power',
'any_number', 'event_amount',
])
export const EFFECT_OPS = new Set([
'damage', 'draw', 'discard', 'mill', 'life', 'pump', 'set_pt', 'grant',
'put_counters', 'remove_counters', 'double_counters', 'proliferate', 'create_token', 'destroy',
'exile', 'sacrifice', 'counter', 'return_to_hand', 'return_to_battlefield',
'put_on_top', 'tap', 'untap', 'scry', 'surveil', 'search', 'shuffle',
'add_mana', 'fight', 'regenerate', 'energy', 'attach', 'restriction',
'keyword_action', 'prevent_damage', 'gain_control', 'emblem', 'transform',
'pay', 'conditional', 'modal', 'look_top', 'schedule', 'level_up',
'put_from_among', 'dig', 'damage_divided', 'exile_graveyards', 'hideaway',
'play_exiled', 'impulse', 'exile_instead_of_dying',
])
export const STATIC_OPS = new Set([
'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped',
'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement',
'cost_reduction', 'cost_increase', 'search_restriction',
'exile_instead_of_graveyard', 'token_multiplier', 'replacement_amount', 'prevent_damage', 'counter_multiplier', 'token_replacement',
])
export const COST_KINDS = new Set([
'mana', 'tap', 'untap', 'tap_other', 'energy', 'loyalty', 'pay_life',
'discard', 'sacrifice', 'sacrifice_self', 'exile_self', 'exile_from_graveyard',
'reveal', 'choice', 'return_to_hand', 'behold', 'waterbend', 'blight',
'choose', 'put_counter', 'remove_counters', 'forage', 'collect_evidence', 'mill',
])
export const CONDITION_KINDS = new Set([
'you_control', 'opponent_controls', 'your_turn', 'not_your_turn',
'source_tapped', 'source_untapped', 'source_attacking', 'life_at_least',
'life_at_most', 'life_above_starting', 'cards_in_graveyard', 'hand_empty',
'creature_died_this_turn', 'you_gained_life_this_turn', 'you_drew_cards_this_turn',
'spells_cast_last_turn', 'no_spells_last_turn', 'attacked_this_turn',
'you_attacked_this_turn', 'defending_player_controls', 'targets', 'was_kicked',
'cast', 'in_graveyard', 'on_battlefield', 'monarch', 'initiative',
'citys_blessing', 'suspended', 'bargained', 'was_creature',
'opponent_lost_life_this_turn', 'life_changed_this_turn', 'descended_this_turn',
'permanent_left_battlefield_this_turn', 'nonland_permanents_entered_this_turn',
'attacked_with_total_power', 'total_power', 'opponent_controls_more_lands',
'distinct_powers', 'graveyard_card_types', 'no_objects', 'cards_in_hand_at_most',
'not_their_turn', 'no_attackers', 'opponent_poison', 'tribute_not_paid',
'had_counters', 'mana_from_treasure', 'mana_spent', 'no_mana_spent',
'mana_symbol_spent', 'kicked_with', 'more_cards_than_each_opponent',
'first_combat_phase', 'not_token', 'cast_spell_this_turn', 'full_party',
'graveyard_count', 'creature_power_greater_than_base', 'if_you_do',
'if_you_dont', 'otherwise', 'you_control_commander', 'distinct_names',
'opponent_damaged_this_turn', 'attacked_with_creatures', 'library_at_most',
])
export const TRIGGER_KINDS = new Set([
'enters', 'dies', 'attacks', 'blocks', 'attacks_or_blocks', 'enters_or_attacks',
'enters_or_dies', 'leaves_battlefield', 'deals_damage', 'upkeep', 'end_step',
'begin_combat', 'main_phase', 'cast', 'becomes_level', 'draw', 'counter_placed',
'becomes_target', 'life',
])
export const ABILITY_KINDS = new Set([
'keyword', 'keywords', 'triggered', 'activated', 'static', 'spell',
'additional_cost', 'alternative_cost', 'overload', 'chapter', 'level_band',
'level_pt', 'unsupported',
])
export function expectKind(value: unknown, allowed: Set<string>, label: string, key = 'kind'): Record<string, unknown> {
if (!isRecord(value) || typeof value[key] !== 'string' || !allowed.has(value[key] as string)) {
throw new Error(`expected ${label}`)
}
return value
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
export function asRecord(value: unknown, label: string): Record<string, unknown> {
if (!isRecord(value)) throw new Error(`${label} must be an object`)
return value
}
export function asString(value: unknown, label: string): string {
if (typeof value !== 'string') throw new Error(`${label} must be a string`)
return value
}
export function asNumber(value: unknown, label: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be a number`)
return value
}
export function asBoolean(value: unknown, label: string): boolean {
if (typeof value !== 'boolean') throw new Error(`${label} must be true or false`)
return value
}
export function optionalString(value: unknown, label: string): string | undefined {
if (value === undefined || value === null) return undefined
return asString(value, label)
}
export function stringArray(value: unknown, label: string): string[] {
if (value === undefined || value === null) return []
if (!Array.isArray(value)) throw new Error(`${label} must be an array`)
return value.map(entry => asString(entry, label))
}
export function asPlayer(value: unknown): PlayerRef {
if (typeof value === 'string' && PLAYER_REFS.has(value as PlayerRef)) return value as PlayerRef
throw new Error(`expected a player, got ${String(value)}`)
}
export function asTriggerPlayer(value: unknown): 'you' | 'opponent' | 'each_player' {
if (typeof value === 'string' && TRIGGER_PLAYERS.has(value)) return value as 'you' | 'opponent' | 'each_player'
throw new Error(`expected you, opponent or eachPlayer, got ${String(value)}`)
}
export function asDuration(value: unknown, fallback: Duration = 'permanent'): Duration {
if (value === undefined || value === null) return fallback
if (typeof value === 'string' && DURATIONS.has(value as Duration)) return value as Duration
throw new Error(`unknown duration "${String(value)}"`)
}
export function asZone(value: unknown): Zone {
if (typeof value === 'string' && ZONES.has(value as Zone)) return value as Zone
throw new Error(`unknown zone "${String(value)}"`)
}
export function asSearchDestination(value: unknown): SearchDestination {
if (typeof value === 'string' && SEARCH_DESTINATIONS.has(value as SearchDestination)) {
return value as SearchDestination
}
throw new Error(`unknown destination "${String(value)}"`)
}
export function asValue(value: unknown): Value {
if (typeof value === 'number') return { kind: 'number', value }
if (isRecord(value) && typeof value.kind === 'string' && VALUE_KINDS.has(value.kind)) {
return value as unknown as Value
}
throw new Error('expected a value (number or value helper)')
}
export function asSelector(value: unknown): ObjectSelector {
if (value instanceof Selector) return { ...value.fields }
if (isRecord(value)) return { ...value } as ObjectSelector
throw new Error('expected a selector')
}
export function isTarget(value: unknown): value is Target {
return isRecord(value) && typeof value.kind === 'string' && [
'self', 'trigger_subject', 'previous_target', 'object', 'player',
'player_or_planeswalker', 'any', 'spell', 'ability', 'divided',
].includes(value.kind)
}
export function asTarget(value: unknown): Target {
if (isTarget(value)) return value
throw new Error('expected a target')
}
export function asEffects(value: unknown): Effect[] {
const resolved = typeof value === 'function' ? value() : value
if (!Array.isArray(resolved)) return [asEffect(resolved)]
return resolved.map(asEffect)
}
export function asEffect(value: unknown): Effect {
return expectKind(value, EFFECT_OPS, 'an effect', 'op') as unknown as Effect
}
export function asStaticEffects(value: unknown): StaticEffect[] {
const resolved = typeof value === 'function' ? value() : value
if (!Array.isArray(resolved)) return [asStaticEffect(resolved)]
return resolved.map(asStaticEffect)
}
export function asStaticEffect(value: unknown): StaticEffect {
return expectKind(value, STATIC_OPS, 'a static effect', 'op') as unknown as StaticEffect
}
export function asCosts(value: unknown): Cost[] {
if (!Array.isArray(value)) throw new Error('expected an array of costs')
return value.map(asCost)
}
export function asCost(value: unknown): Cost {
return expectKind(value, COST_KINDS, 'a cost') as unknown as Cost
}
export function asCondition(value: unknown): Condition {
return expectKind(value, CONDITION_KINDS, 'a condition') as unknown as Condition
}
export function asTrigger(value: unknown): TriggerEvent {
return expectKind(value, TRIGGER_KINDS, 'a trigger event') as unknown as TriggerEvent
}
export function asAbility(value: unknown): Ability {
return expectKind(value, ABILITY_KINDS, 'an ability') as unknown as Ability
}
export function asAbilityArray(value: unknown): Ability[] {
if (!Array.isArray(value)) throw new Error('the implementation must be an array of abilities')
return value.map(asAbility)
}
export function asOptions(value: unknown): Record<string, unknown> {
if (value === undefined || value === null) return Object.create(null) as Record<string, unknown>
return asRecord(value, 'options')
}
// ---------------------------------------------------------------------------
// Selectors
// ---------------------------------------------------------------------------
export class Selector {
readonly fields: ObjectSelector
constructor(fields: ObjectSelector = {}) {
this.fields = fields
}
private with(patch: Partial<ObjectSelector>): Selector {
return new Selector({ ...this.fields, ...patch })
}
withType(...types: unknown[]): Selector {
return this.with({
types: [...(this.fields.types ?? []), ...types.map(type => singularize(asString(type, 'type').toLowerCase()))],
})
}
withSupertype(...supertypes: unknown[]): Selector {
return this.with({
supertypes: [
...(this.fields.supertypes ?? []),
...supertypes.map(type => singularize(asString(type, 'supertype').toLowerCase())),
],
})
}
withSubtype(...subtypes: unknown[]): Selector {
return this.with({
subtypes: [
...(this.fields.subtypes ?? []),
...subtypes.map(type => singularize(asString(type, 'subtype').toLowerCase())),
],
})
}
withColor(...colors: unknown[]): Selector {
return this.with({
colors: [
...(this.fields.colors ?? []),
...colors.map(color => {
const text = asString(color, 'color').toLowerCase()
return COLOR_CODES[text] ?? text.toUpperCase()
}),
],
})
}
withoutColor(...colors: unknown[]): Selector {
return this.with({
excludeColors: [
...(this.fields.excludeColors ?? []),
...colors.map(color => {
const text = asString(color, 'color').toLowerCase()
return COLOR_CODES[text] ?? text.toUpperCase()
}),
],
})
}
matchingAny(): Selector {
return this.with({ match: 'any' })
}
withoutType(...types: unknown[]): Selector {
return this.with({
excludeTypes: [
...(this.fields.excludeTypes ?? []),
...types.map(type => singularize(asString(type, 'type').toLowerCase())),
],
})
}
controlledBy(who: unknown): Selector {
if (who !== 'you' && who !== 'opponent' && who !== 'any') {
throw new Error('controlledBy() expects "you", "opponent" or "any"')
}
return this.with({ controller: who })
}
youControl(): Selector {
return this.with({ controller: 'you' })
}
opponentControls(): Selector {
return this.with({ controller: 'opponent' })
}
ownedBy(who: unknown): Selector {
if (who !== 'you' && who !== 'opponent') throw new Error('ownedBy() expects "you" or "opponent"')
return this.with({ owner: who })
}
other(): Selector {
return this.with({ other: true })
}
tapped(): Selector {
return this.with({ tapped: true })
}
untapped(): Selector {
return this.with({ tapped: false })
}
attacking(): Selector {
return this.with({ attacking: true })
}
token(): Selector {
return this.with({ token: true })
}
nontoken(): Selector {
return this.with({ token: false })
}
equipped(): Selector {
return this.with({ attached: 'equipped' })
}
enchanted(): Selector {
return this.with({ attached: 'enchanted' })
}
inZone(zone: unknown): Selector {
return this.with({ zone: asZone(zone) })
}
named(name: unknown): Selector {
return this.with({ name: asString(name, 'name') })
}
withCounter(counter: unknown, atLeast: unknown = 1): Selector {
return this.with({ counters: { counter: asString(counter, 'counter'), atLeast: asNumber(atLeast, 'counter count') } })
}
withKeyword(...keywords: unknown[]): Selector {
return this.with({
keywords: [...(this.fields.keywords ?? []), ...keywords.map(keyword => asString(keyword, 'keyword'))],
})
}
withoutKeyword(...keywords: unknown[]): Selector {
return this.with({
excludeKeywords: [
...(this.fields.excludeKeywords ?? []),
...keywords.map(keyword => asString(keyword, 'keyword')),
],
})
}
powerAtLeast(amount: unknown): Selector {
return this.with({ power: { ...(this.fields.power ?? {}), atLeast: asNumber(amount, 'power') } })
}
powerAtMost(amount: unknown): Selector {
return this.with({ power: { ...(this.fields.power ?? {}), atMost: asNumber(amount, 'power') } })
}
toughnessAtLeast(amount: unknown): Selector {
return this.with({ toughness: { ...(this.fields.toughness ?? {}), atLeast: asNumber(amount, 'toughness') } })
}
toughnessAtMost(amount: unknown): Selector {
return this.with({ toughness: { ...(this.fields.toughness ?? {}), atMost: asNumber(amount, 'toughness') } })
}
manaValueAtLeast(amount: unknown): Selector {
return this.with({ manaValue: { ...(this.fields.manaValue ?? {}), atLeast: asNumber(amount, 'mana value') } })
}
manaValueAtMost(amount: unknown): Selector {
return this.with({ manaValue: { ...(this.fields.manaValue ?? {}), atMost: asNumber(amount, 'mana value') } })
}
}
// ---------------------------------------------------------------------------
// Targets and values
// ---------------------------------------------------------------------------