commit 7dd9f4b14d129a8d7d179b09c52567609bf9ef39 Author: Aran Roig Date: Tue Oct 27 12:42:57 2026 +0100 First commit diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..47e8820 --- /dev/null +++ b/.env.example @@ -0,0 +1,17 @@ +# Public URL the browser uses to reach the API. +NUXT_PUBLIC_API_BASE=http://localhost:4000 + +# Browser origin(s) allowed to call the API, comma separated. +CORS_ORIGIN=http://localhost:3000 + +# MongoDB connection. Compose reaches a MongoDB running on the host machine by default. +# Set this only when using a different database. +# MONGODB_URI=mongodb://localhost:27017/commander + +# OpenRouter key and model for the card editor's "Draft with AI" button. +# Leave the key empty to disable the route (it returns 503). +OPENROUTER_API_KEY= +OPENROUTER_MODEL=google/gemini-2.5-flash-lite + +# Host port used by docker-compose.yml (production). +FRONTEND_PORT=3000 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c2b9e2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.env +.DS_Store +node_modules diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f38a3e0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,29 @@ +# AGENTS.md + +Online multiplayer Magic: The Gathering (Commander) emulator: Nuxt frontend + Fastify API with a synchronous rules engine that executes compiled card effects. + +## Layout + +- `backend/` — Node 24, Fastify 5, TypeScript (ESM, NodeNext). `src/effects/` is the oracle-text compiler/pseudocode DSL, `src/game/` the rules engine and in-memory match manager. +- `frontend/` — Nuxt 4 / Vue 3, sources under `app/`. +- `backend/docs/card-effects.md` and `backend/docs/game-engine.md` are the detailed references for those subsystems; `README.md` has the full API and config tables. + +## Commands + +```bash +docker compose -f docker-compose.dev.yml up --build # full dev stack (:3000, :4000) +cd backend && npm install && npm run dev # API only +cd frontend && npm install && npm run dev # UI only +cd backend && npm test # all backend tests +cd backend && npm run import:cards # Scryfall bulk data -> data/cards.json +cd backend && npm run compile:cards # oracle text -> data/card-effects.json + pseudo.txt +``` + +## Things to know + +- Backend imports need `.js` extensions (`NodeNext`) even though sources are `.ts`. +- `backend/data/cards.json` (~21 MB) and `card-effects.json` are generated, not committed; run the import/compile scripts after changing the importer or compiler. Missing card data makes `/cards` return `503`. +- Manual card implementations live in `backend/data/card-overrides/` (one file per card, pseudocode DSL) and take precedence over generated output when compiling. +- The effect compiler is conservative: unparseable oracle lines become `unsupported` with original text — never guess or silently drop them. +- Matches are in memory and lost on restart; accounts, saved decks, playmat preferences, and per-deck card backs are in MongoDB through `backend/src/accounts.ts`. Game seats still use a per-seat token in the frontend's `sessionStorage`; the account login token is in a cookie so the server can gate pages. +- Keep style of surrounding code: 2-space indent, single quotes. No linter or formatter is configured. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8eccd69 --- /dev/null +++ b/README.md @@ -0,0 +1,309 @@ +# Commander + +Online multiplayer Magic: The Gathering (Commander) emulator. + +This repository holds a Nuxt frontend, a Fastify API, and a working Magic rules +engine that executes the compiled card effects. You can build or import a +Commander deck in the browser and play a 2–4 player match against other clients. + +## Stack + +- **frontend/** — Nuxt 4, Vue 3, TypeScript, server-side rendering +- **backend/** — Node 24, Fastify 5, TypeScript, Mongoose +- **MongoDB** — accounts, saved decks, playmat and card-back preferences +- **Docker Compose** — hot-reloading development stack and standalone production images + +## Requirements + +- Docker with Compose v2 +- Node 24 + npm only if you want to run the apps outside Docker +- MongoDB reachable on `localhost:27017` (the Compose backend uses host + networking to reach it) + +## Development + +Start both services with hot reload: + +```bash +cp .env.example .env # optional: adjust public URLs and ports +docker compose -f docker-compose.dev.yml up --build +``` + +| Service | URL | +| -------- | ---------------------------- | +| Frontend | http://localhost:3000 | +| API | http://localhost:4000 | +| Health | http://localhost:4000/health | +| MongoDB | mongodb://localhost:27017 | + +Source directories are bind-mounted, so edits reload automatically. Dependencies +live in named volumes and are synced on container start. If the volumes get into +a bad state, reset them with: + +```bash +docker compose -f docker-compose.dev.yml down -v +``` + +Stop the stack with `docker compose -f docker-compose.dev.yml down`. + +### Without Docker + +```bash +# terminal 1 +cd backend && npm install && npm run dev + +# terminal 2 +cd frontend && npm install && npm run dev +``` + +The backend listens on port `4000` and the frontend on `3000` by default. It +connects to MongoDB at `mongodb://localhost:27017/commander`; start a local +MongoDB or set `MONGODB_URI` to point somewhere else. + +## Card data + +Cards come from Scryfall's +[Oracle Cards bulk export](https://scryfall.com/docs/api/bulk-data) — one card +per Oracle ID, filtered to cards legal in Commander. + +```bash +cd backend +npm run import:cards +``` + +This downloads the bulk file and writes `backend/data/cards.json` (about 21 MB, +not committed). It stores each card's rarity and the formats it is legal in, so +re-run it after pulling changes to the importer. Re-run it whenever you want a +fresh card pool. + +In the dev stack the file is visible through the bind mount. For production, run +the import before `docker compose build` so the API image includes the data. If +the file is missing, the card endpoints return `503` with a reminder to run it. + +Card art is not bundled. The first time a card's art is requested, the API +downloads its image from Scryfall and stores it in `backend/data/images/`. The +production Compose stack keeps that directory in the `card_images` named volume, +so the cache survives restarts. Delete the directory to reclaim the space; +images are downloaded again when needed. + +## Card effects + +Oracle text is compiled into a machine-readable effect AST for the game engine. +The compiler is conservative: a line it cannot parse is marked `unsupported` +with its original text, never guessed. + +```bash +cd backend +npm run compile:cards # data/card-effects.json + data/card-effects.pseudo.txt +npm test +``` + +`data/card-effects.pseudo.txt` is the human-readable pseudocode view. The +pseudocode is also an input format: the frontend editor saves one override file +per card under `backend/data/card-overrides/`, and `npm run compile:cards` +validates those files and uses them instead of generated output. See +[backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL, +current coverage, and how to add support for more cards. + +The `/cards` page has an **Editor** view and a **Guide** view that summarizes the +pseudocode syntax. **Draft with AI** sends the selected card's oracle text to an +OpenRouter model and loads the returned pseudocode into the editor without +saving it. The model is instructed to answer with pseudocode only — no +explanations, Markdown or code fences — and the answer must parse before the API +returns it. Set `OPENROUTER_API_KEY` on the backend to enable the button; +`OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. + +## Game engine + +`backend/src/game/` is a synchronous rules engine built on that AST. It covers +zones, turns, priority, the stack, mana and costs, triggered/activated/static +abilities, combat, state-based actions, and effect resolution. + +```ts +import { Game } from './src/game/game.js' +import { deckFromOracleIds } from './src/game/catalog.js' + +const game = new Game({ + seed: 1, + players: [ + { id: 'p1', deck: deckFromOracleIds(decklist1) }, + { id: 'p2', deck: deckFromOracleIds(decklist2) }, + ], +}) +game.start() +game.playLand('p1', cardId) +game.castSpell('p1', spellId, { targets: [{ kind: 'player', id: 'p2' }] }) +game.resolveStack() +``` + +Commander is a first-class format: the commander starts in the command zone, pays +`{2}` more for each previous cast from that zone, returns to the command zone +instead of the graveyard or exile, and loses the game at 21 combat damage from a +single commander. Deck construction checks 100 cards, singleton, color identity, +and a legendary-creature commander. + +See [backend/docs/game-engine.md](backend/docs/game-engine.md) for the action API, +turn and combat flow, supported mechanics, and known limitations. The engine tests +live in `backend/test/game.test.ts` and `backend/test/commander.test.ts`: + +```bash +cd backend +npx tsx --test test/game.test.ts test/commander.test.ts +``` + +## Playing online + +The frontend has five pages: + +- `/account` — create an account or sign in. The API stores only a username, a + salted password hash, and the player's saved data in MongoDB. +- `/` — create a 2–4 player game, join an open lobby, and pick your playmat. +- `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and + export it again. Decks are stored with your account. +- `/cards` — the existing card implementation editor and pseudocode guide. +- `/games/:id` — lobby and game board. The page can also be used as an invite + link; a player with no seat gets a join form. + +Matches live in the API process and are lost on restart. Each player only +receives their own hand and libraries as counts; the server sends personalized +state over server-sent events (SSE), and actions come back over `POST`. The +browser keeps the login token and a random per-seat game token in +`localStorage`/`sessionStorage`; accounts and saved decks, playmat choices, and +each deck's card back live in MongoDB. Each player can pick card art or upload +a JPEG as their own playmat; the choice is shown to everyone in the match and +remembered in the account for new games you host or join. Card backs are chosen +per deck in the deck editor and used for that deck's library pile. + +## Production + +Build and run the optimized images: + +```bash +cp .env.example .env # optional: adjust public URLs and ports +docker compose up -d --build +``` + +| Service | Default URL | +| -------- | ---------------------------- | +| Frontend | http://localhost:3000 | +| API | http://localhost:4000 | + +```bash +docker compose ps # status and health +docker compose logs -f # follow logs +docker compose down # stop +``` + +The production frontend image runs the built Nuxt output directly. The backend +image builds TypeScript and installs production dependencies only. + +## Configuration + +| Variable | Default | Used by | Description | +| ---------------------- | ----------------------- | ---------------- | ---------------------------------------------------- | +| `NUXT_PUBLIC_API_BASE` | `http://localhost:4000` | frontend | Public, browser-facing URL of the API | +| `CORS_ORIGIN` | `http://localhost:3000` | backend | Allowed browser origin(s), comma separated | +| `MONGODB_URI` | `mongodb://localhost:27017/commander` | backend | MongoDB connection string | +| `FRONTEND_PORT` | `3000` | production | Host port for the frontend | +| `BACKEND_PORT` | `4000` | production | Host port for the API | +| `PORT` | `4000` | backend | Port the API listens on inside the container | +| `CARD_OVERRIDES_DIR` | `backend/data/card-overrides` | backend | Where manual implementations are stored | +| `OPENROUTER_API_KEY` | — | backend | Enables the editor's AI pseudocode draft | +| `OPENROUTER_MODEL` | `google/gemini-2.5-flash-lite` | backend | OpenRouter model used for translation | + +When deploying to a real host, set `NUXT_PUBLIC_API_BASE` and `CORS_ORIGIN` to +your public URLs. Both values are applied at runtime in the production image. + +## Project layout + +```text +. +├── backend/ +│ ├── scripts/import-cards.ts # Scryfall bulk importer +│ ├── scripts/compile-cards.ts # oracle text -> effect AST + pseudocode +│ ├── src/cards.ts # card store, lookup, and search +│ ├── src/images.ts # on-disk cache for Scryfall card art +│ ├── src/effects/ # effect DSL, compiler, formatter, pseudocode parser +│ ├── src/effects/translate.ts # natural language -> pseudocode through OpenRouter +│ ├── src/game/ # rules engine, commander rules, match manager +│ ├── src/accounts.ts # Mongo models, auth, decks, and preferences +│ ├── src/server.ts # Fastify entry point and game/deck routes +│ ├── test/ # compiler, pseudocode, engine, and commander tests +│ ├── docs/card-effects.md # DSL reference and coverage +│ ├── docs/game-engine.md # engine API, rules coverage, limitations +│ ├── data/cards.json # generated by npm run import:cards +│ ├── data/card-overrides/ # human-authored implementations, one file per card +│ ├── Dockerfile # dev, build, and production stages +│ └── package.json +├── frontend/ +│ ├── app/app.vue # app shell and navigation +│ ├── app/assets/main.css # shared theme and layout +│ ├── app/pages/index.vue # create/join a game +│ ├── app/pages/account.vue # sign in, register, and sign out +│ ├── app/pages/decks.vue # deck builder and decklist import/export +│ ├── app/pages/games/[id].vue # lobby, board, and live match client +│ ├── app/pages/cards.vue # card implementation editor and guide +│ ├── app/middleware/auth.ts # redirect signed-out visitors to /account +│ ├── app/utils/auth.ts # login token storage and headers +│ ├── app/utils/decks.ts # account deck API and validation +│ ├── app/components/PseudoGuide.vue # pseudocode guide view +│ ├── nuxt.config.ts # runtime config (API base URL) +│ ├── Dockerfile # dev, build, and production stages +│ └── package.json +├── docker-compose.dev.yml # hot-reload development stack +├── docker-compose.yml # production stack +├── .env.example +└── README.md +``` + +## API + +`/auth/me` and every `/me/*` route require the +`Authorization: Bearer ` header returned by `/auth/register` or +`/auth/login`. + +| Method | Path | Response | +| ------ | --------------------- | ------------------------------------------------------- | +| `GET` | `/health` | `{ "status": "ok", "service": "commander-api" }` | +| `GET` | `/cards?q=atraxa` | `{ total, cards }` name search, `limit` capped at 200 | +| `GET` | `/cards/:oracleId` | One card object, or `404` | +| `GET` | `/cards/:oracleId/image` | Card face as JPEG; downloaded from Scryfall once and cached on disk | +| `GET` | `/cards/:oracleId/art` | Wide card art crop used for playmats, cached on disk | +| `GET` | `/cards?status=needs-work` | Filter by `supported`, `partial`, `unsupported`, `needs-work`, `manual`, `all` | +| `GET` | `/cards?format=modern&color=U&type=creature&rarity=rare&cmcMin=1&cmcMax=3` | Format legality, color identity (`WUBRG` includes that color, `C` colorless, `M` multicolor), card type, rarity, and mana value filters | +| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, pseudocode source, manual flag | +| `PUT` | `/cards/:oracleId/implementation` | Validate `{ "source": "..." }` and save the override | +| `DELETE` | `/cards/:oracleId/implementation` | Delete the override and restore generated output | +| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text | +| `GET` | `/cards/:oracleId/override` | Raw override source, or `404` | +| `GET` | `/stats` | Supported, partial, unsupported, and manual counts | +| `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` | +| `POST` | `/auth/login` | Sign in with `{ username, password }`, returns `{ token, username }` | +| `POST` | `/auth/logout` | Invalidate the current bearer token | +| `GET` | `/auth/me` | Current account, requires `Authorization: Bearer ` | +| `GET` | `/me/decks` | The account's saved decks | +| `PUT` | `/me/decks/:id` | Create or replace a saved deck | +| `DELETE` | `/me/decks/:id` | Delete a saved deck | +| `GET` | `/me/preferences` | Saved playmat and card back | +| `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` | +| `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` | +| `POST` | `/cards/resolve` | Resolve exact card names: `{ names: string[] }` | +| `GET` | `/games` | Open and active matches | +| `POST` | `/games` | Create a match from `{ name, deck, maxPlayers, playmat? }` | +| `POST` | `/games/:id/join` | Join a lobby with `{ name, deck, playmat? }` | +| `POST` | `/games/:id/leave` | Leave a lobby or forfeit an active game with `{ token }` | +| `POST` | `/games/:id/deck` | Change your lobby deck with `{ token, deck }` | +| `POST` | `/games/:id/start` | Host starts the match with `{ token }` | +| `POST` | `/games/:id/playmat` | Set your playmat with `{ token, playmat: { kind: "card", oracleId } \| { kind: "upload", data } \| { kind: "none" } }` | +| `GET` | `/playmats/:id` | Uploaded playmat image | +| `POST` | `/games/:id/actions` | Submit `{ token, action }` | +| `GET` | `/games/:id/state` | Personalized state, requires `?token=` | +| `GET` | `/games/:id/events` | Personalized SSE stream, requires `?token=` | + +## Next steps + +- More compiled effects and rules coverage (prevention, control changes, planeswalkers) +- WebSocket transport if SSE backpressure becomes a problem +- Persistence for live games and match history +- Matchmaking, spectators, and reconnect/afk handling +- Partner commanders, companion, and the rest of the Commander variants diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..bee1fdd --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,6 @@ +node_modules +dist +.env +Dockerfile +.dockerignore +data/images diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..0685ba7 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,9 @@ +node_modules +dist +.env +data/cards.json +data/card-effects.json +data/card-effects.pseudo.txt +data/images/ +data/playmats/ +data/*.tmp diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..9bdfa66 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,23 @@ +FROM node:24-alpine AS base +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci + +FROM base AS dev +COPY . . +EXPOSE 4000 +CMD ["npm", "run", "dev"] + +FROM base AS build +COPY . . +RUN npm run build + +FROM node:24-alpine AS production +WORKDIR /app +ENV NODE_ENV=production +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev +COPY --from=build /app/dist ./dist +COPY --from=build /app/data ./data +EXPOSE 4000 +CMD ["node", "dist/server.js"] diff --git a/backend/data/.gitkeep b/backend/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt b/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt new file mode 100644 index 0000000..df2a213 --- /dev/null +++ b/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt @@ -0,0 +1,4 @@ +# Miirym, Sentinel Wyrm [supported] +keywords Flying, Ward {2} +on enters(each other nontoken dragon you control): + create_token(you, 1, copy of the triggering object, not legendary) diff --git a/backend/docs/card-effects.md b/backend/docs/card-effects.md new file mode 100644 index 0000000..5a5efe2 --- /dev/null +++ b/backend/docs/card-effects.md @@ -0,0 +1,260 @@ +# Card effect compiler + +The card database from Scryfall is English prose. The game engine cannot execute +prose, so `backend/src/effects/` compiles every oracle-text line into a small +JSON AST. The AST is the canonical form for the engine. A pretty-printer renders +the same AST as readable pseudocode, and a matching parser reads that pseudocode +back, so a human can replace the generated implementation of a card without +touching JSON. + +This is deliberately **not** a rules engine. It answers "what does the card +say?" in machine-readable form. "What happens when it resolves?" belongs to the +engine that consumes these nodes. + +## Pipeline + +```text +Scryfall oracle text + -> normalize (card name, "this creature", contractions, reminder text) + -> classify (keyword / triggered / activated / static / spell effect) + -> parse targets, values, costs, conditions, durations + -> JSON AST + pseudocode rendering + +data/card-overrides/.pseudo.txt + -> pseudocode parser + -> JSON AST used instead of the generated one +``` + +Every line is parsed as a whole. If any part of a line is not understood, the +line becomes `{ "kind": "unsupported", "reason": ..., "text": ... }` instead of +a guessed effect. A wrong effect is worse than a missing one. + +## Commands + +From `backend/`: + +```bash +npm run compile:cards # writes data/card-effects.json and .pseudo.txt +npm test # compiler, pseudocode parser, and engine tests +npm run dev # API for the frontend editor +``` + +Current output over the imported Commander pool (32,116 cards): + +```text +Cards: 14,141 supported, 10,119 partial, 7,856 unsupported +Ability lines: 37,983/60,470 parsed (62.8%) +``` + +- **supported** — every ability line parsed. +- **partial** — at least one line parsed, at least one unsupported. +- **unsupported** — no line parsed. + +The unsupported lines are the work queue. Re-running the compiler after adding +patterns updates the numbers. + +## Output files + +| File | Contents | +| ---- | -------- | +| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card | +| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode | +| `data/card-overrides/.pseudo.txt` | Human-authored implementations, one file per card | + +The two generated files are git-ignored. Overrides are ordinary source files and +should be committed. + +## Pseudocode + +```text +# Soul Warden [supported] +on enters(each other creature): + gain_life(you, 1) + +# Llanowar Elves [supported] +activate {T}: + add_mana(you, {G}) + +# Krenko, Mob Boss [supported] +activate {T}: + create_token(you, count(creature goblin you control), 1/1 red goblin creature) +``` + +Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads +it back into the same AST the compiler produces. Blocks are indented two spaces. +A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a +new section for a multi-face card. Use `(no abilities)` when a face has none. + +## Manual implementations + +The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a +card, edit its pseudocode, and save. The editor toggles between the text view and a +node canvas where sockets are wired to define effect order and nested bodies; both +edit the same source. The API validates the source before writing it, so a typo +never replaces a working file. Overrides take precedence during +`npm run compile:cards`; invalid override files stop the compile with the line +number. + +| Method | Path | Purpose | +| ------ | ---- | ------- | +| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag | +| `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` | +| `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output | +| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text | +| `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent | +| `GET` | `/stats` | Supported, partial, unsupported, and manual counts | + +`CARD_OVERRIDES_DIR` changes the storage directory (useful for tests). + +### AI drafts + +The editor's **Draft with AI** button calls +`POST /cards/:oracleId/translate`. The backend sends the card's oracle text to +an [OpenRouter](https://openrouter.ai/) model and returns pseudocode, without +saving it. The response is parsed before it reaches the browser, so prose or a +non-parseable guess is reported as an error instead of replacing the editor. + +Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL` +defaults to `google/gemini-2.5-flash-lite`. + +The system prompt contains the syntax reference and a strict output contract: +pseudocode only, no explanations, Markdown, code fences or card header, and no +invented operations. Output is capped at 700 tokens. A fenced answer is +unwrapped defensively, but an invalid answer is not retried (that would spend +more tokens). The translator uses the default model only; there is no per-request +model picker. + + +## AST + +The types live in `src/effects/types.ts`. A card contains one or more abilities: + +```jsonc +{ + "oracle_id": "...", + "name": "Soul Warden", + "status": "supported", + "abilities": [ + { + "kind": "triggered", + "event": { + "kind": "enters", + "subject": { + "kind": "object", + "selector": { "other": true, "types": ["creature"] }, + "mode": "each" + } + }, + "effects": [ + { "op": "life", "player": "you", "amount": { "kind": "number", "value": 1 }, "mode": "gain" } + ], + "optional": false, + "text": "Whenever another creature enters, you gain 1 life." + } + ] +} +``` + +### Ability kinds + +| Kind | Meaning | Example | +| ---- | ------- | ------- | +| `keyword` | One parameterless or parameterized keyword | `Flying`, `Ward {2}`, `Crew 3` | +| `keywords` | Several keywords on one oracle line | `Flying, vigilance` | +| `triggered` | `When`/`Whenever`/`At` ability | `When this enters, draw a card.` | +| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` | +| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` | +| `spell` | Effect line of an instant or sorcery | `Draw two cards.` | +| `unsupported` | Preserved text plus a reason | `Choose one —` | + +### Effects + +| `op` | Payload | +| ---- | ------- | +| `damage` | `target`, `amount`, optional `source` | +| `draw`, `discard`, `mill` | `player`, `amount` | +| `life` | `player`, `amount`, `mode: gain \| lose` | +| `pump` | `target`, `power`, `toughness`, `duration` | +| `grant` | `target`, `keyword`, optional `value`, `duration` | +| `put_counters`, `remove_counters` | `target`, `counter`, `amount` | +| `create_token` | `player`, `amount`, `token` | +| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` | +| `sacrifice` | `player`, `target`, optional `unless` cost | +| `counter` | `what`, `target`, optional `unless` cost | +| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` | +| `search`, `shuffle` | player, selector, destination | +| `add_mana` | `player`, `mana` (`symbols` or `any_color`) | +| `scry`, `surveil` | `player`, `amount` | +| `fight` | two targets | +| `energy` | `player`, `amount` | +| `attach` | target to attach this/trigger object to | +| `restriction` | target, rule, duration | +| `keyword_action` | `action`, optional `amount`, `detail`, `target` | +| `proliferate` | no payload | + +### Targets, values, costs + +- **Targets** are `self`, `trigger_subject`, `any`, `player`, `spell`, `ability`, + or `object` with an `ObjectSelector` and mode `target` / `each` / `choose`. +- **Selectors** carry types, subtypes, controller, colors, zone, tapped/attacking + state, `other`, `attached: equipped|enchanted`, and `includeSelf`. +- **Values** are `number`, `x`, `count(selector)`, `source_power`, + `source_toughness`, `cards_in_hand`, or `event_amount`. +- **Costs** are mana symbols, tap/untap, tapping another permanent, energy, + loyalty, life, discard, sacrifice, self-exile, mill, and removing counters. +- **Conditions** cover controlling permanents, turn ownership, tapped source, + life totals, and graveyard size. +- **Durations** cover permanent, end of turn, your next turn, the end of your + next turn, end of combat, controller's next untap step, and while the source + remains. + +## How a line is parsed + +1. Reminder text in parentheses is removed. Card names and "this creature" / + "this permanent" become `this`. +2. Pure keyword lines are recognized from Scryfall's keyword list plus the + parameterized keyword table. +3. Trigger prefixes (`When this enters`, `Whenever this attacks`, `At the + beginning of your upkeep`, ...) become a `TriggerEvent`. +4. A colon splits an activated ability into costs and effects. +5. A leading duration (`Until end of turn, ...`) moves to the end of the + effect, where the duration parser expects it. +6. Otherwise a static effect is attempted. +7. Instant/sorcery lines fall back to a one-shot effect (`kind: "spell"`). +8. Anything left over is `unsupported`. + +Effects are split on sentences, `, then`, and `and` only when both sides parse. +`When you do, ...` becomes a reflexive `if you do` condition. `it` becomes the +trigger subject only when no explicit target/`that` appears in the same effect; +ambiguous pronouns stay unsupported. + +## Adding support + +For a single card, open the frontend editor, edit the pseudocode, and save; no +compiler change is needed. For a whole class of cards: + +1. Run `npm run compile:cards` and pick a frequent unsupported pattern. +2. Add a regex + AST builder in `src/effects/compile.ts` (or a target/value + parser in `src/effects/parse.ts`). +3. Add a focused test in `test/effects.test.ts`. +4. Run `npm test` and `npm run compile:cards`. + +Prefer narrow, anchored patterns. A broad pattern that misreads one card is a +game bug that is hard to find later. + +## Known gaps + +The remaining unsupported lines are mostly: + +- modal abilities (`Choose one —` and bullets) +- replacement effects (`If ... instead`, `As ... enters, ...`) +- continuous-effect layers and dependency rules +- copy, control-change, and type-change effects +- alternative/additional costs and cost modifiers +- level/class/saga structures and chapter abilities +- quoted token abilities and copying tokens +- complex pronoun/context resolution and "for each" scaling beyond simple counts +- dice, stickers, attractions, dungeons, and other supplemental mechanics + +None of these are blocked by the AST; each needs a parser pattern and an engine +implementation. diff --git a/backend/docs/game-engine.md b/backend/docs/game-engine.md new file mode 100644 index 0000000..a4978d7 --- /dev/null +++ b/backend/docs/game-engine.md @@ -0,0 +1,158 @@ +# Game engine + +`backend/src/game/` is a small but real Magic rules engine. It consumes the compiled +effect AST from `backend/src/effects/types.ts` directly — there is no second card +language. Card definitions are immutable input; a `GameObject` is the per-game +instance that moves between zones. + +## Quick start + +Run the data imports first (see the root README), then: + +```ts +import { Game } from './src/game/game.js' +import { deckFromOracleIds } from './src/game/catalog.js' + +const game = new Game({ + seed: 1, + startingLife: 40, + startingHandSize: 7, + commander: true, + players: [ + { id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 }, + { id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 }, + ], +}) +game.start() +``` + +`commander: true` creates each supplied commander in that player's command zone. The +`deck` should contain the other 99 cards; `validateCommanderDeck(commander, cards)` +in `commander.ts` checks size, singleton, color identity, and the commander type. + +`catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds +intrinsic mana abilities for basic lands, because Scryfall's oracle text only has +reminder text for them and the compiler produces no ability. + +For tests or hand-authored cards, build a `CardDefinition` yourself: + +```ts +const bolt: CardDefinition = { + oracleId: 'lightning-bolt', + name: 'Lightning Bolt', + typeLine: 'Instant', + manaCost: '{R}', + manaValue: 1, + abilities: [{ + kind: 'spell', + optional: false, + text: 'Lightning Bolt deals 3 damage to any target.', + effects: [{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }], + }], +} +``` + +## Actions + +| Method | Purpose | +| ------ | ------- | +| `start()` | Shuffles libraries, draws opening hands, begins turn 1. | +| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. | +| `castSpell(playerId, cardId, { targets, x, mode })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. | +| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. | +| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. | +| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. | +| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. | +| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. | +| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. | +| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. | +| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. | +| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. | +| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. | +| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. | +| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. | +| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. | + +Actions that use the stack move priority to the next living player. Non-instant, +non-flash spells can only be cast in the active player's main phase with an empty +stack. Targets may be supplied explicitly; if omitted, the first legal target is +chosen automatically, which keeps scripted games short. A search effect that matches +several cards pauses instead: other actions are refused until its controller calls +`chooseSearchCard` (the match API uses the `choose_search` action). + +## Turn structure + +```text +untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers + -> declare blockers -> combat damage -> end combat -> postcombat main + -> end step -> cleanup -> next player's turn +``` + +The starting player skips their first draw. Cleanup discards down to seven cards, +clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn` +effects, and empties mana pools. The engine advances phases when every living +player passes in turn; it does not stop at every rules-defined priority window. +The match manager calls `autoAdvance()` after each action, so priority is only +shown to players who can actually do something. + +## Supported + +- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens + cease to exist when they leave the battlefield. +- Commander: command-zone casting, `{2}` tax per previous cast from the command + zone, return to the command zone instead of graveyard/exile/hand/library, and a + loss at 21 combat damage from one commander. Deck construction is validated by + `validateCommanderDeck`. +- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana + abilities plus automatic tapping of untapped mana sources when paying. +- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile, + putting/removing counters, mill, energy, and choice costs. +- Abilities: spell effects, activated abilities, triggered abilities (enters, + leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static + effects, and basic replacement effects for entering tapped/with counters. +- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword, + counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability, + zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy, + attach, restrictions, conditional and modal effects, dig, and divided damage. +- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch, + lifelink, vigilance, haste, indestructible. Regeneration shields replace + destruction. +- State-based actions: life at or below zero, ten poison counters, 21 commander + damage from one commander, lethal or deathtouch damage, zero toughness, and + drawing from an empty library. + +## Known limitations + +- Some effect nodes are accepted but intentionally do nothing yet: + `prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`, + `put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`. + Unsupported oracle lines are already marked by the compiler and never reach here. +- Commander support covers single commanders. Partner, backgrounds, companions, + and "choose a commander" variants are not modelled. The engine always takes the + command-zone replacement instead of asking. +- The legend rule, planeswalker loyalty abilities, attacking planeswalkers, and + protection/menace/defender are not implemented unless expressed as a compiled + restriction. +- Modal spells choose a mode by index (`options.mode`); optional "you may" choices + are not modelled. An optional `pay` is simply not paid when unaffordable. Search + effects with several matching cards do pause for the player's pick. +- Opening hands are kept automatically; there is no mulligan flow. +- Replacement/prevention effects, layers, and dependency ordering are simplified. + Continuous effects apply in creation order rather than in full rules order. +- The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory + multiplayer matches, validates decks, and sends each player a personalized view + (own hand only, libraries as counts) over SSE. +- There is no persistence, account system, or reconnect grace period; a server + restart drops all matches. + +## Tests + +```bash +cd backend +npx tsx --test test/game.test.ts test/commander.test.ts +``` + +The tests cover turn flow, priority, spell resolution, triggers, mana and summoning +sickness, static and temporary pumps, combat, counterspells, tokens, searching, +entering tapped/with counters, decking, lethal damage, commander tax and damage, +decklist import, and multi-defender combat. diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..4c44dd8 --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,1809 @@ +{ + "name": "commander-backend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "commander-backend", + "version": "0.1.0", + "dependencies": { + "@fastify/cors": "^11.3.1", + "fastify": "^5.12.7", + "mongoose": "^9.11.4" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "tsx": "^4.23.15", + "typescript": "^7.0.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fastify/ajv-compiler": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.7.tgz", + "integrity": "sha512-VP0yIfwlc1ohj733keYDqyHm1VWeP9VQxYomunhr90jkC4aNNibbkrRiaNgPgqj1ORxUenILR4qzA/ppYBNAtQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0" + } + }, + "node_modules/@fastify/cors": { + "version": "11.3.1", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.3.1.tgz", + "integrity": "sha512-gZXNzd6FLHzOIfvoK4+Az3Wko2V6Y0MIsLxpyo4AEYl7a9q1JBPwPaxLea4nkr++8FCiJiPpYYo6E02uZW0dqw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^6.0.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/@fastify/deepmerge": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@fastify/deepmerge/-/deepmerge-3.2.4.tgz", + "integrity": "sha512-kc8GQq5gX9RRhw0rov3DMrN8wS8yRlxJRdDzsYwwdBV/wazuVgc/1K7CKL90tlvu3RlHan6Y0R0aE3nJtBz2eQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/error": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.1.tgz", + "integrity": "sha512-MYBumuIwP+5MIpXSyKm6/o1Eigcoij186lWUssX3LH5U8KWqU0ktZhzC4CErIX9EJeQeRGI+zJZQWakBlFbUcg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.1.1.tgz", + "integrity": "sha512-pyxRKk7UpUnnrztP9pF4+ZYxusEQ4LifTyzRdiXmyql1QezNHxO02D25MVU2o4kMeAMYWAjG6RKRlojgkbiDAw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^7.0.0" + } + }, + "node_modules/@fastify/forwarded": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.1.2.tgz", + "integrity": "sha512-89WiRG+hW3VQSfCwg4Hb8b43PeyEX15K5+lEfsZ4EUth/FyOjS/lv8HsVuswUNXWiSnxMGNouE/fq/0w3VumHQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.2.tgz", + "integrity": "sha512-d/gx9sRbUCVgGRGzma46wLcwiY8noTqO2Nmjg/vbTARxHRE5bdh5PIL8s97Lt1X7ScRWRW52eVYxwIoPwIdVUA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@fastify/proxy-addr": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.2.tgz", + "integrity": "sha512-uqB4QsgVoro0XDC+DIftIMGXHdBPn+lK6Ek3xXAIxPMCJfqxnbtyEoMCm2KPUVOuIosd7Cyw9HawEqMFM/UA+g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.1.tgz", + "integrity": "sha512-D4CQtk9IwjCLAvCf1xvHEod3960q8XMUzfmdRU9qjUNlHnesGuTOvJcOTaPm9koZ1caUKA2aTbszZiAkcmSgmg==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/abstract-logging": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", + "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", + "license": "MIT" + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv/node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/avvio": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.3.1.tgz", + "integrity": "sha512-QyTKW61/qlba+cUQBm/sT9X8lri4UdomqSDwCnrnj1IvLVDRRiXRkz4CgBRWB+/cmfC7SK5WQc8T1vSdGvaUcQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastq": "^1.17.1" + } + }, + "node_modules/bson": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.3.tgz", + "integrity": "sha512-oz3LwE3qGEhTCSyhzQRLY3Bj1NLOsjFMf6tcmY5J8M+3R7EVcmoBfSHWvjUK3yXCLDUsGpIuB3aQL4nDZ1EV/g==", + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/cookie": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz", + "integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.1.3.tgz", + "integrity": "sha512-5TDM1yOF/BDFOclKz2G6rs1RsIl5HXMCrg/npmdNIPNQCezshR5kIHjhwBNuMY67jhkTUAm9DguL8xkL/x0Wtw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.2.0", + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0", + "json-schema-ref-resolver": "^3.0.0", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, + "node_modules/fast-uri": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.3.tgz", + "integrity": "sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastify": { + "version": "5.12.7", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.7.tgz", + "integrity": "sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^4.0.5", + "@fastify/error": "^4.0.0", + "@fastify/fast-json-stringify-compiler": "^5.0.0", + "@fastify/proxy-addr": "^5.0.0", + "abstract-logging": "^2.0.1", + "avvio": "^9.0.0", + "fast-json-stringify": "^7.0.0", + "find-my-way": "^9.6.0", + "light-my-request": "^6.0.0", + "pino": "^9.14.0 || ^10.1.0", + "process-warning": "^5.1.0", + "rfdc": "^1.3.1", + "secure-json-parse": "^4.0.0", + "semver": "^7.6.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/fastify-plugin": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.1.tgz", + "integrity": "sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/find-my-way": { + "version": "9.10.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.10.0.tgz", + "integrity": "sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/ipaddr.js": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/json-schema-ref-resolver": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.1.tgz", + "integrity": "sha512-w+HwgljXpVwZ3IidoUR1qPZxSOQ+NRQWuVe6a5pe8XbHsNZE4UAwVPUvzZagn7yBKbJtt6UJnRFYbNTRPZI45Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/kareem": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-3.4.1.tgz", + "integrity": "sha512-UlgCAFNAdk/HLSsbfkmbH8pJqpEN52Ek8RG53Ys1i3Q3gbCQruSrWpplZlgIGyDHX/LNoLW97ei3OG43s7UhUA==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/light-my-request": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.8.0.tgz", + "integrity": "sha512-5Q8PjoSEdtGIB8fikZsTem5vgRo4F2mR6vUKTDW/H1g6MtAt8e3duQbg/QxL5yzg6BZhor2KOUm3hhWMWLTZwg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "dependencies": { + "@fastify/deepmerge": "^3.1.0", + "cookie": "^2.0.0", + "process-warning": "^5.0.0", + "set-cookie-parser": "^3.0.1" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, + "node_modules/mongodb": { + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.7.0.tgz", + "integrity": "sha512-XG1xXEqyouAV8GCb3PuRaujofeXKpAJAPvXYWZgHl6Dz4QHSJ1nRLl0+GpqaLTwKvC0RFE9truOur34RNFY1nw==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.5.0", + "bson": "^7.3.2", + "mongodb-connection-string-url": "^7.0.2" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": "^7.2.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.2.tgz", + "integrity": "sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/mongoose": { + "version": "9.11.4", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-9.11.4.tgz", + "integrity": "sha512-+xME0fduXl1sWF+NZpJHZaNcwQSt+X2vbJ/h7GRSZ/ltLycAkGZSEABhzic0+q3IMF66KqF0viEE5+frchKCAQ==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "kareem": "3.4.1", + "mongodb": "~7.7", + "mpath": "0.9.0", + "mquery": "6.0.1", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-6.0.1.tgz", + "integrity": "sha512-/Nijmq3JcpHwDM+5CwBp5yEl6fUa6jLsIhPsoQywlGXU/ZrKIvSpBzfaGnW9BLqcne/CoUwd1ch7MRqptDgFTA==", + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/pino": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.4.0.tgz", + "integrity": "sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^1.0.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "license": "MIT" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ret": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.1.tgz", + "integrity": "sha512-Z/nyvABwcRnRD2mMP7Kz6G1dFZZqX1mNErOnxF42OCQKE07b9k9hK9SQxHL3LFEZUdzQaLM4dId1E/E6Vm4WhA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/safe-regex2": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.2.tgz", + "integrity": "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/secure-json-parse": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.1.tgz", + "integrity": "sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-cookie-parser": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.2.1.tgz", + "integrity": "sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ==", + "license": "MIT" + }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/thread-stream": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", + "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==", + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/toad-cache": { + "version": "3.7.4", + "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz", + "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..3ec4c32 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,24 @@ +{ + "name": "commander-backend", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "tsx watch src/server.ts", + "build": "tsc", + "start": "node dist/server.js", + "import:cards": "tsx scripts/import-cards.ts", + "compile:cards": "tsx scripts/compile-cards.ts", + "test": "tsx --test test/*.test.ts" + }, + "dependencies": { + "@fastify/cors": "^11.3.1", + "fastify": "^5.12.7", + "mongoose": "^9.11.4" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "tsx": "^4.23.15", + "typescript": "^7.0.2" + } +} diff --git a/backend/scripts/compile-cards.ts b/backend/scripts/compile-cards.ts new file mode 100644 index 0000000..769574f --- /dev/null +++ b/backend/scripts/compile-cards.ts @@ -0,0 +1,103 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { Card } from '../src/cards.js' +import { compileCard } from '../src/effects/compile.js' +import { formatCard } from '../src/effects/format.js' +import { compileImplementation, readAllOverrides } from '../src/effects/implementations.js' +import { PseudoParseError } from '../src/effects/pseudo.js' +import type { Ability, CompiledCard } from '../src/effects/types.js' + +const DATA_DIR = join(process.cwd(), 'data') +const CARDS_FILE = join(DATA_DIR, 'cards.json') +const AST_FILE = join(DATA_DIR, 'card-effects.json') +const PSEUDO_FILE = join(DATA_DIR, 'card-effects.pseudo.txt') + +function formatBytes(bytes: number): string { + return `${(bytes / 1024 / 1024).toFixed(1)} MB` +} + +let cards: Card[] +try { + cards = JSON.parse(await readFile(CARDS_FILE, 'utf8')) as Card[] +} catch { + console.error(`Card data not found at ${CARDS_FILE}. Run "npm run import:cards" first.`) + process.exit(1) +} + +const overrides = await readAllOverrides() +const cardsById = new Map(cards.map(card => [card.oracle_id, card])) +for (const oracleId of overrides.keys()) { + if (!cardsById.has(oracleId)) { + console.warn(`Ignoring override for unknown oracle id: ${oracleId}`) + } +} + +const compiled: CompiledCard[] = [] +const cardCounts = { supported: 0, partial: 0, unsupported: 0 } +const reasons = new Map() +const samples: string[] = [] +let abilityCount = 0 +let manualCount = 0 +let parsedCount = 0 + +function abilitiesOf(card: CompiledCard): Ability[] { + return card.faces ? card.faces.flatMap(face => face.abilities) : card.abilities +} + +function sourceLines(ability: Ability): number { + if (ability.kind === 'keyword' || ability.kind === 'keywords') return 1 + return ability.text.split('\n').length +} + +for (const card of cards) { + const source = overrides.get(card.oracle_id) + let result: CompiledCard + try { + result = source === undefined ? compileCard(card) : compileImplementation(card, source) + } catch (error) { + if (error instanceof PseudoParseError) { + console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`) + console.error(` ${error.message}`) + process.exit(1) + } + throw error + } + if (result.manual) manualCount++ + compiled.push(result) + cardCounts[result.status]++ + + for (const ability of abilitiesOf(result)) { + const lines = sourceLines(ability) + abilityCount += lines + if (ability.kind === 'unsupported') { + reasons.set(ability.reason, (reasons.get(ability.reason) ?? 0) + lines) + if (samples.length < 10 && ability.reason === 'unmatched line') samples.push(ability.text) + } else { + parsedCount += lines + } + } +} + +await mkdir(DATA_DIR, { recursive: true }) +const astOutput = JSON.stringify(compiled) +const pseudoOutput = compiled.map(formatCard).join('\n\n') +await writeFile(AST_FILE, astOutput) +await writeFile(PSEUDO_FILE, pseudoOutput) + +console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`) +console.log( + `Cards: ${cardCounts.supported} supported, ${cardCounts.partial} partial, ${cardCounts.unsupported} unsupported.`, +) +console.log( + `Ability lines: ${parsedCount}/${abilityCount} parsed (${((100 * parsedCount) / abilityCount).toFixed(1)}%).`, +) +console.log('Unsupported reasons:') +for (const [reason, count] of [...reasons.entries()].sort((a, b) => b[1] - a[1])) { + console.log(` ${reason}: ${count}`) +} +if (samples.length) { + console.log('Sample unsupported lines:') + for (const sample of samples) console.log(` - ${sample}`) +} +console.log(`Wrote ${formatBytes(Buffer.byteLength(astOutput))} to ${AST_FILE}`) +console.log(`Wrote ${formatBytes(Buffer.byteLength(pseudoOutput))} to ${PSEUDO_FILE}`) diff --git a/backend/scripts/import-cards.ts b/backend/scripts/import-cards.ts new file mode 100644 index 0000000..13141aa --- /dev/null +++ b/backend/scripts/import-cards.ts @@ -0,0 +1,166 @@ +import { mkdir, rename, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { createInterface } from 'node:readline' +import { Readable } from 'node:stream' +import { createGunzip } from 'node:zlib' +import type { Card, CardFace } from '../src/cards.js' + +const BULK_API = 'https://api.scryfall.com/bulk-data' +const OUT_FILE = join(process.cwd(), 'data', 'cards.json') +const HEADERS = { + 'User-Agent': 'commander-import/0.1', + Accept: 'application/json', +} + +interface BulkData { + type: string + name: string + updated_at: string + compressed_size: number + jsonl_download_uri?: string +} + +interface RawFace { + name: string + mana_cost?: string + type_line?: string + oracle_text?: string + colors?: string[] + power?: string + toughness?: string + loyalty?: string + defense?: string + image_uris?: { normal?: string } +} + +interface RawCard { + oracle_id: string + name: string + layout?: string + mana_cost?: string + cmc?: number + type_line?: string + oracle_text?: string + colors?: string[] + color_identity?: string[] + keywords?: string[] + rarity?: string + power?: string + toughness?: string + loyalty?: string + defense?: string + image_uris?: { normal?: string } + card_faces?: RawFace[] + legalities?: Record +} + +function toFace(face: RawFace): CardFace { + return { + name: face.name, + mana_cost: face.mana_cost, + type_line: face.type_line, + oracle_text: face.oracle_text, + colors: face.colors ?? [], + power: face.power, + toughness: face.toughness, + loyalty: face.loyalty, + defense: face.defense, + image_uri: face.image_uris?.normal, + } +} + +function toCard(raw: RawCard): Card { + return { + oracle_id: raw.oracle_id, + name: raw.name, + layout: raw.layout ?? 'normal', + cmc: raw.cmc ?? 0, + type_line: raw.type_line ?? '', + colors: raw.colors ?? [], + color_identity: raw.color_identity ?? [], + keywords: raw.keywords ?? [], + rarity: raw.rarity, + legal_formats: Object.entries(raw.legalities ?? {}) + .filter(([, status]) => status === 'legal' || status === 'restricted') + .map(([format]) => format), + mana_cost: raw.mana_cost, + oracle_text: raw.oracle_text, + power: raw.power, + toughness: raw.toughness, + loyalty: raw.loyalty, + defense: raw.defense, + image_uri: raw.image_uris?.normal ?? raw.card_faces?.[0]?.image_uris?.normal, + card_faces: raw.card_faces?.map(toFace), + } +} + +function formatBytes(bytes: number): string { + return `${(bytes / 1024 / 1024).toFixed(1)} MB` +} + +const metaResponse = await fetch(BULK_API, { headers: HEADERS }) +if (!metaResponse.ok) { + throw new Error(`Scryfall bulk-data request failed: ${metaResponse.status}`) +} + +const meta = (await metaResponse.json()) as { data: BulkData[] } +const bulk = meta.data.find(entry => entry.type === 'oracle_cards') +if (!bulk?.jsonl_download_uri) { + throw new Error('Scryfall oracle_cards bulk export not found') +} + +console.log( + `Downloading ${bulk.name} (${formatBytes(bulk.compressed_size)}, updated ${bulk.updated_at})...`, +) + +const response = await fetch(bulk.jsonl_download_uri, { headers: HEADERS }) +if (!response.ok || !response.body) { + throw new Error(`Scryfall card download failed: ${response.status}`) +} + +const body = response.body as Parameters[0] +const lines = createInterface({ + input: Readable.fromWeb(body).pipe(createGunzip()), + crlfDelay: Infinity, +}) + +const cards: Card[] = [] +const seen = new Set() +let skipped = 0 + +for await (const line of lines) { + if (!line.trim()) continue + + const raw = JSON.parse(line) as RawCard + if (!raw.oracle_id || !raw.name) { + throw new Error(`Scryfall card is missing oracle_id or name: ${line.slice(0, 120)}`) + } + if (seen.has(raw.oracle_id)) { + throw new Error(`Duplicate oracle_id in Scryfall export: ${raw.oracle_id}`) + } + seen.add(raw.oracle_id) + + if (raw.legalities?.commander !== 'legal') { + skipped++ + continue + } + + cards.push(toCard(raw)) +} + +if (cards.length < 15_000) { + throw new Error(`Imported only ${cards.length} cards, expected at least 15000`) +} + +cards.sort((a, b) => a.name.localeCompare(b.name) || a.oracle_id.localeCompare(b.oracle_id)) + +const output = JSON.stringify(cards) +const tmpFile = `${OUT_FILE}.tmp` +await mkdir(dirname(OUT_FILE), { recursive: true }) +await writeFile(tmpFile, output) +await rename(tmpFile, OUT_FILE) + +console.log( + `Imported ${cards.length} Commander-legal cards (skipped ${skipped} other cards, ${seen.size} total).`, +) +console.log(`Wrote ${formatBytes(Buffer.byteLength(output))} to ${OUT_FILE}`) diff --git a/backend/src/accounts.ts b/backend/src/accounts.ts new file mode 100644 index 0000000..e10e689 --- /dev/null +++ b/backend/src/accounts.ts @@ -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 { + await mongoose.connect(uri) + await Promise.all([User.init(), Session.init(), Deck.init()]) +} + +export async function closeDatabase(): Promise { + 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 { + 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 { + 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 + 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 + 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 + 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) { + 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() + 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() + 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 }>( + '/me/preferences', + { bodyLimit: 6_500_000 }, + async (request, reply) => { + const user = await authenticate(request) + const body = request.body ?? {} + const update: Record = {} + + 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) + }, + ) +} diff --git a/backend/src/cards.ts b/backend/src/cards.ts new file mode 100644 index 0000000..732e59f --- /dev/null +++ b/backend/src/cards.ts @@ -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; byName: Map } | 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() + 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) } +} diff --git a/backend/src/effects/compile.ts b/backend/src/effects/compile.ts new file mode 100644 index 0000000..07469a8 --- /dev/null +++ b/backend/src/effects/compile.ts @@ -0,0 +1,2375 @@ +import type { Card, CardFace } from '../cards.js' +import { + parseCondition, + parseCost, + parseDuration, + parseNumber, + parseSelector, + parseTarget, + parseValue, +} from './parse.js' +import type { + Ability, + CompiledCard, + CompiledFace, + Condition, + Cost, + Effect, + KeywordAbility, + ManaSpec, + ObjectSelector, + StaticEffect, + Target, + TokenSpec, + TriggerEvent, + Value, +} from './types.js' + +type Status = 'supported' | 'partial' | 'unsupported' + +export const SIMPLE_KEYWORDS = new Map([ + ['flying', 'Flying'], + ['trample', 'Trample'], + ['vigilance', 'Vigilance'], + ['haste', 'Haste'], + ['flash', 'Flash'], + ['reach', 'Reach'], + ['menace', 'Menace'], + ['lifelink', 'Lifelink'], + ['deathtouch', 'Deathtouch'], + ['first strike', 'First strike'], + ['double strike', 'Double strike'], + ['defender', 'Defender'], + ['indestructible', 'Indestructible'], + ['hexproof', 'Hexproof'], + ['prowess', 'Prowess'], + ['convoke', 'Convoke'], + ['delve', 'Delve'], + ['shroud', 'Shroud'], + ['shadow', 'Shadow'], + ['horsemanship', 'Horsemanship'], + ['fear', 'Fear'], + ['intimidate', 'Intimidate'], + ['skulk', 'Skulk'], + ['wither', 'Wither'], + ['infect', 'Infect'], + ['persist', 'Persist'], + ['undying', 'Undying'], + ['exalted', 'Exalted'], + ['evolve', 'Evolve'], + ['exploit', 'Exploit'], + ['riot', 'Riot'], + ['cascade', 'Cascade'], + ['banding', 'Banding'], + ['flanking', 'Flanking'], + ['storm', 'Storm'], + ['sunburst', 'Sunburst'], + ['haunt', 'Haunt'], + ['living weapon', 'Living weapon'], + ['battle cry', 'Battle cry'], + ['dethrone', 'Dethrone'], + ['melee', 'Melee'], + ['mentor', 'Mentor'], + ['aftermath', 'Aftermath'], + ['ascend', 'Ascend'], + ['fuse', 'Fuse'], + ['jump-start', 'Jump-start'], + ['improvise', 'Improvise'], + ['undaunted', 'Undaunted'], + ['spectacle', 'Spectacle'], + ['escape', 'Escape'], + ['companion', 'Companion'], + ['daybound', 'Daybound'], + ['nightbound', 'Nightbound'], + ['training', 'Training'], + ['read ahead', 'Read ahead'], + ['casualty', 'Casualty'], + ['enlist', 'Enlist'], + ['bargain', 'Bargain'], + ['gift', 'Gift'], + ['disguise', 'Disguise'], + ['cloak', 'Cloak'], + ['saddle', 'Saddle'], + ['impending', 'Impending'], + ['harmonize', 'Harmonize'], + ['start your engines!', 'Start your engines!'], + ['devoid', 'Devoid'], + ['changeling', 'Changeling'], + ['phasing', 'Phasing'], + ['dredge', 'Dredge'], + ['bloodthirst', 'Bloodthirst'], + ['devour', 'Devour'], + ['graft', 'Graft'], + ['modular', 'Modular'], + ['bushido', 'Bushido'], + ['rampage', 'Rampage'], + ['absorb', 'Absorb'], + ['frenzy', 'Frenzy'], + ['tribute', 'Tribute'], + ['soulshift', 'Soulshift'], +]) + +const PARAMETERIZED_KEYWORDS: Array<[RegExp, string]> = [ + [/^ward\s+(.+)$/, 'Ward'], + [/^ward—(.+)$/, 'Ward'], + [/^equip\s+(.+)$/, 'Equip'], + [/^crew\s+(\d+)$/, 'Crew'], + [/^saddle\s+(\d+)$/, 'Saddle'], + [/^cycling\s+(.+)$/, 'Cycling'], + [/^typecycling\s+(.+)$/, 'Typecycling'], + [/^landcycling\s+(.+)$/, 'Landcycling'], + [/^basic landcycling\s+(.+)$/, 'Basic landcycling'], + [/^flashback(?:\s*[—-]\s*|\s+)(.+)$/, 'Flashback'], + [/^kicker(?:\s*[—-]\s*|\s+)(.+)$/, 'Kicker'], + [/^entwine\s+(.+)$/, 'Entwine'], + [/^fabricate\s+(\d+)$/, 'Fabricate'], + [/^madness\s+(.+)$/, 'Madness'], + [/^suspend\s+(\d+)\s*[—-]\s*(.+)$/, 'Suspend'], + [/^protection from (.+)$/, 'Protection'], + [/^enchant (.+)$/, 'Enchant'], + [/^annihilator\s+(\d+)$/, 'Annihilator'], + [/^afterlife\s+(\d+)$/, 'Afterlife'], + [/^afflict\s+(\d+)$/, 'Afflict'], + [/^amass\s+(.+)$/, 'Amass'], + [/^affinity for (.+)$/, 'Affinity'], + [/^bestow\s+(.+)$/, 'Bestow'], + [/^emerge\s+(.+)$/, 'Emerge'], + [/^mutate\s+(.+)$/, 'Mutate'], + [/^morph\s+(.+)$/, 'Morph'], + [/^megamorph\s+(.+)$/, 'Megamorph'], + [/^manifest\s+(.+)$/, 'Manifest'], + [/^disguise\s+(.+)$/, 'Disguise'], + [/^cloak\s+(.+)$/, 'Cloak'], + [/^escape(?:\s*[—-]\s*|\s+)(.+)$/, 'Escape'], + [/^evoke\s+(.+)$/, 'Evoke'], + [/^echo\s+(.+)$/, 'Echo'], + [/^cumulative upkeep(?:\s*[—-]\s*|\s+)(.+)$/, 'Cumulative upkeep'], + [/^fading\s+(\d+)$/, 'Fading'], + [/^vanishing\s+(\d+)$/, 'Vanishing'], + [/^modular\s+(\d+)$/, 'Modular'], + [/^bushido\s+(\d+)$/, 'Bushido'], + [/^rampage\s+(\d+)$/, 'Rampage'], + [/^absorb\s+(\d+)$/, 'Absorb'], + [/^frenzy\s+(\d+)$/, 'Frenzy'], + [/^tribute\s+(\d+)$/, 'Tribute'], + [/^bloodthirst\s+(\d+)$/, 'Bloodthirst'], + [/^devour\s+(\d+)$/, 'Devour'], + [/^graft\s+(\d+)$/, 'Graft'], + [/^soulshift\s+(\d+)$/, 'Soulshift'], + [/^dredge\s+(\d+)$/, 'Dredge'], + [/^toxic\s+(\d+)$/, 'Toxic'], + [/^backup\s+(\d+)$/, 'Backup'], + [/^firebending\s+(\d+)$/, 'Firebending'], + [/^renown\s+(\d+)$/, 'Renown'], + [/^teamwork\s+(\d+)$/, 'Teamwork'], + [/^squad\s+(\d+)$/, 'Squad'], + [/^mobilize\s+(\d+)$/, 'Mobilize'], + [/^casualty\s+(\d+)$/, 'Casualty'], + [/^level up\s+(.+)$/, 'Level up'], + [/^plot\s+(.+)$/, 'Plot'], + [/^unearth\s+(.+)$/, 'Unearth'], + [/^buyback\s+(.+)$/, 'Buyback'], + [/^foretell\s+(.+)$/, 'Foretell'], + [/^forecast(?:\s*[—-]\s*|\s+)(.+)$/, 'Forecast'], + [/^ninjutsu\s+(.+)$/, 'Ninjutsu'], + [/^dash\s+(.+)$/, 'Dash'], + [/^disturb\s+(.+)$/, 'Disturb'], + [/^warp\s+(.+)$/, 'Warp'], + [/^blitz\s+(.+)$/, 'Blitz'], + [/^encore\s+(.+)$/, 'Encore'], + [/^grandeur(?:\s*[—-]\s*|\s+)(.+)$/, 'Grandeur'], + [/^scavenge\s+(.+)$/, 'Scavenge'], + [/^fortify\s+(.+)$/, 'Fortify'], + [/^outlast\s+(.+)$/, 'Outlast'], + [/^embalm\s+(.+)$/, 'Embalm'], + [/^eternalize\s+(.+)$/, 'Eternalize'], + [/^transfigure\s+(.+)$/, 'Transfigure'], + [/^transmute\s+(.+)$/, 'Transmute'], + [/^reconfigure\s+(.+)$/, 'Reconfigure'], + [/^partner with (.+)$/, 'Partner'], + [/^partner[—-](.+)$/, 'Partner'], + [/^companion\s*[—-]\s*(.+)$/, 'Companion'], + [/^(.+?)walk$/, 'Landwalk'], +] + +const STANDALONE_ACTIONS = new Set([ + 'investigate', + 'proliferate', + 'populate', + 'learn', + 'take the initiative', + 'venture into the dungeon', + 'time travel', + 'open an attraction', + 'manifest dread', + 'the ring tempts you', + 'connive', + 'explore', +]) + +/** Removes reminder text. Oracle text only uses parentheses for reminders. */ +function stripReminders(text: string): string { + let result = text + let previous: string + do { + previous = result + result = result.replace(/\s*\([^()]*\)/g, '') + } while (result !== previous) + return result.replace(/\s+/g, ' ').trim() +} + +function normalize(text: string, cardName: string): string { + let result = stripReminders(text) + .replace(/\u2019/g, "'") + .replace(/\u2212/g, '-') + .replace(/\s+/g, ' ') + .trim() + + const names = [cardName] + const shortName = cardName.split(',')[0]?.trim() + if (shortName && shortName !== cardName) names.push(shortName) + + for (const name of names) { + if (!name) continue + const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + result = result.replace(new RegExp(`\\b${escaped}\\b`, 'gi'), 'this') + } + + result = result + .replace(/\bthis\s+[a-z]+'s\b/gi, 'its') + .replace(/\bthis (?:creature|permanent|artifact|enchantment|land|card|spell|token|vehicle|aura|planeswalker|battle|saga|equipment|class|treasure|food|clue|blood|map|gold|powerstone)\b/gi, 'this') + .replace(/\b~'s\b/g, 'its') + .replace(/~/g, 'this') + .replace(/\bit's\b/gi, 'it is') + .replace(/\bdoesn't\b/gi, 'does not') + .replace(/\bcan't\b/gi, 'cannot') + .replace(/\bwon't\b/gi, 'will not') + + return result.replace(/\s+/g, ' ').trim() +} + +function splitSentences(text: string): string[] { + return text + .split(/(?<=[.!?])\s+(?=\S)/) + .map(part => part.trim()) + .filter(Boolean) +} + +const LEADING_DURATION = /^(until end of turn|until your next turn|until the end of your next turn|until end of combat), /i + +/** "Until end of turn, X" is the same effect as "X until end of turn". */ +function takeLeadingDuration(text: string): { rest: string; duration?: string } { + const match = text.match(LEADING_DURATION) + if (!match) return { rest: text } + return { rest: text.slice(match[0].length), duration: match[1].toLowerCase() } +} + +/** Lowercase oracle text without destroying mana symbol casing ({W} -> {w}). */ +function lowerText(text: string): string { + return text + .toLowerCase() + .replace(/\{([^}]+)\}/g, (_, symbols: string) => `{${symbols.toUpperCase()}}`) +} + +function parseKeywordToken(part: string, known: Set): KeywordAbility | undefined { + const lower = part.trim().toLowerCase() + if (!lower) return undefined + + const knownKeyword = [...known].find(keyword => keyword.toLowerCase() === lower) + if (knownKeyword) return { kind: 'keyword', keyword: knownKeyword } + + const simple = SIMPLE_KEYWORDS.get(lower) + if (simple) return { kind: 'keyword', keyword: simple } + + for (const [pattern, keyword] of PARAMETERIZED_KEYWORDS) { + const match = lower.match(pattern) + if (match) return { kind: 'keyword', keyword, value: match[1] } + } + + return undefined +} + +function parseKeywordLine(text: string, known: Set): KeywordAbility[] | undefined { + const whole = parseKeywordToken(text, known) + if (whole) return [whole] + + const parts = text + .split(/,| and /) + .map(part => part.trim()) + .filter(Boolean) + if (!parts.length) return undefined + + const keywords: KeywordAbility[] = [] + for (const part of parts) { + const keyword = parseKeywordToken(part, known) + if (!keyword) return undefined + keywords.push(keyword) + } + return keywords +} + +function parseGroupTarget(text: string): Target | undefined { + const direct = parseTarget(text) + if (direct) { + if (direct.kind === 'object' && direct.mode === 'choose') return { ...direct, mode: 'each' } + return direct + } + + const selector = parseSelector(text) + if (selector) return { kind: 'object', selector, mode: 'each' } + return undefined +} + +function parseSubject(text: string): Target | undefined { + let subject = text.trim() + subject = subject.replace(/^one or more /, '') + if (subject === 'this') return { kind: 'self' } + + const orAnother = subject.match(/^this or another (.+)$/) + if (orAnother) { + const selector = parseSelector(`another ${orAnother[1]}`) + if (selector) return { kind: 'object', selector, mode: 'each', includeSelf: true } + } + + return parseGroupTarget(subject) +} + +function valueWithSign(text: string): Value | undefined { + const sign = text.startsWith('-') ? -1 : 1 + const raw = text.replace(/^[+-]/, '') + const value = parseValue(raw) + if (!value) return undefined + if (value.kind === 'number') return { kind: 'number', value: sign * value.value } + return value +} + +function forEachSelector(text: string): ObjectSelector | undefined { + return parseSelector(text.replace(/^each /, '')) +} + +function scaleEffect(effect: Effect, selector: ObjectSelector): Effect | undefined { + const count: Value = { kind: 'count', selector } + switch (effect.op) { + case 'damage': + if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined + return { ...effect, amount: count } + case 'draw': + case 'mill': + case 'life': + if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined + return { ...effect, amount: count } + case 'put_counters': + if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined + return { ...effect, amount: count } + case 'create_token': + if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined + return { ...effect, amount: count } + case 'pump': + if (effect.power.kind !== 'number' || effect.toughness.kind !== 'number') return undefined + if (![0, 1].includes(effect.power.value) || ![0, 1].includes(effect.toughness.value)) return undefined + if (effect.power.value === 0 && effect.toughness.value === 0) return undefined + return { + ...effect, + power: effect.power.value === 1 ? count : effect.power, + toughness: effect.toughness.value === 1 ? count : effect.toughness, + } + default: + return undefined + } +} + +function parseToken(text: string): TokenSpec | undefined { + let rest = text.trim().toLowerCase().replace(/\s+tokens?$/, '') + if (rest.startsWith('a ') || rest.startsWith('an ')) rest = rest.replace(/^an? /, '') + const tapped = rest.startsWith('tapped ') + if (tapped) rest = rest.slice(7) + return parseTokenBody(rest, tapped) +} + +function parseTokenBody(text: string, tapped: boolean): TokenSpec | undefined { + let rest = text.trim() + if (!rest) return undefined + if (/\b(copy|named|equal|number of|that's|thats)\b/.test(rest)) return undefined + + const colors: string[] = [] + for (const [word, code] of Object.entries({ white: 'W', blue: 'U', black: 'B', red: 'R', green: 'G' })) { + if (new RegExp(`\\b${word}\\b`).test(rest)) colors.push(code) + } + if (/\bcolorless\b/.test(rest)) colors.push('C') + + let power: Value | undefined + let toughness: Value | undefined + const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/) + if (pt) { + power = parseValue(pt[1]) + toughness = parseValue(pt[2]) + rest = rest.slice(pt[0].length).trim() + } + + const keywords: string[] = [] + const withMatch = rest.match(/\bwith (.+)$/) + if (withMatch) { + const parsed = parseKeywordLine(withMatch[1], new Set()) + if (!parsed) return undefined + for (const keyword of parsed) { + keywords.push(keyword.value ? `${keyword.keyword} ${keyword.value}` : keyword.keyword) + } + rest = rest.slice(0, withMatch.index).trim() + } + + const typeWords = new Set(['artifact', 'creature', 'enchantment', 'instant', 'land', 'planeswalker', 'sorcery', 'battle']) + const types: string[] = [] + const subtypes: string[] = [] + for (const word of rest.split(/[\s,]+/).filter(Boolean)) { + if (word === 'and' || word === 'or') continue + if (['white', 'blue', 'black', 'red', 'green', 'colorless', 'tapped'].includes(word)) continue + if (typeWords.has(word)) { + types.push(word) + continue + } + if (/^[a-z][a-z'-]*$/.test(word)) { + subtypes.push(word.length > 3 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word) + continue + } + return undefined + } + + if (!types.length) types.push('artifact') + if (!subtypes.length && !power) return undefined + + return { types, subtypes, colors, power, toughness, keywords: keywords.length ? keywords : undefined, tapped: tapped || undefined } +} + +function parseDigDestination(text: string): 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' { + if (text === 'into your hand') return 'hand' + if (text === 'into your graveyard') return 'graveyard' + if (text === 'onto the battlefield') return 'battlefield' + if (text === 'on top of your library') return 'top' + return 'bottom' +} + +function parseSearch(text: string): Effect | undefined { + const match = text.match(/^search your (library|library and\/or graveyard) for (.+)$/) + if (!match) return undefined + const zones: ('library' | 'graveyard')[] | undefined = + match[1] === 'library' ? undefined : ['library', 'graveyard'] + const body = match[2].trim() + + // Card names can contain commas, so try every comma as the selector/destination boundary. + for (let index = body.indexOf(', '); index !== -1; index = body.indexOf(', ', index + 1)) { + const selectorText = body.slice(0, index).trim() + const rest = body.slice(index + 2).trim() + + let amount: Value = { kind: 'number', value: 1 } + let nameText = selectorText + const upTo = nameText.match(/^up to (one|two|three|four|five|\d+) (.+)$/) + if (upTo) { + amount = parseValue(upTo[1]) ?? amount + nameText = upTo[2] + } else { + nameText = nameText.replace(/^an? /, '') + } + + const selector = parseSelector(nameText) + if (!selector) continue + + const revealPrefix = /^reveal (?:it|them|that card|those cards),? (?:and )?/ + let destinationText = rest.replace(revealPrefix, '') + let shuffle = false + if (/^then shuffle and put (?:it|them|that card|those cards) on top(?: of your library)?$/.test(destinationText)) { + return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) } + } + if (/^shuffle and put (?:it|them|that card|those cards) on top(?: of your library)?$/.test(destinationText)) { + return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) } + } + if (/^put (?:it|them|that card|those cards) on top of your library, then shuffle$/.test(destinationText)) { + return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) } + } + + const put = destinationText.match( + /^put (?:it|them|that card|those cards|the chosen card) (into your hand|onto the battlefield(?: tapped)?|into your graveyard|on top of your library|on the bottom of your library)(?: under your control)?(?:, then shuffle)?$/, + ) + if (!put) continue + + const destination = + put[1] === 'into your hand' + ? 'hand' + : put[1].startsWith('onto the battlefield') + ? 'battlefield' + : put[1] === 'into your graveyard' + ? 'graveyard' + : put[1] === 'on top of your library' + ? 'top' + : 'bottom' + shuffle = /then shuffle$/.test(destinationText) + const tapped = /\btapped\b/.test(put[1]) + return { op: 'search', player: 'you', selector, amount, destination, tapped, shuffle, ...(zones ? { zones } : {}) } + } + + return undefined +} + +function parseEffect(text: string): Effect | Effect[] | undefined { + const sentence = text.trim().replace(/\.$/, '') + + const search = parseSearch(sentence) + if (search) return search + + let match = sentence.match(/^(.+?) at the beginning of the next turn's upkeep$/) + if (match) { + const inner = parseEffect(match[1]) + if (inner) { + return { op: 'schedule', when: 'next_upkeep', effects: Array.isArray(inner) ? inner : [inner] } + } + } + + match = sentence.match(/^(.+?) at the beginning of the next end step$/) + if (match) { + const inner = parseEffect(match[1]) + if (inner) { + return { op: 'schedule', when: 'next_end_step', effects: Array.isArray(inner) ? inner : [inner] } + } + } + + match = sentence.match( + /^prevent (all|the next (\w+)) (combat )?damage(?: that would be dealt(?: to (.+?))?)?(?: this turn)?$/, + ) + if (match) { + const amount: Value | 'all' = match[1] === 'all' ? 'all' : (parseValue(match[2]) ?? 'all') + const target = match[4] ? parseTarget(match[4]) : undefined + if (match[1] === 'all' || amount !== 'all') { + if (!match[4] || target) { + return { + op: 'prevent_damage', + target: target ?? { kind: 'any' }, + amount, + combatOnly: Boolean(match[3]) || undefined, + duration: 'until_end_of_turn', + } + } + } + } + + match = sentence.match(/^(?:you )?gain control of (.+?)(?: (until end of turn|until your next turn|until the end of your next turn))?$/) + if (match) { + const target = parseGroupTarget(match[1]) + const duration = match[2] ? parseDuration(match[2]) : 'permanent' + if (target && duration) return { op: 'gain_control', target, duration } + } + + match = sentence.match(/^transform (this|this creature|the triggering object)$/) + if (match) { + const target: Target = match[1] === 'the triggering object' ? { kind: 'trigger_subject' } : { kind: 'self' } + return { op: 'transform', target } + } + + match = sentence.match(/^pay ((?:\{[^}]+\})+)$/) + if (match) { + const costs = parseCost(match[1]) + if (costs) return { op: 'pay', costs } + } + + match = sentence.match(/^look at the top (\w+) cards? of your library(?:, then put them back in any order)?$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) { + return { + op: 'look_top', + player: 'you', + amount, + reorder: /then put them back in any order$/.test(sentence) || undefined, + } + } + } + + match = sentence.match(/^this deals (?:(\w+) damage|damage equal to (its power|its toughness)) to (.+)$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : parseValue(match[2]) + const target = parseTarget(match[3]) + if (amount && target) return { op: 'damage', target, amount } + } + + match = sentence.match(/^(.+?) deals (?:(\w+) damage|damage equal to (its power|its toughness)) to (.+)$/) + if (match) { + const source = parseGroupTarget(match[1]) + const amount = match[2] ? parseValue(match[2]) : parseValue(match[3]) + const target = parseTarget(match[4]) + if (source && amount && target) return { op: 'damage', target, amount, source } + } + + match = sentence.match(/^you gain (?:(\w+) life|life equal to (.+))$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : parseValue(match[2]) + if (amount) return { op: 'life', player: 'you', amount, mode: 'gain' } + } + + match = sentence.match(/^gain (?:(\w+) life|life equal to (.+))$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : parseValue(match[2]) + if (amount) return { op: 'life', player: 'you', amount, mode: 'gain' } + } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) gains? (?:(\w+) life|life equal to (.+))$/) + if (match) { + const player = parseTarget(match[1]) + const amount = match[2] ? parseValue(match[2]) : parseValue(match[3]) + if (player?.kind === 'player' && amount) return { op: 'life', player: player.who, amount, mode: 'gain' } + } + + match = sentence.match(/^you lose (\w+) life$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) return { op: 'life', player: 'you', amount, mode: 'lose' } + } + + match = sentence.match(/^lose (\w+) life$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) return { op: 'life', player: 'you', amount, mode: 'lose' } + } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) loses (\w+) life$/) + if (match) { + const player = parseTarget(match[1]) + const amount = parseValue(match[2]) + if (player?.kind === 'player' && amount) return { op: 'life', player: player.who, amount, mode: 'lose' } + } + + match = sentence.match(/^(?:you )?draw (?:(\w+) cards?|cards equal to (.+))$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : parseValue(match[2]) + if (amount) return { op: 'draw', player: 'you', amount } + } + + match = sentence.match(/^(?:you )?draw (that many|that much) cards?$/) + if (match) return { op: 'draw', player: 'you', amount: { kind: 'event_amount' } } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) draws (?:(\w+) cards?|cards equal to (.+))$/) + if (match) { + const player = parseTarget(match[1]) + const amount = match[2] ? parseValue(match[2]) : parseValue(match[3]) + if (player?.kind === 'player' && amount) return { op: 'draw', player: player.who, amount } + } + + match = sentence.match(/^(?:you )?discard (?:(\w+) cards?|your hand)$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'cards_in_hand', player: 'you' } as Value) + if (amount) return { op: 'discard', player: 'you', amount } + } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) discards (?:(\w+) cards?|their hand)$/) + if (match) { + const player = parseTarget(match[1]) + const amount = match[2] ? parseValue(match[2]) : ({ kind: 'cards_in_hand', player: 'you' } as Value) + if (player?.kind === 'player' && amount) return { op: 'discard', player: player.who, amount } + } + + match = sentence.match(/^(?:you )?mill (?:(\w+|that many) cards?|a card)$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) + if (amount) return { op: 'mill', player: 'you', amount } + } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) mills (?:(\w+|that many) cards?|a card)$/) + if (match) { + const player = parseTarget(match[1]) + const amount = match[2] ? parseValue(match[2]) : ({ kind: 'number', value: 1 } as Value) + if (player?.kind === 'player' && amount) return { op: 'mill', player: player.who, amount } + } + + match = sentence.match( + /^put (?:up to )?(one|two|three|four|five|\d+|a|an)? ?(.+?) from among (?:them|those cards) (into your hand|into your graveyard|on top of your library|on the bottom of your library|onto the battlefield)$/, + ) + if (match) { + const amount = match[1] ? parseValue(match[1]) : undefined + const selector = parseSelector(match[2]) + if (amount && selector) { + return { + op: 'put_from_among', + player: 'you', + selector, + amount, + destination: parseDigDestination(match[3]), + } + } + } + + match = sentence.match( + /^put (one|two|three|four|five|\d+) of (?:them|those cards) (into your hand|into your graveyard|on top of your library|on the bottom of your library|onto the battlefield)$/, + ) + if (match) { + const amount = parseValue(match[1]) + if (amount) { + return { op: 'put_from_among', player: 'you', amount, destination: parseDigDestination(match[2]) } + } + } + + match = sentence.match(/^put (?:(\w+) )?(.+?) counters? on (.+)$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) + const target = parseGroupTarget(match[3]) + if (amount && target) return { op: 'put_counters', target, counter: match[2], amount } + } + + match = sentence.match(/^remove (?:(\w+) )?(.+?) counters? from (.+)$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) + const target = parseGroupTarget(match[3]) + if (amount && target) return { op: 'remove_counters', target, counter: match[2], amount } + } + + match = sentence.match(/^create (?:(\w+) )?(?:a |an )?tokens? that(?:'s| is) a copy of (.+)$/) + if (match) { + let targetText = match[2].trim() + const except = targetText.match(/, except (?:the token|it) (?:is not|isn't) legendary$/) + if (except) targetText = targetText.slice(0, except.index).trim() + const target = targetText === 'it' ? ({ kind: 'trigger_subject' } as Target) : parseTarget(targetText) + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) + if (amount && target) { + return { + op: 'create_token', + player: 'you', + amount, + token: { types: [], subtypes: [], colors: [] }, + copyOf: target, + ...(except ? { notLegendary: true } : {}), + } + } + } + + match = sentence.match(/^create (?:((?:that many)|\w+) )?(.+?) tokens?(?: (with .+))?$/) + if (match) { + const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) + const token = parseToken(`${match[2]}${match[3] ? ` ${match[3]}` : ''}`) + if (amount && token) return { op: 'create_token', player: 'you', amount, token } + } + + match = sentence.match(/^destroy (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'destroy', target } + } + + match = sentence.match(/^exile (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'exile', target } + } + + match = sentence.match(/^sacrifice (.+)$/) + if (match) { + const target = parseTarget(match[1]) + if (target) return { op: 'sacrifice', player: 'you', target } + } + + match = sentence.match(/^(target player|target opponent|that player|each player|each opponent) sacrifices? (.+)$/) + if (match) { + const player = parseTarget(match[1]) + const target = parseTarget(match[2]) + if (player?.kind === 'player' && target) return { op: 'sacrifice', player: player.who, target } + } + + match = sentence.match(/^counter target spell(?: unless its controller pays ((?:\{[^}]+\})+))?$/) + if (match) { + const costs = match[1] ? parseCost(match[1]) : undefined + return { + op: 'counter', + what: 'spell', + target: { kind: 'spell', selector: { types: [] }, mode: 'target' }, + unless: costs?.[0], + } + } + + match = sentence.match(/^counter target (.+?) spell(?: unless its controller pays ((?:\{[^}]+\})+))?$/) + if (match) { + const selector = parseSelector(match[1]) + const costs = match[2] ? parseCost(match[2]) : undefined + if (selector) { + return { + op: 'counter', + what: 'spell', + target: { kind: 'spell', selector, mode: 'target' }, + unless: costs?.[0], + } + } + } + + match = sentence.match(/^counter target (activated or triggered ability|ability)$/) + if (match) return { op: 'counter', what: 'ability', target: { kind: 'ability', mode: 'target' } } + + match = sentence.match(/^return (.+?) to (?:its|their) owner's hand$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'return_to_hand', target } + } + + match = sentence.match(/^return (.+?) from your graveyard to your hand$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'return_to_hand', target } + } + + match = sentence.match(/^return (.+?) to your hand$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'return_to_hand', target } + } + + match = sentence.match(/^return (this|this card) from your graveyard to the battlefield(.*)$/) + if (match) return parseEffect(`return ${match[1]} to the battlefield${match[2]}`) + + match = sentence.match(/^return (.+?) to the battlefield( tapped)?( and transformed| transformed)?(?: under (?:your|its owner's) control)?(?: with (an?|one|two|three|four|five|\d+) (?:additional )?(.+?) counters? on (?:it|this|this creature|this permanent|the triggering object))?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) { + const amount = match[4] ? parseValue(match[4]) : undefined + return { + op: 'return_to_battlefield', + target, + tapped: Boolean(match[2]), + transformed: Boolean(match[3]) || undefined, + counters: amount && match[5] ? { counter: match[5], amount } : undefined, + } + } + } + + match = sentence.match(/^put (.+?) onto the battlefield( tapped)?(?: under your control)?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) { + return { op: 'return_to_battlefield', target, tapped: Boolean(match[2]) } + } + } + + match = sentence.match(/^put (.+?) on top of (?:its|their) owner's library$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'put_on_top', target } + } + + match = sentence.match(/^put (.+?) into (?:its|their) owner's hand$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'return_to_hand', target } + } + + match = sentence.match(/^tap (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'tap', target } + } + + match = sentence.match(/^untap (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'untap', target } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+)(?: (until end of turn|until your next turn|until the end of your next turn|until end of combat))?$/) + if (match) { + const target = parseGroupTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + const duration = match[4] ? parseDuration(match[4]) : 'permanent' + if (target && target.kind !== 'player' && power && toughness && duration) { + return { op: 'pump', target, power, toughness, duration } + } + } + + match = sentence.match(/^(.+?) gains? (?:a |an )?(.+?) (until end of turn|until your next turn|until the end of your next turn|until end of combat)$/) + if (match) { + const target = parseGroupTarget(match[1]) + const keywords = parseKeywordLine(match[2], new Set()) + const duration = parseDuration(match[3]) + if (target && keywords?.length && duration) { + return keywords.map(keyword => ({ + op: 'grant' as const, + target, + keyword: keyword.keyword, + value: keyword.value, + duration, + })) + } + } + + match = sentence.match(/^(.+?) gains? (?:a |an )?(.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + const keywords = parseKeywordLine(match[2], new Set()) + if (target && keywords?.length) { + return keywords.map(keyword => ({ + op: 'grant' as const, + target, + keyword: keyword.keyword, + value: keyword.value, + duration: 'permanent' as const, + })) + } + } + + match = sentence.match(/^(.+?) has base power and toughness (\w+)\/(\w+)(?: (until end of turn|until your next turn|until the end of your next turn|until end of combat))?$/) + if (match) { + const target = parseGroupTarget(match[1]) + const power = parseValue(match[2]) + const toughness = parseValue(match[3]) + const duration = match[4] ? parseDuration(match[4]) : 'permanent' + if (target && power && toughness && duration) { + return { op: 'set_pt', target, power, toughness, duration } + } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) and gains? (?:a |an )?(.+?) (until end of turn|until your next turn|until the end of your next turn|until end of combat)$/) + if (match) { + const target = parseGroupTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + const keywords = parseKeywordLine(match[4], new Set()) + const duration = parseDuration(match[5]) + if (target && target.kind !== 'player' && power && toughness && keywords?.length && duration) { + return [ + { op: 'pump', target, power, toughness, duration }, + ...keywords.map(keyword => ({ + op: 'grant' as const, + target, + keyword: keyword.keyword, + value: keyword.value, + duration, + })), + ] + } + } + + match = sentence.match(/^(.+?) (?:can't|cannot) (attack|block)(?: this turn)?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) { + return { + op: 'restriction', + target, + rule: match[2] === 'attack' ? 'cant_attack' : 'cant_block', + duration: /this turn$/.test(sentence) ? 'until_end_of_turn' : 'permanent', + } + } + } + + match = sentence.match(/^add ((?:\{[^}]+\})(?:,? ?(?:or )?\{[^}]+\})*)$/) + if (match) { + const symbols = match[1].match(/\{[^}]+\}/g) + if (symbols) return { op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols } } + } + + match = sentence.match(/^add (one|two|three|four|five|x) mana of any (one )?color( in your commander's color identity)?$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) { + return { + op: 'add_mana', + player: 'you', + mana: { + kind: 'any_color', + amount, + oneColor: Boolean(match[2]), + restriction: match[3] ? "commander's color identity" : undefined, + }, + } + } + } + + match = sentence.match(/^(scry|surveil) (\w+)$/) + if (match) { + const amount = parseValue(match[2]) + if (amount) return { op: match[1] as 'scry' | 'surveil', player: 'you', amount } + } + + match = sentence.match(/^regenerate (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'regenerate', target } + } + + match = sentence.match(/^(.+?) fights (.+)$/) + if (match) { + const a = parseTarget(match[1]) + const b = parseTarget(match[2]) + if (a && b) return { op: 'fight', a, b } + } + + match = sentence.match(/^you get (that many \{e\}|(?:\{e\})+)$/i) + if (match) { + if (/^that many/i.test(match[1])) { + return { op: 'energy', player: 'you', amount: { kind: 'event_amount' } } + } + const amount = match[1].match(/\{e\}/gi)?.length ?? 0 + if (amount) return { op: 'energy', player: 'you', amount: { kind: 'number', value: amount } } + } + + match = sentence.match(/^attach (?:it|this|the triggering object) to (.+)$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'attach', target } + } + + match = sentence.match(/^(.+?) cannot attack or block( this turn)?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) { + return [ + { op: 'restriction', target, rule: 'cant_attack', duration: 'until_end_of_turn' }, + { op: 'restriction', target, rule: 'cant_block', duration: 'until_end_of_turn' }, + ] + } + } + + match = sentence.match(/^(.+?) cannot block( this turn)?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'restriction', target, rule: 'cant_block', duration: 'until_end_of_turn' } + } + + match = sentence.match(/^(.+?) cannot attack( this turn)?$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'restriction', target, rule: 'cant_attack', duration: 'until_end_of_turn' } + } + + match = sentence.match(/^(.+?) does not untap during its controller's next untap step$/) + if (match) { + const target = parseGroupTarget(match[1]) + if (target) return { op: 'restriction', target, rule: 'doesnt_untap', duration: 'until_controllers_next_untap_step' } + } + + match = sentence.match(/^sacrifice (.+?) unless (?:you|its controller) pays? (.+)$/) + if (match) { + const target = parseTarget(match[1]) + const unless = parseCost(match[2]) + if (target && unless?.[0]) return { op: 'sacrifice', player: 'you', target, unless: unless[0] } + } + + match = sentence.match(/^level (\d+)$/) + if (match) return { op: 'level_up', level: Number(match[1]) } + + match = sentence.match(/^(?:you )?(take the initiative|venture into the dungeon|become the monarch)$/) + if (match) return { op: 'keyword_action', action: match[1] } + + match = sentence.match(/^(?:the triggering object|this) (explores|connives)$/) + if (match) { + const target: Target = match[0].startsWith('the triggering object') + ? { kind: 'trigger_subject' } + : { kind: 'self' } + const action = match[1] === 'explores' ? 'explore' : 'connive' + return { op: 'keyword_action', action, target } + } + + match = sentence.match(/^incubate (\w+)$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) return { op: 'keyword_action', action: 'incubate', amount } + } + + match = sentence.match(/^amass (.+?) (\w+)$/) + if (match) { + const amount = parseValue(match[2]) + if (amount) return { op: 'keyword_action', action: 'amass', amount, detail: match[1] } + } + + match = sentence.match(/^(bolster|support|earthbend) (\w+)$/) + if (match) { + const amount = parseValue(match[2]) + if (amount) return { op: 'keyword_action', action: match[1], amount } + } + + if (STANDALONE_ACTIONS.has(sentence)) { + return { op: 'keyword_action', action: sentence } + } + + if (sentence === 'shuffle your library') return { op: 'shuffle', player: 'you' } + + return undefined +} + +function parseEffectSentence(text: string): Effect[] | undefined { + const emblem = text.trim().match(/^you get an emblem with "(.+)"$/i) + if (emblem) return [{ op: 'emblem', text: emblem[1] }] + + let sentence = lowerText(text).trim().replace(/\.$/, '') + sentence = sentence.replace(/^then /, '') + + const scaled = sentence.match(/^(.+?) for each (.+)$/) + if (scaled) { + const selector = forEachSelector(scaled[2]) + const base = parseEffect(scaled[1]) + if (selector && base && !Array.isArray(base)) { + const effect = scaleEffect(base, selector) + if (effect) return [effect] + } + return undefined + } + + const whereX = sentence.match(/^(.+?), where x is the number of (.+)$/) + if (whereX) { + const selector = parseSelector(whereX[2]) + const base = parseEffect(whereX[1]) + if (selector && base && !Array.isArray(base)) { + return [replaceX(base, { kind: 'count', selector })] + } + return undefined + } + + const direct = parseEffect(sentence) + if (direct) return Array.isArray(direct) ? direct : [direct] + + if (sentence.includes(' and ')) { const parts = sentence.split(' and ') + if (parts.length === 2) { + const first = parseEffectSentence(parts[0]) + const second = parseEffectSentence(parts[1]) + if (first && second) return [...first, ...second] + } + } + + if (sentence.includes(', then ')) { + const parts = sentence.split(', then ') + const effects: Effect[] = [] + for (const part of parts) { + const parsed = parseEffectSentence(part) + if (!parsed) return undefined + effects.push(...parsed) + } + return effects + } + + return undefined +} + +function replaceX(effect: Effect, value: Value): Effect { + const replace = (current: Value): Value => (current.kind === 'x' ? value : current) + switch (effect.op) { + case 'damage': + return { ...effect, amount: replace(effect.amount) } + case 'draw': + case 'mill': + case 'life': + return { ...effect, amount: replace(effect.amount) } + case 'put_counters': + case 'remove_counters': + return { ...effect, amount: replace(effect.amount) } + case 'create_token': + return { ...effect, amount: replace(effect.amount) } + case 'pump': + return { ...effect, power: replace(effect.power), toughness: replace(effect.toughness) } + case 'search': + return { ...effect, amount: replace(effect.amount) } + default: + return effect + } +} + +const PRIMARY_TARGET_OPS = new Set([ + 'pump', + 'grant', + 'set_pt', + 'gain_control', + 'tap', + 'untap', + 'destroy', + 'exile', + 'return_to_hand', + 'return_to_battlefield', + 'sacrifice', + 'put_counters', + 'attach', + 'regenerate', +]) + +function primaryTargetOf(effects: Effect[]): Target | undefined { + for (const effect of effects) { + if (!('target' in effect) || !PRIMARY_TARGET_OPS.has(effect.op)) continue + const target = (effect as { target: Target }).target + if ( + target.kind === 'object' || + target.kind === 'self' || + target.kind === 'trigger_subject' || + target.kind === 'previous_target' + ) { + return target + } + } + return undefined +} + +function parsePick(text: string): Value | undefined { + if (text === 'any number') return { kind: 'any_number' } + return parseValue(text) +} + +function parseDig(text: string): Effect | undefined { + const reorder = text.match( + /^look at the top (\w+) cards? of (your|target player's) library, then put them back in any order(?:\. you may (?:have that player )?shuffle)?$/, + ) + if (reorder) { + const amount = parseValue(reorder[1]) + if (!amount) return undefined + return { + op: 'look_top', + player: reorder[2] === 'your' ? 'you' : 'target_player', + amount, + reorder: true, + } + } + + const prefix = text.match(/^look at the top (\w+) cards? of your library\. (.+)$/) + if (!prefix) return undefined + const amount = parseValue(prefix[1]) + if (!amount) return undefined + const body = prefix[2].trim().replace(/\.$/, '') + + let match = body.match( + /^put (up to )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+|any number) (?:of them|of those cards) into your hand and the (?:other|rest)(?: of those cards)? (on the bottom of your library(?: in (any|a random) order)?|into your graveyard|on top of your library(?: in any order)?)$/, + ) + if (match) { + const pick = parsePick(match[2]) + if (pick) { + const destination = match[3] + const rest = destination.startsWith('on the bottom') + ? 'bottom' + : destination.startsWith('into your graveyard') + ? 'graveyard' + : 'top' + const order = /in a random order$/.test(destination) ? 'random' : 'any' + return { + op: 'dig', + player: 'you', + amount, + pick, + upTo: Boolean(match[1]) || undefined, + to: 'hand', + rest, + order, + } + } + } + + match = body.match( + /^(you may )?reveal (?:up to )?(one|two|three|four|five|\d+)? ?(.+?) from among them and put (?:it|them) into your hand\. put the rest (on the bottom of your library(?: in (any|a random) order)?|into your graveyard)$/, + ) + if (match) { + const selector = parseSelector(match[3]) + const pick = match[2] ? parsePick(match[2]) : ({ kind: 'number', value: 1 } as Value) + if (selector && pick) { + const destination = match[4] + const rest = destination.startsWith('on the bottom') ? 'bottom' : 'graveyard' + const order = /in a random order$/.test(destination) ? 'random' : 'any' + return { + op: 'dig', + player: 'you', + amount, + pick, + upTo: /^(?:you may )?reveal up to /.test(body) || undefined, + pickSelector: selector, + to: 'hand', + rest, + order, + optional: Boolean(match[1]) || undefined, + } + } + } + + match = body.match( + /^put up to (one|two|three|four|five|\d+) (.+?) from among them onto the battlefield( tapped)?(?: and the rest on the bottom of your library(?: in (any|a random) order)?|\. put the rest on the bottom of your library(?: in (any|a random) order)?)$/, + ) + if (match) { + const selector = parseSelector(match[2]) + const pick = parsePick(match[1]) + if (selector && pick) { + return { + op: 'dig', + player: 'you', + amount, + pick, + upTo: true, + pickSelector: selector, + to: 'battlefield', + tapped: Boolean(match[3]) || undefined, + rest: 'bottom', + order: /in a random order$/.test(body) ? 'random' : 'any', + } + } + } + + match = body.match( + /^(you may )?put (any number|one|two|three|four|five|\d+) of them into your hand and the rest into your graveyard$/, + ) + if (match) { + const pick = parsePick(match[2]) + if (pick) { + return { + op: 'dig', + player: 'you', + amount, + pick, + to: 'hand', + rest: 'graveyard', + optional: Boolean(match[1]) || undefined, + } + } + } + + return undefined +} + +function parseEffects(text: string): { effects: Effect[]; optional: boolean } | undefined { + let rest = text.trim().replace(/\.$/, '') + let optional = false + if (/^you may /i.test(rest)) { + optional = true + rest = rest.slice(8) + } + + const leading = takeLeadingDuration(rest) + rest = leading.rest + + const dig = parseDig(rest) + if (dig) return { effects: [dig], optional: optional || (dig.op === 'dig' && Boolean(dig.optional)) } + + const sentences = splitSentences(rest) + if (!sentences.length) return undefined + if (leading.duration) sentences[0] = `${sentences[0].replace(/\.$/, '')} ${leading.duration}` + + const effects: Effect[] = [] + let previousTarget: Target | undefined + for (const rawSentence of sentences) { + let sentence = rawSentence + .replace(/^when you do, /i, 'if you do, ') + .replace(/^when you don't, /i, "if you don't, ") + const leadingIt = /^it\b/i.test(sentence) + if (previousTarget && leadingIt) { + sentence = `the chosen target${sentence.slice(2)}` + } + if (previousTarget) { + sentence = sentence + .replace(/\bthat creature\b/gi, 'the chosen target') + .replace(/\bit\b(?!['’]s)/gi, 'the chosen target') + } + const spend = sentence.match(/^spend this mana only to (.+)$/i) + if (spend) { + const last = effects[effects.length - 1] + if (last?.op === 'add_mana') { + last.mana.restriction = spend[1] + continue + } + return undefined + } + + const conditional = sentence.match(/^if (.+?), (.+)$/i) + if (conditional) { + const raw = conditional[1].trim().toLowerCase() + const condition: Condition | undefined = + raw === 'you do' + ? { kind: 'if_you_do' } + : raw === "you don't" || raw === 'you do not' + ? { kind: 'if_you_dont' } + : parseCondition(conditional[1]) + if (condition) { + let inner = parseEffectSentence(conditional[2]) + if (!inner && /^you may /i.test(conditional[2])) { + inner = parseEffectSentence(conditional[2].slice(8)) + } + if (inner) { + effects.push({ op: 'conditional', condition, effects: inner }) + continue + } + } + return undefined + } + + const otherwise = sentence.match(/^otherwise, (.+)$/i) + if (otherwise) { + let inner = parseEffectSentence(otherwise[1]) + if (!inner && /^you may /i.test(otherwise[1])) { + inner = parseEffectSentence(otherwise[1].slice(8)) + } + if (inner) { + effects.push({ op: 'conditional', condition: { kind: 'otherwise' }, effects: inner }) + continue + } + return undefined + } + + const trailingIf = sentence.match(/^(.+?) if (.+)$/i) + if (trailingIf) { + const condition = parseCondition(trailingIf[2]) + const inner = condition ? parseEffectSentence(trailingIf[1]) : undefined + if (condition && inner) { + effects.push({ op: 'conditional', condition, effects: inner }) + continue + } + } + + let parsed: Effect[] | undefined + if (/, then /i.test(sentence)) { + const parts = sentence.split(/,\s+then\s+/i) + const combined: Effect[] = [] + for (const part of parts) { + const inner = parseEffectSentence(part) + if (!inner) { + combined.length = 0 + break + } + combined.push(...inner) + } + if (combined.length) parsed = combined + } + if (!parsed) parsed = parseEffectSentence(sentence) + if (!parsed && /^you may /i.test(sentence)) { + parsed = parseEffectSentence(sentence.slice(8)) + if (parsed) optional = true + } + if (!parsed) return undefined + if (!leadingIt) { + const newTarget = primaryTargetOf(parsed) + if (newTarget) previousTarget = newTarget + } + effects.push(...parsed) + } + + return { effects, optional } +} + +function resolveIt(text: string, pronoun: string): string { + if (/^it\b/i.test(text)) return `${pronoun}${text.slice(2)}` + if (/\b(?:target|that|those)\b/.test(text)) return text + // A card/token/permanent mentioned in the effect introduces a new referent; + // replacing "it" there would guess. Leave it unsupported instead. + if (/\b(?:card|cards|token|tokens|permanent|permanents|creature|creatures|spell|spells)\b/.test(text)) return text + return text.replace(/\bit\b/g, pronoun) +} + +function parseTriggerPrefix(text: string): { event: TriggerEvent; rest: string } | undefined { + let rest = text.trim() + + let match = rest.match(/^when(?:ever)? this (enters|dies|attacks|blocks|leaves the battlefield)(?: the battlefield)?, (.+)$/) + if (match) { + const kind = match[1] as 'enters' | 'dies' | 'attacks' | 'blocks' | 'leaves the battlefield' + const eventKind = kind === 'leaves the battlefield' ? 'leaves_battlefield' : kind + return { event: { kind: eventKind, subject: { kind: 'self' } } as TriggerEvent, rest: match[2] } + } + + match = rest.match(/^when(?:ever)? this becomes level (\d+), (.+)$/) + if (match) { + return { event: { kind: 'becomes_level', level: Number(match[1]) }, rest: match[2] } + } + + match = rest.match(/^when(?:ever)? this enters or attacks, (.+)$/) + if (match) return { event: { kind: 'enters_or_attacks', subject: { kind: 'self' } }, rest: match[1] } + + match = rest.match(/^when(?:ever)? this enters or dies, (.+)$/) + if (match) return { event: { kind: 'enters_or_dies', subject: { kind: 'self' } }, rest: match[1] } + + match = rest.match(/^when(?:ever)? this attacks or blocks, (.+)$/) + if (match) return { event: { kind: 'attacks_or_blocks', subject: { kind: 'self' } }, rest: match[1] } + + match = rest.match(/^when(?:ever)? this blocks or becomes blocked(?: by a creature)?, (.+)$/) + if (match) return { event: { kind: 'blocks', subject: { kind: 'self' } }, rest: match[1] } + + match = rest.match(/^when(?:ever)? this becomes blocked(?: by a creature)?, (.+)$/) + if (match) return { event: { kind: 'blocks', subject: { kind: 'self' } }, rest: match[1] } + + match = rest.match(/^when(?:ever)? this deals (combat )?damage to (a player|an opponent|a creature|a planeswalker|one or more players|you), (.+)$/) + if (match) { + const recipient = + match[2] === 'a creature' || match[2] === 'a planeswalker' + ? 'permanent' + : 'player' + return { + event: { + kind: 'deals_damage', + subject: { kind: 'self' }, + recipient, + combat: Boolean(match[1]), + }, + rest: match[3], + } + } + + match = rest.match(/^when(?:ever)? this becomes the target of (?:a spell or ability|a spell|an ability)(?: an opponent controls)?, (.+)$/) + if (match) { + return { event: { kind: 'becomes_target', subject: { kind: 'self' } }, rest: match[1] } + } + + match = rest.match(/^when(?:ever)? this is put into a graveyard from (?:the battlefield|anywhere), (.+)$/) + if (match) { + return { event: { kind: 'dies', subject: { kind: 'self' } }, rest: match[1] } + } + + match = rest.match(/^whenever (you|an opponent|a player) (gains?|loses?) life, (.+)$/) + if (match) { + const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player' + const mode = match[2].startsWith('gain') ? 'gain' : 'lose' + return { event: { kind: 'life', who, mode }, rest: match[3] } + } + + match = rest.match(/^whenever (you|an opponent|a player) draws? (.+?), (.+)$/) + if (match) { + const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player' + const clause = match[2].trim() + let ordinal: number | undefined + const ordinalMatch = clause.match(/^(?:your|their) (\w+) card each turn$/) + if (ordinalMatch) { + ordinal = parseNumber(ordinalMatch[1]) + if (ordinal === undefined) return undefined + } else if (!/^(?:a card|their card|one or more cards|a card this turn)$/.test(clause)) { + return undefined + } + return { event: { kind: 'draw', who, ordinal }, rest: match[3] } + } + + match = rest.match(/^at the beginning of (your|each player's|each opponent's|each|the) upkeep, (.+)$/) + if (match) { + const who = match[1] === 'your' ? 'you' : 'each_player' + return { event: { kind: 'upkeep', who }, rest: match[2] } + } + + match = rest.match(/^at the beginning of (your|each player's|each opponent's|each|the) end step, (.+)$/) + if (match) { + const who = match[1] === 'your' ? 'you' : 'each_player' + return { event: { kind: 'end_step', who }, rest: match[2] } + } + + match = rest.match(/^at the beginning of combat on (your|each player's|each opponent's) turn, (.+)$/) + if (match) { + const who = match[1] === 'your' ? 'you' : 'each_player' + return { event: { kind: 'begin_combat', who }, rest: match[2] } + } + + match = rest.match(/^at the beginning of (your|each player's|each opponent's) (first|postcombat) main phase, (.+)$/) + if (match) { + const who = match[1] === 'your' ? 'you' : 'each_player' + return { + event: { kind: 'main_phase', who, phase: match[2] === 'first' ? 'first' : 'postcombat' }, + rest: match[3], + } + } + + match = rest.match(/^whenever (you|an opponent|a player) casts?(?: or cop(y|ies))? (.+?), (.+)$/) + if (match) { + let spellText = match[3].trim() + const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player' + const orCopy = Boolean(match[2]) + let ordinal: number | undefined + const nth = spellText.match(/^(?:your|their) (\w+) spell each turn$/) + if (nth) { + ordinal = parseNumber(nth[1]) + if (ordinal === undefined) return undefined + spellText = 'a spell' + } + let targetsSelf = false + if (/ that targets this$/.test(spellText)) { + targetsSelf = true + spellText = spellText.replace(/ that targets this$/, '') + } + const spell = spellText === 'a spell' || spellText === 'spell' + ? { types: [] } + : parseSelector(spellText.replace(/ spells?$/, '')) + if (spell) { + return { + event: { kind: 'cast', who, spell, targetsSelf: targetsSelf || undefined, ordinal, orCopy: orCopy || undefined }, + rest: match[4], + } + } + } + + match = rest.match(/^whenever (?:one or more )?(.+?) counters? are put on (.+?), (.+)$/) + if (match) { + const subject = parseSubject(match[2]) + if (subject) { + return { event: { kind: 'counter_placed', subject, counter: match[1] }, rest: match[3] } + } + } + + match = rest.match(/^whenever (?:one or more )?(.+?) deals? (combat )?damage to (a player|a player or battle|an opponent|a creature|a planeswalker|you), (.+)$/) + if (match) { + const subject = parseSubject(match[1]) + const recipient = + match[3] === 'a creature' || match[3] === 'a planeswalker' + ? 'permanent' + : 'player' + if (subject) { + return { + event: { kind: 'deals_damage', subject, recipient, combat: Boolean(match[2]) }, + rest: match[4], + } + } + } + + match = rest.match(/^when(?:ever)? (?:one or more )?(.+?) (enters?|dies?|attacks?|blocks?|leaves? the battlefield), (.+)$/) + if (match) { + const subject = parseSubject(match[1]) + if (subject) { + const raw = match[2] + const kind = raw.startsWith('enter') + ? 'enters' + : raw.startsWith('die') + ? 'dies' + : raw.startsWith('attack') + ? 'attacks' + : raw.startsWith('block') + ? 'blocks' + : 'leaves_battlefield' + return { event: { kind, subject } as TriggerEvent, rest: match[3] } + } + } + + return undefined +} + +function parseStaticTarget(text: string): Target | undefined { + if (text.trim() === 'this') return { kind: 'self' } + const direct = parseTarget(text) + if (direct && direct.kind === 'object') return { ...direct, mode: 'each' } + const selector = parseSelector(text) + if (selector) return { kind: 'object', selector, mode: 'each' } + return undefined +} + +function parseStaticEffects(text: string): StaticEffect[] | undefined { + const sentence = text.trim().replace(/\.$/, '') + + let match = sentence.match(/^(?:its|this's) (base )?power and toughness are each equal to (.+)$/) + if (match) { + const value = parseValue(match[2]) + if (value) { + return [{ + op: 'set_pt', + target: { kind: 'self' }, + power: value, + toughness: value, + base: Boolean(match[1]) || undefined, + }] + } + } + + match = sentence.match(/^(?:its|this's) (base )?power is equal to (.+)$/) + if (match) { + const value = parseValue(match[2]) + if (value) { + return [{ op: 'set_pt', target: { kind: 'self' }, power: value, base: Boolean(match[1]) || undefined }] + } + } + + match = sentence.match(/^(?:its|this's) (base )?toughness is equal to (.+)$/) + if (match) { + const value = parseValue(match[2]) + if (value) { + return [{ op: 'set_pt', target: { kind: 'self' }, toughness: value, base: Boolean(match[1]) || undefined }] + } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) for each (.+)$/) + if (match) { + const target = parseStaticTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + const selector = forEachSelector(match[4]) + if (target && power && toughness && selector) { + const count: Value = { kind: 'count', selector } + const scaled = (value: Value): Value | undefined => { + if (value.kind !== 'number' || (value.value !== 0 && value.value !== 1)) return undefined + return value.value === 1 ? count : value + } + const scaledPower = scaled(power) + const scaledToughness = scaled(toughness) + if (scaledPower && scaledToughness) { + return [{ op: 'pump', target, power: scaledPower, toughness: scaledToughness }] + } + } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) and (?:has|have) "(.+)"$/) + if (match) { + const target = parseStaticTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + if (target && power && toughness) { + const ability = compileLine(match[4], 'Quoted', new Set(), false) + if (ability.kind !== 'unsupported') { + return [ + { op: 'pump', target, power, toughness }, + { op: 'grant_ability', target, ability }, + ] + } + } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) and (?:has|have) (.+)$/) + if (match) { + const target = parseStaticTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + const keywords = parseKeywordLine(match[4], new Set()) + if (target && power && toughness && keywords) { + return [ + { op: 'pump', target, power, toughness }, + ...keywords.map(keyword => ({ + op: 'grant' as const, + target, + keyword: keyword.keyword, + value: keyword.value, + })), + ] + } + } + + match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+)$/) + if (match) { + const target = parseStaticTarget(match[1]) + const power = valueWithSign(match[2]) + const toughness = valueWithSign(match[3]) + if (target && power && toughness) return [{ op: 'pump', target, power, toughness }] + } + + match = sentence.match(/^(.+?) (?:has|have) "(.+)"$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) { + const ability = compileLine(match[2], 'Quoted', new Set(), false) + if (ability.kind !== 'unsupported') return [{ op: 'grant_ability', target, ability }] + } + } + + match = sentence.match(/^(.+?) (?:has|have) (.+)$/) + if (match) { + const target = parseStaticTarget(match[1]) + const keywords = parseKeywordLine(match[2], new Set()) + if (target && keywords) { + return keywords.map(keyword => ({ + op: 'grant', + target, + keyword: keyword.keyword, + value: keyword.value, + })) + } + } + + if (sentence === 'you have no maximum hand size') { + return [{ + op: 'restriction', + target: { kind: 'player', who: 'you', mode: 'target' }, + rule: 'no_max_hand_size', + }] + } + + if (sentence === 'you may look at the top card of your library any time') { + return [{ + op: 'restriction', + target: { kind: 'player', who: 'you', mode: 'target' }, + rule: 'may_look_at_top', + }] + } + + if (sentence === 'this can be your commander') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'can_be_commander' }] + } + + if (sentence === 'you may choose not to untap this during your untap step') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'may_choose_not_to_untap' }] + } + + if (sentence === 'this enters prepared') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'enters_prepared' }] + } + + if (sentence === 'if this is in your opening hand, you may begin the game with it on the battlefield') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'begin_on_battlefield' }] + } + + if (sentence === 'this can block only creatures with flying') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'can_block_only_flying' }] + } + + if (sentence === "this cannot be blocked by more than one creature") { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_blocked_by_more_than_one' }] + } + + if (sentence === "this can't be blocked by more than one creature") { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_blocked_by_more_than_one' }] + } + + if (sentence === 'this cannot attack alone') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_attack_alone' }] + } + + if (sentence === 'this cannot block alone') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_block_alone' }] + } + + if (sentence === 'this must be blocked if able' || sentence === 'all creatures able to block this do so') { + return [{ op: 'restriction', target: { kind: 'self' }, rule: 'must_be_blocked' }] + } + + if (sentence === 'you may play an additional land on each of your turns') { + return [{ + op: 'restriction', + target: { kind: 'player', who: 'you', mode: 'target' }, + rule: 'additional_land_drop', + value: { kind: 'number', value: 1 }, + }] + } + + match = sentence.match(/^this cannot be blocked by creatures with power (\w+) or (greater|more|less)$/) + if (match) { + const value = parseValue(match[1]) + if (value) { + return [{ + op: 'restriction', + target: { kind: 'self' }, + rule: 'cant_be_blocked_by_power', + value, + comparison: match[2] === 'less' ? 'or_less' : 'or_greater', + }] + } + } + + match = sentence.match(/^this cannot attack unless defending player controls (.+)$/) + if (match) { + const selector = parseSelector(match[1]) + if (selector) { + return [{ + op: 'restriction', + target: { kind: 'self' }, + rule: 'cant_attack_unless', + condition: { kind: 'defending_player_controls', selector }, + }] + } + } + + if (sentence === 'you control enchanted creature') { + const target = parseStaticTarget('enchanted creature') + if (target) return [{ op: 'control', target }] + } + + match = sentence.match(/^as this enters, choose (?:a|an) (.+)$/) + if (match) { + const what = + match[1] === 'creature type' + ? 'creature_type' + : match[1] === 'color' + ? 'color' + : match[1] === 'card name' + ? 'card_name' + : match[1] === 'player' + ? 'player' + : match[1] === 'opponent' + ? 'opponent' + : match[1] === 'number' + ? 'number' + : undefined + if (what) return [{ op: 'choose', what }] + } + + match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/) + if (match) { + return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }] + } + + match = sentence.match(/^if this would leave the battlefield, exile it instead$/) + if (match) { + return [{ op: 'replacement', what: 'leaves_battlefield', instead: 'exile', target: { kind: 'self' } }] + } + + let costText = sentence + let costCondition: Condition | undefined + let costAmount: Value | undefined + const costWhereX = costText.match(/^(.+?), where x is (.+)$/) + if (costWhereX) { + const value = parseValue(costWhereX[2]) + if (value) { + costText = costWhereX[1] + costAmount = value + } + } + const costIf = costText.match(/^(.+?) if (.+)$/) + if (costIf) { + const parsed = parseCondition(costIf[2]) + if (parsed) { + costText = costIf[1] + costCondition = parsed + } + } + match = costText.match(/^(.+?) costs? ((?:\{[^}]+\})+) less to cast(?: for each (.+))?$/) + if (match) { + const target = parseStaticTarget(match[1]) + let amount: Value | undefined = costAmount + if (!amount && match[3]) { + const selector = parseSelector(match[3]) + if (selector) amount = { kind: 'count', selector } + } else if (!amount) { + const inner = match[2].match(/\{([^}]+)\}/)?.[1] + if (inner) amount = parseValue(inner.toLowerCase()) + } + if (target && amount) { + return [{ op: 'cost_reduction', target, amount, condition: costCondition }] + } + } + + match = sentence.match(/^(.+?) cannot attack or block$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) { + return [ + { op: 'restriction', target, rule: 'cant_attack' }, + { op: 'restriction', target, rule: 'cant_block' }, + ] + } + } + + match = sentence.match(/^(.+?) cannot attack$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'cant_attack' }] + } + + match = sentence.match(/^(.+?) cannot block$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'cant_block' }] + } + + match = sentence.match(/^(.+?) cannot be blocked$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'cant_be_blocked' }] + } + + match = sentence.match(/^(.+?) cannot be countered$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'cant_be_countered' }] + } + + match = sentence.match(/^(.+?) does not untap during (?:its controller's|your) untap step$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'doesnt_untap' }] + } + + match = sentence.match(/^(.+?) attacks each combat if able$/) + if (match) { + const target = parseStaticTarget(match[1]) + if (target) return [{ op: 'restriction', target, rule: 'must_attack' }] + } + + if (sentence === 'this enters tapped') { + return [{ op: 'enters_tapped', target: { kind: 'self' } }] + } + const entersTappedUnless = sentence.match(/^this enters tapped unless (.+)$/) + if (entersTappedUnless) { + const unless = parseCondition(entersTappedUnless[1]) + if (unless) return [{ op: 'enters_tapped', target: { kind: 'self' }, unless }] + } + + match = sentence.match(/^(.+?) enters with (?:(\w+) )?(?:additional )?(.+?) counters? on it(?: for each (.+))?$/) + if (match) { + const target = parseStaticTarget(match[1]) + let amount = match[2] ? parseValue(match[2]) : ({ kind: 'number', value: 1 } as Value) + if (match[4]) { + const selector = parseSelector(match[4]) + if (selector) amount = { kind: 'count', selector } + } + if (target && amount) { + return [{ op: 'enters_with_counters', target, counter: match[3], amount }] + } + } + + return undefined +} + +function parseStaticAbility(text: string): { effects: StaticEffect[]; condition?: Condition } | undefined { + let rest = text.trim().replace(/\.$/, '') + + // A leading duration makes this a one-shot effect, not a continuous one. + if (takeLeadingDuration(rest).duration) return undefined + + let condition: Condition | undefined + const conditionPrefix = rest.match(/^(?:during your turn|as long as it is your turn), (.+)$/) + if (conditionPrefix) { + condition = { kind: 'your_turn' } + rest = conditionPrefix[1] + } else { + const longAsPrefix = rest.match(/^as long as (.+?), (.+)$/) + if (longAsPrefix) { + condition = parseCondition(longAsPrefix[1]) + if (!condition) return undefined + rest = longAsPrefix[2] + } else { + const conditionSuffix = rest.match(/^(.+?) as long as (.+)$/) + if (conditionSuffix) { + condition = parseCondition(conditionSuffix[2]) + if (!condition) return undefined + rest = conditionSuffix[1] + } else { + const ifSuffix = rest.match(/^(.+?) if (.+)$/) + if (ifSuffix) { + const parsed = parseCondition(ifSuffix[2]) + if (parsed) { + condition = parsed + rest = ifSuffix[1] + } + } + } + } + } + + const effects = parseStaticEffects(rest) + return effects ? { effects, condition } : undefined +} + +function parseActivatedAbility(text: string): Ability | undefined { + const colon = text.indexOf(':') + if (colon < 0) return undefined + + const costText = text.slice(0, colon).trim() + let effectText = text.slice(colon + 1).trim() + + const costs: Cost[] = [] + const loyalty = costText.match(/^([+-]\d+|0)$/) + if (loyalty) { + costs.push({ kind: 'loyalty', amount: Number(loyalty[1]) }) + } else if (/^[+-]x$/i.test(costText)) { + return undefined + } else { + const parsedCosts = parseCost(costText) + if (!parsedCosts) return undefined + costs.push(...parsedCosts) + } + + let timing: 'instant' | 'sorcery' | undefined + let condition: Condition | undefined + let activationsPerTurn: number | undefined + + const perTurn = effectText.match(/\bActivate only (once|twice|\d+ times?) each turn\.?$/) + if (perTurn) { + activationsPerTurn = perTurn[1] === 'once' ? 1 : perTurn[1] === 'twice' ? 2 : Number.parseInt(perTurn[1], 10) + effectText = effectText.slice(0, perTurn.index).trim() + } + + const sorcery = effectText.match(/\bActivate only as a sorcery\.?$/) + if (sorcery) { + timing = 'sorcery' + effectText = effectText.slice(0, sorcery.index).trim() + } + + const duringTurn = effectText.match(/\bActivate only during your turn\.?$/) + if (duringTurn) { + condition = { kind: 'your_turn' } + effectText = effectText.slice(0, duringTurn.index).trim() + } + + const onlyIf = effectText.match(/\bActivate only if (.+?)\.?$/) + if (onlyIf) { + const parsed = parseCondition(onlyIf[1]) + if (!parsed) return undefined + condition = parsed + effectText = effectText.slice(0, onlyIf.index).trim() + } + + if (/\bAny player may activate\b/i.test(effectText)) return undefined + if (!effectText) return undefined + + const parsed = parseEffects(resolveIt(effectText, 'this')) + if (!parsed) return undefined + + return { + kind: 'activated', + costs, + effects: parsed.effects, + condition, + timing, + activationsPerTurn, + optional: parsed.optional, + text, + } +} + +function compileLine(rawLine: string, name: string, known: Set, isSpell: boolean): Ability { + const line = normalize(rawLine, name) + if (!line) return { kind: 'unsupported', reason: 'empty', text: rawLine } + + let body = line + const abilityWord = body.match(/^[A-Z][a-z]+(?: [a-z]+)* — (.+)$/) + if (abilityWord) body = abilityWord[1] + const lower = body.toLowerCase() + + if (/^[•·]/.test(line) || /^choose (?:one|two|three|four|five|one or both|one or more)\b/.test(line.toLowerCase())) { + return { kind: 'unsupported', reason: 'modal', text: line } + } + const chapter = body.match(/^([ivx]+(?:, [ivx]+)*) — (.+)$/i) + if (chapter) { + const effects = parseEffects(resolveIt(chapter[2], 'this')) + if (!effects) return { kind: 'unsupported', reason: 'saga effect', text: line } + return { + kind: 'chapter', + chapters: chapter[1].split(',').map(value => value.trim().toUpperCase()), + effects: effects.effects, + optional: effects.optional, + text: line, + } + } + + const levelBand = lower.match(/^level (\d+)(?:-(\d+)|\+)$/) + if (levelBand) { + return { + kind: 'level_band', + min: Number(levelBand[1]), + max: levelBand[2] ? Number(levelBand[2]) : undefined, + text: line, + } + } + + const levelPt = lower.match(/^(\d+)\/(\d+)$/) + if (levelPt) { + return { + kind: 'level_pt', + power: { kind: 'number', value: Number(levelPt[1]) }, + toughness: { kind: 'number', value: Number(levelPt[2]) }, + text: line, + } + } + + const additionalCost = lower.match(/^as an additional cost to cast this(?: spell)?, (.+)$/) + if (additionalCost) { + let costText = additionalCost[1].replace(/\.$/, '') + const optional = /^you may /i.test(costText) + if (optional) costText = costText.replace(/^you may /i, '') + const costs = parseCost(costText) + if (costs) return { kind: 'additional_cost', costs, optional, text: line } + return { kind: 'unsupported', reason: 'additional cost', text: line } + } + + const keywords = parseKeywordLine(body, known) + if (keywords) { + return keywords.length === 1 ? keywords[0] : { kind: 'keywords', keywords } + } + + const trigger = parseTriggerPrefix(lower) + if (trigger) { + let effectText = trigger.rest + let condition: Condition | undefined + const conditional = effectText.match(/^if (.+?), (.+)$/) + if (conditional) { + condition = parseCondition(conditional[1]) + if (!condition) return { kind: 'unsupported', reason: 'trigger condition', text: line } + effectText = conditional[2] + } + + const pronoun = 'subject' in trigger.event ? 'the triggering object' : 'this' + effectText = resolveIt(effectText, pronoun) + + const effects = parseEffects(effectText) + if (!effects) return { kind: 'unsupported', reason: 'trigger effect', text: line } + + return { + kind: 'triggered', + event: trigger.event, + condition, + effects: effects.effects, + optional: effects.optional, + text: line, + } + } + + const activated = parseActivatedAbility(body) + if (activated) return activated + + const staticAbility = parseStaticAbility(lower) + if (staticAbility) { + return { + kind: 'static', + effects: staticAbility.effects, + condition: staticAbility.condition, + text: line, + } + } + + if (isSpell) { + const spellEffects = parseEffects(resolveIt(lower, 'this')) + if (spellEffects) { + return { + kind: 'spell', + effects: spellEffects.effects, + optional: spellEffects.optional, + text: line, + } + } + } + + return { kind: 'unsupported', reason: 'unmatched line', text: line } +} + +export function statusOf(abilities: Ability[]): Status { + if (!abilities.length) return 'supported' + const supported = abilities.filter(ability => ability.kind !== 'unsupported').length + if (supported === abilities.length) return 'supported' + return supported === 0 ? 'unsupported' : 'partial' +} + +const MODAL_CHOOSE = /choose (one or both|one or more|up to one|up to two|up to three|one that hasn't been chosen|one|two|three|four|five)\b/ + +function modalBounds(phrase: string, modeCount: number): { min: number; max: number } { + switch (phrase) { + case 'one': + case "one that hasn't been chosen": + return { min: 1, max: 1 } + case 'two': + return { min: 2, max: 2 } + case 'three': + return { min: 3, max: 3 } + case 'four': + return { min: 4, max: 4 } + case 'five': + return { min: 5, max: 5 } + case 'one or both': + return { min: 1, max: 2 } + case 'one or more': + return { min: 1, max: modeCount } + case 'up to one': + return { min: 0, max: 1 } + case 'up to two': + return { min: 0, max: 2 } + case 'up to three': + return { min: 0, max: 3 } + default: + return { min: 1, max: 1 } + } +} + +function compileModalGroup( + header: string, + bullets: string[], + name: string, + known: Set, + isSpell: boolean, +): Ability { + const text = [header, ...bullets].join('\n') + const normalizedHeader = normalize(header, name) + const lowerHeader = normalizedHeader.toLowerCase() + const chooseMatch = lowerHeader.match(MODAL_CHOOSE) + if (!chooseMatch) return { kind: 'unsupported', reason: 'modal', text } + + const modes: Effect[][] = [] + for (const bullet of bullets) { + const body = normalize(bullet.replace(/^[•·]\s*/, '').trim(), name) + const parsed = parseEffects(resolveIt(body, 'this')) + if (!parsed) return { kind: 'unsupported', reason: 'modal effect', text } + modes.push(parsed.effects) + } + if (!modes.length) return { kind: 'unsupported', reason: 'modal', text } + + const bounds = modalBounds(chooseMatch[1], modes.length) + const modal: Effect = { + op: 'modal', + min: bounds.min, + max: Math.min(bounds.max, modes.length), + modes, + } + + const chooseIndex = lowerHeader.indexOf(chooseMatch[0]) + const prefix = normalizedHeader.slice(0, chooseIndex).trim() + + if (!prefix) { + if (isSpell) return { kind: 'spell', effects: [modal], optional: false, text } + return { kind: 'unsupported', reason: 'modal context', text } + } + + if (prefix.endsWith(':')) { + const costText = prefix.slice(0, -1).trim() + const costs: Cost[] = [] + const loyalty = costText.match(/^([+-]\d+|0)$/) + if (loyalty) { + costs.push({ kind: 'loyalty', amount: Number(loyalty[1]) }) + } else { + const parsed = parseCost(costText) + if (!parsed) return { kind: 'unsupported', reason: 'modal cost', text } + costs.push(...parsed) + } + return { kind: 'activated', costs, effects: [modal], optional: false, text } + } + + const trigger = parseTriggerPrefix(lowerHeader) + if (trigger) { + let rest = trigger.rest + let optional = false + if (/^you may /i.test(rest)) { + optional = true + rest = rest.slice(8) + } + let condition: Condition | undefined + const conditional = rest.match(/^if (.+?), (.+)$/) + if (conditional) { + condition = parseCondition(conditional[1]) + if (!condition) return { kind: 'unsupported', reason: 'trigger condition', text } + } + return { + kind: 'triggered', + event: trigger.event, + condition, + effects: [modal], + optional, + text, + } + } + + return { kind: 'unsupported', reason: 'modal context', text } +} + +function compileFace(face: CardFace | { name: string; oracle_text?: string; type_line?: string }, keywords: string[]): CompiledFace { + const text = face.oracle_text ?? '' + const known = new Set(keywords) + const isSpell = /\b(?:instant|sorcery)\b/i.test(face.type_line ?? '') + const lines = text + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + const abilities: Ability[] = [] + for (let i = 0; i < lines.length; i++) { + const line = lines[i] + if (MODAL_CHOOSE.test(line.toLowerCase()) && i + 1 < lines.length && /^[•·]/.test(lines[i + 1])) { + const bullets: string[] = [] + let j = i + 1 + while (j < lines.length && /^[•·]/.test(lines[j])) { + bullets.push(lines[j]) + j++ + } + abilities.push(compileModalGroup(line, bullets, face.name, known, isSpell)) + i = j - 1 + continue + } + const ability = compileLine(line, face.name, known, isSpell) + if (!(ability.kind === 'unsupported' && ability.reason === 'empty')) abilities.push(ability) + } + return { name: face.name, status: statusOf(abilities), abilities } +} + +export function compileCard(card: Card): CompiledCard { + if (card.card_faces?.length) { + const faces = card.card_faces.map(face => compileFace(face, card.keywords)) + const statuses = faces.map(face => face.status) + const status: Status = statuses.includes('unsupported') + ? statuses.every(value => value === 'unsupported') ? 'unsupported' : 'partial' + : statuses.includes('partial') ? 'partial' : 'supported' + return { oracle_id: card.oracle_id, name: card.name, status, abilities: [], faces } + } + + const face = compileFace( + { name: card.name, oracle_text: card.oracle_text, type_line: card.type_line }, + card.keywords, + ) + return { + oracle_id: card.oracle_id, + name: card.name, + status: face.status, + abilities: face.abilities, + } +} + +export function compileText(text: string, name = 'Test Card', keywords: string[] = [], typeLine = 'Instant'): Ability[] { + return compileFace({ name, oracle_text: text, type_line: typeLine }, keywords).abilities +} diff --git a/backend/src/effects/format.ts b/backend/src/effects/format.ts new file mode 100644 index 0000000..e28b7e5 --- /dev/null +++ b/backend/src/effects/format.ts @@ -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 = { 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') +} diff --git a/backend/src/effects/implementations.ts b/backend/src/effects/implementations.ts new file mode 100644 index 0000000..28e0c6e --- /dev/null +++ b/backend/src/effects/implementations.ts @@ -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> { + const result = new Map() + 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 { + 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 { + 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 "## " 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 { + 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 + 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> { + const cards = allCards() + const auto = loadCompiledIndex().byId + const overrides = await readAllOverrides() + const result = new Map() + + 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> | undefined + +export function implementationIndex(): Promise> { + statusIndex ??= buildStatusIndex() + return statusIndex +} + +export function invalidateImplementationIndex(): void { + statusIndex = undefined +} diff --git a/backend/src/effects/parse.ts b/backend/src/effects/parse.ts new file mode 100644 index 0000000..1fac006 --- /dev/null +++ b/backend/src/effects/parse.ts @@ -0,0 +1,1142 @@ +import type { + Condition, + Cost, + Duration, + ObjectSelector, + PlayerRef, + Target, + Value, + Zone, +} from './types.js' + +const NUMBER_WORDS: Record = { + a: 1, + an: 1, + one: 1, + two: 2, + three: 3, + four: 4, + five: 5, + six: 6, + seven: 7, + eight: 8, + nine: 9, + ten: 10, + eleven: 11, + twelve: 12, + thirteen: 13, + fourteen: 14, + fifteen: 15, + sixteen: 16, + seventeen: 17, + eighteen: 18, + nineteen: 19, + twenty: 20, + second: 2, + third: 3, + fourth: 4, + fifth: 5, + sixth: 6, + seventh: 7, + eighth: 8, + ninth: 9, + tenth: 10, +} + +const TYPE_WORDS = new Set([ + 'artifact', + 'battle', + 'creature', + 'enchantment', + 'instant', + 'land', + 'permanent', + 'planeswalker', + 'sorcery', +]) + +const SUPERTYPE_WORDS = new Set(['basic', 'legendary', 'snow', 'world', 'ongoing', 'commander']) + +const COLOR_WORDS: Record = { + white: 'W', + blue: 'U', + black: 'B', + red: 'R', + green: 'G', +} + +const STATE_WORDS = new Set(['attacking', 'blocking', 'tapped', 'untapped', 'token', 'nontoken', 'other']) + +const PLURALS: Record = { + elves: 'elf', + dwarves: 'dwarf', + wolves: 'wolf', + thieves: 'thief', + leaves: 'leaf', + mice: 'mouse', + oxen: 'ox', + people: 'person', + merfolk: 'merfolk', + fish: 'fish', + sheep: 'sheep', + deer: 'deer', +} + +/** Words that mean the selector is qualified in a way the AST can't express yet. */ +const REJECT_WORDS = new Set([ + 'with', + 'without', + 'that', + 'whose', + 'named', + 'except', + 'unless', + 'equal', + 'chosen', + 'face', + 'faced', + 'copy', + 'from', + 'in', + 'on', + 'at', + 'during', + 'while', + 'before', + 'after', + 'first', + 'more', + 'less', + 'than', + 'power', + 'toughness', + 'mana', + 'value', + 'additional', + 'it', + 'its', + 'them', + 'they', + 'their', +]) + +const NON_CREATURE_SUBTYPES: Record = { + equipment: 'artifact', + vehicle: 'artifact', + treasure: 'artifact', + food: 'artifact', + clue: 'artifact', + blood: 'artifact', + map: 'artifact', + gold: 'artifact', + powerstone: 'artifact', + aura: 'enchantment', + saga: 'enchantment', + class: 'enchantment', + forest: 'land', + island: 'land', + swamp: 'land', + mountain: 'land', + plains: 'land', + gate: 'land', + tower: 'land', + cave: 'land', + desert: 'land', +} + +function typeForSubtype(subtype: string): string { + return NON_CREATURE_SUBTYPES[subtype] ?? 'creature' +} + +export function parseNumber(text: string): number | undefined { + const trimmed = text.trim() + if (/^-?\d+$/.test(trimmed)) return Number(trimmed) + return NUMBER_WORDS[trimmed] +} + +export function singularize(word: string): string { + if (word === 'plains') return word + if (PLURALS[word]) return PLURALS[word] + if (word.length > 3 && word.endsWith('s') && !word.endsWith('ss') && !word.endsWith('us')) { + return word.slice(0, -1) + } + return word +} + +export function parseValue(text: string): Value | undefined { + const trimmed = text.trim() + + if (trimmed === 'x') return { kind: 'x' } + if (trimmed === 'that much' || trimmed === 'that many') return { kind: 'event_amount' } + if (/^(its|this creature's|this permanent's) power$/.test(trimmed)) return { kind: 'source_power' } + if (/^(its|this creature's|this permanent's) toughness$/.test(trimmed)) return { kind: 'source_toughness' } + + const number = parseNumber(trimmed) + if (number !== undefined) return { kind: 'number', value: number } + + const hand = trimmed.match(/^(?:the number of|equal to the number of) cards? in (your|target player's|that player's|an opponent's) hand$/) + if (hand) return { kind: 'cards_in_hand', player: parsePlayerRef(hand[1]) ?? 'you' } + + if (/^(?:the number of |equal to the number of )?cards in the hand of the opponent with the most cards in hand$/.test(trimmed)) { + return { kind: 'max_cards_in_hand' } + } + + const maxOpponent = trimmed.match(/^(?:the )?greatest number of (.+?) an opponent controls$/) + if (maxOpponent) { + const selector = parseSelector(maxOpponent[1]) + if (selector) return { kind: 'max_opponent_count', selector } + } + + const totalManaValue = trimmed.match(/^(?:the )?total mana value of (.+)$/) + if (totalManaValue) { + const selector = parseSelector(totalManaValue[1]) + if (selector) return { kind: 'total_mana_value', selector } + } + + const totalPowerValue = trimmed.match(/^(?:the )?total power of (.+)$/) + if (totalPowerValue) { + const selector = parseSelector(totalPowerValue[1]) + if (selector) return { kind: 'total_power', selector } + } + + const count = trimmed.match(/^(?:the number of|equal to the number of) (.+)$/) + if (count) { + const selector = parseSelector(count[1]) + if (selector) return { kind: 'count', selector } + } + + // "equal to its power" after the article was trimmed above. + return undefined +} + +export function parsePlayerRef(text: string): PlayerRef | undefined { + switch (text.trim()) { + case 'you': + case 'your': + return 'you' + case 'target player': + return 'target_player' + case 'that player': + return 'that_player' + case 'target opponent': + case 'an opponent': + case 'opponent': + return 'opponent' + case 'each opponent': + return 'each_opponent' + case 'each player': + return 'each_player' + case 'its controller': + case 'their controller': + return 'its_controller' + case 'its owner': + case 'their owner': + return 'its_owner' + default: + return undefined + } +} + +function parseZoneSuffix(text: string): { rest: string; zone?: Zone } { + const suffixes: Array<[RegExp, Zone]> = [ + [/ from your graveyard$/, 'graveyard'], + [/ in your graveyard$/, 'graveyard'], + [/ from a graveyard$/, 'graveyard'], + [/ from your library$/, 'library'], + [/ from your hand$/, 'hand'], + [/ in exile$/, 'exile'], + [/ on the stack$/, 'stack'], + [/ on the battlefield$/, 'battlefield'], + ] + + for (const [pattern, zone] of suffixes) { + if (pattern.test(text)) return { rest: text.replace(pattern, ''), zone } + } + return { rest: text } +} + +function parseControllerSuffix( + text: string, +): { rest: string; controller?: ObjectSelector['controller']; owner?: ObjectSelector['owner'] } | undefined { + if (/(?: you control but don't own)$/.test(text)) { + return { rest: text.replace(/ you control but don't own$/, ''), controller: 'you', owner: 'opponent' } + } + if (/(?: you don't control)$/.test(text)) { + return { rest: text.replace(/ you don't control$/, ''), controller: 'opponent' } + } + if (/(?: you control| you cast)$/.test(text)) { + return { rest: text.replace(/(?: you control| you cast)$/, ''), controller: 'you' } + } + if (/ you own$/.test(text)) { + return { rest: text.replace(/ you own$/, ''), owner: 'you' } + } + if (/ you don't own$/.test(text)) { + return { rest: text.replace(/ you don't own$/, ''), owner: 'opponent' } + } + if (/(?: an opponent controls| your opponents control)$/.test(text)) { + return { + rest: text.replace(/(?: an opponent controls| your opponents control)$/, ''), + controller: 'opponent', + } + } + return { rest: text } +} + +const SELECTOR_KEYWORDS = new Set([ + 'flying', + 'reach', + 'trample', + 'vigilance', + 'haste', + 'menace', + 'lifelink', + 'deathtouch', + 'indestructible', + 'hexproof', + 'defender', + 'prowess', + 'flash', + 'convoke', + 'delve', + 'infect', + 'wither', + 'fear', + 'intimidate', + 'first strike', + 'double strike', + 'battle cry', + 'exalted', +]) + +function parseQualifierSuffix(rest: string, selector: ObjectSelector): string { + let text = rest + let changed = true + while (changed) { + changed = false + + let match = text.match(/^(.+?) with power (\w+) or (greater|more|less|fewer)$/) + if (match) { + const amount = parseNumber(match[2]) + if (amount !== undefined) { + selector.power = + match[3] === 'greater' || match[3] === 'more' ? { atLeast: amount } : { atMost: amount } + text = match[1].trim() + changed = true + continue + } + } + + match = text.match(/^(.+?) with toughness (\w+) or (greater|more|less|fewer)$/) + if (match) { + const amount = parseNumber(match[2]) + if (amount !== undefined) { + selector.toughness = + match[3] === 'greater' || match[3] === 'more' ? { atLeast: amount } : { atMost: amount } + text = match[1].trim() + changed = true + continue + } + } + + match = text.match(/^(.+?) with mana value (\w+) or (greater|more|less|fewer)$/) + if (match) { + const amount = parseNumber(match[2]) + if (amount !== undefined) { + selector.manaValue = + match[3] === 'greater' || match[3] === 'more' ? { atLeast: amount } : { atMost: amount } + text = match[1].trim() + changed = true + continue + } + } + + match = text.match(/^(.+?) with (.+)$/) + if (match && SELECTOR_KEYWORDS.has(match[2])) { + selector.keywords = [...(selector.keywords ?? []), match[2]] + text = match[1].trim() + changed = true + continue + } + + match = text.match(/^(.+?) without (.+)$/) + if (match && SELECTOR_KEYWORDS.has(match[2])) { + selector.excludeKeywords = [...(selector.excludeKeywords ?? []), match[2]] + text = match[1].trim() + changed = true + continue + } + } + return text +} + +/** + * Parses the noun phrase after "target"/"each"/"a". Returns undefined rather + * than guessing when the phrase contains a qualifier the AST cannot express. + */ +export function parseSelector(text: string): ObjectSelector | undefined { + let rest = text.trim().replace(/\band\/or\b/gi, 'or') + if (!rest) return undefined + if (/^(?:this|it|that|these|those|them|they)\b/i.test(rest)) return undefined + + const selector: ObjectSelector = {} + + const named = rest.match(/^(.+?) named (.+)$/) + if (named && !/ named /i.test(named[2])) { + selector.name = named[2].trim() + rest = named[1].trim() + } + if (/\bnamed\b/i.test(rest)) return undefined + + rest = rest.replace(/^an? /, '') + rest = rest.replace(/^(?:all|each) /, '') + if (rest.startsWith('another ')) { + selector.other = true + rest = rest.slice(8) + } + if (rest.startsWith('other ')) { + selector.other = true + rest = rest.slice(6) + } + + if (rest.startsWith('equipped ')) { + selector.attached = 'equipped' + rest = rest.slice(9) + } else if (rest.startsWith('enchanted ')) { + selector.attached = 'enchanted' + rest = rest.slice(10) + } + + const counters = rest.match( + /^(.+?) with (a|an|one|two|three|four|five|six|one or more|\d+) (.+?) counters? on (?:it|them)$/, + ) + if (counters) { + selector.counters = { + counter: counters[3], + atLeast: counters[2] === 'one or more' ? 1 : (parseNumber(counters[2]) ?? 1), + } + rest = counters[1].trim() + } + + if (/ other than this$/.test(rest)) { + selector.other = true + rest = rest.replace(/ other than this$/, '') + } + + rest = rest.replace(/ of (?:their|your) choice$/, '') + + const zoneResult = parseZoneSuffix(rest) + rest = zoneResult.rest + if (zoneResult.zone) selector.zone = zoneResult.zone + + rest = parseQualifierSuffix(rest, selector) + + const controllerResult = parseControllerSuffix(rest) + if (!controllerResult) return undefined + rest = controllerResult.rest + if (controllerResult.controller) selector.controller = controllerResult.controller + if (controllerResult.owner) selector.owner = controllerResult.owner + + rest = parseQualifierSuffix(rest, selector) + + if (rest === 'card' || rest === 'cards') { + selector.types = [] + return selector + } + + const words = rest.split(/[\s,]+/).filter(Boolean) + if (!words.length) return undefined + + const types: string[] = [] + const excludeTypes: string[] = [] + const supertypes: string[] = [] + const subtypes: string[] = [] + const colors: string[] = [] + let match: ObjectSelector['match'] + + for (const rawWord of words) { + const word = singularize(rawWord) + + if (REJECT_WORDS.has(rawWord)) return undefined + + if (word === 'or') { + match = 'any' + continue + } + if (word === 'and' || word === ',') continue + + if (word === 'card' || word === 'cards' || word === 'spell' || word === 'spells') continue + + if (word === 'self') { + // "this" should be handled by parseTarget, not a selector. + return undefined + } + + if (COLOR_WORDS[word]) { + colors.push(COLOR_WORDS[word]) + continue + } + if (word === 'colorless') { + colors.push('C') + continue + } + + if (SUPERTYPE_WORDS.has(word)) { + supertypes.push(word) + continue + } + + if (TYPE_WORDS.has(word)) { + types.push(word) + continue + } + + const negative = word.match(/^non(.+)$/) + if (negative && TYPE_WORDS.has(negative[1])) { + excludeTypes.push(negative[1]) + continue + } + + if (STATE_WORDS.has(word)) { + if (word === 'token') selector.token = true + else if (word === 'nontoken') selector.token = false + else if (word === 'other') selector.other = true + else if (word === 'attacking') selector.attacking = true + else if (word === 'tapped') selector.tapped = true + else if (word === 'untapped') selector.tapped = false + continue + } + + if (/^[a-z][a-z'-]*$/.test(word)) { + subtypes.push(singularize(word)) + continue + } + + return undefined + } + + if (!types.length) { + if (subtypes.length) { + types.push(typeForSubtype(subtypes[0])) + } else if (!(excludeTypes.length || colors.length || supertypes.length || selector.name)) { + return undefined + } + } + + selector.types = types + if (match) selector.match = match + if (excludeTypes.length) selector.excludeTypes = excludeTypes + if (supertypes.length) selector.supertypes = supertypes + if (subtypes.length) selector.subtypes = subtypes + if (colors.length) selector.colors = colors + + return selector +} + +function parseSpellSelector(text: string): ObjectSelector | undefined { + const rest = text.trim() + if (rest === 'spell' || rest === 'spells') return { types: [] } + if (rest.startsWith('non')) { + const excluded = rest.slice(3).replace(/ spells?$/, '') + if (TYPE_WORDS.has(excluded)) return { types: [], excludeTypes: [excluded] } + } + const selector = parseSelector(rest.replace(/ spells?$/, '')) + if (!selector) return undefined + return selector +} + +export function parseTarget(text: string): Target | undefined { + let rest = text.trim() + if (!rest) return undefined + + if (rest === 'any target' || rest === 'target creature or player' || rest === 'target permanent or player') { + return { kind: 'any' } + } + if (rest === 'target player or planeswalker') return { kind: 'player_or_planeswalker', mode: 'target' } + if (rest === 'this' || rest === 'this card' || rest === 'this spell') return { kind: 'self' } + if (/^this (?:creature|permanent|artifact|enchantment|land|token|vehicle|planeswalker|battle)$/.test(rest)) { + return { kind: 'self' } + } + if (rest === 'the triggering object' || rest === 'that creature' || rest === 'that permanent' || rest === 'that token') { + return { kind: 'trigger_subject' } + } + if (rest === 'the chosen target' || rest === 'the previous target') { + return { kind: 'previous_target' } + } + + const player = parsePlayerRef(rest) + if (player) return { kind: 'player', who: player, mode: rest.startsWith('each ') ? 'each' : 'target' } + + if (/^target (?:player|opponent)$/.test(rest)) { + return { kind: 'player', who: rest === 'target opponent' ? 'opponent' : 'target_player', mode: 'target' } + } + if (/^each (?:player|opponent)$/.test(rest)) { + return { kind: 'player', who: rest === 'each opponent' ? 'each_opponent' : 'each_player', mode: 'each' } + } + if (rest === 'players') { + return { kind: 'player', who: 'each_player', mode: 'each' } + } + + const spell = rest.match(/^target (.+?) spells?$/) + if (spell) { + const selector = parseSpellSelector(spell[1]) + if (!selector) return undefined + return { kind: 'spell', selector, mode: 'target' } + } + + const countTarget = rest.match(/^(\w+) target (.+)$/) + if (countTarget) { + const amount = parseNumber(countTarget[1]) + if (amount !== undefined) { + const selector = parseSelector(countTarget[2]) + if (selector) return { kind: 'object', selector, mode: 'target', count: amount } + } + } + + if (rest !== 'a' && rest !== 'an') { + const leadingQuantity = rest.match(/^(\w+) (.+)$/) + if (leadingQuantity) { + const amount = parseNumber(leadingQuantity[1]) + if (amount !== undefined) { + const selector = parseSelector(leadingQuantity[2]) + if (selector) return { kind: 'object', selector, mode: 'choose', count: amount } + } + } + } + + let upTo = false + let count: number | undefined + const upToMatch = rest.match(/^up to (one|two|three|four|five|\d+) target (.+)$/) + if (upToMatch) { + upTo = true + count = parseNumber(upToMatch[1]) + rest = `target ${upToMatch[2]}` + } + + let mode: 'target' | 'each' | 'choose' = 'target' + let another = false + if (rest.startsWith('another target ')) { + rest = rest.slice(15) + another = true + } else if (rest.startsWith('target ')) { + rest = rest.slice(7) + } else if (rest.startsWith('each ')) { + rest = rest.slice(5) + mode = 'each' + } else if (rest.startsWith('all ')) { + rest = rest.slice(4) + mode = 'each' + } else if (rest.startsWith('a ') || rest.startsWith('an ')) { + rest = rest.replace(/^an? /, '') + mode = 'choose' + } else { + return undefined + } + + if (rest.startsWith('another ')) { + rest = rest.slice(8) + another = true + } + + const selector = parseSelector(rest) + if (!selector) return undefined + if (another) selector.other = true + return { + kind: 'object', + selector, + mode, + ...(count !== undefined ? { count } : {}), + ...(upTo ? { upTo: true } : {}), + } +} + +export function parseDuration(text: string): Duration | undefined { + switch (text.trim()) { + case 'until end of turn': + return 'until_end_of_turn' + case 'until your next turn': + return 'until_your_next_turn' + case 'until the end of your next turn': + return 'until_end_of_your_next_turn' + case 'until end of combat': + return 'until_end_of_combat' + case "until its controller's next untap step": + return 'until_controllers_next_untap_step' + case 'for as long as this remains on the battlefield': + return 'while_source_on_battlefield' + default: + return undefined + } +} + +export function parseCondition(text: string): Condition | undefined { + const trimmed = text.trim() + + if (trimmed === 'it is your turn') return { kind: 'your_turn' } + if (trimmed === "it isn't your turn" || trimmed === 'it is not your turn') return { kind: 'not_your_turn' } + if (trimmed === 'this is tapped') return { kind: 'source_tapped' } + if (trimmed === 'this is untapped') return { kind: 'source_untapped' } + if (trimmed === 'this is attacking') return { kind: 'source_attacking' } + if (trimmed === 'this was kicked' || trimmed === 'it was kicked') return { kind: 'was_kicked' } + if (trimmed === 'this attacked this turn') return { kind: 'attacked_this_turn' } + if (trimmed === 'you attacked this turn') return { kind: 'you_attacked_this_turn' } + + if (trimmed === 'you cast it') return { kind: 'cast' } + if (trimmed === 'you cast it from your hand') return { kind: 'cast', fromHand: true } + if (trimmed === 'it was cast') return { kind: 'cast' } + if (trimmed === 'this is in your graveyard' || trimmed === 'it is in your graveyard') { + return { kind: 'in_graveyard' } + } + if (trimmed === 'this is on the battlefield' || trimmed === 'it is on the battlefield') { + return { kind: 'on_battlefield' } + } + if (trimmed === "you're the monarch") return { kind: 'monarch' } + if (trimmed === 'you have the initiative') return { kind: 'initiative' } + if (trimmed === "you have the city's blessing") return { kind: 'citys_blessing' } + if (trimmed === 'this is suspended') return { kind: 'suspended' } + if (trimmed === 'it was bargained') return { kind: 'bargained' } + if (trimmed === 'it was a creature') return { kind: 'was_creature' } + if (trimmed === 'an opponent lost life this turn') return { kind: 'opponent_lost_life_this_turn' } + if (trimmed === 'you gained or lost life this turn') return { kind: 'life_changed_this_turn' } + if (trimmed === 'you descended this turn') return { kind: 'descended_this_turn' } + if (trimmed === 'a permanent left the battlefield under your control this turn') { + return { kind: 'permanent_left_battlefield_this_turn', controller: 'you' } + } + if (trimmed === 'a permanent you controlled left the battlefield this turn') { + return { kind: 'permanent_left_battlefield_this_turn', controller: 'you' } + } + + const entered = trimmed.match( + /^(\w+) or more nonland permanents entered the battlefield under your control this turn$/, + ) + if (entered) { + const amount = parseNumber(entered[1]) + if (amount !== undefined) return { kind: 'nonland_permanents_entered_this_turn', atLeast: amount } + } + + const attackedPower = trimmed.match( + /^you attacked with creatures with total power (\w+) or greater this combat$/, + ) + if (attackedPower) { + const amount = parseNumber(attackedPower[1]) + if (amount !== undefined) return { kind: 'attacked_with_total_power', atLeast: amount } + } + + const totalPower = trimmed.match(/^creatures you control have total power (\w+) or greater$/) + if (totalPower) { + const amount = parseNumber(totalPower[1]) + if (amount !== undefined) return { kind: 'total_power', controller: 'you', atLeast: amount } + } + + if (trimmed === 'an opponent controls more lands than you') { + return { kind: 'opponent_controls_more_lands' } + } + + const distinct = trimmed.match( + /^you control (\w+) or more creatures with different powers$/, + ) + if (distinct) { + const amount = parseNumber(distinct[1]) + if (amount !== undefined) return { kind: 'distinct_powers', atLeast: amount } + } + + const cardTypes = trimmed.match( + /^there are (\w+) or more card types among cards in your graveyard$/, + ) + if (cardTypes) { + const amount = parseNumber(cardTypes[1]) + if (amount !== undefined) return { kind: 'graveyard_card_types', atLeast: amount } + } + + const noObjects = trimmed.match(/^no (.+?) (?:are|is) on the battlefield$/) + if (noObjects) { + const selector = parseSelector(noObjects[1]) + if (selector) return { kind: 'no_objects', selector } + } + + const handAtMost = trimmed.match( + /^(that player|an opponent|each opponent) has (?:no|(\w+) or fewer) cards? in hand$/, + ) + if (handAtMost) { + const who = handAtMost[1] === 'that player' ? 'that_player' : handAtMost[1] === 'each opponent' ? 'each_opponent' : 'opponent' + const amount = handAtMost[2] ? parseNumber(handAtMost[2]) : 0 + if (amount !== undefined) return { kind: 'cards_in_hand_at_most', who, atMost: amount } + } + + if (trimmed === 'it is not their turn') return { kind: 'not_their_turn' } + if (trimmed === 'no creatures attacked this turn' || trimmed === "you didn't attack with a creature this turn") { + return { kind: 'no_attackers' } + } + + const poison = trimmed.match(/^an opponent has (\w+) or more poison counters$/) + if (poison) { + const amount = parseNumber(poison[1]) + if (amount !== undefined) return { kind: 'opponent_poison', atLeast: amount } + } + + if (trimmed === "tribute wasn't paid") return { kind: 'tribute_not_paid' } + if (trimmed === 'it had counters on it' || trimmed === 'this has counters on it') { + return { kind: 'had_counters' } + } + const hadCounter = trimmed.match(/^it had (?:a |an )?(.+?) counters? on it$/) + if (hadCounter) return { kind: 'had_counters', counter: hadCounter[1] } + + if (trimmed === 'mana from a treasure was spent to cast it') { + return { kind: 'mana_from_treasure' } + } + const manaSpent = trimmed.match(/^at least (\w+) mana was spent to cast it$/) + if (manaSpent) { + const amount = parseNumber(manaSpent[1]) + if (amount !== undefined) return { kind: 'mana_spent', atLeast: amount } + } + if (trimmed === 'no mana was spent to cast it') return { kind: 'no_mana_spent' } + const symbolSpent = trimmed.match(/^((?:\{[^}]+\})+) was spent to cast it$/) + if (symbolSpent) return { kind: 'mana_symbol_spent', symbols: symbolSpent[1].toUpperCase() } + const kickedWith = trimmed.match(/^it was kicked with its ((?:\{[^}]+\})+) kicker$/) + if (kickedWith) return { kind: 'kicked_with', cost: kickedWith[1].toUpperCase() } + + if (trimmed === 'you have more cards in hand than each opponent') { + return { kind: 'more_cards_than_each_opponent' } + } + if (trimmed === 'it is the first combat phase of the turn') return { kind: 'first_combat_phase' } + if (trimmed === 'it is not a token') return { kind: 'not_token' } + + if (trimmed === "you've cast a noncreature spell this turn") { + return { kind: 'cast_spell_this_turn', noncreature: true } + } + if (trimmed === "you've cast a spell this turn") return { kind: 'cast_spell_this_turn' } + if (trimmed === 'you have a full party') return { kind: 'full_party' } + + const graveyard = trimmed.match(/^there are (\w+) or more cards in (your|an opponent's|target player's) graveyard$/) + if (graveyard) { + const amount = parseNumber(graveyard[1]) + const player = graveyard[2] === 'your' ? 'you' : graveyard[2] === "an opponent's" ? 'opponent' : 'target_player' + if (amount !== undefined) return { kind: 'cards_in_graveyard', player, atLeast: amount } + } + const ownGraveyard = trimmed.match(/^you have (\w+) or more cards in your graveyard$/) + if (ownGraveyard) { + const amount = parseNumber(ownGraveyard[1]) + if (amount !== undefined) return { kind: 'cards_in_graveyard', player: 'you', atLeast: amount } + } + + const graveyardCount = trimmed.match(/^there are (\w+) or more (.+?) in your graveyard$/) + if (graveyardCount) { + const amount = parseNumber(graveyardCount[1]) + const selector = parseSelector(graveyardCount[2]) + if (amount !== undefined && selector) { + return { kind: 'graveyard_count', selector, atLeast: amount } + } + } + + const greaterBase = trimmed.match( + /^you control (?:a|an|one or more) creatures? with (power|toughness) greater than its base (?:power|toughness)$/, + ) + if (greaterBase) { + return { + kind: 'creature_power_greater_than_base', + controller: 'you', + stat: greaterBase[1] as 'power' | 'toughness', + } + } + + if (trimmed === 'you have no cards in hand') return { kind: 'hand_empty', player: 'you' } + if (trimmed === "an opponent has no cards in hand") return { kind: 'hand_empty', player: 'opponent' } + + if (trimmed === 'a creature died this turn') return { kind: 'creature_died_this_turn' } + if (trimmed === 'a creature you control died this turn') { + return { kind: 'creature_died_this_turn', controller: 'you' } + } + if (trimmed === 'a creature an opponent controls died this turn') { + return { kind: 'creature_died_this_turn', controller: 'opponent' } + } + + if (trimmed === 'you gained life this turn') return { kind: 'you_gained_life_this_turn' } + const gained = trimmed.match(/^you gained (\w+) or more life this turn$/) + if (gained) { + const amount = parseNumber(gained[1]) + if (amount !== undefined) return { kind: 'you_gained_life_this_turn', atLeast: amount } + } + + if (trimmed === 'you drew a card this turn') return { kind: 'you_drew_cards_this_turn', atLeast: 1 } + const drew = trimmed.match(/^you drew (\w+) or more cards this turn$/) + if (drew) { + const amount = parseNumber(drew[1]) + if (amount !== undefined) return { kind: 'you_drew_cards_this_turn', atLeast: amount } + } + + if (trimmed === 'no spells were cast last turn') return { kind: 'no_spells_last_turn' } + const spells = trimmed.match(/^(you|an opponent|a player|each player) cast (\w+) or more spells last turn$/) + if (spells) { + const amount = parseNumber(spells[2]) + if (amount !== undefined) { + const who = spells[1] === 'you' ? 'you' : spells[1] === 'an opponent' ? 'opponent' : spells[1] === 'a player' ? 'a_player' : 'each_player' + return { kind: 'spells_cast_last_turn', who, atLeast: amount } + } + } + + const defending = trimmed.match(/^defending player controls (.+)$/) + if (defending) { + const selector = parseSelector(defending[1]) + if (selector) return { kind: 'defending_player_controls', selector } + } + + const targets = trimmed.match(/^it targets (.+)$/) + if (targets) { + const selector = parseSelector(targets[1]) + if (selector) return { kind: 'targets', selector } + } + + const above = trimmed.match(/^you have at least (\d+) life more than your starting life total$/) + if (above) return { kind: 'life_above_starting', player: 'you', amount: Number(above[1]) } + + const control = trimmed.match(/^you control (?:at least )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+) (?:or more )?(.+)$/) + if (control) { + const selector = parseSelector(control[2]) + if (selector) { + return { kind: 'you_control', selector, atLeast: parseNumber(control[1]) } + } + } + const simpleControl = trimmed.match(/^you control (.+)$/) + if (simpleControl) { + const selector = parseSelector(simpleControl[1]) + if (selector) return { kind: 'you_control', selector } + } + const noControl = trimmed.match(/^you control no (.+)$/) + if (noControl) { + const selector = parseSelector(noControl[1]) + if (selector) return { kind: 'you_control', selector, atLeast: 0 } + } + + const opponentControl = trimmed.match(/^(?:an opponent controls|an opponent has|you don't control) (.+)$/) + if (opponentControl) { + const selector = parseSelector(opponentControl[1]) + if (selector) return { kind: 'opponent_controls', selector } + } + + const atLeast = trimmed.match(/^(?:your life total is at least|you have at least) (\d+) life$/) + if (atLeast) return { kind: 'life_at_least', player: 'you', amount: Number(atLeast[1]) } + const atMost = trimmed.match(/^(?:your life total is at most|you have at most) (\d+) life$/) + if (atMost) return { kind: 'life_at_most', player: 'you', amount: Number(atMost[1]) } + const lifeOrMore = trimmed.match(/^you have (\d+) or more life$/) + if (lifeOrMore) return { kind: 'life_at_least', player: 'you', amount: Number(lifeOrMore[1]) } + const lifeOrLess = trimmed.match(/^you have (\d+) or less life$/) + if (lifeOrLess) return { kind: 'life_at_most', player: 'you', amount: Number(lifeOrLess[1]) } + const opponentLife = trimmed.match(/^(?:an opponent|target opponent|each opponent) has (\d+) or (less|more) life$/) + if (opponentLife) { + const player = trimmed.startsWith('target') ? 'target_player' : trimmed.startsWith('each') ? 'each_opponent' : 'opponent' + return { + kind: opponentLife[2] === 'less' ? 'life_at_most' : 'life_at_least', + player, + amount: Number(opponentLife[1]), + } + } + + return undefined +} + +function parseManaSymbols(text: string): string[] | undefined { + const matches = text.match(/\{[^}]+\}/g) + if (!matches || matches.join('') !== text.replace(/\s+/g, '')) return undefined + return matches +} + +export function parseCost(text: string, allowChoice = true): Cost[] | undefined { + const trimmed = text.trim() + const lower = trimmed.toLowerCase() + if (!trimmed) return undefined + + if (allowChoice) { + for (let index = trimmed.indexOf(' or '); index !== -1; index = trimmed.indexOf(' or ', index + 1)) { + const left = trimmed.slice(0, index).trim() + const right = trimmed.slice(index + 4).trim() + const leftCosts = parseCost(left, false) + const rightCosts = parseCost(right, false) + if (leftCosts && rightCosts) { + return [{ kind: 'choice', options: [leftCosts, rightCosts] }] + } + } + } + + // Pure mana / tap / energy symbols. + if (/^(?:\{[^}]+\})+$/.test(trimmed)) { + const symbols = parseManaSymbols(trimmed) + if (!symbols) return undefined + const costs: Cost[] = [] + const mana: string[] = [] + for (const symbol of symbols) { + const normalized = symbol.toLowerCase() + if (normalized === '{t}') costs.push({ kind: 'tap' }) + else if (normalized === '{q}') costs.push({ kind: 'untap' }) + else if (normalized === '{e}') { + const last = costs[costs.length - 1] + if (last?.kind === 'energy') last.amount += 1 + else costs.push({ kind: 'energy', amount: 1 }) + } else mana.push(symbol) + } + if (mana.length) costs.push({ kind: 'mana', symbols: mana.join('') }) + return costs + } + + const parts = lower.split(/, |; /) + const costs: Cost[] = [] + for (const part of parts) { + if (/^(?:\{[^}]+\})+$/.test(part)) { + const parsed = parseCost(part) + if (!parsed) return undefined + costs.push(...parsed) + continue + } + + const paySymbols = part.match(/^pay ((?:\{[^}]+\})+)$/) + if (paySymbols) { + const parsed = parseCost(paySymbols[1], false) + if (!parsed) return undefined + costs.push(...parsed) + continue + } + + const life = part.match(/^pay (\w+) life$/) + if (life) { + const amount = parseValue(life[1]) + if (!amount) return undefined + costs.push({ kind: 'pay_life', amount }) + continue + } + + const sacrifice = part.match(/^sacrifice (.+)$/) + if (sacrifice) { + if (sacrifice[1] === 'this' || sacrifice[1] === 'this creature' || sacrifice[1] === 'this permanent') { + costs.push({ kind: 'sacrifice_self' }) + continue + } + const selector = parseSelector(sacrifice[1]) + if (!selector) return undefined + costs.push({ kind: 'sacrifice', selector }) + continue + } + + const tapOther = part.match(/^tap (?:any number of )?(?:an? )?(?:untapped )?(.+)$/) + if (tapOther && tapOther[1] !== 'this') { + const selector = parseSelector(tapOther[1]) + if (!selector) return undefined + costs.push({ kind: 'tap_other', selector }) + continue + } + + const mill = part.match(/^mill (.+)$/) + if (mill) { + const amount = parseValue(mill[1].replace(/ cards?$/, '')) + if (!amount) return undefined + costs.push({ kind: 'mill', amount }) + continue + } + + const discard = part.match(/^discard (.+?)( at random)?$/) + if (discard) { + const raw = discard[1].replace(/ cards?$/, '') + const amount = raw === 'your hand' ? ({ kind: 'cards_in_hand', player: 'you' } as Value) : parseValue(raw) + if (!amount) return undefined + costs.push({ kind: 'discard', amount, player: 'you', random: Boolean(discard[2]) || undefined }) + continue + } + + const exileFromGraveyard = part.match(/^exile (.+) from your graveyard$/) + if (exileFromGraveyard) { + let raw = exileFromGraveyard[1] + let amount: Value | undefined + const quantity = raw.match(/^(a|an|one|two|three|four|five|six|seven|eight|nine|ten|x|\d+) (.+)$/) + if (quantity) { + amount = parseValue(quantity[1]) + raw = quantity[2] + } + const selector = parseSelector(raw) + if (!selector) return undefined + costs.push({ kind: 'exile_from_graveyard', selector, amount }) + continue + } + + const reveal = part.match(/^reveal (.+?)(?: from your hand)?$/) + if (reveal) { + const selector = parseSelector(reveal[1]) + if (!selector) return undefined + costs.push({ kind: 'reveal', selector }) + continue + } + + const returnToHand = part.match(/^return (.+?) to (?:its|their) owner's hand$/) + if (returnToHand) { + const selector = parseSelector(returnToHand[1]) + if (!selector) return undefined + costs.push({ kind: 'return_to_hand', selector }) + continue + } + + const behold = part.match(/^behold (?:a|an) (.+)$/) + if (behold) { + const selector = parseSelector(behold[1]) + if (!selector) return undefined + costs.push({ kind: 'behold', selector }) + continue + } + + const waterbend = part.match(/^waterbend (\{.+\}|x)$/) + if (waterbend) { + const inner = waterbend[1].startsWith('{') ? waterbend[1].slice(1, -1) : waterbend[1] + const amount = parseValue(inner.toLowerCase()) + if (!amount) return undefined + costs.push({ kind: 'waterbend', amount }) + continue + } + + const blight = part.match(/^blight (\w+)$/) + if (blight) { + const amount = parseValue(blight[1]) + if (!amount) return undefined + costs.push({ kind: 'blight', amount }) + continue + } + + const choose = part.match(/^choose (?:a|an) (.+)$/) + if (choose) { + costs.push({ kind: 'choose', what: choose[1] }) + continue + } + + const putCounter = part.match(/^put (?:a|an|one|two|three|four|five|\d+) (.+?) counters? on (.+)$/) + if (putCounter) { + const selector = parseSelector(putCounter[2]) + if (!selector) return undefined + costs.push({ kind: 'put_counter', counter: putCounter[1], selector }) + continue + } + + const removeCounters = part.match(/^remove (a|an|one|two|three|four|five|six|seven|eight|nine|ten|\d+) (.+?) counters? from (.+)$/) + if (removeCounters) { + const amount = parseValue(removeCounters[1]) + const target = removeCounters[3] + const selector = target === 'this' ? undefined : parseSelector(target) + if (!amount || (target !== 'this' && !selector)) return undefined + costs.push({ kind: 'remove_counters', counter: removeCounters[2], amount, ...(selector ? { selector } : {}) }) + continue + } + + if (part === 'forage') { + costs.push({ kind: 'forage' }) + continue + } + + const collectEvidence = part.match(/^collect evidence (\d+)$/) + if (collectEvidence) { + costs.push({ kind: 'collect_evidence', amount: Number(collectEvidence[1]) }) + continue + } + + if (part === 'exile this card from your graveyard' || part === 'exile this from your graveyard' || part === 'exile this') { + costs.push({ kind: 'exile_self' }) + continue + } + + return undefined + } + + return costs.length ? costs : undefined +} diff --git a/backend/src/effects/pseudo.ts b/backend/src/effects/pseudo.ts new file mode 100644 index 0000000..e027258 --- /dev/null +++ b/backend/src/effects/pseudo.ts @@ -0,0 +1,1811 @@ +// Two-way card pseudocode. `format.ts` renders this syntax and this module reads +// it back, so a human can edit an implementation without touching JSON. +// +// The syntax is exactly the formatter output: one ability per unindented block, +// effects indented below it. Headers such as `# Card [status]` are ignored, and +// `## Face` starts a new face section. + +import { SIMPLE_KEYWORDS } from './compile.js' +import { parseNumber, parsePlayerRef, parseValue, singularize } from './parse.js' +import type { + Ability, + Condition, + Cost, + Duration, + Effect, + KeywordAbility, + ManaSpec, + ObjectSelector, + PlayerRef, + StaticEffect, + Target, + TokenSpec, + TriggerEvent, + Value, + Zone, +} from './types.js' + +export class PseudoParseError extends Error { + readonly line: number + + constructor(message: string, line: number) { + super(`line ${line}: ${message}`) + this.name = 'PseudoParseError' + this.line = line + } +} + +export interface ParsedFacePseudo { + name: string + abilities: Ability[] +} + +export interface ParsedCardPseudo { + abilities: Ability[] + faces?: ParsedFacePseudo[] +} + +interface SourceLine { + text: string + indent: number + line: number +} + +interface Block { + header: SourceLine + body: SourceLine[] +} + +const PLAYERS = new Set([ + 'you', + 'opponent', + 'each_opponent', + 'each_player', + 'target_player', + 'that_player', + 'its_controller', + 'its_owner', +]) + +const TYPE_WORDS = new Set([ + 'artifact', + 'battle', + 'creature', + 'enchantment', + 'instant', + 'land', + 'permanent', + 'planeswalker', + 'sorcery', +]) + +const SUPERTYPES = new Set(['basic', 'legendary', 'snow', 'world', 'ongoing', 'commander']) + +const COLOR_WORDS: Record = { + white: 'W', + blue: 'U', + black: 'B', + red: 'R', + green: 'G', + colorless: 'C', +} + +const DURATIONS = new Map([ + ['until end of turn', 'until_end_of_turn'], + ['until your next turn', 'until_your_next_turn'], + ['until the end of your next turn', 'until_end_of_your_next_turn'], + ['until end of combat', 'until_end_of_combat'], + ["until its controller's next untap step", 'until_controllers_next_untap_step'], + ['for as long as this remains on the battlefield', 'while_source_on_battlefield'], +]) + +function fail(line: SourceLine, message: string): never { + throw new PseudoParseError(message, line.line) +} + +function countIndent(text: string): number { + const match = text.match(/^[ \t]*/) + return match?.[0].replace(/\t/g, ' ').length ?? 0 +} + +/** Splits on `separator` at the top level of parentheses, brackets, and quotes. */ +function splitTopLevel(text: string, separator: string): string[] { + const parts: string[] = [] + let depth = 0 + let quote = false + let escape = false + let start = 0 + + for (let index = 0; index < text.length; index++) { + const char = text[index] + if (quote) { + if (escape) escape = false + else if (char === '\\') escape = true + else if (char === '"') quote = false + continue + } + if (char === '"') { + quote = true + continue + } + if (char === '(' || char === '[' || char === '{') depth++ + else if (char === ')' || char === ']' || char === '}') depth-- + else if (depth === 0 && text.startsWith(separator, index)) { + parts.push(text.slice(start, index)) + index += separator.length - 1 + start = index + 1 + } + } + parts.push(text.slice(start)) + return parts +} + +function splitPowerToughness(text: string): [string, string] | undefined { + const index = firstTopLevelIndex(text, '/') + if (index < 0) return undefined + return [text.slice(0, index).trim(), text.slice(index + 1).trim()] +} + +function lastTopLevelIndex(text: string, separator: string): number { + let found = -1 + for (let index = firstTopLevelIndex(text, separator); index >= 0; index = firstTopLevelIndex(text, separator, index + 1)) { + found = index + } + return found +} + +function firstTopLevelIndex(text: string, separator: string, from = 0): number { + let depth = 0 + let quote = false + let escape = false + + for (let index = 0; index < text.length; index++) { + const char = text[index] + if (quote) { + if (escape) escape = false + else if (char === '\\') escape = true + else if (char === '"') quote = false + continue + } + if (char === '"') { + quote = true + continue + } + if (char === '(' || char === '[' || char === '{') depth++ + else if (char === ')' || char === ']' || char === '}') depth-- + else if (depth === 0 && index >= from && text.startsWith(separator, index)) return index + } + return -1 +} + +interface Call { + name: string + args: string[] + end: number +} + +function readCallPrefix(text: string): Call | undefined { + const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/) + if (!match) return undefined + + const open = match[0].length - 1 + let depth = 0 + let quote = false + let escape = false + for (let index = open; index < text.length; index++) { + const char = text[index] + if (quote) { + if (escape) escape = false + else if (char === '\\') escape = true + else if (char === '"') quote = false + continue + } + if (char === '"') { + quote = true + continue + } + if (char === '(') depth++ + else if (char === ')') { + depth-- + if (depth === 0) { + return { + name: match[1], + args: splitTopLevel(text.slice(open + 1, index), ',').map(arg => arg.trim()), + end: index + 1, + } + } + } + } + return undefined +} + +function parseCall(text: string): Call | undefined { + const call = readCallPrefix(text.trim()) + return call && call.end === text.trim().length ? call : undefined +} + +function arg(args: string[], index: number, line: SourceLine): string { + const value = args[index] + if (value === undefined) fail(line, 'missing argument') + return value.trim() +} + +function parsePlayer(text: string, line: SourceLine): PlayerRef { + const trimmed = text.trim() + if (PLAYERS.has(trimmed as PlayerRef)) return trimmed as PlayerRef + const parsed = parsePlayerRef(trimmed) + if (parsed) return parsed + return fail(line, `unknown player "${trimmed}"`) +} + +function parsePlayerOrThrow(text: string, line: SourceLine, allowed: readonly T[]): T { + const player = parsePlayer(text, line) + if (!allowed.includes(player as T)) fail(line, `player "${player}" is not allowed here`) + return player as T +} + +function parseValueText(text: string, line: SourceLine): Value { + const trimmed = text.trim() + if (trimmed === 'all') return fail(line, '"all" is not a numeric value') + + const call = parseCall(trimmed) + if (call?.name === 'count' && call.args.length === 1) { + return { kind: 'count', selector: parseSelector(call.args[0], line) } + } + + let match = trimmed.match(/^greatest number of (.+) an opponent controls$/) + if (match) return { kind: 'max_opponent_count', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^total mana value of (.+)$/) + if (match) return { kind: 'total_mana_value', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^total power of (.+)$/) + if (match) return { kind: 'total_power', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^cards in (your|that player's|an opponent's|target player's) hand$/) + if (match) { + return { + kind: 'cards_in_hand', + player: match[1] === 'your' ? 'you' : match[1] === 'that player\'s' ? 'that_player' : match[1] === 'target player\'s' ? 'target_player' : 'opponent', + } + } + + if (trimmed === 'cards in the hand of the opponent with the most cards') { + return { kind: 'max_cards_in_hand' } + } + if (trimmed === 'any number') return { kind: 'any_number' } + if (trimmed === 'X' || trimmed === 'x') return { kind: 'x' } + if (trimmed === 'its power') return { kind: 'source_power' } + if (trimmed === 'its toughness') return { kind: 'source_toughness' } + + const parsed = parseValue(trimmed) + if (parsed) return parsed + return fail(line, `cannot read value "${trimmed}"`) +} + +function parseValuePrefix(text: string): { value: Value; rest: string } | undefined { + const trimmed = text.trim() + let match = trimmed.match(/^(greatest number of .+? an opponent controls)(?:\s+(.+))?$/) + if (match) return { value: { kind: 'max_opponent_count', selector: { types: [] } }, rest: match[2] ?? '' } + + const call = readCallPrefix(trimmed) + if (call?.name === 'count') { + return { value: { kind: 'count', selector: { types: [] } }, rest: trimmed.slice(call.end).trim() } + } + + match = trimmed.match(/^(total mana value of .+|total power of .+|cards in (?:your|that player's|an opponent's|target player's) hand|its power|its toughness|any number|that much|X|x|-?\d+)(?:\s+(.+))?$/) + if (!match) return undefined + const valueText = match[1] + const staticValue = parseValue(valueText === 'X' ? 'x' : valueText) + if (!staticValue && valueText !== 'any number') return undefined + return { value: staticValue ?? { kind: 'any_number' }, rest: match[2] ?? '' } +} + +function parseSelector(text: string, line: SourceLine): ObjectSelector { + const selector = parseSelectorText(text) + if (!selector) return fail(line, `cannot read selector "${text.trim()}"`) + return selector +} + +function parseSelectorText(text: string): ObjectSelector | undefined { + let rest = text.trim() + if (!rest) return undefined + + if (rest === 'card' || rest === 'cards') return { types: [] } + + const selector: ObjectSelector = {} + + const zoneSuffixes: Array<[string, Zone]> = [ + [' from a graveyard', 'graveyard'], + [' from a library', 'library'], + [' from a hand', 'hand'], + [' in exile', 'exile'], + [' on the battlefield', 'battlefield'], + [' on the stack', 'stack'], + ] + for (const [suffix, zone] of zoneSuffixes) { + if (rest.endsWith(suffix)) { + selector.zone = zone + rest = rest.slice(0, -suffix.length).trim() + break + } + } + + if (rest.endsWith(" you don't own")) { + selector.owner = 'opponent' + rest = rest.slice(0, -' you don\'t own'.length).trim() + } else if (rest.endsWith(' you own')) { + selector.owner = 'you' + rest = rest.slice(0, -' you own'.length).trim() + } + + if (rest.endsWith(' an opponent controls')) { + selector.controller = 'opponent' + rest = rest.slice(0, -' an opponent controls'.length).trim() + } else if (rest.endsWith(' you control')) { + selector.controller = 'you' + rest = rest.slice(0, -' you control'.length).trim() + } + + const named = rest.match(/^(.*?)\bnamed (.+)$/) + if (named) { + selector.name = named[2].trim() + rest = named[1].trim() + } + + let match = rest.match(/^(.*?) mana value (\d+) or (greater|less)$/) + if (match) { + selector.manaValue = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } + rest = match[1].trim() + } + match = rest.match(/^(.*?) power (\d+) or (greater|less)$/) + if (match) { + selector.power = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } + rest = match[1].trim() + } + match = rest.match(/^(.*?) toughness (\d+) or (greater|less)$/) + if (match) { + selector.toughness = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } + rest = match[1].trim() + } + match = rest.match(/^(.*?) power (\d+)\+$/) + if (match) { + selector.power = { atLeast: Number(match[2]) } + rest = match[1].trim() + } + match = rest.match(/^(.*?) toughness (\d+)\+$/) + if (match) { + selector.toughness = { atLeast: Number(match[2]) } + rest = match[1].trim() + } + match = rest.match(/^(.*?) mana value (\d+)\+$/) + if (match) { + selector.manaValue = { atLeast: Number(match[2]) } + rest = match[1].trim() + } + + match = rest.match(/^(.*?) without (.+)$/) + if (match) { + selector.excludeKeywords = match[2].split(' and ').map(value => value.trim()).filter(Boolean) + rest = match[1].trim() + } + + match = rest.match(/^(.*?) with (\d+)\+ (.+?) counters(?: with (.+))?$/) + if (match) { + selector.counters = { counter: match[3], atLeast: Number(match[2]) } + if (match[4]) selector.keywords = match[4].split(' and ').map(value => value.trim()).filter(Boolean) + rest = match[1].trim() + } else { + match = rest.match(/^(.*?) with (.+)$/) + if (match) { + selector.keywords = match[2].split(' and ').map(value => value.trim()).filter(Boolean) + rest = match[1].trim() + } + } + + let changed = true + while (changed && rest) { + changed = false + for (const [word, key] of [ + ['other', 'other'], + ['tapped', 'tapped'], + ['untapped', 'untapped'], + ['attacking', 'attacking'], + ['token', 'token'], + ['nontoken', 'nontoken'], + ['equipped', 'equipped'], + ['enchanted', 'enchanted'], + ] as const) { + if (rest === word || rest.startsWith(`${word} `)) { + if (key === 'other') selector.other = true + else if (key === 'tapped') selector.tapped = true + else if (key === 'untapped') selector.tapped = false + else if (key === 'attacking') selector.attacking = true + else if (key === 'token') selector.token = true + else if (key === 'nontoken') selector.token = false + else if (key === 'equipped') selector.attached = 'equipped' + else if (key === 'enchanted') selector.attached = 'enchanted' + rest = rest.slice(word.length).trim() + changed = true + break + } + } + } + + const colors: string[] = [] + while (rest) { + const color = rest.match(/^(white|blue|black|red|green|colorless)(?: and )?(.*)$/) + if (!color) break + colors.push(COLOR_WORDS[color[1]]) + rest = color[2].trim() + } + if (colors.length) selector.colors = colors + + const types: string[] = [] + const supertypes: string[] = [] + const subtypes: string[] = [] + const excludeTypes: string[] = [] + let matchAny = false + + for (const rawWord of rest.split(/\s+/).filter(Boolean)) { + if (rawWord === 'and') continue + if (rawWord === 'or') { + matchAny = true + continue + } + if (rawWord.startsWith('non-')) { + const types = rawWord.slice(4).split('/') + if (types.every(type => TYPE_WORDS.has(singularize(type)))) { + for (const type of types) excludeTypes.push(singularize(type)) + continue + } + subtypes.push(singularize(rawWord)) + continue + } + const word = singularize(rawWord) + if (SUPERTYPES.has(word)) { + supertypes.push(word) + continue + } + if (TYPE_WORDS.has(word)) { + types.push(word) + continue + } + if (/^[a-z][a-z'-]*$/.test(word)) { + subtypes.push(word) + continue + } + return undefined + } + + if (types.length) selector.types = types + if (matchAny) selector.match = 'any' + if (excludeTypes.length) selector.excludeTypes = excludeTypes + if (supertypes.length) selector.supertypes = supertypes + if (subtypes.length) selector.subtypes = subtypes + + return selector +} + +function parseTarget(text: string, line: SourceLine): Target { + const trimmed = text.trim() + if (!trimmed) fail(line, 'missing target') + + if (trimmed === 'this') return { kind: 'self' } + if (trimmed === 'the triggering object') return { kind: 'trigger_subject' } + if (trimmed === 'the chosen target' || trimmed === 'the previous target') return { kind: 'previous_target' } + if (trimmed === 'any target') return { kind: 'any' } + if (trimmed === 'target player or planeswalker') return { kind: 'player_or_planeswalker', mode: 'target' } + if (trimmed === 'target ability') return { kind: 'ability', mode: 'target' } + if (trimmed === 'target spell') return { kind: 'spell', selector: { types: [] }, mode: 'target' } + + const spell = trimmed.match(/^target (.+) spell$/) + if (spell) return { kind: 'spell', selector: parseSelector(spell[1], line), mode: 'target' } + + if (trimmed.startsWith('divided(')) { + const call = parseCall(trimmed) + if (call?.name === 'divided') { + const maxText = arg(call.args, 0, line) + const max = maxText === 'any number' ? 'any' : Number(maxText) + if (max !== 'any' && !Number.isFinite(max)) fail(line, `bad divided target count "${maxText}"`) + return { + kind: 'divided', + max, + selector: call.args[1] ? parseSelector(call.args[1], line) : undefined, + } + } + } + + if (PLAYERS.has(trimmed as PlayerRef) || parsePlayerRef(trimmed)) { + const who = parsePlayer(trimmed, line) + return { kind: 'player', who, mode: trimmed.startsWith('each ') ? 'each' : 'target' } + } + + let rest = trimmed + let mode: 'target' | 'each' | 'choose' = 'choose' + let includeSelf = false + let upTo = false + let count: number | undefined + + const upToBefore = rest.match(/^up to (\w+) target (.+)$/) + if (upToBefore) { + upTo = true + count = parseNumber(upToBefore[1]) + rest = `target ${upToBefore[2]}` + } + + if (rest.startsWith('target ')) { + mode = 'target' + rest = rest.slice(7).trim() + } else if (rest.startsWith('each ')) { + mode = 'each' + rest = rest.slice(5).trim() + } + + const quantity = rest.match(/^(up to )?(\w+) (.+)$/) + if ( + quantity + && parseNumber(quantity[2]) !== undefined + && quantity[2] !== 'a' + && quantity[2] !== 'an' + ) { + upTo = Boolean(quantity[1]) + count = parseNumber(quantity[2]) + rest = quantity[3].trim() + } + + if (rest.startsWith('this or ')) { + includeSelf = true + rest = rest.slice(8).trim() + } + + return { + kind: 'object', + selector: parseSelector(rest, line), + mode, + ...(count !== undefined ? { count } : {}), + ...(upTo ? { upTo: true } : {}), + ...(includeSelf ? { includeSelf: true } : {}), + } +} + +function parseDurationText(text: string, line: SourceLine): Duration { + const trimmed = text.trim() + if (!trimmed || trimmed === 'permanent') return 'permanent' + const duration = DURATIONS.get(trimmed) + if (!duration) fail(line, `cannot read duration "${trimmed}"`) + return duration +} + +function parseKeyword(text: string): KeywordAbility { + const trimmed = text.trim() + const lower = trimmed.toLowerCase() + const simple = [...SIMPLE_KEYWORDS.entries()].sort((a, b) => b[0].length - a[0].length) + for (const [key, keyword] of simple) { + if (lower === key) return { kind: 'keyword', keyword: trimmed } + if (lower.startsWith(`${key} `)) return { kind: 'keyword', keyword, value: trimmed.slice(key.length + 1) } + } + + const match = trimmed.match(/^(\S+)(?: (.+))?$/) + if (!match) return { kind: 'keyword', keyword: trimmed } + return { + kind: 'keyword', + keyword: match[1].charAt(0).toUpperCase() + match[1].slice(1), + value: match[2], + } +} + +function parseKeywordList(text: string): KeywordAbility[] { + return splitTopLevel(text, ',').map(part => parseKeyword(part.trim())).filter(Boolean) +} + +function parseCosts(text: string, line: SourceLine): Cost[] { + const trimmed = text.trim() + if (!trimmed) fail(line, 'missing cost') + const parts = splitTopLevel(trimmed, ',').map(part => part.trim()).filter(Boolean) + const costs: Cost[] = [] + for (const part of parts) costs.push(parseCost(part, line)) + return costs +} + +function tryCostOption(text: string, line: SourceLine): Cost[] | undefined { + try { + return splitTopLevel(text, ' + ').map(part => parseCost(part, line)) + } catch { + return undefined + } +} + +function parseCost(text: string, line: SourceLine): Cost { + const trimmed = text.trim() + + if (trimmed.startsWith('(') && trimmed.endsWith(')')) { + const inner = trimmed.slice(1, -1) + const parts = splitTopLevel(inner, ' or ') + for (let split = 1; split < parts.length; split++) { + const left = tryCostOption(parts.slice(0, split).join(' or '), line) + const right = tryCostOption(parts.slice(split).join(' or '), line) + if (left && right) return { kind: 'choice', options: [left, right] } + } + const options = parts.map(option => + splitTopLevel(option, ' + ').map(part => parseCost(part, line)), + ) + if (options.length > 1) return { kind: 'choice', options } + } + + const energy = trimmed.match(/^\{E\} x(\d+)$/) + if (energy) return { kind: 'energy', amount: Number(energy[1]) } + + if (/^(?:\{[^}]+\})+$/.test(trimmed)) { + const symbols = trimmed.match(/\{[^}]+\}/g) ?? [] + const costs: Cost[] = [] + const mana: string[] = [] + for (const symbol of symbols) { + const lower = symbol.toLowerCase() + if (lower === '{t}') costs.push({ kind: 'tap' }) + else if (lower === '{q}') costs.push({ kind: 'untap' }) + else if (lower === '{e}') { + const last = costs[costs.length - 1] + if (last?.kind === 'energy') last.amount += 1 + else costs.push({ kind: 'energy', amount: 1 }) + } else mana.push(symbol) + } + if (mana.length) costs.push({ kind: 'mana', symbols: mana.join('') }) + return costs.length === 1 ? costs[0] : { kind: 'choice', options: costs.map(cost => [cost]) } + } + + let match = trimmed.match(/^([+-]?\d+) loyalty$/) + if (match) return { kind: 'loyalty', amount: Number(match[1]) } + + match = trimmed.match(/^pay (.+) life$/) + if (match) return { kind: 'pay_life', amount: parseValueText(match[1], line) } + + if (trimmed === 'sacrifice this') return { kind: 'sacrifice_self' } + match = trimmed.match(/^sacrifice (.+)$/) + if (match) return { kind: 'sacrifice', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^tap (.+)$/) + if (match) return { kind: 'tap_other', selector: parseSelector(match[1], line) } + + if (trimmed === 'exile this from a graveyard' || trimmed === 'exile this') { + return { kind: 'exile_self' } + } + match = trimmed.match(/^exile (.+?) from your graveyard$/) + if (match) { + const body = match[1].trim() + const prefixed = parseValuePrefix(body) + return { + kind: 'exile_from_graveyard', + selector: parseSelector(prefixed?.rest || body, line), + amount: prefixed?.value, + } + } + + match = trimmed.match(/^reveal (.+) from your hand$/) + if (match) return { kind: 'reveal', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^return (.+) to its owner's hand$/) + if (match) return { kind: 'return_to_hand', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^behold (.+)$/) + if (match) return { kind: 'behold', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^waterbend (.+)$/) + if (match) return { kind: 'waterbend', amount: parseValueText(match[1], line) } + + match = trimmed.match(/^blight (.+)$/) + if (match) return { kind: 'blight', amount: parseValueText(match[1], line) } + + match = trimmed.match(/^choose (.+)$/) + if (match) return { kind: 'choose', what: match[1] } + + match = trimmed.match(/^put (.+?) counters? on (.+)$/) + if (match) return { kind: 'put_counter', counter: match[1], selector: parseSelector(match[2], line) } + + match = trimmed.match(/^remove (.+?) (.+?) counter(?:s|\(s\))? from (.+)$/) + if (match) { + return { + kind: 'remove_counters', + counter: match[2], + amount: parseValueText(match[1], line), + ...(match[3] === 'this' ? {} : { selector: parseSelector(match[3], line) }), + } + } + + if (trimmed === 'forage') return { kind: 'forage' } + + match = trimmed.match(/^collect evidence (\d+)$/) + if (match) return { kind: 'collect_evidence', amount: Number(match[1]) } + + match = trimmed.match(/^mill (.+) card\(s\)$/) + if (match) return { kind: 'mill', amount: parseValueText(match[1], line) } + + if (trimmed === 'discard your hand') { + return { kind: 'discard', amount: { kind: 'cards_in_hand', player: 'you' }, player: 'you' } + } + match = trimmed.match(/^discard (.+?) card\(s\)( at random)?$/) + if (match) { + return { + kind: 'discard', + amount: parseValueText(match[1], line), + player: 'you', + random: Boolean(match[2]) || undefined, + } + } + + return fail(line, `cannot read cost "${trimmed}"`) +} + +function parseEffectExprList(text: string, line: SourceLine): Effect[] { + const parts = splitTopLevel(text, ';').map(part => part.trim()).filter(Boolean) + if (!parts.length) fail(line, 'expected an effect') + return parts.map(part => parseEffectExpr(part, line)) +} + +function parseEffectExpr(text: string, line: SourceLine): Effect { + const call = parseCall(text) + if (!call) fail(line, `expected an effect call, got "${text}"`) + const { name, args } = call + + switch (name) { + case 'damage': { + const source = args[2]?.replace(/^from /, '').trim() + return { + op: 'damage', + target: parseTarget(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + ...(source ? { source: parseTarget(source, line) } : {}), + } + } + case 'damage_divided': + return { + op: 'damage_divided', + amount: parseValueText(arg(args, 0, line), line), + target: parseTarget(arg(args, 1, line), line), + } + case 'draw': + return { op: 'draw', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } + case 'discard': + return { + op: 'discard', + player: parsePlayer(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + random: args[2]?.trim() === 'at random' || undefined, + } + case 'mill': + return { op: 'mill', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } + case 'gain_life': + case 'lose_life': + return { + op: 'life', + player: parsePlayer(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + mode: name === 'gain_life' ? 'gain' : 'lose', + } + case 'pump': + case 'set_pt': { + const pt = splitPowerToughness(arg(args, 1, line)) + if (!pt) fail(line, `expected power/toughness, got "${args[1]}"`) + return { + op: name, + target: parseTarget(arg(args, 0, line), line), + power: parseValueText(pt[0], line), + toughness: parseValueText(pt[1], line), + duration: args[2] ? parseDurationText(args[2], line) : 'permanent', + } + } + case 'grant': { + const last = args[args.length - 1]?.trim() + const hasDuration = args.length > 2 && (DURATIONS.has(last) || last === 'permanent') + const keyword = parseKeyword(args.slice(1, hasDuration ? -1 : undefined).join(', ')) + return { + op: 'grant', + target: parseTarget(arg(args, 0, line), line), + keyword: keyword.keyword, + value: keyword.value, + duration: hasDuration ? parseDurationText(last, line) : 'permanent', + } + } + case 'put_counters': + case 'remove_counters': + return { + op: name, + target: parseTarget(arg(args, 0, line), line), + counter: args.slice(1, -1).join(', ').trim(), + amount: parseValueText(arg(args, args.length - 1, line), line), + } + case 'proliferate': + return { op: 'proliferate' } + case 'create_token': { + const rest = args.slice(2).join(', ').trim() + if (rest.startsWith('copy of ')) { + const notLegendary = /, not legendary$/.test(rest) + const targetText = rest.slice(8).replace(/, not legendary$/, '').trim() + return { + op: 'create_token', + player: parsePlayer(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + token: { types: [], subtypes: [], colors: [] }, + copyOf: parseTarget(targetText, line), + ...(notLegendary ? { notLegendary: true } : {}), + } + } + return { + op: 'create_token', + player: parsePlayer(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + token: parseTokenSpec(rest, line), + } + } + case 'destroy': + case 'exile': + case 'tap': + case 'untap': + case 'regenerate': + case 'return_to_hand': + case 'put_on_top': + return { op: name, target: parseTarget(arg(args, 0, line), line) } + case 'sacrifice': { + const rest = arg(args, 1, line) + const unlessIndex = lastTopLevelIndex(rest, ' unless ') + const targetText = unlessIndex >= 0 ? rest.slice(0, unlessIndex).trim() : rest + const unlessText = unlessIndex >= 0 ? rest.slice(unlessIndex + 8).trim() : undefined + return { + op: 'sacrifice', + player: parsePlayer(arg(args, 0, line), line), + target: parseTarget(targetText, line), + ...(unlessText ? { unless: parseCost(unlessText, line) } : {}), + } + } + case 'counter': { + const what = arg(args, 0, line) + if (what !== 'spell' && what !== 'ability') fail(line, `unknown counter kind "${what}"`) + const rest = arg(args, 1, line) + const unlessIndex = lastTopLevelIndex(rest, ' unless ') + const targetText = unlessIndex >= 0 ? rest.slice(0, unlessIndex).trim() : rest + const unlessText = unlessIndex >= 0 ? rest.slice(unlessIndex + 8).trim() : undefined + return { + op: 'counter', + what, + target: parseTarget(targetText, line), + ...(unlessText ? { unless: parseCost(unlessText, line) } : {}), + } + } + case 'return_to_battlefield': { + let tapped = false + let transformed: boolean | undefined + let counters: { counter: string; amount: Value } | undefined + for (const extra of args.slice(1)) { + const trimmed = extra.trim() + if (trimmed === 'tapped') tapped = true + else if (trimmed === 'transformed') transformed = true + else { + const counter = trimmed.match(/^(.+?) (.+) counters$/) + if (!counter) fail(line, `cannot read return_to_battlefield option "${trimmed}"`) + counters = { amount: parseValueText(counter[1], line), counter: counter[2] } + } + } + return { + op: 'return_to_battlefield', + target: parseTarget(arg(args, 0, line), line), + tapped, + transformed, + counters, + } + } + case 'scry': + case 'surveil': + return { op: name, player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } + case 'search': { + const destinationIndex = args.findIndex(value => /^to /.test(value.trim())) + if (destinationIndex < 0) fail(line, 'search needs a destination') + const destination = args[destinationIndex].trim().replace(/^to /, '') + if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(destination)) { + fail(line, `unknown search destination "${destination}"`) + } + const before = args.slice(1, destinationIndex) + const amountText = before[before.length - 1] + if (amountText === undefined) fail(line, 'search needs an amount') + return { + op: 'search', + player: parsePlayer(arg(args, 0, line), line), + selector: parseSelector(before.slice(0, -1).join(', '), line), + amount: parseValueText(amountText, line), + destination: destination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', + tapped: args.includes('tapped'), + shuffle: args.includes('shuffle'), + ...(args.includes('library+graveyard') ? { zones: ['library', 'graveyard'] as ('library' | 'graveyard')[] } : {}), + } + } + case 'shuffle': + return { op: 'shuffle', player: parsePlayer(arg(args, 0, line), line) } + case 'add_mana': + return { op: 'add_mana', player: parsePlayer(arg(args, 0, line), line), mana: parseMana(arg(args, 1, line), line) } + case 'fight': + return { op: 'fight', a: parseTarget(arg(args, 0, line), line), b: parseTarget(arg(args, 1, line), line) } + case 'energy': + return { op: 'energy', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } + case 'attach': + return { op: 'attach', target: parseTarget(arg(args, args.length - 1, line), line) } + case 'restrict': { + const rule = arg(args, 1, line) + if (rule !== 'cant_attack' && rule !== 'cant_block' && rule !== 'doesnt_untap') { + fail(line, `unknown restriction rule "${rule}"`) + } + return { + op: 'restriction', + target: parseTarget(arg(args, 0, line), line), + rule, + duration: args[2] ? parseDurationText(args[2], line) : 'permanent', + } + } + case 'prevent_damage': + case 'prevent_combat_damage': { + const amountText = arg(args, 1, line) + return { + op: 'prevent_damage', + target: parseTarget(arg(args, 0, line), line), + amount: amountText === 'all' ? 'all' : parseValueText(amountText, line), + combatOnly: name === 'prevent_combat_damage' || undefined, + duration: args[2] ? parseDurationText(args[2], line) : 'permanent', + } + } + case 'gain_control': + return { + op: 'gain_control', + target: parseTarget(arg(args, 0, line), line), + duration: args[1] ? parseDurationText(args[1], line) : 'permanent', + } + case 'emblem': + return { op: 'emblem', text: unquote(arg(args, 0, line), line) } + case 'transform': + return { op: 'transform', target: parseTarget(arg(args, 0, line), line) } + case 'pay': + return { op: 'pay', costs: args.map(part => parseCost(part, line)) } + case 'look_top': + return { + op: 'look_top', + player: parsePlayer(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + reorder: args.includes('reorder') || undefined, + } + case 'level_up': + return { op: 'level_up', level: Number(arg(args, 0, line)) } + case 'put_from_among': { + const last = arg(args, args.length - 1, line) + if (!last.startsWith('to ')) fail(line, 'put_from_among needs a destination') + const destination = last.slice(3) + if (!['hand', 'graveyard', 'battlefield', 'top', 'bottom'].includes(destination)) { + fail(line, `unknown destination "${destination}"`) + } + return { + op: 'put_from_among', + player: 'you', + amount: parseValueText(arg(args, 0, line), line), + ...(args.length > 2 ? { selector: parseSelector(args[1], line) } : {}), + destination: destination as 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom', + } + } + case 'dig': + return parseDig(args, line) + default: + return parseKeywordAction(name, args, line) + } +} + +function parseMana(text: string, line: SourceLine): ManaSpec { + const trimmed = text.trim() + if (/^(?:\{[^}]+\})+/.test(trimmed)) { + const symbols = trimmed.match(/\{[^}]+\}/g) ?? [] + const restriction = trimmed.match(/\(only (.+)\)$/)?.[1] + return { kind: 'symbols', symbols, restriction } + } + + const match = trimmed.match(/^(.+) mana of any( one)? color(?: \(only (.+)\))?$/) + if (!match) fail(line, `cannot read mana "${trimmed}"`) + return { + kind: 'any_color', + amount: parseValueText(match[1], line), + oneColor: Boolean(match[2]), + restriction: match[3], + } +} + +function parseDig(args: string[], line: SourceLine): Effect { + const amount = parseValueText(arg(args, 0, line), line) + const first = arg(args, 1, line) + const upTo = first.startsWith('up to ') + const pickMatch = (upTo ? first.slice(6) : first).match(/^(.*?) to (hand|battlefield)( tapped)?$/) + if (!pickMatch) fail(line, `cannot read dig destination in "${first}"`) + + const pickBody = pickMatch[1].trim() + const prefixed = parseValuePrefix(pickBody) + if (!prefixed) fail(line, `cannot read dig card count in "${pickBody}"`) + + let rest = 'bottom' + let order: 'any' | 'random' | undefined + let optional = false + for (const extra of args.slice(2)) { + const trimmed = extra.trim() + if (trimmed === 'optional') optional = true + else if (trimmed.startsWith('rest ')) { + const parts = trimmed.slice(5).split(' ') + rest = parts[0] + if (parts[1] === 'any' || parts[1] === 'random') order = parts[1] + } else fail(line, `cannot read dig option "${trimmed}"`) + } + + if (!['bottom', 'graveyard', 'top'].includes(rest)) fail(line, `unknown dig rest destination "${rest}"`) + return { + op: 'dig', + player: 'you', + amount, + pick: prefixed.value, + ...(prefixed.rest ? { pickSelector: parseSelector(prefixed.rest, line) } : {}), + upTo: upTo || undefined, + to: pickMatch[2] as 'hand' | 'battlefield', + tapped: Boolean(pickMatch[3]) || undefined, + rest: rest as 'bottom' | 'graveyard' | 'top', + order, + optional: optional || undefined, + } +} + +function parseKeywordAction(name: string, args: string[], line: SourceLine): Effect { + const action = name.replace(/_/g, ' ') + let target: Target | undefined + let amount: Value | undefined + let detail: string | undefined + + if (args.length === 1) { + if (args[0].trim()) { + try { + target = parseTarget(args[0], line) + } catch { + amount = parseValueText(args[0], line) + } + } + } else if (args.length >= 2) { + amount = parseValueText(args[0], line) + detail = args.slice(1).join(', ') + } + + return { op: 'keyword_action', action, ...(amount ? { amount } : {}), ...(target ? { target } : {}), ...(detail ? { detail } : {}) } +} + +function unquote(text: string, line: SourceLine): string { + const trimmed = text.trim() + if (!trimmed.startsWith('"') || !trimmed.endsWith('"')) fail(line, 'expected a quoted string') + return trimmed.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\') +} + +function parseTokenSpec(text: string, line: SourceLine): TokenSpec { + let rest = text.trim() + const tapped = rest.startsWith('tapped ') + if (tapped) rest = rest.slice(7) + + let power: Value | undefined + let toughness: Value | undefined + const pt = rest.match(/^(\S+)\/(\S+) /) + if (pt) { + power = parseValueText(pt[1], line) + toughness = parseValueText(pt[2], line) + rest = rest.slice(pt[0].length) + } + + const colors: string[] = [] + while (rest) { + const color = rest.match(/^(white|blue|black|red|green|colorless)(?: and )?(.*)$/) + if (!color) break + colors.push(COLOR_WORDS[color[1]]) + rest = color[2].trim() + } + + let keywords: string[] | undefined + const withMatch = rest.match(/^(.*?) with (.+)$/) + if (withMatch) { + rest = withMatch[1].trim() + keywords = withMatch[2].split(', ').map(value => value.trim()).filter(Boolean) + } + + const types: string[] = [] + const subtypes: string[] = [] + for (const word of rest.split(/\s+/).filter(Boolean)) { + if (word === 'and') continue + const singular = singularize(word) + if (TYPE_WORDS.has(singular)) types.push(singular) + else if (/^[a-z][a-z'-]*$/.test(singular)) subtypes.push(singular) + else fail(line, `cannot read token type "${word}"`) + } + + return { + types: types.length ? types : [power ? 'creature' : 'artifact'], + subtypes, + colors, + power, + toughness, + keywords, + tapped: tapped || undefined, + } +} + +function parseConditionText(text: string, line: SourceLine): Condition { + const trimmed = text.trim() + + if (trimmed === 'it is your turn') return { kind: 'your_turn' } + if (trimmed === "it isn't your turn" || trimmed === 'it is not your turn') return { kind: 'not_your_turn' } + if (trimmed === 'this is tapped') return { kind: 'source_tapped' } + if (trimmed === 'this is untapped') return { kind: 'source_untapped' } + if (trimmed === 'this is attacking') return { kind: 'source_attacking' } + if (trimmed === 'this was kicked') return { kind: 'was_kicked' } + if (trimmed === 'this attacked this turn') return { kind: 'attacked_this_turn' } + if (trimmed === 'you attacked this turn') return { kind: 'you_attacked_this_turn' } + if (trimmed === 'you cast it') return { kind: 'cast' } + if (trimmed === 'you cast it from your hand') return { kind: 'cast', fromHand: true } + if (trimmed === 'this is in your graveyard') return { kind: 'in_graveyard' } + if (trimmed === 'this is on the battlefield') return { kind: 'on_battlefield' } + if (trimmed === "you're the monarch") return { kind: 'monarch' } + if (trimmed === 'you have the initiative') return { kind: 'initiative' } + if (trimmed === "you have the city's blessing") return { kind: 'citys_blessing' } + if (trimmed === 'this is suspended') return { kind: 'suspended' } + if (trimmed === 'it was bargained') return { kind: 'bargained' } + if (trimmed === 'it was a creature') return { kind: 'was_creature' } + if (trimmed === 'an opponent lost life this turn') return { kind: 'opponent_lost_life_this_turn' } + if (trimmed === 'you gained or lost life this turn') return { kind: 'life_changed_this_turn' } + if (trimmed === 'you descended this turn') return { kind: 'descended_this_turn' } + if (trimmed === 'a permanent you controlled left the battlefield this turn') { + return { kind: 'permanent_left_battlefield_this_turn', controller: 'you' } + } + if (trimmed === 'you have more cards in hand than each opponent') return { kind: 'more_cards_than_each_opponent' } + if (trimmed === 'it is the first combat phase of the turn') return { kind: 'first_combat_phase' } + if (trimmed === 'it is not a token') return { kind: 'not_token' } + if (trimmed === "you've cast a spell this turn") return { kind: 'cast_spell_this_turn' } + if (trimmed === "you've cast a noncreature spell this turn") { + return { kind: 'cast_spell_this_turn', noncreature: true } + } + if (trimmed === 'you have a full party') return { kind: 'full_party' } + if (trimmed === 'no spells were cast last turn') return { kind: 'no_spells_last_turn' } + if (trimmed === 'no creatures attacked this turn') return { kind: 'no_attackers' } + if (trimmed === "tribute wasn't paid") return { kind: 'tribute_not_paid' } + if (trimmed === 'mana from a Treasure was spent to cast it') return { kind: 'mana_from_treasure' } + if (trimmed === 'no mana was spent to cast it') return { kind: 'no_mana_spent' } + if (trimmed === 'you gained life this turn') return { kind: 'you_gained_life_this_turn' } + if (trimmed === 'you drew a card this turn') return { kind: 'you_drew_cards_this_turn', atLeast: 1 } + if (trimmed === 'you have no cards in hand') return { kind: 'hand_empty', player: 'you' } + if (trimmed === 'an opponent has no cards in hand') return { kind: 'hand_empty', player: 'opponent' } + if (trimmed === 'a creature died this turn') return { kind: 'creature_died_this_turn' } + if (trimmed === 'a creature you control died this turn') { + return { kind: 'creature_died_this_turn', controller: 'you' } + } + if (trimmed === 'a creature an opponent controls died this turn') { + return { kind: 'creature_died_this_turn', controller: 'opponent' } + } + if (trimmed === 'an opponent controls more lands than you') return { kind: 'opponent_controls_more_lands' } + if (trimmed === 'it is not their turn') return { kind: 'not_their_turn' } + if (trimmed === 'it had counters on it') return { kind: 'had_counters' } + if (trimmed === 'you do') return { kind: 'if_you_do' } + if (trimmed === "you don't") return { kind: 'if_you_dont' } + if (trimmed === 'otherwise') return { kind: 'otherwise' } + if (trimmed === 'defending player controls') return fail(line, 'missing defending-player selector') + + let match = trimmed.match(/^you control (\d+)\+ creatures with different powers$/) + if (match) return { kind: 'distinct_powers', atLeast: Number(match[1]) } + match = trimmed.match(/^you control a creature with (power|toughness) greater than its base (?:power|toughness)$/) + if (match) { + return { kind: 'creature_power_greater_than_base', controller: 'you', stat: match[1] as 'power' | 'toughness' } + } + match = trimmed.match(/^you control at least (\d+) (.+)$/) + if (match) return { kind: 'you_control', selector: parseSelector(match[2], line), atLeast: Number(match[1]) } + match = trimmed.match(/^you control (.+)$/) + if (match) return { kind: 'you_control', selector: parseSelector(match[1], line) } + match = trimmed.match(/^an opponent controls (.+)$/) + if (match) return { kind: 'opponent_controls', selector: parseSelector(match[1], line) } + + match = trimmed.match(/^(.+) has at least (\d+) life more than their starting life total$/) + if (match) { + return { kind: 'life_above_starting', player: parsePlayer(match[1], line), amount: Number(match[2]) } + } + match = trimmed.match(/^(.+) has at least (\d+) life$/) + if (match) return { kind: 'life_at_least', player: parsePlayer(match[1], line), amount: Number(match[2]) } + match = trimmed.match(/^(.+) has at most (\d+) life$/) + if (match) return { kind: 'life_at_most', player: parsePlayer(match[1], line), amount: Number(match[2]) } + + match = trimmed.match(/^(.+) has (\d+)\+ cards in their graveyard$/) + if (match) return { kind: 'cards_in_graveyard', player: parsePlayer(match[1], line), atLeast: Number(match[2]) } + match = trimmed.match(/^(.+) has no cards in hand$/) + if (match) return { kind: 'hand_empty', player: parsePlayer(match[1], line) } + match = trimmed.match(/^(.+) has (\d+) or fewer cards in hand$/) + if (match) return { kind: 'cards_in_hand_at_most', who: parsePlayer(match[1], line), atMost: Number(match[2]) } + + match = trimmed.match(/^you gained at least (\d+) life this turn$/) + if (match) return { kind: 'you_gained_life_this_turn', atLeast: Number(match[1]) } + match = trimmed.match(/^you drew (\d+)\+ cards this turn$/) + if (match) return { kind: 'you_drew_cards_this_turn', atLeast: Number(match[1]) } + match = trimmed.match(/^(.+) cast (\d+)\+ spells last turn$/) + if (match) { + const who = match[1] + if (who !== 'you' && who !== 'opponent' && who !== 'each_player' && who !== 'a_player') { + fail(line, `unknown spell caster "${who}"`) + } + return { kind: 'spells_cast_last_turn', who, atLeast: Number(match[2]) } + } + + match = trimmed.match(/^(\d+)\+ nonland permanents entered the battlefield under your control this turn$/) + if (match) return { kind: 'nonland_permanents_entered_this_turn', atLeast: Number(match[1]) } + match = trimmed.match(/^you attacked with total power (\d+)\+ this combat$/) + if (match) return { kind: 'attacked_with_total_power', atLeast: Number(match[1]) } + match = trimmed.match(/^creatures you control have total power (\d+)\+$/) + if (match) return { kind: 'total_power', controller: 'you', atLeast: Number(match[1]) } + match = trimmed.match(/^there are (\d+)\+ card types among cards in your graveyard$/) + if (match) return { kind: 'graveyard_card_types', atLeast: Number(match[1]) } + match = trimmed.match(/^there are (\d+)\+ (.+?) in your graveyard$/) + if (match) return { kind: 'graveyard_count', selector: parseSelector(match[2], line), atLeast: Number(match[1]) } + match = trimmed.match(/^no (.+) on the battlefield$/) + if (match) return { kind: 'no_objects', selector: parseSelector(match[1], line) } + match = trimmed.match(/^an opponent has (\d+)\+ poison counters$/) + if (match) return { kind: 'opponent_poison', atLeast: Number(match[1]) } + match = trimmed.match(/^it had a (.+) counter on it$/) + if (match) return { kind: 'had_counters', counter: match[1] } + match = trimmed.match(/^at least (\d+) mana was spent to cast it$/) + if (match) return { kind: 'mana_spent', atLeast: Number(match[1]) } + match = trimmed.match(/^((?:\{[^}]+\})+) was spent to cast it$/) + if (match) return { kind: 'mana_symbol_spent', symbols: match[1] } + match = trimmed.match(/^((?:\{[^}]+\})+)$/) + if (match) return { kind: 'mana_symbol_spent', symbols: match[1] } + match = trimmed.match(/^it was kicked with ((?:\{[^}]+\})+)$/) + if (match) return { kind: 'kicked_with', cost: match[1] } + match = trimmed.match(/^defending player controls (.+)$/) + if (match) return { kind: 'defending_player_controls', selector: parseSelector(match[1], line) } + match = trimmed.match(/^it targets (.+)$/) + if (match) return { kind: 'targets', selector: parseSelector(match[1], line) } + + return fail(line, `cannot read condition "${trimmed}"`) +} + +function parseTrigger(text: string, line: SourceLine): TriggerEvent { + const call = parseCall(text) + if (!call) fail(line, `cannot read trigger "${text}"`) + const { name, args } = call + + switch (name) { + case 'enters': + case 'dies': + case 'attacks': + case 'blocks': + case 'attacks_or_blocks': + case 'enters_or_attacks': + case 'enters_or_dies': + case 'leaves_battlefield': + return { kind: name, subject: parseTarget(arg(args, 0, line), line) } + case 'deals_damage': + case 'deals_combat_damage': { + const recipient = arg(args, 1, line) + if (!['player', 'creature', 'permanent', 'any'].includes(recipient)) { + fail(line, `unknown damage recipient "${recipient}"`) + } + return { + kind: 'deals_damage', + subject: parseTarget(arg(args, 0, line), line), + recipient: recipient as 'player' | 'creature' | 'permanent' | 'any', + combat: name === 'deals_combat_damage', + } + } + case 'upkeep': + case 'end_step': + case 'begin_combat': + return { + kind: name, + who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), + } + case 'first_main_phase': + case 'postcombat_main_phase': + return { + kind: 'main_phase', + who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), + phase: name === 'first_main_phase' ? 'first' : 'postcombat', + } + case 'cast': { + const spellText = arg(args, 1, line) + const spell: ObjectSelector = spellText === 'any spell' + ? { types: [] } + : parseSelector(spellText.replace(/ spells?$/, ''), line) + const ordinalText = args.find(value => /^#\d+ each turn$/.test(value.trim())) + return { + kind: 'cast', + who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), + spell, + targetsSelf: args.includes('targets this') || undefined, + orCopy: args.includes('or copy') || undefined, + ordinal: ordinalText ? Number(ordinalText.trim().match(/\d+/)?.[0]) : undefined, + } + } + case 'becomes_level': + return { kind: 'becomes_level', level: Number(arg(args, 0, line)) } + case 'draw': { + const ordinalText = args[1]?.trim() + return { + kind: 'draw', + who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), + ...(ordinalText ? { ordinal: Number(ordinalText.match(/\d+/)?.[0]) } : {}), + } + } + case 'counter_placed': + return { + kind: 'counter_placed', + subject: parseTarget(arg(args, 0, line), line), + ...(args[1] ? { counter: args[1].trim() } : {}), + } + case 'becomes_target': + return { kind: 'becomes_target', subject: parseTarget(arg(args, 0, line), line) } + case 'gain_life': + case 'lose_life': + return { + kind: 'life', + who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), + mode: name === 'gain_life' ? 'gain' : 'lose', + } + default: + return fail(line, `cannot read trigger "${text}"`) + } +} + +function parseEffects(lines: SourceLine[]): Effect[] { + if (!lines.length) fail(lines[0] ?? { text: '', indent: 0, line: 1 }, 'expected an effect') + const base = Math.min(...lines.map(line => line.indent)) + return parseEffectSequence(lines, 0, base).effects +} + +function parseEffectSequence( + lines: SourceLine[], + start: number, + base: number, +): { effects: Effect[]; next: number } { + const effects: Effect[] = [] + let index = start + + while (index < lines.length) { + const line = lines[index] + if (line.indent < base) break + if (line.indent > base) fail(line, 'unexpected indentation') + + const text = line.text.trim() + + let match = text.match(/^if (.+):$/) + if (match) { + const nested = collectIndented(lines, index + 1, base) + if (!nested.lines.length) fail(line, 'if needs an indented body') + effects.push({ op: 'conditional', condition: parseConditionText(match[1], line), effects: parseEffects(nested.lines) }) + index = nested.next + continue + } + + match = text.match(/^choose (\d+)(?:-(\d+))?:$/) + if (match) { + const nested = collectIndented(lines, index + 1, base) + if (!nested.lines.length) fail(line, 'choose needs an indented body') + const modeIndent = nested.lines[0].indent + const modes: Effect[][] = [] + let modeIndex = 0 + while (modeIndex < nested.lines.length) { + const modeLine = nested.lines[modeIndex] + const mode = modeLine.text.trim().match(/^(\d+)\.\s*(.*)$/) + if (!mode || modeLine.indent !== modeIndent) fail(modeLine, 'choose modes must be numbered') + const modeLines: SourceLine[] = splitTopLevel(mode[2], ';') + .map(part => part.trim()) + .filter(Boolean) + .map(part => ({ text: part, indent: 0, line: modeLine.line })) + let next = modeIndex + 1 + while (next < nested.lines.length && nested.lines[next].indent > modeIndent) { + modeLines.push({ ...nested.lines[next], indent: nested.lines[next].indent - modeIndent }) + next++ + } + modes[Number(mode[1]) - 1] = parseEffectSequence(modeLines, 0, 0).effects + modeIndex = next + } + if (!modes.length || modes.some(mode => !mode)) fail(line, 'choose modes must be numbered from 1') + const min = Number(match[1]) + const max = match[2] ? Number(match[2]) : min + effects.push({ op: 'modal', min, max, modes }) + index = nested.next + continue + } + + match = text.match(/^schedule\((next_upkeep|next_end_step)\):$/) + if (match) { + const nested = collectIndented(lines, index + 1, base) + if (!nested.lines.length) fail(line, 'schedule needs an indented body') + effects.push({ op: 'schedule', when: match[1] as 'next_upkeep' | 'next_end_step', effects: parseEffects(nested.lines) }) + index = nested.next + continue + } + + effects.push(...parseEffectExprList(text, line)) + index++ + } + + return { effects, next: index } +} + +function collectIndented(lines: SourceLine[], start: number, base: number): { lines: SourceLine[]; next: number } { + let index = start + while (index < lines.length && lines[index].indent > base) index++ + return { lines: lines.slice(start, index), next: index } +} + +function parseStaticEffects(lines: SourceLine[]): StaticEffect[] { + if (!lines.length) fail(lines[0] ?? { text: '', indent: 0, line: 1 }, 'expected a static effect') + const base = Math.min(...lines.map(line => line.indent)) + const effects: StaticEffect[] = [] + let index = 0 + + while (index < lines.length) { + const line = lines[index] + if (line.indent !== base) fail(line, 'unexpected indentation') + const text = line.text.trim() + + if (text.startsWith('grant_ability(') && text.endsWith('):')) { + const call = parseCall(text.slice(0, -1)) + if (!call || call.name !== 'grant_ability') fail(line, `cannot read static effect "${text}"`) + const nested = collectIndented(lines, index + 1, base) + if (!nested.lines.length) fail(line, 'grant_ability needs an indented ability') + const abilities = parseBlocks(nested.lines) + if (abilities.length !== 1) fail(line, 'grant_ability needs exactly one ability') + effects.push({ + op: 'grant_ability', + target: parseTarget(arg(call.args, 0, line), line), + ability: abilities[0], + }) + index = nested.next + continue + } + + effects.push(parseStaticEffect(text, line)) + index++ + } + + return effects +} + +function parseStaticEffect(text: string, line: SourceLine): StaticEffect { + const call = parseCall(text) + if (!call) fail(line, `expected a static effect, got "${text}"`) + const { name, args } = call + + switch (name) { + case 'pump': { + const pt = splitPowerToughness(arg(args, 1, line)) + if (!pt) fail(line, `expected power/toughness, got "${args[1]}"`) + return { + op: 'pump', + target: parseTarget(arg(args, 0, line), line), + power: parseValueText(pt[0], line), + toughness: parseValueText(pt[1], line), + } + } + case 'grant': { + const keyword = parseKeyword(args.slice(1).join(', ')) + return { + op: 'grant', + target: parseTarget(arg(args, 0, line), line), + keyword: keyword.keyword, + value: keyword.value, + } + } + case 'grant_ability': { + let abilityText = arg(args, 1, line).trim() + if (abilityText.startsWith('(') && abilityText.endsWith(')')) abilityText = abilityText.slice(1, -1) + return { + op: 'grant_ability', + target: parseTarget(arg(args, 0, line), line), + ability: parseInlineAbility(abilityText, line), + } + } + case 'restrict': { + const target = parseTarget(arg(args, 0, line), line) + const rest = args.slice(1).join(', ').trim() + const ifIndex = lastTopLevelIndex(rest, ' if ') + const before = ifIndex >= 0 ? rest.slice(0, ifIndex).trim() : rest + const condition = ifIndex >= 0 ? parseConditionText(rest.slice(ifIndex + 4), line) : undefined + const rule = before.split(/\s+/)[0] + const detail = before.slice(rule.length).trim() + return { + op: 'restriction', + target, + rule, + ...(detail ? { detail } : {}), + ...(condition ? { condition } : {}), + } + } + case 'enters_tapped': { + const unlessIndex = lastTopLevelIndex(text, ', unless ') + const targetText = unlessIndex >= 0 ? arg(args, 0, line) : arg(args, 0, line) + const unlessArg = args.length > 1 ? args.slice(1).join(', ').replace(/^unless /, '') : undefined + return { + op: 'enters_tapped', + target: parseTarget(targetText, line), + ...(unlessArg ? { unless: parseConditionText(unlessArg, line) } : {}), + } + } + case 'enters_with_counters': + return { + op: 'enters_with_counters', + target: parseTarget(arg(args, 0, line), line), + counter: args.slice(1, -1).join(', ').trim(), + amount: parseValueText(arg(args, args.length - 1, line), line), + } + case 'set_pt': { + const base = args[1]?.trim() === 'base' + const ptText = arg(args, base ? 2 : 1, line) + const pt = splitPowerToughness(ptText) + if (!pt) fail(line, `expected power/toughness, got "${ptText}"`) + return { + op: 'set_pt', + target: parseTarget(arg(args, 0, line), line), + power: pt[0] === '?' ? undefined : parseValueText(pt[0], line), + toughness: pt[1] === '?' ? undefined : parseValueText(pt[1], line), + base: base || undefined, + } + } + case 'control': + return { op: 'control', target: parseTarget(arg(args, 0, line), line) } + case 'choose': { + const what = arg(args, 0, line) + if (!['creature_type', 'color', 'card_name', 'player', 'opponent', 'number'].includes(what)) { + fail(line, `unknown choice "${what}"`) + } + return { op: 'choose', what: what as 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' } + } + case 'replace': { + const what = arg(args, 0, line) + if (!['dies', 'leaves_battlefield', 'discard', 'draw'].includes(what)) fail(line, `unknown replacement "${what}"`) + const targetText = args.length > 2 ? args[1] : undefined + const instead = arg(args, args.length - 1, line).replace(/^instead /, '') + if (!['exile', 'return_to_hand', 'return_to_library', 'prevent'].includes(instead)) { + fail(line, `unknown replacement result "${instead}"`) + } + return { + op: 'replacement', + what: what as 'dies' | 'leaves_battlefield' | 'discard' | 'draw', + instead: instead as 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent', + ...(targetText ? { target: parseTarget(targetText, line) } : {}), + } + } + case 'cost_reduction': { + const rest = args[2]?.trim() + return { + op: 'cost_reduction', + target: parseTarget(arg(args, 0, line), line), + amount: parseValueText(arg(args, 1, line), line), + ...(rest?.startsWith('if ') ? { condition: parseConditionText(rest.slice(3), line) } : {}), + } + } + case 'unsupported': + return fail(line, 'unsupported is an ability, not a static effect') + default: + return fail(line, `cannot read static effect "${text}"`) + } +} + +function parseInlineAbility(text: string, line: SourceLine): Ability { + const trimmed = text.trim() + const colon = firstTopLevelIndex(trimmed, ':') + if (colon < 0) return parseAbilityBlock({ header: { text: trimmed, indent: 0, line: line.line }, body: [] }) + + const header = trimmed.slice(0, colon + 1) + const bodyText = trimmed.slice(colon + 1).trim() + const body = bodyText + ? splitTopLevel(bodyText, ';').map(effect => ({ text: ` ${effect.trim()}`, indent: 2, line: line.line })) + : [] + return parseAbilityBlock({ header: { text: header, indent: 0, line: line.line }, body }) +} + +function parseAbilityBlock(block: Block): Ability { + const header = block.header.text.trim() + const body = block.body + + const unsupported = header.match(/^unsupported \(([^)]*)\): ?(.*)$/) + if (unsupported) { + const text = [unsupported[2], ...body.map(line => line.text.trim())].filter(Boolean).join('\n') + return { kind: 'unsupported', reason: unsupported[1], text } + } + + let match = header.match(/^keyword (.+)$/) + if (match) return parseKeyword(match[1]) + + match = header.match(/^keywords (.+)$/) + if (match) return { kind: 'keywords', keywords: parseKeywordList(match[1]) } + + match = header.match(/^level_pt\((.+)\/(.+)\)$/) + if (match) { + return { + kind: 'level_pt', + power: parseValueText(match[1], block.header), + toughness: parseValueText(match[2], block.header), + text: header, + } + } + + match = header.match(/^level (\d+)(?:-(\d+)|\+)(?:: (.+)\/(.+))?$/) + if (match) { + return { + kind: 'level_band', + min: Number(match[1]), + max: match[2] ? Number(match[2]) : undefined, + power: match[3] ? parseValueText(match[3], block.header) : undefined, + toughness: match[4] ? parseValueText(match[4], block.header) : undefined, + text: header, + } + } + + match = header.match(/^additional cost( \(may\))?: ?(.*)$/) + if (match) { + const costsText = [match[2], ...body.map(line => line.text.trim())].filter(Boolean).join(', ') + return { kind: 'additional_cost', costs: parseCosts(costsText, block.header), optional: Boolean(match[1]), text: header } + } + + if (!header.endsWith(':')) fail(block.header, `expected an ability block, got "${header}"`) + let rest = header.slice(0, -1) + + match = rest.match(/^chapter (.+?)( \(may\))?$/) + if (match) { + return { + kind: 'chapter', + chapters: splitTopLevel(match[1], ',').map(value => value.trim().toUpperCase()), + effects: parseEffects(body), + optional: Boolean(match[2]), + text: header, + } + } + + if (rest === 'spell' || rest === 'spell (may)') { + return { kind: 'spell', effects: parseEffects(body), optional: rest.endsWith('(may)'), text: header } + } + + match = rest.match(/^static(?: if (.+))?$/) + if (match) { + return { kind: 'static', effects: parseStaticEffects(body), ...(match[1] ? { condition: parseConditionText(match[1], block.header) } : {}), text: header } + } + + if (rest.startsWith('on ')) { + let triggerText = rest.slice(3).trim() + const optional = triggerText.endsWith(' (may)') + if (optional) triggerText = triggerText.slice(0, -6).trim() + const call = readCallPrefix(triggerText) + if (!call) fail(block.header, `cannot read trigger "${triggerText}"`) + let tail = triggerText.slice(call.end).trim() + let condition: Condition | undefined + if (tail.startsWith('if ')) { + condition = parseConditionText(tail.slice(3), block.header) + tail = '' + } + if (tail) fail(block.header, `unexpected trigger text "${tail}"`) + return { + kind: 'triggered', + event: parseTrigger(triggerText.slice(0, call.end).trim(), block.header), + condition, + effects: parseEffects(body), + optional, + text: header, + } + } + + if (rest.startsWith('activate ')) { + let costsText = rest.slice(9).trim() + let optional = false + let timing: 'instant' | 'sorcery' | undefined + let activationsPerTurn: number | undefined + + if (costsText.endsWith(' (may)')) { + optional = true + costsText = costsText.slice(0, -6).trim() + } + if (costsText.endsWith(' (sorcery speed)')) { + timing = 'sorcery' + costsText = costsText.slice(0, -16).trim() + } + const perTurn = costsText.match(/ \((\d+)\/turn\)$/) + if (perTurn) { + activationsPerTurn = Number(perTurn[1]) + costsText = costsText.slice(0, perTurn.index).trim() + } + + let condition: Condition | undefined + const ifIndex = lastTopLevelIndex(costsText, ' if ') + if (ifIndex >= 0) { + condition = parseConditionText(costsText.slice(ifIndex + 4), block.header) + costsText = costsText.slice(0, ifIndex).trim() + } + + return { + kind: 'activated', + costs: parseCosts(costsText, block.header), + effects: parseEffects(body), + condition, + timing, + activationsPerTurn, + optional, + text: header, + } + } + + return fail(block.header, `cannot read ability "${header}"`) +} + +interface Section { + name?: string + lines: SourceLine[] + empty: boolean +} + +function splitSections(lines: SourceLine[]): Section[] { + const sections: Section[] = [{ lines: [], empty: false }] + for (const line of lines) { + const trimmed = line.text.trim() + if (!trimmed) continue + if (trimmed.startsWith('##')) { + const name = trimmed.replace(/^##\s*/, '').replace(/\s+\[[^\]]*\]$/, '').trim() + if (!name) fail(line, 'face section needs a name') + sections.push({ name, lines: [], empty: false }) + continue + } + if (trimmed.startsWith('#')) continue + if (trimmed === '(no abilities)') { + sections[sections.length - 1].empty = true + continue + } + sections[sections.length - 1].lines.push(line) + } + return sections +} + +function parseBlocks(lines: SourceLine[]): Ability[] { + if (!lines.length) return [] + const base = Math.min(...lines.map(line => line.indent)) + const blocks: Block[] = [] + + for (const line of lines) { + const indent = line.indent - base + if (indent < 0) fail(line, 'unexpected indentation') + if (indent === 0) { + blocks.push({ header: line, body: [] }) + } else { + const block = blocks[blocks.length - 1] + if (!block) fail(line, 'indented line without an ability') + block.body.push({ ...line, indent }) + } + } + + if (!blocks.length) return [] + return blocks.map(parseAbilityBlock) +} + +function toSourceLines(source: string): SourceLine[] { + const lines: SourceLine[] = [] + source.replace(/\r\n?/g, '\n').split('\n').forEach((raw, index) => { + if (!raw.trim()) return + lines.push({ text: raw, indent: countIndent(raw), line: index + 1 }) + }) + return lines +} + +export function parsePseudoCard(source: string): ParsedCardPseudo { + if (!source.trim()) throw new PseudoParseError('the implementation is empty', 1) + const sections = splitSections(toSourceLines(source)) + const named = sections.filter((section): section is Section & { name: string } => Boolean(section.name)) + + if (named.length) { + const leading = sections[0] + if (leading.lines.length) throw new PseudoParseError('abilities before the first "## face" section', leading.lines[0].line) + const faces = named.map(section => ({ + name: section.name, + abilities: parseBlocks(section.lines), + })) + return { abilities: [], faces } + } + + const abilities = parseBlocks(sections[0]?.lines ?? []) + if (!abilities.length && !sections[0]?.empty) { + throw new PseudoParseError('the implementation has no abilities', 1) + } + return { abilities } +} diff --git a/backend/src/effects/translate.ts b/backend/src/effects/translate.ts new file mode 100644 index 0000000..723004d --- /dev/null +++ b/backend/src/effects/translate.ts @@ -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 "## " 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 [ if ][ (may)]: + activate [, ...][ if ][ (N/turn)][ (sorcery speed)][ (may)]: + static[ if ]: + spell[(may)]: + keyword [ value] + keywords , + additional cost[(may)]: + chapter , [(may)]: + level -[: /] + level +[: /] + level_pt(/) + +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, |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 , each , + up to N target , N , this or , divided([, ]) + +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 ", "without ", +"power N+" / "power N or less", "toughness N+" / "toughness N or less", +"mana value N+" / "mana value N or less", "named ", +"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack". + +Values: a number, X, count(), its power, its toughness, +cards in your hand, cards in that player's hand, total power of , +total mana value of , greatest number of 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 , +tap , exile this from a graveyard, exile N from your graveyard, +reveal from your hand, return to its owner's hand, +behold , waterbend , blight , choose , +put counter on , 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 : + + choose [-]: + 1. + 2. + schedule(next_upkeep|next_end_step): + + +Static effects: + pump(target, power/toughness) + grant(target, Keyword[ value]) + restrict(target, rule[ detail][ if ]) + enters_tapped(target[, unless ]) + enters_with_counters(target, counter, amount) + grant_ability(target): + + 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 ]) + +Common conditions: you control , you control at least N , +an opponent controls , it is your turn, it isn't your turn, +this is tapped, this is untapped, this is attacking, has at least N life, + has at most N life, has N+ cards in their graveyard, + 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 (): +- For multi-face cards, output only the "## " 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 { + 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 +} diff --git a/backend/src/effects/types.ts b/backend/src/effects/types.ts new file mode 100644 index 0000000..53ec32a --- /dev/null +++ b/backend/src/effects/types.ts @@ -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 +} diff --git a/backend/src/game/catalog.ts b/backend/src/game/catalog.ts new file mode 100644 index 0000000..e9a3052 --- /dev/null +++ b/backend/src/game/catalog.ts @@ -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 = { + plains: 'W', + island: 'U', + swamp: 'B', + mountain: 'R', + forest: 'G', +} + +let catalog: Map | 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 { + 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 +} diff --git a/backend/src/game/commander.ts b/backend/src/game/commander.ts new file mode 100644 index 0000000..018b1f3 --- /dev/null +++ b/backend/src/game/commander.ts @@ -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() + 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() + 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)] } +} diff --git a/backend/src/game/game.ts b/backend/src/game/game.ts new file mode 100644 index 0000000..1643752 --- /dev/null +++ b/backend/src/game/game.ts @@ -0,0 +1,2999 @@ +import type { + Ability, + Condition, + Cost, + Duration, + Effect, + ManaSpec, + ObjectSelector, + PlayerRef, + StaticEffect, + Target, + TokenSpec, + TriggerEvent, + Value, + Zone, +} from '../effects/types.js' +import type { + ActionOptions, + CardDefinition, + CombatAttack, + CombatBlock, + GameObject, + GameConfig, + ManaColor, + ManaPool, + PendingSearch, + Phase, + PlayerState, + StackItem, + Step, + TargetChoice, +} from './types.js' + +export class GameError extends Error {} + +type ResolvedTarget = + | { kind: 'player'; id: string } + | { kind: 'object'; object: GameObject } + | { kind: 'stack'; item: StackItem } + +interface EventContext { + kind: TriggerEvent['kind'] + player?: string + subject?: GameObject + amount?: number + counter?: string + ordinal?: number + mode?: 'gain' | 'lose' + recipient?: 'player' | 'creature' | 'permanent' | 'any' + combat?: boolean + spell?: GameObject + spellItem?: StackItem +} + +interface EffectContext { + source: GameObject + controller: string + targets: TargetChoice[] + lastTarget?: ResolvedTarget + triggerSubject?: GameObject + eventPlayer?: string + eventAmount?: number + x: number + mode: number +} + +interface ContinuousEffect { + id: string + sourceId: string + controller: string + effect: Extract + affectedIds: string[] + duration: Duration + createdTurn: number +} + +interface ManaCost { + generic: number + colored: ManaColor[] + hybrid: { colors: ManaColor[]; life: number }[] +} + +const MANA_COLORS: ManaColor[] = ['W', 'U', 'B', 'R', 'G', 'C'] +const COLOR_NAMES: Record = { + white: 'W', + blue: 'U', + black: 'B', + red: 'R', + green: 'G', + colorless: 'C', +} + +function emptyPool(): ManaPool { + return { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 } +} + +function parseManaCost(symbols: string, x = 0): ManaCost { + const cost: ManaCost = { generic: 0, colored: [], hybrid: [] } + for (const match of symbols.matchAll(/\{([^}]+)\}/g)) { + const symbol = match[1].toUpperCase() + if (/^\d+$/.test(symbol)) { + cost.generic += Number(symbol) + } else if (symbol === 'X') { + cost.generic += x + } else if (symbol === 'S') { + cost.colored.push('C') + } else if (/^[WUBRGC]$/.test(symbol)) { + cost.colored.push(symbol as ManaColor) + } else if (symbol.includes('/')) { + const parts = symbol.split('/') + const colors = parts + .filter(part => /^[WUBRG]$/.test(part)) + .map(part => part as ManaColor) + if (colors.length) cost.hybrid.push({ colors, life: parts.includes('P') ? 2 : 0 }) + else cost.generic += 1 + } else { + cost.generic += 1 + } + } + return cost +} + +function manaValueOf(definition: CardDefinition): number { + if (definition.manaValue !== undefined) return definition.manaValue + const cost = parseManaCost(definition.manaCost ?? '') + return cost.generic + cost.colored.length + cost.hybrid.length +} + +function colorOfSymbol(symbol: string): ManaColor { + const bare = symbol.replace(/[{}]/g, '').toUpperCase() + if (bare === 'S') return 'C' + if (/^[WUBRGC]$/.test(bare)) return bare as ManaColor + return 'C' +} + +function tokenCard(token: { types: string[]; subtypes: string[]; name?: string; colors: string[]; power?: number; toughness?: number; keywords?: string[] }): CardDefinition { + return { + oracleId: `token:${token.name ?? (token.subtypes.join(' ') || token.types.join(' '))}`, + name: token.name ?? (token.subtypes.map(word => word[0]?.toUpperCase() + word.slice(1)).join(' ') || 'Token'), + typeLine: [token.types.join(' '), token.subtypes.length ? `— ${token.subtypes.join(' ')}` : ''].join(' ').trim(), + manaValue: 0, + colors: token.colors, + power: token.power, + toughness: token.toughness, + abilities: (token.keywords ?? []).map(keyword => ({ kind: 'keyword', keyword })), + } +} + +/** + * A deliberately small but real Magic rules engine: zones, priority, the stack, + * turn phases, combat, state-based actions, mana, triggered/activated/static + * abilities, and an interpreter for the compiled card-effect AST. + */ +export class Game { + readonly players: PlayerState[] + readonly objects = new Map() + readonly stack: StackItem[] = [] + readonly log: string[] = [] + + turn = 0 + activePlayer = '' + phase: Phase = 'beginning' + step: Step = 'untap' + priority = '' + status: 'not_started' | 'active' | 'finished' = 'not_started' + winner?: string + /** Blocks all other actions until the searching player picks a card. */ + pendingSearch?: PendingSearch + + private readonly config: GameConfig + private readonly rng: () => number + private readonly startingHandSize: number + private readonly firstPlayer: string + private readonly continuousEffects: ContinuousEffect[] = [] + private passesInRow = 0 + private blockersDeclared = new Set() + private nextId = 0 + private autoManaDepth = 0 + private autoAdvanceDepth = 0 + private statDepth = 0 + private keywordDepth = 0 + private combatDamageDone = false + + constructor(config: GameConfig) { + if (config.players.length < 2) throw new GameError('A game needs at least two players') + const ids = new Set(config.players.map(player => player.id)) + if (ids.size !== config.players.length) throw new GameError('Player ids must be unique') + + this.config = config + this.startingHandSize = config.startingHandSize ?? 7 + this.firstPlayer = config.firstPlayer ?? config.players[0].id + if (!ids.has(this.firstPlayer)) throw new GameError(`Unknown first player: ${this.firstPlayer}`) + this.rng = config.seed === undefined ? Math.random : mulberry32(config.seed) + + const startingLife = config.startingLife ?? 40 + this.players = config.players.map(player => ({ + id: player.id, + name: player.name ?? player.id, + life: player.life ?? startingLife, + lost: false, + manaPool: emptyPool(), + library: [], + hand: [], + graveyard: [], + exile: [], + battlefield: [], + command: [], + commanderDamage: {}, + commanderCasts: {}, + landPlayedThisTurn: false, + cardsDrawnThisTurn: 0, + lifeGainedThisTurn: 0, + spellsCastThisTurn: 0, + creaturesDiedThisTurn: 0, + nonlandPermanentsEnteredThisTurn: 0, + attackedThisTurn: false, + energy: 0, + poison: 0, + })) + + for (const playerConfig of config.players) { + for (const definition of playerConfig.deck) { + const object = this.createObject(definition, playerConfig.id) + this.getPlayer(playerConfig.id).library.push(object.id) + } + if (config.commander && playerConfig.commander) { + const commander = this.createObject(playerConfig.commander, playerConfig.id) + commander.isCommander = true + commander.zone = 'command' + this.getPlayer(playerConfig.id).command.push(commander.id) + this.getPlayer(playerConfig.id).commanderId = commander.id + } + } + } + + get player(): PlayerState { + return this.getPlayer(this.activePlayer) + } + + getPlayer(id: string): PlayerState { + const player = this.players.find(entry => entry.id === id) + if (!player) throw new GameError(`Unknown player: ${id}`) + return player + } + + getObject(id: string): GameObject { + const object = this.objects.get(id) + if (!object) throw new GameError(`Unknown object: ${id}`) + return object + } + + /** Starts the game, shuffles libraries, draws opening hands, and begins turn 1. */ + start(): void { + if (this.status !== 'not_started') throw new GameError('Game already started') + for (const player of this.players) this.shuffleLibrary(player) + for (const player of this.players) { + for (let i = 0; i < this.startingHandSize; i++) { + if (!player.library.length) break + this.drawCard(player.id, true) + } + } + + this.status = 'active' + this.turn = 1 + this.activePlayer = this.firstPlayer + this.beginTurn() + } + + /** + * Adds a card directly to a zone. Intended for setup, tests, and future + * deck-building flows; by default no enter/leave triggers fire. + */ + addCard( + playerId: string, + definition: CardDefinition, + zone: Zone, + options: { controller?: string; tapped?: boolean; silent?: boolean } = {}, + ): GameObject { + const object = this.createObject(definition, playerId) + this.moveToZone(object, zone, { ...options, silent: options.silent ?? true }) + return object + } + + /** Purely cosmetic board layout: normalized center within the controller's mat. */ + movePermanent(playerId: string, cardId: string, x: number, y: number): void { + const object = this.getObject(cardId) + if (object.zone !== 'battlefield') throw new GameError('That card is not on the battlefield') + if (object.controller !== playerId) throw new GameError('You do not control that permanent') + if (!Number.isFinite(x) || !Number.isFinite(y)) throw new GameError('Invalid position') + object.position = { + x: Math.min(1, Math.max(0, x)), + y: Math.min(1, Math.max(0, y)), + } + } + + /** Moves an object to a zone, firing leave/enter triggers unless silenced. */ + moveToZone( + objectOrId: GameObject | string, + zone: Zone, + options: { controller?: string; tapped?: boolean; silent?: boolean; toTop?: boolean } = {}, + ): GameObject { + const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId + // A commander may go to the command zone instead of the graveyard, exile, + // hand, or library. This engine always takes that replacement. + const destination: Zone = object.isCommander && zone !== 'battlefield' && zone !== 'stack' && zone !== 'command' + ? 'command' + : zone + const from = object.zone + this.removeFromZone(object) + object.zone = destination + + if (destination === 'battlefield') { + object.controller = options.controller ?? object.owner + object.tapped = options.tapped ?? false + object.damage = 0 + object.deathtouched = false + object.attacking = undefined + object.blockedBy = [] + object.blocking = undefined + object.activations = {} + object.enteredTurn = this.turn + this.getPlayer(object.controller).battlefield.push(object.id) + if (from !== 'battlefield') { + if (this.turn > 0 && !this.isLand(object)) { + this.getPlayer(object.controller).nonlandPermanentsEnteredThisTurn++ + } + if (!options.silent) { + this.applyEntersReplacements(object) + this.dispatchEvent({ kind: 'enters', player: object.controller, subject: object }) + } + } + } else { + object.position = undefined + object.controller = object.owner + const owner = this.getPlayer(object.owner) + if (destination === 'hand') owner.hand.push(object.id) + else if (destination === 'graveyard') owner.graveyard.push(object.id) + else if (destination === 'exile') owner.exile.push(object.id) + else if (destination === 'command') { + object.tapped = false + owner.command.push(object.id) + } else if (destination === 'library') { + if (options.toTop) owner.library.unshift(object.id) + else owner.library.push(object.id) + } + } + + if (from === 'battlefield' && destination !== 'battlefield') { + this.handleLeavesBattlefield(object, destination) + } + + if (object.isToken && from === 'battlefield' && destination !== 'battlefield') { + this.objects.delete(object.id) + } + + return object + } + + getPower(objectOrId: GameObject | string): number { + const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId + const base = object.definition.power ?? 0 + if (this.statDepth > 0) return base + this.statDepth++ + try { + let power = base + let toughness = object.definition.toughness ?? 0 + + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'set_pt') continue + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source)) + if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source)) + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue + const context = this.continuousContext(continuous) + if (continuous.effect.power) power = this.value(continuous.effect.power, context) + if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context) + } + + const counterPower = this.counterStat(object.counters, 'power') + const counterToughness = this.counterStat(object.counters, 'toughness') + power += counterPower + toughness += counterToughness + + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'pump') continue + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + const context = this.staticContext(staticSource.source) + power += this.value(effect.power, context) + toughness += this.value(effect.toughness, context) + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue + const context = this.continuousContext(continuous) + power += this.value(continuous.effect.power, context) + toughness += this.value(continuous.effect.toughness, context) + } + return power + } finally { + this.statDepth-- + } + } + + getToughness(objectOrId: GameObject | string): number { + const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId + const base = object.definition.toughness ?? 0 + if (this.statDepth > 0) return base + this.statDepth++ + try { + let power = base + let toughness = object.definition.toughness ?? 0 + + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'set_pt') continue + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source)) + if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source)) + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue + const context = this.continuousContext(continuous) + if (continuous.effect.power) power = this.value(continuous.effect.power, context) + if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context) + } + + toughness += this.counterStat(object.counters, 'toughness') + + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'pump') continue + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + toughness += this.value(effect.toughness, this.staticContext(staticSource.source)) + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue + toughness += this.value(continuous.effect.toughness, this.continuousContext(continuous)) + } + return toughness + } finally { + this.statDepth-- + } + } + + hasKeyword(objectOrId: GameObject | string, keyword: string): boolean { + const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId + const wanted = keyword.toLowerCase() + if (this.keywordDepth > 0) { + for (const ability of object.definition.abilities ?? []) { + if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true + } + return false + } + this.keywordDepth++ + try { + for (const ability of object.definition.abilities ?? []) { + if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true + if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) { + return true + } + } + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'grant' || effect.keyword.toLowerCase() !== wanted) continue + if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) return true + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'grant' || continuous.effect.keyword.toLowerCase() !== wanted) continue + if (continuous.affectedIds.includes(object.id)) return true + } + return false + } finally { + this.keywordDepth-- + } + } + + playLand(playerId: string, cardId: string): GameObject { + this.requirePriority(playerId) + const player = this.getPlayer(playerId) + if (this.activePlayer !== playerId) throw new GameError('Only the active player may play a land') + if (this.phase !== 'precombat_main' && this.phase !== 'postcombat_main') { + throw new GameError('Lands can only be played during a main phase') + } + if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty') + if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn') + if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand') + const object = this.getObject(cardId) + if (!this.isLand(object)) throw new GameError('That card is not a land') + + player.landPlayedThisTurn = true + this.moveToZone(object, 'battlefield', { controller: playerId, silent: false }) + this.passesInRow = 0 + this.logMessage(`${player.name} plays ${object.definition.name}`) + this.runStateBasedActions() + return object + } + + castSpell(playerId: string, cardId: string, options: ActionOptions = {}): StackItem { + this.requirePriority(playerId) + if (this.status !== 'active') throw new GameError('Game is not active') + const player = this.getPlayer(playerId) + const fromCommand = player.command.includes(cardId) + if (!fromCommand && !player.hand.includes(cardId)) throw new GameError('Card is not in hand') + const object = this.getObject(cardId) + if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone') + if (this.isLand(object)) throw new GameError('Land cards are played, not cast') + if (!this.canCastAtThisTime(playerId, object)) { + throw new GameError('That spell cannot be cast right now') + } + + const abilities = object.definition.abilities ?? [] + const effects = abilities.filter((ability): ability is Extract => ability.kind === 'spell') + .flatMap(ability => ability.effects) + const targets = this.selectTargets(effects, object, playerId, options.targets ?? [], options.mode ?? 0) + const tax = fromCommand ? (player.commanderCasts[object.id] ?? 0) * 2 : 0 + this.payMana(playerId, `${object.definition.manaCost ?? ''}${'{2}'.repeat(tax / 2)}`, options.x ?? 0) + + this.moveToZone(object, 'stack', { controller: playerId, silent: true }) + if (fromCommand) player.commanderCasts[object.id] = (player.commanderCasts[object.id] ?? 0) + 1 + const item: StackItem = { + id: this.generateId('stack'), + kind: 'spell', + source: object, + controller: playerId, + label: object.definition.name, + effects, + targets, + x: options.x ?? 0, + mode: options.mode ?? 0, + } + this.stack.push(item) + player.spellsCastThisTurn++ + this.passesInRow = 0 + this.priority = this.nextAlivePlayer(playerId) + this.dispatchEvent({ kind: 'cast', player: playerId, subject: object, spell: object, spellItem: item }) + this.logMessage(`${player.name} casts ${object.definition.name}`) + return item + } + + activateAbility(playerId: string, sourceId: string, abilityIndex: number, options: ActionOptions = {}): StackItem | undefined { + this.requirePriority(playerId) + const source = this.getObject(sourceId) + if (source.zone !== 'battlefield') throw new GameError('Ability source is not on the battlefield') + if (source.controller !== playerId) throw new GameError('You do not control that permanent') + const ability = (source.definition.abilities ?? [])[abilityIndex] + if (!ability || ability.kind !== 'activated') throw new GameError('That is not an activated ability') + if (ability.condition && !this.checkCondition(ability.condition, source)) throw new GameError('Ability condition is not met') + if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) { + throw new GameError('Activate only as a sorcery') + } + if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source) + && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) { + throw new GameError('That creature has summoning sickness') + } + const activations = source.activations[abilityIndex] ?? 0 + if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) { + throw new GameError('Ability activation limit reached') + } + + const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0) + const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0) + this.payCosts(ability.costs, playerId, source, context) + source.activations[abilityIndex] = activations + 1 + + // Mana abilities bypass the stack, which also makes auto-payment possible. + if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) { + this.applyEffects(context, ability.effects) + this.passesInRow = 0 + this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`) + return undefined + } + + const item: StackItem = { + id: this.generateId('stack'), + kind: 'ability', + source, + controller: playerId, + label: ability.text, + effects: ability.effects, + targets, + x: options.x ?? 0, + mode: options.mode ?? 0, + } + this.stack.push(item) + this.passesInRow = 0 + this.priority = this.nextAlivePlayer(playerId) + this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`) + return item + } + + /** Declares attackers, beginning combat first if necessary. */ + declareAttackers(playerId: string, attacks: CombatAttack[]): void { + this.requirePriority(playerId) + if (this.stack.length) throw new GameError('Cannot declare attackers while the stack is not empty') + if (this.activePlayer !== playerId) throw new GameError('Only the active player can attack') + if (this.phase === 'precombat_main') { + this.phase = 'combat' + this.step = 'declare_attackers' + this.dispatchEvent({ kind: 'begin_combat', player: playerId }) + } + if (this.phase !== 'combat' || this.step !== 'declare_attackers') { + throw new GameError('Not in the declare attackers step') + } + + const seen = new Set() + for (const attack of attacks) { + if (seen.has(attack.attackerId)) throw new GameError('A creature can only attack once') + seen.add(attack.attackerId) + const attacker = this.getObject(attack.attackerId) + this.requireCanAttack(attacker, playerId) + const defender = this.getPlayer(attack.defenderId) + if (defender.id === playerId) throw new GameError('A player cannot attack themselves') + attacker.attacking = attack.defenderId + if (!this.hasKeyword(attacker, 'Vigilance')) attacker.tapped = true + this.getPlayer(playerId).attackedThisTurn = true + this.dispatchEvent({ kind: 'attacks', player: playerId, subject: attacker }) + } + + this.step = attacks.length ? 'declare_blockers' : 'end_combat' + this.blockersDeclared.clear() + this.passesInRow = 0 + this.priority = this.nextAlivePlayer(playerId) + this.logMessage(`${this.getPlayer(playerId).name} attacks with ${attacks.length} creature(s)`) + } + + /** Marks a player as having forfeited. */ + concede(playerId: string): void { + if (this.status !== 'active') throw new GameError('Game is not active') + this.losePlayer(playerId) + if (this.priority === playerId) this.priority = this.nextAlivePlayer(playerId) + } + + /** Declares blockers for the current combat. */ + declareBlockers(playerId: string, blocks: CombatBlock[]): void { + if (this.phase !== 'combat' || this.step !== 'declare_blockers') throw new GameError('Not in the declare blockers step') + if (this.stack.length) throw new GameError('Cannot declare blockers while the stack is not empty') + if (this.pendingSearch) throw new GameError('Choose a card from your library first') + if (this.priority !== playerId) throw new GameError('You do not have priority') + + const seen = new Set() + for (const block of blocks) { + if (seen.has(block.blockerId)) throw new GameError('A creature can only block once') + seen.add(block.blockerId) + const blocker = this.getObject(block.blockerId) + const attacker = this.getObject(block.attackerId) + if (blocker.controller !== playerId) throw new GameError('You do not control that blocker') + if (blocker.zone !== 'battlefield' || attacker.zone !== 'battlefield') throw new GameError('Object is not on the battlefield') + if (!this.isCreature(blocker)) throw new GameError('Only creatures can block') + if (blocker.tapped) throw new GameError('Tapped creatures cannot block') + if (blocker.blocking) throw new GameError('Creature is already blocking') + if (attacker.attacking !== playerId) throw new GameError('That creature is not attacking you') + if (this.hasRestriction(blocker, 'cant_block')) throw new GameError('That creature cannot block') + if (this.hasKeyword(attacker, 'Flying') && !this.hasKeyword(blocker, 'Flying') && !this.hasKeyword(blocker, 'Reach')) { + throw new GameError('That creature cannot block a flyer') + } + blocker.blocking = attacker.id + attacker.blockedBy.push(blocker.id) + this.dispatchEvent({ kind: 'blocks', player: playerId, subject: blocker }) + } + + this.blockersDeclared.add(playerId) + this.logMessage(`${this.getPlayer(playerId).name} declares ${blocks.length} blocker(s)`) + if ([...this.defendingPlayers()].every(id => this.blockersDeclared.has(id))) { + this.finishBlocking() + } else { + this.passesInRow = 0 + this.priority = this.nextAlivePlayer(playerId) + } + } + + private defendingPlayers(): Set { + return new Set(this.battlefieldObjects() + .filter(object => object.attacking) + .map(object => object.attacking as string)) + } + + private finishBlocking(): void { + this.step = 'combat_damage' + this.combatDamageDone = false + this.passesInRow = 0 + this.priority = this.activePlayer + } + + /** Resolves the combat damage step. Also runs automatically when both players pass. */ + resolveCombatDamage(): void { + if (this.phase !== 'combat' || this.step !== 'combat_damage') throw new GameError('Not in the combat damage step') + if (this.combatDamageDone) throw new GameError('Combat damage has already been dealt') + this.combatDamageDone = true + this.dealCombatDamage() + this.runStateBasedActions() + } + + /** Passes priority. When all players pass, the top of the stack resolves or the phase advances. */ + pass(playerId?: string): void { + if (this.status !== 'active') throw new GameError('Game is not active') + if (this.pendingSearch) throw new GameError('Choose a card from your library first') + const actual = playerId ?? this.priority + if (this.priority !== actual) throw new GameError('You do not have priority') + const alive = this.alivePlayers().length + this.passesInRow++ + + if (!this.stack.length && this.phase === 'combat' && this.step === 'declare_blockers') { + const defenders = this.defendingPlayers() + if (defenders.has(actual)) this.blockersDeclared.add(actual) + if ([...defenders].every(id => this.blockersDeclared.has(id))) { + this.finishBlocking() + } else { + this.priority = this.nextAlivePlayer(actual) + } + return + } + + if (this.stack.length) { + if (this.passesInRow >= alive) { + this.passesInRow = 0 + this.resolveTop() + this.priority = this.getPlayer(this.activePlayer).lost ? this.nextAlivePlayer(this.activePlayer) : this.activePlayer + } else { + this.priority = this.nextAlivePlayer(actual) + } + return + } + + if (this.passesInRow >= alive) { + this.passesInRow = 0 + this.advancePhase() + } else { + this.priority = this.nextAlivePlayer(actual) + } + } + + /** Convenience for tests and scripted games: resolve the stack without advancing phases. */ + resolveStack(): void { + let guard = 0 + while (this.stack.length && this.status === 'active' && !this.pendingSearch && guard++ < 1000) { + this.pass(this.priority) + } + } + + /** Ends the active player's turn, skipping any remaining combat. */ + endTurn(playerId: string): void { + this.requirePriority(playerId) + if (playerId !== this.activePlayer) throw new GameError('Only the active player can end the turn') + if (this.stack.length) throw new GameError('Cannot end the turn while the stack is not empty') + this.clearCombat() + this.phase = 'ending' + this.step = 'end_step' + this.dispatchEvent({ kind: 'end_step', player: playerId }) + this.resolveStack() + if (this.status !== 'active' || this.pendingSearch) return + this.finishTurn() + } + + /** + * Whether the player could legally play a card from hand or the command zone + * right now. Used for the client's playable state and for auto-passing. + */ + canPlayCard(playerId: string, cardId: string): boolean { + if (this.status !== 'active' || this.priority !== playerId || this.pendingSearch) return false + const player = this.getPlayer(playerId) + const fromCommand = player.command.includes(cardId) + if (!fromCommand && !player.hand.includes(cardId)) return false + const object = this.getObject(cardId) + if (fromCommand && !object.isCommander) return false + + if (this.isLand(object)) { + return this.activePlayer === playerId + && (this.phase === 'precombat_main' || this.phase === 'postcombat_main') + && !this.stack.length + && !player.landPlayedThisTurn + } + + if (!this.canCastAtThisTime(playerId, object)) return false + const tax = fromCommand ? (player.commanderCasts[cardId] ?? 0) * 2 : 0 + if (!this.canAffordMana(playerId, `${object.definition.manaCost ?? ''}${'{2}'.repeat(tax / 2)}`, 0)) { + return false + } + return this.hasLegalTargets(object, playerId) + } + + /** + * Finishes one pick of a paused library search. Searches pause when several + * cards match so the player chooses instead of taking the first one. + */ + chooseSearchCard(playerId: string, cardId: string): void { + const pending = this.pendingSearch + if (!pending) throw new GameError('No search is waiting for a choice') + if (pending.playerId !== playerId) throw new GameError('You are not searching your library') + const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId) + if (!object) throw new GameError('That card is not a legal choice') + + this.moveSearchedCard(object, playerId, pending.destination, pending.tapped) + pending.remaining-- + if (pending.remaining <= 0 || !this.searchCandidates(playerId).length) { + this.pendingSearch = undefined + if (pending.shuffle) this.shuffleLibrary(this.getPlayer(playerId)) + this.priority = this.getPlayer(this.activePlayer).lost + ? this.nextAlivePlayer(this.activePlayer) + : this.activePlayer + } + this.runStateBasedActions() + } + + /** Cards the pending search may pick, in library order. Empty for other players. */ + searchCandidates(playerId: string): GameObject[] { + const pending = this.pendingSearch + if (!pending || pending.playerId !== playerId) return [] + return this.findSearchCandidates(playerId, pending.selector, pending.zones) + } + + /** + * Passes priority for players who cannot do anything meaningful. Stops at the + * first player who can act, or when the turn ends, so turns never run on. + */ + autoAdvance(): void { + if (this.status !== 'active' || this.pendingSearch || this.autoAdvanceDepth > 0) return + this.autoAdvanceDepth++ + const turn = this.turn + try { + let guard = 0 + while (this.status === 'active' && !this.pendingSearch && this.turn === turn && guard++ < 100) { + const actor = this.priority + if (!actor || this.hasMeaningfulAction(actor)) break + this.pass(actor) + } + } finally { + this.autoAdvanceDepth-- + } + } + + // --------------------------------------------------------------------------- + // Turn structure + // --------------------------------------------------------------------------- + + private beginTurn(): void { + const player = this.getPlayer(this.activePlayer) + this.phase = 'beginning' + this.step = 'untap' + this.passesInRow = 0 + this.priority = player.id + player.landPlayedThisTurn = false + player.cardsDrawnThisTurn = 0 + player.lifeGainedThisTurn = 0 + player.spellsCastThisTurn = 0 + player.creaturesDiedThisTurn = 0 + player.nonlandPermanentsEnteredThisTurn = 0 + player.attackedThisTurn = false + player.manaPool = emptyPool() + + this.removeExpiringEffects(player.id) + for (const id of [...player.battlefield]) { + const object = this.objects.get(id) + if (!object || object.zone !== 'battlefield') continue + if (!this.hasRestriction(object, 'doesnt_untap')) object.tapped = false + } + + this.step = 'upkeep' + this.dispatchEvent({ kind: 'upkeep', player: player.id }) + if (this.status !== 'active') return + + this.step = 'draw' + // The first player skips their first draw step, as in Commander. + if (this.turn > 1) { + this.drawCard(player.id, false) + if (this.status !== 'active') return + } + + this.phase = 'precombat_main' + this.step = 'main' + this.priority = player.id + this.passesInRow = 0 + } + + private finishTurn(): void { + const player = this.getPlayer(this.activePlayer) + while (player.hand.length > 7) { + const cardId = player.hand[player.hand.length - 1] + this.moveToZone(cardId, 'graveyard', { silent: true }) + } + for (const object of this.objects.values()) { + if (object.zone === 'battlefield') { + object.damage = 0 + object.deathtouched = false + } + } + this.removeEffectsByDuration('until_end_of_turn') + this.removeEndOfNextTurnEffects(player.id) + this.clearCombat() + for (const entry of this.players) entry.manaPool = emptyPool() + + if (this.status !== 'active') return + this.turn++ + this.activePlayer = this.nextAlivePlayer(this.activePlayer) + this.beginTurn() + } + + private advancePhase(): void { + if (this.status !== 'active') return + if (this.stack.length) return + this.emptyManaPools() + + if (this.step === 'main' && this.phase === 'precombat_main') { + this.phase = 'combat' + this.step = 'begin_combat' + this.dispatchEvent({ kind: 'begin_combat', player: this.activePlayer }) + this.step = 'declare_attackers' + this.priority = this.activePlayer + this.passesInRow = 0 + return + } + if (this.step === 'declare_attackers') { + this.step = 'end_combat' + this.passesInRow = 0 + this.priority = this.activePlayer + return + } + if (this.step === 'declare_blockers') { + this.step = 'combat_damage' + this.combatDamageDone = false + this.passesInRow = 0 + this.priority = this.activePlayer + return + } + if (this.step === 'combat_damage') { + this.combatDamageDone = true + this.dealCombatDamage() + this.runStateBasedActions() + this.passesInRow = 0 + this.priority = this.activePlayer + return + } + if (this.step === 'end_combat') { + this.clearCombat() + this.removeEffectsByDuration('until_end_of_combat') + this.phase = 'postcombat_main' + this.step = 'main' + this.passesInRow = 0 + this.priority = this.activePlayer + return + } + if (this.step === 'main' && this.phase === 'postcombat_main') { + this.phase = 'ending' + this.step = 'end_step' + this.dispatchEvent({ kind: 'end_step', player: this.activePlayer }) + this.passesInRow = 0 + this.priority = this.activePlayer + return + } + if (this.step === 'end_step') { + this.finishTurn() + } + } + + private clearCombat(): void { + this.blockersDeclared.clear() + for (const object of this.objects.values()) { + if (object.zone !== 'battlefield') continue + object.attacking = undefined + object.blockedBy = [] + object.blocking = undefined + } + this.combatDamageDone = false + } + + // --------------------------------------------------------------------------- + // Stack + // --------------------------------------------------------------------------- + + private resolveTop(): void { + const item = this.stack.pop() + if (!item) return + if (item.kind === 'spell' && item.source.zone !== 'stack') return + + const context = this.contextFor( + item.source, + item.controller, + item.targets, + item.x, + item.mode, + item.triggerSubject, + item.eventPlayer, + item.eventAmount, + ) + + if (item.kind === 'spell') { + if (this.isPermanent(item.source)) { + if (item.source.zone === 'stack') { + this.moveToZone(item.source, 'battlefield', { controller: item.controller, silent: false }) + } + this.applyEffects(context, item.effects) + } else { + this.applyEffects(context, item.effects) + if (item.source.zone === 'stack') this.moveToZone(item.source, 'graveyard', { silent: true }) + } + } else { + this.applyEffects(context, item.effects) + } + + this.logMessage(`Resolved ${item.label}`) + this.runStateBasedActions() + } + + private counterStackItem(item: StackItem): void { + const index = this.stack.indexOf(item) + if (index >= 0) this.stack.splice(index, 1) + if (item.kind === 'spell' && item.source.zone === 'stack') { + this.moveToZone(item.source, 'graveyard', { silent: true }) + } + this.logMessage(`Countered ${item.label}`) + } + + // --------------------------------------------------------------------------- + // Casting, mana, and costs + // --------------------------------------------------------------------------- + + private canCastAtThisTime(playerId: string, object: GameObject): boolean { + const instant = this.isInstant(object) + const flash = this.hasKeywordForDefinition(object.definition, 'Flash') + if (instant || flash) return true + return this.isMainPhaseWithEmptyStack(playerId) + } + + private isMainPhaseWithEmptyStack(playerId: string): boolean { + return this.activePlayer === playerId + && (this.phase === 'precombat_main' || this.phase === 'postcombat_main') + && this.step === 'main' + && this.stack.length === 0 + } + + private payMana(playerId: string, symbols: string, x: number): void { + if (!symbols) return + const player = this.getPlayer(playerId) + const cost = parseManaCost(symbols, x) + const pool = { ...player.manaPool } + const tapped = player.battlefield + .map(id => this.objects.get(id)) + .filter((object): object is GameObject => Boolean(object?.tapped)) + .map(object => object.id) + this.autoTapForMana(player, cost) + if (!this.canPayMana(player, cost)) { + player.manaPool = pool + for (const id of player.battlefield) { + const object = this.objects.get(id) + if (object) object.tapped = tapped.includes(id) + } + throw new GameError('Not enough mana') + } + this.deductMana(player, cost) + } + + private canPayMana(player: PlayerState, cost: ManaCost): boolean { + const pool = { ...player.manaPool } + const payColor = (color: ManaColor): boolean => { + if (pool[color] <= 0) return false + pool[color]-- + return true + } + for (const color of cost.colored) { + if (!payColor(color)) return false + } + for (const hybrid of cost.hybrid) { + const color = hybrid.colors.find(entry => pool[entry] > 0) + if (color) pool[color]-- + else if (!(hybrid.life > 0 && player.life >= hybrid.life)) return false + } + const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + return remaining >= cost.generic + } + + private deductMana(player: PlayerState, cost: ManaCost): void { + for (const color of cost.colored) player.manaPool[color]-- + for (const hybrid of cost.hybrid) { + const color = hybrid.colors.find(entry => player.manaPool[entry] > 0) + if (color) player.manaPool[color]-- + else if (hybrid.life > 0) this.loseLife(player.id, hybrid.life) + else throw new GameError('Not enough mana') + } + let generic = cost.generic + for (const color of MANA_COLORS) { + const used = Math.min(player.manaPool[color], generic) + player.manaPool[color] -= used + generic -= used + } + if (generic > 0) throw new GameError('Not enough mana') + } + + private autoTapForMana(player: PlayerState, cost: ManaCost): void { + if (this.autoManaDepth > 0) return + let guard = 0 + while (!this.canPayMana(player, cost) && guard++ < 25) { + const source = this.players + .flatMap(entry => entry.battlefield) + .map(id => this.objects.get(id)) + .find((object): object is GameObject => Boolean(object && object.zone === 'battlefield' + && object.controller === player.id + && !object.tapped + && this.findFreeManaAbility(object) !== undefined)) + if (!source) break + this.autoManaDepth++ + try { + this.activateManaSource(source, cost) + } finally { + this.autoManaDepth-- + } + } + } + + private findFreeManaAbility(source: GameObject): { index: number; ability: Extract } | undefined { + const abilities = source.definition.abilities ?? [] + for (let index = 0; index < abilities.length; index++) { + const ability = abilities[index] + if (ability.kind !== 'activated') continue + if (!ability.effects.length || !ability.effects.every(effect => effect.op === 'add_mana')) continue + if (ability.costs.length !== 1 || ability.costs[0].kind !== 'tap') continue + if (source.tapped) continue + if (this.isCreature(source) && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) continue + return { index, ability } + } + return undefined + } + + private activateManaSource(source: GameObject, cost: ManaCost): void { + const found = this.findFreeManaAbility(source) + if (!found) return + const player = this.getPlayer(source.controller) + for (const entry of found.ability.costs) { + if (entry.kind === 'tap') source.tapped = true + } + const color = this.neededColor(player, cost) + for (const effect of found.ability.effects) { + if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color) + } + } + + private neededColor(player: PlayerState, cost: ManaCost): ManaColor { + for (const color of cost.colored) { + if (player.manaPool[color] <= 0) return color + } + const hybridColor = cost.hybrid.flatMap(entry => entry.colors).find(color => player.manaPool[color] <= 0) + return hybridColor ?? 'W' + } + + private addMana(playerId: string, mana: ManaSpec, preferred: ManaColor = 'W'): void { + const player = this.getPlayer(playerId) + if (mana.kind === 'symbols') { + for (const symbol of mana.symbols) player.manaPool[colorOfSymbol(symbol)]++ + } else { + const amount = this.value(mana.amount, { + source: this.playerSource(playerId), + controller: playerId, + targets: [], + x: 0, + mode: 0, + }) + for (let i = 0; i < amount; i++) player.manaPool[preferred]++ + } + } + + private payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void { + for (const cost of costs) { + if (cost.kind !== 'mana' && !this.canPayNonManaCost(cost, playerId, source)) { + throw new GameError('Cannot pay ability cost') + } + } + for (const cost of costs) { + if (cost.kind === 'mana') this.payMana(playerId, cost.symbols, context.x) + else this.payNonManaCost(cost, playerId, source, context) + } + } + + private canPayNonManaCost(cost: Cost, playerId: string, source: GameObject): boolean { + const player = this.getPlayer(playerId) + switch (cost.kind) { + case 'tap': + return !source.tapped + case 'untap': + return source.tapped + case 'tap_other': + return this.objectsMatching(cost.selector, source).some(object => !object.tapped) + case 'energy': + return player.energy >= cost.amount + case 'pay_life': + return player.life > this.value(cost.amount, this.staticContext(source)) + case 'discard': + return player.hand.length >= this.value(cost.amount, this.staticContext(source)) + case 'sacrifice': + return this.objectsMatching(cost.selector, source).length > 0 + case 'sacrifice_self': + return source.zone === 'battlefield' + case 'exile_self': + return source.zone === 'graveyard' + case 'exile_from_graveyard': + return this.objectsMatching(cost.selector, source).length > 0 + case 'return_to_hand': + return this.objectsMatching(cost.selector, source).length > 0 + case 'put_counter': + return this.objectsMatching(cost.selector, source).length > 0 + case 'remove_counters': { + const amount = this.value(cost.amount, this.staticContext(source)) + const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source] + return objects.some(object => (object.counters[cost.counter] ?? 0) >= amount) + } + case 'mill': + return player.library.length >= (cost.amount.kind === 'number' ? cost.amount.value : 0) + case 'choice': + return cost.options.some(option => option.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source))) + case 'waterbend': + return this.canPayMana(player, parseManaCost('{0}', 0)) + case 'reveal': + case 'behold': + case 'choose': + return true + default: + return false + } + } + + private payNonManaCost(cost: Cost, playerId: string, source: GameObject, context: EffectContext): void { + const player = this.getPlayer(playerId) + switch (cost.kind) { + case 'tap': + source.tapped = true + return + case 'untap': + source.tapped = false + return + case 'tap_other': { + const target = this.objectsMatching(cost.selector, source).find(object => !object.tapped) + if (!target) throw new GameError('No permanent to tap') + target.tapped = true + return + } + case 'energy': + player.energy -= cost.amount + return + case 'loyalty': + this.addCounters(source, 'loyalty', cost.amount, true) + return + case 'pay_life': + this.loseLife(playerId, this.value(cost.amount, context)) + return + case 'discard': { + const amount = this.value(cost.amount, context) + this.discardCards(playerId, amount, cost.random, context) + return + } + case 'sacrifice': { + const target = this.objectsMatching(cost.selector, source)[0] + if (!target) throw new GameError('No permanent to sacrifice') + this.moveToZone(target, 'graveyard', { silent: false }) + return + } + case 'sacrifice_self': + this.moveToZone(source, 'graveyard', { silent: false }) + return + case 'exile_self': + this.moveToZone(source, 'exile', { silent: false }) + return + case 'exile_from_graveyard': { + const target = this.objectsMatching(cost.selector, source)[0] + if (!target) throw new GameError('No card to exile') + this.moveToZone(target, 'exile', { silent: false }) + return + } + case 'return_to_hand': { + const target = this.objectsMatching(cost.selector, source)[0] + if (!target) throw new GameError('No permanent to return') + this.moveToZone(target, 'hand', { silent: false }) + return + } + case 'put_counter': { + const target = this.objectsMatching(cost.selector, source)[0] + if (!target) throw new GameError('No permanent for counter') + this.addCounters(target, cost.counter, 1) + return + } + case 'remove_counters': { + const amount = this.value(cost.amount, context) + const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source] + const target = objects.find(object => (object.counters[cost.counter] ?? 0) >= amount) + if (!target) throw new GameError('No counters to remove') + target.counters[cost.counter] = Math.max(0, (target.counters[cost.counter] ?? 0) - amount) + return + } + case 'mill': + this.millCards(playerId, this.value(cost.amount, context)) + return + case 'reveal': + case 'behold': + case 'choose': + return + case 'choice': { + const option = cost.options.find(entries => entries.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source))) + if (!option) throw new GameError('No payable cost choice') + this.payCosts(option, playerId, source, context) + return + } + case 'waterbend': + case 'blight': + case 'forage': + case 'collect_evidence': + throw new GameError(`Unsupported cost: ${cost.kind}`) + default: + throw new GameError(`Unsupported cost: ${(cost as { kind: string }).kind}`) + } + } + + // --------------------------------------------------------------------------- + // Targeting + // --------------------------------------------------------------------------- + + private selectTargets( + effects: Effect[], + source: GameObject, + controller: string, + provided: TargetChoice[], + mode: number, + ): TargetChoice[] { + const selected: TargetChoice[] = [] + const queue = [...provided] + + const take = (target: Target, playerOnly: 'opponent' | 'any' | undefined): void => { + if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target') return + if (target.kind === 'object' && target.mode === 'each') return + if (target.kind === 'player' && target.mode === 'each') return + const count = target.kind === 'object' ? target.count ?? 1 : 1 + const upTo = target.kind === 'object' && Boolean(target.upTo) + for (let i = 0; i < count; i++) { + const explicit = queue.shift() + if (explicit) { + if (!this.targetChoiceMatches(explicit, target, source, playerOnly)) throw new GameError('Invalid target') + selected.push(explicit) + continue + } + const legal = this.legalTargets(target, source, controller, playerOnly) + if (!legal.length) { + if (upTo) break + throw new GameError('No legal target') + } + selected.push(legal[0]) + } + } + + const walk = (list: Effect[]): void => { + for (const effect of list) { + if (effect.op === 'conditional') { + walk(effect.effects) + continue + } + if (effect.op === 'modal') { + const chosen = effect.modes[mode] ?? effect.modes[0] ?? [] + walk(chosen) + continue + } + if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) { + const who = effect.player === 'opponent' ? 'opponent' : 'any' + take({ kind: 'player', who: effect.player, mode: 'target' }, who) + } + if ('target' in effect && effect.target) take(effect.target, undefined) + if (effect.op === 'fight') { + take(effect.a, undefined) + take(effect.b, undefined) + } + if (effect.op === 'damage_divided') take(effect.target, undefined) + } + } + walk(effects) + return selected + } + + private legalTargets( + target: Target, + source: GameObject, + controller: string, + playerOnly: 'opponent' | 'any' | undefined, + ): TargetChoice[] { + switch (target.kind) { + case 'object': { + return this.objectsMatching(target.selector, source) + .map(object => ({ kind: 'object' as const, id: object.id })) + } + case 'player': { + const players = playerOnly === 'opponent' ? this.opponentsOf(controller) : this.alivePlayers().map(player => player.id) + return players.map(id => ({ kind: 'player' as const, id })) + } + case 'player_or_planeswalker': { + const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) + for (const object of this.battlefieldObjects()) { + if (this.hasType(object, 'planeswalker')) choices.push({ kind: 'object', id: object.id }) + } + return choices + } + case 'any': { + const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) + for (const object of this.battlefieldObjects()) choices.push({ kind: 'object', id: object.id }) + return choices + } + case 'spell': + return [...this.stack].reverse() + .filter(item => item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack')) + .map(item => ({ kind: 'spell' as const, id: item.id })) + case 'ability': + return [...this.stack].reverse() + .filter(item => item.kind === 'ability') + .map(item => ({ kind: 'spell' as const, id: item.id })) + case 'divided': + return this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) + default: + return [] + } + } + + private targetChoiceMatches( + choice: TargetChoice, + target: Target, + source: GameObject, + playerOnly: 'opponent' | 'any' | undefined, + ): boolean { + const isOpponent = (id: string): boolean => this.opponentsOf(source.controller).includes(id) + if (choice.kind === 'player') { + if (target.kind === 'any' || target.kind === 'player' || target.kind === 'player_or_planeswalker') { + return playerOnly !== 'opponent' || isOpponent(choice.id) + } + return false + } + if (choice.kind === 'object') { + const object = this.objects.get(choice.id) + if (!object) return false + if (target.kind === 'any' || target.kind === 'player_or_planeswalker') { + return target.kind === 'any' ? object.zone === 'battlefield' : this.hasType(object, 'planeswalker') + } + if (target.kind !== 'object') return false + return this.matchesSelector(object, target.selector, source) + } + if (choice.kind === 'spell') { + const item = this.findStackItem(choice.id) + if (!item) return false + if (target.kind === 'spell') { + return item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack') + } + return target.kind === 'ability' && item.kind === 'ability' + } + return false + } + + private resolveTargets(context: EffectContext, target: Target): ResolvedTarget[] { + let result: ResolvedTarget[] = [] + switch (target.kind) { + case 'self': + result = [{ kind: 'object', object: context.source }] + break + case 'trigger_subject': + if (context.triggerSubject) result = [{ kind: 'object', object: context.triggerSubject }] + break + case 'previous_target': + if (context.lastTarget) result = [context.lastTarget] + break + case 'object': + if (target.mode === 'each') { + result = this.objectsMatching(target.selector, context.source) + .map(object => ({ kind: 'object' as const, object })) + } else { + const count = target.count ?? 1 + for (let i = 0; i < count; i++) { + const choice = context.targets.shift() + if (!choice) break + if (choice.kind === 'object') { + const object = this.objects.get(choice.id) + if (object) result.push({ kind: 'object', object }) + } + } + } + break + case 'player': + if (target.mode === 'each') { + result = this.playersForEffect(target.who, context).map(id => ({ kind: 'player' as const, id })) + } else { + const choice = context.targets.shift() + if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] + else { + const id = this.playersForEffect(target.who, context)[0] + if (id) result = [{ kind: 'player', id }] + } + } + break + case 'player_or_planeswalker': + case 'any': { + const choice = context.targets.shift() + if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] + else if (choice?.kind === 'object') { + const object = this.objects.get(choice.id) + if (object) result = [{ kind: 'object', object }] + } + break + } + case 'spell': + case 'ability': { + const choice = context.targets.shift() + if (choice?.kind === 'spell') { + const item = this.findStackItem(choice.id) + if (item) result = [{ kind: 'stack', item }] + } + break + } + case 'divided': { + const choice = context.targets.shift() + if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] + else if (choice?.kind === 'object') { + const object = this.objects.get(choice.id) + if (object) result = [{ kind: 'object', object }] + } + break + } + } + if (result.length) context.lastTarget = result[0] + return result + } + + private playersForEffect(ref: PlayerRef, context: EffectContext): string[] { + const controller = context.source.controller + switch (ref) { + case 'you': + return [controller] + case 'opponent': { + const choice = context.targets.shift() + if (choice?.kind === 'player') return [choice.id] + return [this.opponentsOf(controller)[0]].filter(Boolean) + } + case 'each_opponent': + return this.opponentsOf(controller) + case 'each_player': + return this.alivePlayers().map(player => player.id) + case 'target_player': { + const choice = context.targets.shift() + return [choice?.kind === 'player' ? choice.id : undefined].filter((id): id is string => Boolean(id)) + } + case 'that_player': + return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean) + case 'its_controller': + return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : [] + case 'its_owner': + return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : [] + } + } + + private playersForValue(ref: PlayerRef, context: EffectContext): string[] { + const controller = context.source.controller + switch (ref) { + case 'you': + return [controller] + case 'opponent': + return [this.opponentsOf(controller)[0]].filter(Boolean) + case 'each_opponent': + return this.opponentsOf(controller) + case 'each_player': + return this.alivePlayers().map(player => player.id) + case 'target_player': + return [context.lastTarget?.kind === 'player' ? context.lastTarget.id : this.opponentsOf(controller)[0]].filter(Boolean) + case 'that_player': + return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean) + case 'its_controller': + return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : [] + case 'its_owner': + return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : [] + } + } + + // --------------------------------------------------------------------------- + // Effects + // --------------------------------------------------------------------------- + + private applyEffects(context: EffectContext, effects: Effect[]): void { + for (const effect of effects) { + if (this.status === 'finished') return + switch (effect.op) { + case 'damage': { + const targets = this.resolveTargets(context, effect.target) + const amount = Math.max(0, this.value(effect.amount, context)) + let source = context.source + if (effect.source) { + const sourceTarget = this.resolveTargets(context, effect.source)[0] + if (sourceTarget?.kind === 'object') source = sourceTarget.object + } + for (const target of targets) this.damageTarget(target, amount, source, false) + break + } + case 'draw': { + const amount = this.value(effect.amount, context) + for (const playerId of this.playersForEffect(effect.player, context)) this.drawCards(playerId, amount) + break + } + case 'discard': { + const amount = this.value(effect.amount, context) + for (const playerId of this.playersForEffect(effect.player, context)) { + this.discardCards(playerId, amount, effect.random, context) + } + break + } + case 'mill': { + const amount = this.value(effect.amount, context) + for (const playerId of this.playersForEffect(effect.player, context)) this.millCards(playerId, amount) + break + } + case 'life': { + const amount = this.value(effect.amount, context) + for (const playerId of this.playersForEffect(effect.player, context)) { + if (effect.mode === 'gain') this.gainLife(playerId, amount) + else this.loseLife(playerId, amount) + } + break + } + case 'pump': { + const targets = this.resolveTargets(context, effect.target) + const ids = targets.filter((target): target is Extract => target.kind === 'object') + .map(target => target.object.id) + this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) + break + } + case 'set_pt': { + const targets = this.resolveTargets(context, effect.target) + const ids = targets.filter((target): target is Extract => target.kind === 'object') + .map(target => target.object.id) + this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) + break + } + case 'grant': { + const targets = this.resolveTargets(context, effect.target) + const ids = targets.filter((target): target is Extract => target.kind === 'object') + .map(target => target.object.id) + this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) + break + } + case 'put_counters': { + const amount = this.value(effect.amount, context) + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') this.addCounters(target.object, effect.counter, amount) + } + break + } + case 'remove_counters': { + const amount = this.value(effect.amount, context) + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind !== 'object') continue + target.object.counters[effect.counter] = Math.max(0, (target.object.counters[effect.counter] ?? 0) - amount) + } + break + } + case 'proliferate': { + for (const object of this.battlefieldObjects()) { + for (const counter of Object.keys(object.counters)) { + if (object.counters[counter] > 0) object.counters[counter]++ + } + } + break + } + case 'create_token': { + const amount = Math.max(0, this.value(effect.amount, context)) + const players = this.playersForEffect(effect.player, context) + for (const playerId of players) { + for (let i = 0; i < amount; i++) { + if (effect.copyOf) { + const source = this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object') + if (source?.kind === 'object') this.createTokenCopy(playerId, source.object, effect.notLegendary) + } else { + this.createToken(playerId, effect.token, context) + } + } + } + break + } + case 'destroy': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') this.destroyPermanent(target.object) + } + break + } + case 'exile': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') this.moveToZone(target.object, 'exile', { silent: false }) + } + break + } + case 'sacrifice': { + const players = this.playersForEffect(effect.player, context) + if (effect.unless && this.tryPayUnless(effect.unless, players[0], context.source, context)) break + const targets = this.resolveTargets(context, effect.target) + for (const target of targets) { + if (target.kind === 'object' && players.includes(target.object.controller)) { + this.moveToZone(target.object, 'graveyard', { silent: false }) + } + } + break + } + case 'counter': { + if (effect.unless && this.tryPayUnless(effect.unless, context.controller, context.source, context)) break + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'stack') this.counterStackItem(target.item) + } + break + } + case 'return_to_hand': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') this.moveToZone(target.object, 'hand', { silent: false }) + } + break + } + case 'return_to_battlefield': { + const targets = this.resolveTargets(context, effect.target) + for (const target of targets) { + if (target.kind !== 'object') continue + this.moveToZone(target.object, 'battlefield', { + controller: context.controller, + tapped: effect.tapped, + silent: false, + }) + if (effect.counters) { + this.addCounters(target.object, effect.counters.counter, this.value(effect.counters.amount, context)) + } + } + break + } + case 'put_on_top': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') this.moveToZone(target.object, 'library', { toTop: true, silent: false }) + } + break + } + case 'tap': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') target.object.tapped = true + } + break + } + case 'untap': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') target.object.tapped = false + } + break + } + case 'scry': + case 'surveil': + break + case 'search': { + const amount = Math.max(0, this.value(effect.amount, context)) + for (const playerId of this.playersForEffect(effect.player, context)) { + this.searchLibrary(playerId, effect.selector, amount, effect.destination, effect.tapped, effect.shuffle, effect.zones) + } + break + } + case 'shuffle': { + for (const playerId of this.playersForEffect(effect.player, context)) this.shuffleLibrary(this.getPlayer(playerId)) + break + } + case 'add_mana': { + for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana) + break + } + case 'fight': { + const a = this.resolveTargets(context, effect.a)[0] + const b = this.resolveTargets(context, effect.b)[0] + if (a?.kind === 'object' && b?.kind === 'object') { + const aPower = this.getPower(a.object) + const bPower = this.getPower(b.object) + this.damageTarget({ kind: 'object', object: a.object }, bPower, b.object, false) + this.damageTarget({ kind: 'object', object: b.object }, aPower, a.object, false) + } + break + } + case 'regenerate': { + for (const target of this.resolveTargets(context, effect.target)) { + if (target.kind === 'object') target.object.regenerationShields++ + } + break + } + case 'energy': { + const amount = this.value(effect.amount, context) + for (const playerId of this.playersForEffect(effect.player, context)) this.getPlayer(playerId).energy += amount + break + } + case 'attach': { + const target = this.resolveTargets(context, effect.target)[0] + if (target?.kind === 'object') this.attach(context.source, target.object) + break + } + case 'restriction': { + const targets = this.resolveTargets(context, effect.target) + const ids = targets.filter((target): target is Extract => target.kind === 'object') + .map(target => target.object.id) + this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) + break + } + case 'keyword_action': + break + case 'prevent_damage': + case 'gain_control': + case 'emblem': + case 'transform': + case 'schedule': + case 'level_up': + case 'put_from_among': + case 'look_top': + break + case 'pay': + try { + this.payCosts(effect.costs, context.controller, context.source, context) + } catch { + // "You may pay" — doing nothing is the legal choice when it is not payable. + } + break + case 'conditional': + if (this.checkCondition(effect.condition, context.source)) this.applyEffects(context, effect.effects) + break + case 'modal': { + const chosen = effect.modes[context.mode] ?? effect.modes[0] + if (chosen) this.applyEffects(context, chosen) + break + } + case 'dig': + this.dig(context, effect) + break + case 'damage_divided': { + const targets = this.resolveTargets(context, effect.target) + const amount = this.value(effect.amount, context) + if (targets.length) { + const each = Math.floor(amount / targets.length) + for (const target of targets) this.damageTarget(target, each, context.source, false) + } + break + } + } + } + } + + private dig( + context: EffectContext, + effect: Extract, + ): void { + const player = this.getPlayer(context.controller) + const amount = this.value(effect.amount, context) + const top = player.library.slice(0, amount).map(id => this.getObject(id)) + const pickCount = this.value(effect.pick, context) + const picked = top.filter(object => !effect.pickSelector || this.matchesSelector(object, effect.pickSelector, context.source, 'library')) + .slice(0, pickCount) + for (const object of picked) { + if (effect.to === 'battlefield') { + this.moveToZone(object, 'battlefield', { controller: context.controller, tapped: effect.tapped, silent: false }) + } else { + this.moveToZone(object, 'hand', { silent: false }) + } + } + for (const object of top) { + if (picked.includes(object)) continue + if (effect.rest === 'graveyard') this.moveToZone(object, 'graveyard', { silent: false }) + else if (effect.rest === 'bottom') this.moveToZone(object, 'library', { silent: true }) + else this.moveToZone(object, 'library', { toTop: true, silent: true }) + } + } + + private tryPayUnless(cost: Cost, playerId: string | undefined, source: GameObject, context: EffectContext): boolean { + if (!playerId) return false + try { + if (cost.kind === 'mana') { + this.payMana(playerId, cost.symbols, context.x) + } else { + if (!this.canPayNonManaCost(cost, playerId, source)) return false + this.payNonManaCost(cost, playerId, source, context) + } + return true + } catch { + return false + } + } + + private addContinuousEffect( + source: GameObject, + controller: string, + effect: Extract, + affectedIds: string[], + duration: Duration, + ): void { + this.continuousEffects.push({ + id: this.generateId('effect'), + sourceId: source.id, + controller, + effect, + affectedIds, + duration, + createdTurn: this.turn, + }) + } + + private continuousContext(effect: ContinuousEffect): EffectContext { + const source = this.objects.get(effect.sourceId) ?? this.playerSource(effect.controller) + return this.contextFor(source, effect.controller, [], 0, 0) + } + + private staticContext(source: GameObject): EffectContext { + return this.contextFor(source, source.controller, [], 0, 0) + } + + private contextFor( + source: GameObject, + controller: string, + targets: TargetChoice[], + x: number, + mode: number, + triggerSubject?: GameObject, + eventPlayer?: string, + eventAmount?: number, + ): EffectContext { + return { source, controller, targets: [...targets], x, mode, triggerSubject, eventPlayer, eventAmount } + } + + private value(value: Value, context: EffectContext): number { + switch (value.kind) { + case 'number': + return value.value + case 'x': + return context.x + case 'count': + return this.objectsMatching(value.selector, context.source).length + case 'source_power': + return this.getPower(context.source) + case 'source_toughness': + return this.getToughness(context.source) + case 'cards_in_hand': { + const playerId = this.playersForValue(value.player, context)[0] + return playerId ? this.getPlayer(playerId).hand.length : 0 + } + case 'max_cards_in_hand': + return Math.max(...this.alivePlayers().map(player => player.hand.length), 0) + case 'max_opponent_count': + return Math.max(...this.opponentsOf(context.source.controller).map(playerId => this.objectsMatching(value.selector, context.source) + .filter(object => object.controller === playerId).length), 0) + case 'total_mana_value': + return this.objectsMatching(value.selector, context.source) + .reduce((total, object) => total + manaValueOf(object.definition), 0) + case 'total_power': + return this.objectsMatching(value.selector, context.source) + .reduce((total, object) => total + this.getPower(object), 0) + case 'any_number': + return 0 + case 'event_amount': + return context.eventAmount ?? 0 + } + } + + private damageTarget( + target: ResolvedTarget, + amount: number, + source: GameObject, + combat: boolean, + ): void { + if (amount <= 0) return + if (target.kind === 'player') { + if (combat && source.isCommander) { + const defender = this.getPlayer(target.id) + defender.commanderDamage[source.id] = (defender.commanderDamage[source.id] ?? 0) + amount + } + this.loseLife(target.id, amount) + this.dispatchEvent({ kind: 'deals_damage', player: source.controller, subject: source, recipient: 'player', amount, combat }) + } else if (target.kind === 'object') { + const object = target.object + if (object.zone !== 'battlefield') return + object.damage += amount + if (this.hasKeyword(source, 'Deathtouch')) object.deathtouched = true + this.dispatchEvent({ + kind: 'deals_damage', + player: source.controller, + subject: source, + recipient: this.isCreature(object) ? 'creature' : 'permanent', + amount, + combat, + }) + } + if (this.hasKeyword(source, 'Lifelink')) this.gainLife(source.controller, amount) + } + + private destroyPermanent(object: GameObject): void { + if (object.zone !== 'battlefield') return + if (this.hasKeyword(object, 'Indestructible')) return + if (object.regenerationShields > 0) { + object.regenerationShields-- + object.tapped = true + object.damage = 0 + object.deathtouched = false + object.attacking = undefined + object.blockedBy = [] + object.blocking = undefined + return + } + this.moveToZone(object, 'graveyard', { silent: false }) + } + + private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject { + const definition = tokenCard({ + ...spec, + power: spec.power ? this.value(spec.power, context) : undefined, + toughness: spec.toughness ? this.value(spec.toughness, context) : undefined, + }) + const player = this.getPlayer(playerId) + const object: GameObject = { + id: this.generateId('token'), + definition, + owner: playerId, + controller: playerId, + zone: 'battlefield', + tapped: false, + damage: 0, + deathtouched: false, + counters: {}, + isToken: true, + token: spec, + enteredTurn: this.turn, + blockedBy: [], + attachments: [], + regenerationShields: 0, + activations: {}, + } + this.objects.set(object.id, object) + this.moveToZone(object, 'battlefield', { controller: playerId, tapped: spec.tapped ?? false, silent: false }) + return object + } + + private createTokenCopy(playerId: string, source: GameObject, notLegendary = false): GameObject { + const definition = notLegendary + ? { ...source.definition, typeLine: source.definition.typeLine.replace(/\bLegendary\s+/i, '') } + : source.definition + const object: GameObject = { + id: this.generateId('token'), + definition, + owner: playerId, + controller: playerId, + zone: 'battlefield', + tapped: false, + damage: 0, + deathtouched: false, + counters: {}, + isToken: true, + token: source.token, + enteredTurn: this.turn, + blockedBy: [], + attachments: [], + regenerationShields: 0, + activations: {}, + } + this.objects.set(object.id, object) + this.moveToZone(object, 'battlefield', { controller: playerId, tapped: false, silent: false }) + return object + } + + private attach(source: GameObject, target: GameObject): void { + if (source.attachedTo) { + const previous = this.objects.get(source.attachedTo) + if (previous) previous.attachments = previous.attachments.filter(id => id !== source.id) + } + source.attachedTo = target.id + if (!target.attachments.includes(source.id)) target.attachments.push(source.id) + } + + private addCounters(object: GameObject, counter: string, amount: number, silent = false): void { + if (amount === 0) return + object.counters[counter] = Math.max(0, (object.counters[counter] ?? 0) + amount) + if (!silent) this.dispatchEvent({ kind: 'counter_placed', player: object.controller, subject: object, amount, counter }) + } + + // --------------------------------------------------------------------------- + // Triggers, statics, and conditions + // --------------------------------------------------------------------------- + + private dispatchEvent(event: EventContext): void { + if (this.status !== 'active') return + const sources = this.battlefieldObjects() + if (event.subject && event.subject.zone !== 'battlefield' && !sources.includes(event.subject)) { + sources.push(event.subject) + } + sources.sort((a, b) => { + const aFirst = a.controller === this.activePlayer ? 0 : 1 + const bFirst = b.controller === this.activePlayer ? 0 : 1 + return aFirst - bFirst + }) + + let added = 0 + for (const source of sources) { + for (const ability of source.definition.abilities ?? []) { + if (ability.kind !== 'triggered') continue + if (ability.condition && !this.checkCondition(ability.condition, source)) continue + if (!this.matchesTrigger(event, ability.event, source)) continue + let targets: TargetChoice[] + try { + targets = this.selectTargets(ability.effects, source, source.controller, [], 0) + } catch { + continue + } + this.stack.push({ + id: this.generateId('stack'), + kind: 'ability', + source, + controller: source.controller, + label: ability.text, + effects: ability.effects, + targets, + x: 0, + mode: 0, + triggerSubject: event.subject, + eventPlayer: event.player, + eventAmount: event.amount, + }) + added++ + } + } + if (added) { + this.passesInRow = 0 + this.priority = this.activePlayer + } + } + + private matchesTrigger(event: EventContext, trigger: TriggerEvent, source: GameObject): boolean { + switch (trigger.kind) { + case 'enters': + case 'dies': + case 'attacks': + case 'blocks': + case 'leaves_battlefield': + return event.kind === trigger.kind && this.subjectMatches(trigger.subject, source, event) + case 'enters_or_attacks': + return (event.kind === 'enters' || event.kind === 'attacks') + && this.subjectMatches(trigger.subject, source, event) + case 'enters_or_dies': + return (event.kind === 'enters' || event.kind === 'dies') + && this.subjectMatches(trigger.subject, source, event) + case 'attacks_or_blocks': + return (event.kind === 'attacks' || event.kind === 'blocks') + && this.subjectMatches(trigger.subject, source, event) + case 'counter_placed': + return event.kind === 'counter_placed' + && this.subjectMatches(trigger.subject, source, event) + && (!trigger.counter || trigger.counter === event.counter) + case 'upkeep': + case 'end_step': + case 'begin_combat': + return event.kind === trigger.kind && this.whoMatches(trigger.who, source, event.player) + case 'main_phase': + return event.kind === 'main_phase' && this.whoMatches(trigger.who, source, event.player) + case 'cast': + if (event.kind !== 'cast' || !event.spell) return false + if (!this.whoMatches(trigger.who, source, event.player)) return false + if (!this.matchesSelector(event.spell, trigger.spell, source, 'stack')) return false + if (trigger.targetsSelf && !(event.spellItem?.targets.some(choice => choice.kind === 'object' && choice.id === source.id))) { + return false + } + return true + case 'draw': + if (event.kind !== 'draw' || !this.whoMatches(trigger.who, source, event.player)) return false + return !trigger.ordinal || trigger.ordinal === event.ordinal + case 'life': + if (event.kind !== 'life' || !this.whoMatches(trigger.who, source, event.player)) return false + return trigger.mode === event.mode + case 'deals_damage': + if (event.kind !== 'deals_damage' || !this.subjectMatches(trigger.subject, source, event)) return false + if (trigger.combat && !event.combat) return false + return trigger.recipient === 'any' || trigger.recipient === event.recipient + case 'becomes_target': + case 'becomes_level': + return false + } + } + + private subjectMatches(target: Target, source: GameObject, event: EventContext): boolean { + if (!event.subject) return false + if (target.kind === 'self' || target.kind === 'trigger_subject') return event.subject.id === source.id + if (target.kind !== 'object') return false + if (target.selector.other && event.subject.id === source.id && !target.includeSelf) return false + return this.matchesSelector(event.subject, target.selector, source, event.subject.zone) + } + + private whoMatches(who: 'you' | 'opponent' | 'each_player', source: GameObject, eventPlayer: string | undefined): boolean { + if (who === 'each_player') return true + if (!eventPlayer) return false + return who === 'you' ? source.controller === eventPlayer : source.controller !== eventPlayer + } + + private staticAbilities(): { source: GameObject; ability: Extract }[] { + const result: { source: GameObject; ability: Extract }[] = [] + for (const source of this.battlefieldObjects()) { + for (const ability of source.definition.abilities ?? []) { + if (ability.kind !== 'static') continue + if (ability.condition && !this.checkCondition(ability.condition, source)) continue + result.push({ source, ability }) + } + } + return result + } + + private staticTargets(source: GameObject, target: Target): GameObject[] { + if (target.kind === 'self') return [source] + if (target.kind !== 'object') return [] + return this.objectsMatching(target.selector, source) + } + + private applyEntersReplacements(object: GameObject): void { + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op === 'enters_tapped') { + if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue + if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) { + object.tapped = true + } + } else if (effect.op === 'enters_with_counters') { + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + const amount = this.value(effect.amount, this.staticContext(staticSource.source)) + this.addCounters(object, effect.counter, amount, true) + } + } + } + } + + private hasRestriction(object: GameObject, rule: string): boolean { + for (const staticSource of this.staticAbilities()) { + for (const effect of staticSource.ability.effects) { + if (effect.op !== 'restriction' || (effect.rule !== rule && !effect.rule.startsWith(`${rule}_`))) continue + if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) return true + } + } + for (const continuous of this.continuousEffects) { + if (continuous.effect.op !== 'restriction' || continuous.effect.rule !== rule) continue + if (continuous.affectedIds.includes(object.id)) return true + } + return false + } + + private checkCondition(condition: Condition, source: GameObject): boolean { + const controller = source.controller + switch (condition.kind) { + case 'you_control': + return this.objectsMatching(condition.selector, source).filter(object => object.controller === controller).length + >= (condition.atLeast ?? 1) + case 'opponent_controls': + return this.opponentsOf(controller).some(playerId => this.objectsMatching(condition.selector, source) + .some(object => object.controller === playerId)) + case 'your_turn': + return this.activePlayer === controller + case 'not_your_turn': + return this.activePlayer !== controller + case 'source_tapped': + return source.tapped + case 'source_untapped': + return !source.tapped + case 'source_attacking': + return Boolean(source.attacking) + case 'life_at_least': + return this.playersForValue(condition.player, this.staticContext(source)) + .some(playerId => this.getPlayer(playerId).life >= condition.amount) + case 'life_at_most': + return this.playersForValue(condition.player, this.staticContext(source)) + .some(playerId => this.getPlayer(playerId).life <= condition.amount) + case 'cards_in_graveyard': + return this.playersForValue(condition.player, this.staticContext(source)) + .some(playerId => this.getPlayer(playerId).graveyard.length >= condition.atLeast) + case 'hand_empty': + return this.playersForValue(condition.player, this.staticContext(source)) + .some(playerId => this.getPlayer(playerId).hand.length === 0) + case 'creature_died_this_turn': + return this.getPlayer(controller).creaturesDiedThisTurn > 0 + case 'you_gained_life_this_turn': + return this.getPlayer(controller).lifeGainedThisTurn >= (condition.atLeast ?? 1) + case 'you_drew_cards_this_turn': + return this.getPlayer(controller).cardsDrawnThisTurn >= (condition.atLeast ?? 1) + case 'attacked_this_turn': + return this.getPlayer(controller).attackedThisTurn + case 'you_attacked_this_turn': + return this.getPlayer(controller).attackedThisTurn + case 'no_objects': + return this.objectsMatching(condition.selector, source).length === 0 + case 'cards_in_hand_at_most': + return this.playersForValue(condition.who, this.staticContext(source)) + .some(playerId => this.getPlayer(playerId).hand.length <= condition.atMost) + case 'on_battlefield': + return source.zone === 'battlefield' + case 'in_graveyard': + return source.zone === 'graveyard' + case 'not_token': + return !source.isToken + case 'full_party': + return false + default: + return false + } + } + + // --------------------------------------------------------------------------- + // Combat damage + // --------------------------------------------------------------------------- + + private dealCombatDamage(): void { + const attackers = this.battlefieldObjects().filter(object => object.attacking) + const anyFirstStrike = attackers.some(object => this.hasKeyword(object, 'First strike') || this.hasKeyword(object, 'Double strike')) + || attackers.some(object => object.blockedBy + .map(id => this.objects.get(id)) + .some(blocker => blocker && (this.hasKeyword(blocker, 'First strike') || this.hasKeyword(blocker, 'Double strike')))) + + if (anyFirstStrike) this.dealCombatDamageRound(true) + this.dealCombatDamageRound(false) + this.step = 'end_combat' + this.passesInRow = 0 + this.priority = this.activePlayer + } + + private dealCombatDamageRound(firstStrike: boolean): void { + for (const attacker of this.battlefieldObjects()) { + if (attacker.zone !== 'battlefield' || !attacker.attacking) continue + const doubleStrike = this.hasKeyword(attacker, 'Double strike') + const first = this.hasKeyword(attacker, 'First strike') + if (firstStrike ? (!first && !doubleStrike) : (first && !doubleStrike)) continue + + let power = this.getPower(attacker) + const blockers = attacker.blockedBy + .map(id => this.objects.get(id)) + .filter((object): object is GameObject => Boolean(object && object.zone === 'battlefield' && object.blocking === attacker.id)) + const deathtouch = this.hasKeyword(attacker, 'Deathtouch') + const trample = this.hasKeyword(attacker, 'Trample') + + if (!blockers.length) { + this.damageDefender(attacker, power) + } else { + let remaining = power + for (let index = 0; index < blockers.length && remaining > 0; index++) { + const blocker = blockers[index] + const lethal = deathtouch ? 1 : Math.max(0, this.getToughness(blocker) - blocker.damage) + const assign = index === blockers.length - 1 && !trample + ? remaining + : Math.min(remaining, Math.max(lethal, 1)) + if (assign <= 0) continue + this.damageTarget({ kind: 'object', object: blocker }, assign, attacker, true) + remaining -= assign + } + if (trample && remaining > 0) this.damageDefender(attacker, remaining) + + for (const blocker of blockers) { + if (blocker.zone !== 'battlefield' || blocker.blocking !== attacker.id) continue + const blockerDouble = this.hasKeyword(blocker, 'Double strike') + const blockerFirst = this.hasKeyword(blocker, 'First strike') + if (firstStrike ? (!blockerFirst && !blockerDouble) : (blockerFirst && !blockerDouble)) continue + this.damageTarget({ kind: 'object', object: attacker }, this.getPower(blocker), blocker, true) + } + } + } + this.runStateBasedActions() + } + + private damageDefender(attacker: GameObject, amount: number): void { + const defenderId = attacker.attacking + if (!defenderId) return + const player = this.players.find(entry => entry.id === defenderId) + if (player) { + this.damageTarget({ kind: 'player', id: player.id }, amount, attacker, true) + return + } + const permanent = this.objects.get(defenderId) + if (permanent?.zone === 'battlefield') { + this.damageTarget({ kind: 'object', object: permanent }, amount, attacker, true) + } + } + + private requireCanAttack(attacker: GameObject, playerId: string): void { + if (attacker.zone !== 'battlefield') throw new GameError('Attacker is not on the battlefield') + if (attacker.controller !== playerId) throw new GameError('You do not control that creature') + if (!this.isCreature(attacker)) throw new GameError('Only creatures can attack') + if (attacker.tapped) throw new GameError('Tapped creatures cannot attack') + if (attacker.enteredTurn >= this.turn && !this.hasKeyword(attacker, 'Haste')) { + throw new GameError('That creature has summoning sickness') + } + if (this.hasRestriction(attacker, 'cant_attack')) throw new GameError('That creature cannot attack') + } + + private hasMeaningfulAction(playerId: string): boolean { + if (this.status !== 'active' || this.priority !== playerId) return false + const player = this.getPlayer(playerId) + if (player.lost) return false + + if (this.phase === 'combat' && this.step === 'declare_attackers' && !this.stack.length + && this.activePlayer === playerId && this.canAttackWithAny(playerId)) { + return true + } + if (this.phase === 'combat' && this.step === 'declare_blockers' && !this.stack.length + && this.canBlockWithAny(playerId)) { + return true + } + + if ([...player.hand, ...player.command].some(id => this.canPlayCard(playerId, id))) return true + + for (const id of player.battlefield) { + const object = this.objects.get(id) + if (!object) continue + const abilities = object.definition.abilities ?? [] + for (let index = 0; index < abilities.length; index++) { + const ability = abilities[index] + if (ability.kind !== 'activated') continue + // Mana abilities alone do not advance the game; counting them would + // stop auto-pass on every untapped land. + if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) continue + if (this.isActivatedAbilityPlayable(playerId, object, index, ability)) return true + } + } + return false + } + + private isActivatedAbilityPlayable( + playerId: string, + source: GameObject, + index: number, + ability: Extract, + ): boolean { + if (source.zone !== 'battlefield' || source.controller !== playerId) return false + if (ability.condition && !this.checkCondition(ability.condition, source)) return false + if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) return false + if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source) + && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) { + return false + } + if (ability.activationsPerTurn !== undefined + && (source.activations[index] ?? 0) >= ability.activationsPerTurn) { + return false + } + for (const cost of ability.costs) { + if (cost.kind === 'mana') { + if (!this.canAffordMana(playerId, cost.symbols, 0)) return false + } else if (!this.canPayNonManaCost(cost, playerId, source)) { + return false + } + } + return this.hasLegalTargets(source, playerId, ability.effects) + } + + private hasLegalTargets(source: GameObject, playerId: string, effects?: Effect[]): boolean { + const list = effects ?? (source.definition.abilities ?? []) + .filter((ability): ability is Extract => ability.kind === 'spell') + .flatMap(ability => ability.effects) + try { + this.selectTargets(list, source, playerId, [], 0) + return true + } catch (error) { + if (error instanceof GameError) return false + throw error + } + } + + /** + * Affordability check that mirrors auto-tapping without changing the game. + * shortcut: any_color sources are counted as flexible even when they must + * produce one color, so rare "one color only" sources can be overestimated; + * upgrade if a card ever needs an exact color split from such a source. + */ + private canAffordMana(playerId: string, symbols: string, x: number): boolean { + if (!symbols) return true + const player = this.getPlayer(playerId) + const cost = parseManaCost(symbols, x) + const pool = { ...player.manaPool } + let flexible = 0 + for (const object of this.battlefieldObjects()) { + if (object.controller !== playerId) continue + const found = this.findFreeManaAbility(object) + if (!found) continue + for (const effect of found.ability.effects) { + if (effect.op !== 'add_mana') continue + if (effect.mana.kind === 'symbols') { + for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++ + } else { + flexible += this.value(effect.mana.amount, { + source: object, + controller: playerId, + targets: [], + x: 0, + mode: 0, + }) + } + } + } + + let life = player.life + const take = (color: ManaColor): boolean => { + if (pool[color] > 0) { + pool[color]-- + return true + } + if (flexible > 0) { + flexible-- + return true + } + return false + } + + for (const color of cost.colored) { + if (!take(color)) return false + } + for (const hybrid of cost.hybrid) { + if (hybrid.colors.some(take)) continue + if (!(hybrid.life > 0 && life >= hybrid.life)) return false + life -= hybrid.life + } + const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + flexible + return remaining >= cost.generic + } + + private canAttackWithAny(playerId: string): boolean { + return this.battlefieldObjects().some(object => { + try { + this.requireCanAttack(object, playerId) + return true + } catch (error) { + if (error instanceof GameError) return false + throw error + } + }) + } + + private canBlockWithAny(playerId: string): boolean { + const attackers = this.battlefieldObjects().filter(object => object.attacking === playerId) + if (!attackers.length) return false + return this.battlefieldObjects().some(blocker => { + if (blocker.controller !== playerId) return false + if (!this.isCreature(blocker) || blocker.tapped || blocker.blocking) return false + if (this.hasRestriction(blocker, 'cant_block')) return false + return attackers.some(attacker => !this.hasKeyword(attacker, 'Flying') + || this.hasKeyword(blocker, 'Flying') + || this.hasKeyword(blocker, 'Reach')) + }) + } + + // --------------------------------------------------------------------------- + // Zones, state-based actions, and utilities + // --------------------------------------------------------------------------- + + private handleLeavesBattlefield(object: GameObject, destination: Zone): void { + if (object.attachedTo) { + const attached = this.objects.get(object.attachedTo) + if (attached) attached.attachments = attached.attachments.filter(id => id !== object.id) + object.attachedTo = undefined + } + for (const attachmentId of [...object.attachments]) { + const attachment = this.objects.get(attachmentId) + if (attachment) attachment.attachedTo = undefined + } + object.attachments = [] + object.attacking = undefined + object.blockedBy = [] + object.blocking = undefined + + for (let index = this.continuousEffects.length - 1; index >= 0; index--) { + const effect = this.continuousEffects[index] + if (effect.sourceId !== object.id) continue + if (effect.duration === 'permanent' || effect.duration === 'while_source_on_battlefield') { + this.continuousEffects.splice(index, 1) + } + } + + if (destination === 'graveyard' && this.isCreature(object)) { + this.getPlayer(object.controller).creaturesDiedThisTurn++ + this.dispatchEvent({ kind: 'dies', player: object.controller, subject: object }) + } + this.dispatchEvent({ kind: 'leaves_battlefield', player: object.controller, subject: object }) + } + + private runStateBasedActions(): void { + if (this.status !== 'active') return + let changed = true + let guard = 0 + while (changed && guard++ < 50 && this.status === 'active') { + changed = false + for (const player of this.players) { + if (!player.lost && (player.life <= 0 || player.poison >= 10 + || Object.values(player.commanderDamage).some(damage => damage >= 21))) { + this.losePlayer(player.id) + changed = true + } + } + if (this.status !== 'active') return + for (const id of [...this.battlefieldObjects().map(object => object.id)]) { + const object = this.objects.get(id) + if (!object || object.zone !== 'battlefield' || !this.isCreature(object)) continue + const lethal = this.getToughness(object) <= 0 + || object.damage >= this.getToughness(object) + || (object.deathtouched && object.damage > 0) + if (!lethal) continue + if (this.hasKeyword(object, 'Indestructible')) continue + if (object.regenerationShields > 0) { + object.regenerationShields-- + object.tapped = true + object.damage = 0 + object.deathtouched = false + object.attacking = undefined + object.blockedBy = [] + object.blocking = undefined + } else { + this.moveToZone(object, 'graveyard', { silent: false }) + } + changed = true + } + } + } + + private losePlayer(playerId: string): void { + const player = this.getPlayer(playerId) + if (player.lost) return + player.lost = true + this.logMessage(`${player.name} loses the game`) + const alive = this.alivePlayers() + if (alive.length <= 1) { + this.status = 'finished' + this.winner = alive[0]?.id + if (this.winner) this.logMessage(`${this.getPlayer(this.winner).name} wins`) + } + } + + private gainLife(playerId: string, amount: number): void { + if (amount <= 0) return + const player = this.getPlayer(playerId) + if (player.lost) return + player.life += amount + player.lifeGainedThisTurn += amount + this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'gain' }) + } + + private loseLife(playerId: string, amount: number): void { + if (amount <= 0) return + const player = this.getPlayer(playerId) + if (player.lost) return + player.life -= amount + this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'lose' }) + this.runStateBasedActions() + } + + private drawCard(playerId: string, silent: boolean): void { + const player = this.getPlayer(playerId) + if (player.lost) return + if (!player.library.length) { + this.losePlayer(playerId) + return + } + const id = player.library.shift() + if (!id) return + player.hand.push(id) + const object = this.getObject(id) + object.zone = 'hand' + object.controller = playerId + player.cardsDrawnThisTurn++ + if (!silent) { + this.dispatchEvent({ kind: 'draw', player: playerId, amount: 1, ordinal: player.cardsDrawnThisTurn }) + } + } + + private drawCards(playerId: string, amount: number): void { + for (let i = 0; i < amount; i++) this.drawCard(playerId, false) + } + + private discardCards(playerId: string, amount: number, random: boolean | undefined, context: EffectContext): void { + const player = this.getPlayer(playerId) + for (let i = 0; i < amount && player.hand.length; i++) { + const index = random ? Math.floor(this.rng() * player.hand.length) : 0 + const id = player.hand[index] + this.moveToZone(id, 'graveyard', { silent: false }) + } + void context + } + + private millCards(playerId: string, amount: number): void { + const player = this.getPlayer(playerId) + for (let i = 0; i < amount && player.library.length; i++) { + const id = player.library[0] + this.moveToZone(id, 'graveyard', { silent: true }) + } + } + + private searchLibrary( + playerId: string, + selector: ObjectSelector, + amount: number, + destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', + tapped: boolean, + shuffle: boolean, + zones?: ('library' | 'graveyard')[], + ): void { + // shortcut: a search only pauses itself; later effects in the same ability + // still run before the pick, and a second search in that ability is skipped. + // Most search lines are a single effect. + if (this.pendingSearch) return + const player = this.getPlayer(playerId) + let remaining = amount + while (remaining > 0) { + const candidates = this.findSearchCandidates(playerId, selector, zones) + if (!candidates.length) break + if (candidates.length > 1) { + this.pendingSearch = { playerId, selector, remaining, destination, tapped, shuffle, zones } + return + } + this.moveSearchedCard(candidates[0], playerId, destination, tapped) + remaining-- + } + if (shuffle) this.shuffleLibrary(player) + } + + private findSearchCandidates( + playerId: string, + selector: ObjectSelector, + zones?: ('library' | 'graveyard')[], + ): GameObject[] { + const player = this.getPlayer(playerId) + const source = this.playerSource(playerId) + const allowed = zones ?? ['library'] + const ids = allowed.includes('library') ? [...player.library] : [] + if (allowed.includes('graveyard')) ids.push(...player.graveyard) + return ids.map(id => this.getObject(id)) + .filter(object => object.owner === playerId + && this.matchesSelector(object, selector, source, object.zone)) + } + + private moveSearchedCard( + object: GameObject, + playerId: string, + destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', + tapped: boolean, + ): void { + if (destination === 'battlefield') { + this.moveToZone(object, 'battlefield', { controller: playerId, tapped, silent: false }) + } else if (destination === 'hand') { + this.moveToZone(object, 'hand', { silent: false }) + } else if (destination === 'graveyard') { + this.moveToZone(object, 'graveyard', { silent: false }) + } else if (destination === 'top') { + this.moveToZone(object, 'library', { toTop: true, silent: false }) + } else { + this.moveToZone(object, 'library', { silent: false }) + } + } + + private shuffleLibrary(player: PlayerState): void { + for (let index = player.library.length - 1; index > 0; index--) { + const swap = Math.floor(this.rng() * (index + 1)) + const temp = player.library[index] + player.library[index] = player.library[swap] + player.library[swap] = temp + } + } + + private removeFromZone(object: GameObject): void { + const owner = this.getPlayer(object.owner) + if (object.zone === 'battlefield') { + const controller = this.getPlayer(object.controller) + controller.battlefield = controller.battlefield.filter(id => id !== object.id) + } else if (object.zone === 'hand') owner.hand = owner.hand.filter(id => id !== object.id) + else if (object.zone === 'graveyard') owner.graveyard = owner.graveyard.filter(id => id !== object.id) + else if (object.zone === 'exile') owner.exile = owner.exile.filter(id => id !== object.id) + else if (object.zone === 'command') owner.command = owner.command.filter(id => id !== object.id) + else if (object.zone === 'library') owner.library = owner.library.filter(id => id !== object.id) + } + + private objectsMatching(selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): GameObject[] { + const zone = zoneOverride ?? selector.zone ?? 'battlefield' + return [...this.objects.values()].filter(object => this.matchesSelector(object, selector, source, zone)) + } + + private matchesSelector(object: GameObject, selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): boolean { + const zone = zoneOverride ?? selector.zone ?? 'battlefield' + if (object.zone !== zone) return false + if (selector.other && object.id === source.id) return false + + const typeLine = object.definition.typeLine.toLowerCase() + const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean)) + if (selector.types?.length) { + const matches = selector.types.map(type => words.has(type.toLowerCase())) + if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false + } + if (selector.excludeTypes?.some(type => words.has(type.toLowerCase()))) return false + if (selector.supertypes?.some(type => !words.has(type.toLowerCase()))) return false + if (selector.subtypes?.some(type => !words.has(type.toLowerCase()))) return false + + if (selector.controller === 'you' && object.controller !== source.controller) return false + if (selector.controller === 'opponent' && object.controller === source.controller) return false + if (selector.owner === 'you' && object.owner !== source.controller) return false + if (selector.owner === 'opponent' && object.owner === source.controller) return false + + const colors = object.definition.colors ?? [] + if (selector.colors?.some(color => !colors.includes(color))) return false + if (selector.tapped !== undefined && object.tapped !== selector.tapped) return false + if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false + if (selector.token !== undefined && object.isToken !== selector.token) return false + if (selector.name && object.definition.name.toLowerCase() !== selector.name.toLowerCase()) return false + if (selector.counters) { + const count = object.counters[selector.counters.counter] ?? 0 + if (count < selector.counters.atLeast) return false + } + if (selector.power) { + const power = this.getPower(object) + if (selector.power.atLeast !== undefined && power < selector.power.atLeast) return false + if (selector.power.atMost !== undefined && power > selector.power.atMost) return false + } + if (selector.toughness) { + const toughness = this.getToughness(object) + if (selector.toughness.atLeast !== undefined && toughness < selector.toughness.atLeast) return false + if (selector.toughness.atMost !== undefined && toughness > selector.toughness.atMost) return false + } + if (selector.manaValue) { + const value = manaValueOf(object.definition) + if (selector.manaValue.atLeast !== undefined && value < selector.manaValue.atLeast) return false + if (selector.manaValue.atMost !== undefined && value > selector.manaValue.atMost) return false + } + if (selector.keywords?.some(keyword => !this.hasKeyword(object, keyword))) return false + if (selector.excludeKeywords?.some(keyword => this.hasKeyword(object, keyword))) return false + if (selector.attached) { + const attached = [...this.objects.values()].some(attachment => attachment.attachedTo === object.id + && (selector.attached === 'equipped' ? this.hasType(attachment, 'equipment') : this.hasType(attachment, 'aura'))) + if (!attached) return false + } + return true + } + + // --------------------------------------------------------------------------- + // Rules helpers + // --------------------------------------------------------------------------- + + private isCreature(object: GameObject): boolean { + return this.hasType(object, 'creature') + } + + private isLand(object: GameObject): boolean { + return this.hasType(object, 'land') + } + + private isInstant(object: GameObject): boolean { + return this.hasType(object, 'instant') + } + + private isInstantOrSorcery(object: GameObject): boolean { + return this.hasType(object, 'instant') || this.hasType(object, 'sorcery') + } + + private isPermanent(object: GameObject): boolean { + if (this.isInstantOrSorcery(object)) return false + return ['creature', 'artifact', 'enchantment', 'planeswalker', 'battle', 'land'] + .some(type => this.hasType(object, type)) + } + + private hasType(object: GameObject, type: string): boolean { + const words = object.definition.typeLine.toLowerCase().split(/[\s—–\-/,()]+/) + return words.includes(type.toLowerCase()) + } + + private hasKeywordForDefinition(definition: CardDefinition, keyword: string): boolean { + const wanted = keyword.toLowerCase() + for (const ability of definition.abilities ?? []) { + if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true + if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) return true + } + return false + } + + private battlefieldObjects(): GameObject[] { + return [...this.objects.values()].filter(object => object.zone === 'battlefield') + } + + private alivePlayers(): PlayerState[] { + return this.players.filter(player => !player.lost) + } + + private opponentsOf(playerId: string): string[] { + return this.alivePlayers().filter(player => player.id !== playerId).map(player => player.id) + } + + private nextAlivePlayer(playerId: string): string { + const start = this.players.findIndex(player => player.id === playerId) + for (let offset = 1; offset <= this.players.length; offset++) { + const player = this.players[(start + offset) % this.players.length] + if (!player.lost) return player.id + } + return playerId + } + + private requirePriority(playerId: string): void { + if (this.status !== 'active') throw new GameError('Game is not active') + if (this.pendingSearch) throw new GameError('Choose a card from your library first') + if (this.priority !== playerId) throw new GameError('You do not have priority') + } + + private emptyManaPools(): void { + for (const player of this.players) player.manaPool = emptyPool() + } + + private removeExpiringEffects(playerId: string): void { + for (let index = this.continuousEffects.length - 1; index >= 0; index--) { + const effect = this.continuousEffects[index] + if ((effect.duration === 'until_your_next_turn' || effect.duration === 'until_controllers_next_untap_step') + && effect.controller === playerId) { + this.continuousEffects.splice(index, 1) + } + } + } + + /** "Until the end of your next turn" skips the turn the effect was created in. */ + private removeEndOfNextTurnEffects(playerId: string): void { + for (let index = this.continuousEffects.length - 1; index >= 0; index--) { + const effect = this.continuousEffects[index] + if (effect.duration === 'until_end_of_your_next_turn' && effect.controller === playerId + && effect.createdTurn !== this.turn) { + this.continuousEffects.splice(index, 1) + } + } + } + + private removeEffectsByDuration(duration: Duration): void { + for (let index = this.continuousEffects.length - 1; index >= 0; index--) { + if (this.continuousEffects[index].duration === duration) this.continuousEffects.splice(index, 1) + } + } + + private counterStat(counters: Record, stat: 'power' | 'toughness'): number { + let total = 0 + for (const [counter, count] of Object.entries(counters)) { + const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/) + if (!match) continue + const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}` + total += Number(value) + } + return total + } + + private findStackItem(id: string): StackItem | undefined { + return this.stack.find(item => item.id === id) ?? this.stack.find(item => item.source.id === id) + } + + private playerSource(playerId: string): GameObject { + return { + id: `player:${playerId}`, + definition: { oracleId: `player:${playerId}`, name: this.getPlayer(playerId).name, typeLine: '' }, + owner: playerId, + controller: playerId, + zone: 'battlefield', + tapped: false, + damage: 0, + deathtouched: false, + counters: {}, + isToken: false, + enteredTurn: 0, + blockedBy: [], + attachments: [], + regenerationShields: 0, + activations: {}, + } + } + + private createObject(definition: CardDefinition, owner: string): GameObject { + const object: GameObject = { + id: this.generateId('card'), + definition, + owner, + controller: owner, + zone: 'library', + tapped: false, + damage: 0, + deathtouched: false, + counters: {}, + isToken: false, + enteredTurn: 0, + blockedBy: [], + attachments: [], + regenerationShields: 0, + activations: {}, + } + this.objects.set(object.id, object) + return object + } + + private generateId(prefix: string): string { + this.nextId++ + return `${prefix}_${this.nextId}` + } + + private logMessage(message: string): void { + this.log.push(message) + } +} + +function mulberry32(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let value = state + value = Math.imul(value ^ (value >>> 15), value | 1) + value ^= value + Math.imul(value ^ (value >>> 7), value | 61) + return ((value ^ (value >>> 14)) >>> 0) / 4294967296 + } +} diff --git a/backend/src/game/rooms.ts b/backend/src/game/rooms.ts new file mode 100644 index 0000000..f870a3b --- /dev/null +++ b/backend/src/game/rooms.ts @@ -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 + 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 + 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 void>> +} + +const matches = new Map() + +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 { + 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) + } + } + } +} diff --git a/backend/src/game/types.ts b/backend/src/game/types.ts new file mode 100644 index 0000000..1a7174d --- /dev/null +++ b/backend/src/game/types.ts @@ -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 + +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 + /** Times each commander has been cast from the command zone. */ + commanderCasts: Record + 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 + 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 +} + +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' diff --git a/backend/src/images.ts b/backend/src/images.ts new file mode 100644 index 0000000..9515272 --- /dev/null +++ b/backend/src/images.ts @@ -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>() + +/** 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + if (!PLAYMAT_ID.test(id)) return + await rm(join(dir, `${id}.jpg`), { force: true }) +} diff --git a/backend/src/server.ts b/backend/src/server.ts new file mode 100644 index 0000000..6c7bddc --- /dev/null +++ b/backend/src/server.ts @@ -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([ + '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 { + 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', +}) diff --git a/backend/test/accounts.test.ts b/backend/test/accounts.test.ts new file mode 100644 index 0000000..711d284 --- /dev/null +++ b/backend/test/accounts.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { hashPassword, verifyPassword } from '../src/accounts.js' + +test('passwords are salted and verified', async () => { + const first = await hashPassword('correct horse battery staple') + const second = await hashPassword('correct horse battery staple') + + assert.notEqual(first.salt, second.salt) + assert.notEqual(first.hash, second.hash) + assert.equal(await verifyPassword('correct horse battery staple', first.salt, first.hash), true) + assert.equal(await verifyPassword('wrong password', first.salt, first.hash), false) +}) diff --git a/backend/test/cards.test.ts b/backend/test/cards.test.ts new file mode 100644 index 0000000..730fa66 --- /dev/null +++ b/backend/test/cards.test.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import type { Card } from '../src/cards.js' +import { matchesCardFilters } from '../src/cards.js' + +function card(overrides: Partial = {}): Card { + return { + oracle_id: 'test', + name: 'Test Card', + layout: 'normal', + cmc: 3, + type_line: 'Legendary Creature — Human', + colors: ['G', 'U'], + color_identity: ['G', 'U'], + keywords: [], + rarity: 'rare', + legal_formats: ['commander', 'legacy'], + ...overrides, + } +} + +const cardByIdentity = card({ color_identity: ['G', 'U'] }) + +test('card filters match format legality, color identity, type, rarity, and mana value', () => { + assert.equal(matchesCardFilters(cardByIdentity, { format: 'legacy' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { format: 'standard' }), false) + assert.equal(matchesCardFilters(cardByIdentity, {}), true) + + assert.equal(matchesCardFilters(cardByIdentity, { color: 'U' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { color: 'M' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { color: 'C' }), false) + assert.equal(matchesCardFilters(card({ color_identity: [] }), { color: 'C' }), true) + + assert.equal(matchesCardFilters(cardByIdentity, { type: 'legendary' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { type: 'creature' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { type: 'land' }), false) + + const modalCard = card({ + type_line: 'Sorcery', + card_faces: [ + { name: 'Front', type_line: 'Sorcery', colors: [] }, + { name: 'Back', type_line: 'Land', colors: [] }, + ], + }) + assert.equal(matchesCardFilters(modalCard, { type: 'land' }), true) + + assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'rare' }), true) + assert.equal(matchesCardFilters(cardByIdentity, { rarity: 'common' }), false) + + assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 3, cmcMax: 3 }), true) + assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false) + assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false) +}) diff --git a/backend/test/commander.test.ts b/backend/test/commander.test.ts new file mode 100644 index 0000000..d2c8d54 --- /dev/null +++ b/backend/test/commander.test.ts @@ -0,0 +1,159 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import type { Card } from '../src/cards.js' +import { canBeCommander, importDeckText, validateCommanderDeck } from '../src/game/commander.js' +import { Game } from '../src/game/game.js' +import type { CardDefinition } from '../src/game/types.js' + +function card(name: string, overrides: Partial = {}): Card { + return { + oracle_id: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'), + name, + layout: 'normal', + cmc: 0, + type_line: 'Creature — Test', + colors: [], + color_identity: [], + keywords: [], + ...overrides, + } +} + +function commanderCard(name: string, overrides: Partial = {}): Card { + return card(name, { + type_line: 'Legendary Creature — Test', + color_identity: ['G'], + ...overrides, + }) +} + +function basicLand(name: string): Card { + return card(name, { type_line: 'Basic Land — Forest', color_identity: ['G'] }) +} + +function commanderDefinition(name: string, overrides: Partial = {}): CardDefinition { + return { + oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'), + name, + typeLine: 'Legendary Creature — Test', + manaCost: '{1}', + manaValue: 1, + colors: ['G'], + colorIdentity: ['G'], + power: 2, + toughness: 2, + abilities: [], + ...overrides, + } +} + +test('commander deck validation enforces size, singleton, identity, and commander type', () => { + const commander = commanderCard('Test Commander') + const legal = Array.from({ length: 99 }, () => basicLand('Forest')) + assert.deepEqual(validateCommanderDeck(commander, legal), []) + + assert.match(validateCommanderDeck(commander, legal.slice(1)).join(' '), /exactly 100/) + + const duplicate = [...legal.slice(1), card('Sol Ring', { color_identity: [] }), card('Sol Ring', { color_identity: [] })] + assert.match(validateCommanderDeck(commander, duplicate).join(' '), /only basic lands may repeat/) + + const offColor = [...legal.slice(1), card('Counterspell', { color_identity: ['U'] })] + assert.match(validateCommanderDeck(commander, offColor).join(' '), /outside the commander's color identity/) + + assert.match(validateCommanderDeck(card('Not Legendary'), legal).join(' '), /cannot be a commander/) + assert.equal(canBeCommander(card('Planeswalker Commander', { oracle_text: 'This can be your commander.' })), true) +}) + +test('decklist import reads sections, quantities, and set suffixes', () => { + const known = new Map([ + ['Test Commander', commanderCard('Test Commander')], + ['Sol Ring', card('Sol Ring')], + ['Forest', basicLand('Forest')], + ]) + const result = importDeckText(` +Commander +1 Test Commander (TST) 1 + +Deck +1 Sol Ring (TST) 2 +2 Forest (TST) 3 *F* +`, name => known.get(name)) + assert.equal(result.commander?.name, 'Test Commander') + assert.equal(result.cards.length, 3) + assert.equal(result.cards.filter(entry => entry.name === 'Forest').length, 2) + assert.match(result.errors.join(' '), /exactly 100/) +}) + +test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => { + const commander = commanderDefinition('Test Commander') + const game = new Game({ + seed: 1, + startingHandSize: 0, + commander: true, + players: [ + { id: 'p1', deck: [], commander }, + { id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, + ], + }) + game.start() + const forest = { + oracleId: 'forest', + name: 'Forest', + typeLine: 'Basic Land — Forest', + abilities: [{ + kind: 'activated' as const, + costs: [{ kind: 'tap' as const }], + effects: [{ op: 'add_mana' as const, player: 'you' as const, mana: { kind: 'symbols' as const, symbols: ['{G}'] } }], + optional: false, + text: '{T}: Add {G}.', + }], + } + + const player = game.getPlayer('p1') + assert.equal(player.command.length, 1) + const object = game.getObject(player.command[0]) + assert.equal(object.isCommander, true) + + for (let index = 0; index < 4; index++) game.addCard('p1', forest, 'battlefield') + game.castSpell('p1', object.id) + game.resolveStack() + assert.equal(object.zone, 'battlefield') + assert.equal(player.commanderCasts[object.id], 1) + + game.moveToZone(object, 'graveyard') + assert.equal(object.zone, 'command') + assert.equal(player.graveyard.length, 0) + + game.castSpell('p1', object.id) + game.resolveStack() + assert.equal(object.zone, 'battlefield') + assert.equal(player.commanderCasts[object.id], 2) + assert.equal(player.battlefield.map(id => game.getObject(id)).filter(land => land.tapped).length, 4) +}) + +test('twenty-one commander damage loses the game', () => { + const commander = commanderDefinition('Big Commander', { power: 21, manaCost: '{0}', manaValue: 0 }) + const game = new Game({ + seed: 1, + startingHandSize: 0, + commander: true, + players: [ + { id: 'p1', deck: [], commander }, + { id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, + ], + }) + game.start() + const object = game.getObject(game.getPlayer('p1').command[0]) + + game.castSpell('p1', object.id) + game.resolveStack() + object.enteredTurn = 0 + + game.declareAttackers('p1', [{ attackerId: object.id, defenderId: 'p2' }]) + game.declareBlockers('p2', []) + game.resolveCombatDamage() + + assert.equal(game.getPlayer('p2').commanderDamage[object.id], 21) + assert.equal(game.getPlayer('p2').lost, true) + assert.equal(game.winner, 'p1') +}) diff --git a/backend/test/effects.test.ts b/backend/test/effects.test.ts new file mode 100644 index 0000000..293cf81 --- /dev/null +++ b/backend/test/effects.test.ts @@ -0,0 +1,297 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { compileText } from '../src/effects/compile.js' +import { formatAbility } from '../src/effects/format.js' +import { parsePseudoCard } from '../src/effects/pseudo.js' +import type { Ability, Effect, Target } from '../src/effects/types.js' + +function creature(text: string, keywords: string[] = []): Ability[] { + return compileText(text, 'Test Creature', keywords, 'Creature — Human') +} + +function spell(text: string): Ability[] { + return compileText(text, 'Test Spell', [], 'Instant') +} + +test('keyword lines become keyword abilities', () => { + const [ability] = creature('Flying, vigilance, lifelink') + assert.equal(ability.kind, 'keywords') + if (ability.kind !== 'keywords') return + assert.deepEqual(ability.keywords.map(keyword => keyword.keyword), ['Flying', 'Vigilance', 'Lifelink']) +}) + +test('enters trigger with a draw effect', () => { + const [ability] = creature('When this creature enters, draw a card.') + assert.equal(ability.kind, 'triggered') + if (ability.kind !== 'triggered') return + assert.deepEqual(ability.event, { kind: 'enters', subject: { kind: 'self' } }) + assert.equal(ability.effects.length, 1) + assert.equal(ability.effects[0].op, 'draw') +}) + +test('activated mana ability', () => { + const [ability] = creature('{T}: Add {G}.') + assert.equal(ability.kind, 'activated') + if (ability.kind !== 'activated') return + assert.deepEqual(ability.costs, [{ kind: 'tap' }]) + assert.deepEqual(ability.effects[0], { + op: 'add_mana', + player: 'you', + mana: { kind: 'symbols', symbols: ['{G}'] }, + }) +}) + +test('search effect keeps destination, tapped, and shuffle', () => { + const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.') + assert.equal(ability.kind, 'spell') + if (ability.kind !== 'spell') return + assert.deepEqual(ability.effects[0], { + op: 'search', + player: 'you', + selector: { types: ['land'], supertypes: ['basic'] }, + amount: { kind: 'number', value: 1 }, + destination: 'battlefield', + tapped: true, + shuffle: true, + }) +}) + +test('"it" refers to the triggering object when unambiguous', () => { + const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.') + assert.equal(ability.kind, 'triggered') + if (ability.kind !== 'triggered') return + const effect = ability.effects[0] + assert.equal(effect.op, 'put_counters') + if (effect.op !== 'put_counters') return + assert.deepEqual(effect.target, { kind: 'trigger_subject' }) +}) + +test('ambiguous "it" is left unsupported instead of guessed', () => { + const [ability] = creature( + 'When this creature enters, tap target creature an opponent controls and put a stun counter on it.', + ) + assert.equal(ability.kind, 'unsupported') +}) + +test('modal text is unsupported', () => { + const [ability] = creature('Choose one —') + assert.equal(ability.kind, 'unsupported') + if (ability.kind !== 'unsupported') return + assert.equal(ability.reason, 'modal') +}) + +test('static anthem', () => { + const [ability] = creature('Creatures you control get +1/+1.') + assert.equal(ability.kind, 'static') + if (ability.kind !== 'static') return + assert.equal(ability.effects[0].op, 'pump') + if (ability.effects[0].op !== 'pump') return + assert.equal(ability.effects[0].power.kind, 'number') + const target = ability.effects[0].target as Extract + assert.equal(target.mode, 'each') + assert.equal(target.selector.controller, 'you') +}) + +test('enters-with-counters is a static replacement effect', () => { + const [ability] = creature('This creature enters with X +1/+1 counters on it.') + assert.equal(ability.kind, 'static') + if (ability.kind !== 'static') return + assert.deepEqual(ability.effects[0], { + op: 'enters_with_counters', + target: { kind: 'self' }, + counter: '+1/+1', + amount: { kind: 'x' }, + }) +}) + +test('trigger condition cards in graveyard', () => { + const [ability] = creature( + 'Threshold — As long as there are seven or more cards in your graveyard, this creature gets +1/+1 and has first strike.', + ) + assert.equal(ability.kind, 'static') + if (ability.kind !== 'static') return + assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 }) +}) + +test('formatter renders pseudocode', () => { + const [ability] = creature('When this creature enters, draw a card.') + const text = formatAbility(ability) + assert.match(text, /on enters\(this\)/) + assert.match(text, /draw\(you, 1\)/) +}) + +test('token copy of the triggering nontoken Dragon loses legendary', () => { + const [ability] = creature( + "Whenever another nontoken Dragon you control enters, create a token that's a copy of it, except the token isn't legendary.", + ) + assert.equal(ability.kind, 'triggered') + if (ability.kind !== 'triggered') return + assert.deepEqual(ability.event, { + kind: 'enters', + subject: { + kind: 'object', + selector: { + other: true, + controller: 'you', + token: false, + types: ['creature'], + subtypes: ['dragon'], + }, + mode: 'each', + }, + }) + const effect = ability.effects[0] + assert.equal(effect.op, 'create_token') + if (effect.op !== 'create_token') return + assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' }) + assert.equal(effect.notLegendary, true) + assert.equal(formatAbility(ability), 'on enters(each other nontoken dragon creature you control):\n create_token(you, 1, copy of the triggering object, not legendary)') +}) + +test('all effects are typed', () => { + const [ability] = spell('Draw two cards, then discard a card.') + assert.equal(ability.kind, 'spell') + if (ability.kind !== 'spell') return + const effects: Effect[] = ability.effects + assert.deepEqual(effects.map(effect => effect.op), ['draw', 'discard']) +}) + +test('a leading duration applies to the effect', () => { + const [ability] = spell('Until end of turn, target creature gets +2/+0 and gains first strike.') + assert.equal(ability.kind, 'spell') + if (ability.kind !== 'spell') return + const [pump, grant] = ability.effects + assert.equal(pump.op, 'pump') + assert.equal(grant.op, 'grant') + if (pump.op !== 'pump' || grant.op !== 'grant') return + assert.equal(pump.duration, 'until_end_of_turn') + assert.equal(grant.duration, 'until_end_of_turn') +}) + +test('"When you do" becomes a reflexive condition and energy costs are payable', () => { + const [ability] = creature( + 'Whenever a creature attacks, you may pay {3}. When you do, put a +1/+1 counter on that creature.', + ) + assert.equal(ability.kind, 'triggered') + if (ability.kind !== 'triggered') return + const conditional = ability.effects[1] + assert.equal(conditional.op, 'conditional') + if (conditional.op !== 'conditional') return + assert.deepEqual(conditional.condition, { kind: 'if_you_do' }) + + const [activated] = creature('{T}, Pay {E}{E}: This creature deals 1 damage to target creature.') + assert.equal(activated.kind, 'activated') + if (activated.kind !== 'activated') return + assert.deepEqual(activated.costs, [ + { kind: 'tap' }, + { kind: 'energy', amount: 2 }, + ]) +}) + +test('for-each pump keeps the zero stat', () => { + const [ability] = creature('This creature gets +1/+0 for each artifact you control.') + assert.equal(ability.kind, 'static') + if (ability.kind !== 'static') return + const effect = ability.effects[0] + assert.equal(effect.op, 'pump') + if (effect.op !== 'pump') return + assert.deepEqual(effect.power, { kind: 'count', selector: { types: ['artifact'], controller: 'you' } }) + assert.deepEqual(effect.toughness, { kind: 'number', value: 0 }) +}) + +test('"When " triggers and bare "gain life" effects parse', () => { + const [dies] = creature('When enchanted creature dies, return this to its owner\'s hand.') + assert.equal(dies.kind, 'triggered') + if (dies.kind !== 'triggered') return + assert.deepEqual(dies.event, { + kind: 'dies', + subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' }, + }) + + const [upkeep] = creature('At the beginning of your upkeep, you may gain 1 life.') + assert.equal(upkeep.kind, 'triggered') + if (upkeep.kind !== 'triggered') return + assert.equal(upkeep.optional, true) + assert.deepEqual(upkeep.effects[0], { + op: 'life', + player: 'you', + amount: { kind: 'number', value: 1 }, + mode: 'gain', + }) +}) + +test('a trailing condition becomes a static condition', () => { + const [ability] = creature('This creature cannot attack if defending player controls an untapped land.') + assert.equal(ability.kind, 'static') + if (ability.kind !== 'static') return + assert.deepEqual(ability.condition, { + kind: 'defending_player_controls', + selector: { tapped: false, types: ['land'] }, + }) +}) + +test('"until the end of your next turn" gets its own duration', () => { + for (const text of [ + 'Target creature gets +2/+2 until the end of your next turn.', + 'Until the end of your next turn, target creature gets +2/+2.', + ]) { + const [ability] = spell(text) + assert.equal(ability.kind, 'spell') + if (ability.kind !== 'spell') return + const effect = ability.effects[0] + assert.equal(effect.op, 'pump') + if (effect.op !== 'pump') return + assert.equal(effect.duration, 'until_end_of_your_next_turn') + + const pseudo = formatAbility(ability) + assert.match(pseudo, /until the end of your next turn/) + assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) + } +}) + +test('parameterized keywords accept an em dash', () => { + const [escape] = creature('Escape—{2}{R}, Exile three other cards from your graveyard.') + assert.equal(escape.kind, 'keyword') + if (escape.kind !== 'keyword') return + assert.equal(escape.keyword, 'Escape') + + const [fabricate] = creature('Fabricate 1') + assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' }) +}) + +test('counter-removal costs parse and round-trip through pseudocode', () => { + const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.') + assert.equal(self.kind, 'activated') + if (self.kind !== 'activated') return + assert.deepEqual(self.costs, [ + { kind: 'mana', symbols: '{2}{u}' }, + { kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } }, + ]) + + const pseudo = formatAbility(self) + assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/) + assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) + + const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.') + assert.equal(other.kind, 'activated') + if (other.kind !== 'activated') return + assert.deepEqual(other.costs, [{ + kind: 'remove_counters', + counter: 'spore', + amount: { kind: 'number', value: 3 }, + selector: { controller: 'you', types: ['creature'] }, + }]) +}) + +test('a trigger returns its own card from the graveyard', () => { + const [ability] = creature('When this dies, return this from your graveyard to the battlefield with a finality counter on it.') + assert.equal(ability.kind, 'triggered') + if (ability.kind !== 'triggered') return + assert.deepEqual(ability.effects, [{ + op: 'return_to_battlefield', + target: { kind: 'self' }, + tapped: false, + transformed: undefined, + counters: { counter: 'finality', amount: { kind: 'number', value: 1 } }, + }]) +}) diff --git a/backend/test/game.test.ts b/backend/test/game.test.ts new file mode 100644 index 0000000..8e8351f --- /dev/null +++ b/backend/test/game.test.ts @@ -0,0 +1,647 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { Game, GameError } from '../src/game/game.js' +import type { Ability, Effect } from '../src/effects/types.js' +import type { CardDefinition } from '../src/game/types.js' + +function card(name: string, overrides: Partial = {}): CardDefinition { + return { + oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'), + name, + typeLine: 'Creature — Test', + manaValue: 0, + colors: [], + abilities: [], + ...overrides, + } +} + +function creature(name: string, power: number, toughness: number, abilities: Ability[] = []): CardDefinition { + return card(name, { typeLine: 'Creature — Test', power, toughness, abilities }) +} + +function spell(name: string, effects: Effect[], manaCost = ''): CardDefinition { + return card(name, { typeLine: 'Instant', manaCost, manaValue: 0, abilities: [{ kind: 'spell', effects, optional: false, text: name }] }) +} + +function land(name: string, color: string): CardDefinition { + return card(name, { + typeLine: `Basic Land — ${name}`, + power: undefined, + toughness: undefined, + abilities: [{ + kind: 'activated', + costs: [{ kind: 'tap' }], + effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }], + optional: false, + text: `{T}: Add {${color}}.`, + }], + }) +} + +function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game { + const game = new Game({ + seed: 7, + startingHandSize: 0, + players: players.map(player => ({ id: player.id, life: player.life, deck: player.deck ?? [card('Filler')] })), + }) + return game +} + +test('turns start at the first main phase, draw opening hands, and pass to the next player', () => { + const forest = land('Forest', 'G') + const game = new Game({ + seed: 1, + startingHandSize: 7, + players: [ + { id: 'p1', deck: Array.from({ length: 10 }, () => forest) }, + { id: 'p2', deck: Array.from({ length: 10 }, () => forest) }, + ], + }) + game.start() + + assert.equal(game.turn, 1) + assert.equal(game.activePlayer, 'p1') + assert.equal(game.phase, 'precombat_main') + assert.equal(game.step, 'main') + assert.equal(game.priority, 'p1') + assert.equal(game.getPlayer('p1').life, 40) + assert.equal(game.getPlayer('p1').hand.length, 7) + assert.equal(game.getPlayer('p1').library.length, 3) + + game.endTurn('p1') + + assert.equal(game.turn, 2) + assert.equal(game.activePlayer, 'p2') + assert.equal(game.getPlayer('p2').hand.length, 8) + assert.equal(game.getPlayer('p1').hand.length, 7) +}) + +test('passing priority twice advances from the main phase into combat', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + + game.pass('p1') + assert.equal(game.priority, 'p2') + game.pass('p2') + + assert.equal(game.phase, 'combat') + assert.equal(game.step, 'declare_attackers') + assert.equal(game.priority, 'p1') +}) + +test('a spell goes on the stack, auto-taps mana, and resolves its compiled effect', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield') + const bolt = game.addCard('p1', spell('Lightning Bolt', [ + { op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }, + ], '{R}'), 'hand') + + game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] }) + + assert.equal(game.stack.length, 1) + assert.equal(mountain.tapped, true) + assert.equal(game.priority, 'p2') + + game.resolveStack() + + assert.equal(game.stack.length, 0) + assert.equal(game.getPlayer('p2').life, 37) + assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id)) +}) + +test('permanents can be repositioned by their controller and positions are cleared on zone changes', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield') + + game.movePermanent('p1', bear.id, 0.25, 0.75) + assert.deepEqual(bear.position, { x: 0.25, y: 0.75 }) + + game.movePermanent('p1', bear.id, -1, 2) + assert.deepEqual(bear.position, { x: 0, y: 1 }) + assert.throws(() => game.movePermanent('p2', bear.id, 0.5, 0.5), /control/) + + game.moveToZone(bear, 'graveyard') + assert.equal(bear.position, undefined) +}) + +test('enters triggers from compiled card code fire and resolve through the stack', () => { + const soulWarden = card('Soul Warden', { + typeLine: 'Creature — Human Cleric', + power: 1, + toughness: 1, + colors: ['W'], + abilities: [{ + kind: 'triggered', + event: { + kind: 'enters', + subject: { kind: 'object', selector: { other: true, types: ['creature'] }, mode: 'each' }, + }, + effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'gain' }], + optional: false, + text: 'Whenever another creature enters, you gain 1 life.', + }], + }) + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + game.addCard('p1', soulWarden, 'battlefield') + const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1), 'hand') + + game.castSpell('p1', elves.id) + game.resolveStack() + + assert.equal(game.getPlayer('p1').life, 41) + assert.ok(game.getPlayer('p1').battlefield.includes(elves.id)) +}) + +test('activated mana abilities produce mana and creatures have summoning sickness', () => { + const solRing = card('Sol Ring', { + typeLine: 'Artifact', + power: undefined, + toughness: undefined, + abilities: [{ + kind: 'activated', + costs: [{ kind: 'tap' }], + effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{C}', '{C}'] } }], + optional: false, + text: '{T}: Add {C}{C}.', + }], + }) + const game = setup([{ id: 'p1', deck: Array.from({ length: 5 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 5 }, () => card('Filler')) }]) + game.start() + const ring = game.addCard('p1', solRing, 'battlefield') + const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1, [{ + kind: 'activated', + costs: [{ kind: 'tap' }], + effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{G}'] } }], + optional: false, + text: '{T}: Add {G}.', + }]), 'battlefield') + + game.activateAbility('p1', ring.id, 0) + assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 2 }) + assert.equal(ring.tapped, true) + assert.throws(() => game.activateAbility('p1', elves.id, 0), GameError) + + game.endTurn('p1') + game.endTurn('p2') + assert.equal(elves.tapped, false) + game.activateAbility('p1', elves.id, 0) + assert.equal(game.getPlayer('p1').manaPool.G, 1) +}) + +test('static pump effects apply to matching creatures only', () => { + const anthem = card('Glorious Anthem', { + typeLine: 'Enchantment', + power: undefined, + toughness: undefined, + abilities: [{ + kind: 'static', + effects: [{ + op: 'pump', + target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' }, + power: { kind: 'number', value: 1 }, + toughness: { kind: 'number', value: 1 }, + }], + text: 'Creatures you control get +1/+1.', + }], + }) + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const anthemObject = game.addCard('p1', anthem, 'battlefield') + const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield') + const enemy = game.addCard('p2', creature('Enemy Bear', 2, 2), 'battlefield') + + assert.equal(game.getPower(bear), 3) + assert.equal(game.getToughness(bear), 3) + assert.equal(game.getPower(enemy), 2) + assert.equal(game.getPower(anthemObject), 0) +}) + +test('temporary pump effects expire at end of turn', () => { + const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }]) + game.start() + const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield') + const growth = game.addCard('p1', spell('Giant Growth', [{ + op: 'pump', + target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' }, + power: { kind: 'number', value: 3 }, + toughness: { kind: 'number', value: 3 }, + duration: 'until_end_of_turn', + }]), 'hand') + + game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] }) + game.resolveStack() + assert.equal(game.getPower(bear), 5) + assert.equal(game.getToughness(bear), 5) + + game.endTurn('p1') + assert.equal(game.getPower(bear), 2) +}) + +test('"until the end of your next turn" lasts through the controller next turn', () => { + const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }]) + game.start() + const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield') + const growth = game.addCard('p1', spell('Growth', [{ + op: 'pump', + target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' }, + power: { kind: 'number', value: 3 }, + toughness: { kind: 'number', value: 3 }, + duration: 'until_end_of_your_next_turn', + }]), 'hand') + + game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] }) + game.resolveStack() + assert.equal(game.getPower(bear), 5) + + game.endTurn('p1') + assert.equal(game.getPower(bear), 5) + + game.endTurn('p2') + assert.equal(game.getPower(bear), 5) + + game.endTurn('p1') + assert.equal(game.getPower(bear), 2) +}) + +test('combat damage kills creatures and moves them to the graveyard', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + const attacker = game.addCard('p1', creature('Attacker', 2, 2), 'battlefield') + const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield') + game.start() + + game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }]) + assert.equal(game.step, 'declare_blockers') + assert.equal(game.priority, 'p2') + assert.equal(attacker.tapped, true) + + game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }]) + game.resolveCombatDamage() + + assert.equal(game.getPlayer('p2').life, 40) + assert.equal(game.step, 'end_combat') + assert.ok(game.getPlayer('p1').graveyard.includes(attacker.id)) + assert.ok(game.getPlayer('p2').graveyard.includes(blocker.id)) +}) + +test('unblocked attackers deal damage to the defending player', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + const attacker = game.addCard('p1', creature('Attacker', 3, 3), 'battlefield') + game.start() + + game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }]) + game.declareBlockers('p2', []) + game.resolveCombatDamage() + + assert.equal(game.getPlayer('p2').life, 37) +}) + +test('counterspell counters a spell on the stack', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + game.addCard('p1', land('Mountain', 'R'), 'battlefield') + game.addCard('p2', land('Island', 'U'), 'battlefield') + game.addCard('p2', land('Island', 'U'), 'battlefield') + const bolt = game.addCard('p1', spell('Lightning Bolt', [ + { op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }, + ], '{R}'), 'hand') + const counterspell = game.addCard('p2', spell('Counterspell', [ + { op: 'counter', what: 'spell', target: { kind: 'spell', selector: { types: [] }, mode: 'target' } }, + ], '{U}{U}'), 'hand') + + game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] }) + game.castSpell('p2', counterspell.id) + assert.equal(game.stack.length, 2) + + game.resolveStack() + + assert.equal(game.getPlayer('p2').life, 40) + assert.equal(game.stack.length, 0) + assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id)) + assert.ok(game.getPlayer('p2').graveyard.includes(counterspell.id)) +}) + +test('activated abilities create tokens that enter the battlefield', () => { + const maker = card('Goblin Maker', { + typeLine: 'Artifact', + power: undefined, + toughness: undefined, + abilities: [{ + kind: 'activated', + costs: [{ kind: 'tap' }], + effects: [{ + op: 'create_token', + player: 'you', + amount: { kind: 'number', value: 1 }, + token: { name: 'Goblin', types: ['creature'], subtypes: ['goblin'], colors: ['R'], power: { kind: 'number', value: 1 }, toughness: { kind: 'number', value: 1 } }, + }], + optional: false, + text: '{T}: Create a 1/1 Goblin.', + }], + }) + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const source = game.addCard('p1', maker, 'battlefield') + + game.activateAbility('p1', source.id, 0) + assert.equal(game.stack.length, 1) + game.resolveStack() + + const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken) + assert.equal(tokens.length, 1) + assert.equal(tokens[0].definition.name, 'Goblin') + assert.equal(game.getPower(tokens[0]), 1) +}) + +test('search effects find cards in the library and put them onto the battlefield tapped', () => { + const forest = land('Forest', 'G') + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const found = game.addCard('p1', forest, 'library') + const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{ + op: 'search', + player: 'you', + selector: { types: ['land'], supertypes: ['basic'] }, + amount: { kind: 'number', value: 1 }, + destination: 'battlefield', + tapped: true, + shuffle: true, + }]), 'hand') + + game.castSpell('p1', rampantGrowth.id) + game.resolveStack() + + assert.ok(game.getPlayer('p1').battlefield.includes(found.id)) + assert.equal(found.tapped, true) +}) + +test('search effects let the player pick among multiple matching cards', () => { + const forest = land('Forest', 'G') + const island = land('Island', 'U') + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const forestObject = game.addCard('p1', forest, 'library') + const islandObject = game.addCard('p1', island, 'library') + const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{ + op: 'search', + player: 'you', + selector: { types: ['land'], supertypes: ['basic'] }, + amount: { kind: 'number', value: 1 }, + destination: 'battlefield', + tapped: true, + shuffle: true, + }]), 'hand') + + game.castSpell('p1', rampantGrowth.id) + game.resolveStack() + + assert.equal(game.pendingSearch?.playerId, 'p1') + assert.deepEqual( + game.searchCandidates('p1').map(object => object.id).sort(), + [forestObject.id, islandObject.id].sort(), + ) + assert.equal(forestObject.zone, 'library') + assert.throws(() => game.pass('p1'), GameError) + + game.chooseSearchCard('p1', islandObject.id) + + assert.equal(game.pendingSearch, undefined) + assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id)) + assert.equal(islandObject.tapped, true) + assert.ok(game.getPlayer('p1').library.includes(forestObject.id)) +}) + +test('autoAdvance stops instead of passing while a search needs a pick', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + game.addCard('p1', land('Forest', 'G'), 'library') + game.addCard('p1', land('Island', 'U'), 'library') + const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{ + op: 'search', + player: 'you', + selector: { types: ['land'], supertypes: ['basic'] }, + amount: { kind: 'number', value: 1 }, + destination: 'battlefield', + tapped: true, + shuffle: true, + }]), 'hand') + + game.castSpell('p1', rampantGrowth.id) + game.autoAdvance() + + assert.equal(game.pendingSearch?.playerId, 'p1') + assert.equal(game.priority, 'p1') +}) + +test('static replacement effects make permanents enter tapped with counters', () => { + const slow = creature('Slow Bear', 2, 2, [{ + kind: 'static', + effects: [{ op: 'enters_tapped', target: { kind: 'self' } }], + text: 'This enters tapped.', + }, { + kind: 'static', + effects: [{ + op: 'enters_with_counters', + target: { kind: 'self' }, + counter: '+1/+1', + amount: { kind: 'number', value: 1 }, + }], + text: 'This enters with a +1/+1 counter.', + }]) + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const bear = game.addCard('p1', slow, 'hand') + + game.castSpell('p1', bear.id) + game.resolveStack() + + assert.equal(bear.tapped, true) + assert.equal(bear.counters['+1/+1'], 1) + assert.equal(game.getPower(bear), 3) + assert.equal(game.getToughness(bear), 3) +}) + +test('a player who runs out of cards loses and the last player wins', () => { + const game = new Game({ + seed: 3, + startingHandSize: 0, + players: [ + { id: 'p1', deck: [card('Filler')] }, + { id: 'p2', deck: [] }, + ], + }) + game.start() + game.endTurn('p1') + + assert.equal(game.status, 'finished') + assert.equal(game.winner, 'p1') + assert.equal(game.getPlayer('p2').lost, true) +}) + +test('lethal damage to a player ends the game', () => { + const game = setup([{ id: 'p1' }, { id: 'p2', life: 3 }]) + game.start() + game.addCard('p1', land('Mountain', 'R'), 'battlefield') + const bolt = game.addCard('p1', spell('Lightning Bolt', [ + { op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }, + ], '{R}'), 'hand') + + game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] }) + game.resolveStack() + + assert.equal(game.status, 'finished') + assert.equal(game.winner, 'p1') + assert.equal(game.getPlayer('p2').life, 0) +}) + +test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield') + const expensive = game.addCard('p1', spell('Expensive Spell', [], '{R}{R}'), 'hand') + + assert.throws(() => game.castSpell('p1', expensive.id), GameError) + assert.equal(mountain.tapped, false) + assert.equal(game.getPlayer('p1').manaPool.R, 0) + assert.ok(game.getPlayer('p1').hand.includes(expensive.id)) +}) + +test('phyrexian mana can be paid with exactly enough life', () => { + const game = setup([{ id: 'p1', life: 2 }, { id: 'p2' }]) + game.start() + const spellCard = game.addCard('p1', spell('Gitaxian Probe', [], '{W/P}'), 'hand') + + assert.doesNotThrow(() => game.castSpell('p1', spellCard.id)) + assert.equal(game.getPlayer('p1').life, 0) + assert.equal(game.status, 'finished') + assert.equal(game.winner, 'p2') +}) + +test('an unless cost auto-taps the mana sources of the payer', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield') + const forests = [ + game.addCard('p2', land('Forest', 'G'), 'battlefield'), + game.addCard('p2', land('Forest', 'G'), 'battlefield'), + ] + const edict = game.addCard('p1', spell('Edict', [{ + op: 'sacrifice', + player: 'opponent', + target: { kind: 'object', selector: { types: ['creature'] } }, + unless: { kind: 'mana', symbols: '{2}' }, + }]), 'hand') + + game.castSpell('p1', edict.id, { + targets: [{ kind: 'player', id: 'p2' }, { kind: 'object', id: bear.id }], + }) + game.resolveStack() + + assert.equal(bear.zone, 'battlefield') + assert.ok(forests.every(forest => forest.tapped)) + assert.equal(game.getPlayer('p2').manaPool.G, 0) +}) + +test('canPlayCard reports legal lands and spells for the player with priority', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }]) + game.start() + const forest = game.addCard('p1', land('Forest', 'G'), 'hand') + const bear = game.addCard('p1', card('Grizzly Bears', { + typeLine: 'Creature — Bear', + power: 2, + toughness: 2, + manaCost: '{G}', + }), 'hand') + + assert.equal(game.canPlayCard('p1', forest.id), true) + assert.equal(game.canPlayCard('p1', bear.id), false) + assert.equal(game.canPlayCard('p2', forest.id), false) + + game.playLand('p1', forest.id) + assert.equal(game.canPlayCard('p1', bear.id), true) +}) + +test('autoAdvance skips empty phases and stops when someone can act', () => { + const expensive = card('Expensive', { manaCost: '{5}' }) + const game = new Game({ + seed: 3, + startingHandSize: 0, + players: [ + { id: 'p1', deck: [expensive] }, + { id: 'p2', deck: [expensive] }, + ], + }) + game.start() + game.addCard('p1', land('Forest', 'G'), 'battlefield') + + // The only action is a mana ability, which should not hold the phase open. + game.autoAdvance() + assert.equal(game.turn, 2) + assert.equal(game.activePlayer, 'p2') + assert.equal(game.phase, 'precombat_main') + assert.equal(game.priority, 'p2') + + const hasty = creature('Hasty', 2, 2, [{ kind: 'keyword', keyword: 'Haste' }]) + game.addCard('p2', hasty, 'battlefield') + game.autoAdvance() + assert.equal(game.turn, 2) + assert.equal(game.phase, 'combat') + assert.equal(game.step, 'declare_attackers') + assert.equal(game.priority, 'p2') +}) + +test('every defending player declares blocks before combat damage in multiplayer', () => { + const game = setup([{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }]) + game.start() + const first = game.addCard('p1', creature('First Attacker', 2, 2), 'battlefield') + const second = game.addCard('p1', creature('Second Attacker', 3, 3), 'battlefield') + first.enteredTurn = 0 + second.enteredTurn = 0 + + game.declareAttackers('p1', [ + { attackerId: first.id, defenderId: 'p2' }, + { attackerId: second.id, defenderId: 'p3' }, + ]) + assert.equal(game.step, 'declare_blockers') + + game.declareBlockers('p2', []) + assert.equal(game.step, 'declare_blockers') + assert.equal(game.priority, 'p3') + + game.declareBlockers('p3', []) + assert.equal(game.step, 'combat_damage') + + game.resolveCombatDamage() + assert.equal(game.getPlayer('p2').life, 38) + assert.equal(game.getPlayer('p3').life, 37) +}) + +test('counter-removal costs are paid and fail when counters run out', () => { + const vessel = card('Spore Vessel', { + typeLine: 'Artifact', + power: undefined, + toughness: undefined, + abilities: [{ + kind: 'activated', + costs: [{ kind: 'remove_counters', counter: 'spore', amount: { kind: 'number', value: 2 } }], + effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }], + optional: false, + text: 'Remove two spore counters from this: Draw a card.', + }], + }) + const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2' }]) + game.start() + const source = game.addCard('p1', vessel, 'battlefield') + source.counters.spore = 3 + + game.activateAbility('p1', source.id, 0) + game.resolveStack() + assert.equal(source.counters.spore, 1) + assert.equal(game.getPlayer('p1').hand.length, 1) + + assert.throws(() => game.activateAbility('p1', source.id, 0), GameError) + assert.equal(source.counters.spore, 1) +}) diff --git a/backend/test/images.test.ts b/backend/test/images.test.ts new file mode 100644 index 0000000..dfe54e6 --- /dev/null +++ b/backend/test/images.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { + PlaymatError, + cardImage, + deletePlaymatImage, + playmatImage, + scryfallArtUrl, + scryfallImageUrl, + storePlaymatImage, +} from '../src/images.js' + +const ART = Buffer.from([0xff, 0xd8, 0xff, 0xd9]) + +test('only https URLs on the Scryfall image host are accepted', () => { + assert.equal( + scryfallImageUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'), + 'https://cards.scryfall.io/normal/front/a/b/art.jpg?123', + ) + assert.equal(scryfallImageUrl('http://cards.scryfall.io/art.jpg'), undefined) + assert.equal(scryfallImageUrl('https://example.com/art.jpg'), undefined) + assert.equal(scryfallImageUrl('not a url'), undefined) + assert.equal(scryfallImageUrl(undefined), undefined) +}) + +test('playmat art swaps the card image for the wide Scryfall crop', () => { + assert.equal( + scryfallArtUrl('https://cards.scryfall.io/normal/front/a/b/art.jpg?123'), + 'https://cards.scryfall.io/art_crop/front/a/b/art.jpg?123', + ) + assert.equal(scryfallArtUrl(undefined), undefined) + assert.equal(scryfallArtUrl('https://example.com/normal/art.jpg'), undefined) +}) + +test('uploaded playmats are stored, served and deleted', async () => { + const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-')) + const jpeg = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.from('pixels')]) + + try { + const id = await storePlaymatImage(`data:image/jpeg;base64,${jpeg.toString('base64')}`, dir) + assert.deepEqual(await playmatImage(id, dir), jpeg) + + await deletePlaymatImage(id, dir) + assert.equal(await playmatImage(id, dir), undefined) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test('uploaded playmats must be JPEG data URLs with a JPEG signature', async () => { + const dir = await mkdtemp(join(tmpdir(), 'commander-playmats-')) + + try { + await assert.rejects(storePlaymatImage('data:image/png;base64,AAAA', dir), PlaymatError) + await assert.rejects(storePlaymatImage('data:image/jpeg;base64,AAAA', dir), PlaymatError) + await assert.rejects(storePlaymatImage('not an image', dir), PlaymatError) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test('card art is downloaded once and then served from the disk cache', async () => { + let requests = 0 + const server = createServer((_request, response) => { + requests++ + response.writeHead(200, { 'Content-Type': 'image/jpeg' }) + response.end(ART) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const dir = await mkdtemp(join(tmpdir(), 'commander-images-')) + + try { + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/art.jpg` + + assert.deepEqual(await cardImage('card-id', url, dir), ART) + assert.deepEqual(await readFile(join(dir, 'card-id.jpg')), ART) + + assert.deepEqual(await cardImage('card-id', url, dir), ART) + assert.equal(requests, 1) + } finally { + await new Promise(resolve => server.close(resolve)) + await rm(dir, { recursive: true, force: true }) + } +}) diff --git a/backend/test/pseudo.test.ts b/backend/test/pseudo.test.ts new file mode 100644 index 0000000..3c743f4 --- /dev/null +++ b/backend/test/pseudo.test.ts @@ -0,0 +1,92 @@ +import assert from 'node:assert/strict' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import type { Card } from '../src/cards.js' +import { formatCard } from '../src/effects/format.js' +import { + compileImplementation, + deleteOverride, + readAllOverrides, + readOverride, + writeOverride, +} from '../src/effects/implementations.js' +import { parsePseudoCard, PseudoParseError } from '../src/effects/pseudo.js' + +const CARD: Card = { + oracle_id: '00000000-0000-4000-8000-000000000001', + name: 'Test Card', + layout: 'normal', + cmc: 1, + type_line: 'Creature — Human', + colors: [], + color_identity: [], + keywords: [], +} + +const SOURCE = `on enters(this): + choose 1: + 1. exile(target other creature you own); schedule(next_end_step): + return_to_battlefield(the chosen target) +static: + grant_ability(each enchanted land): + on upkeep(you) (may): + pay({W}{W}) + if you do: + gain_life(you, 1)` + +test('pseudocode round-trips through the compiler and formatter', () => { + const compiled = compileImplementation(CARD, SOURCE) + assert.equal(compiled.manual, true) + assert.equal(compiled.status, 'supported') + + const rendered = formatCard(compiled) + const reparsed = compileImplementation(CARD, rendered) + assert.equal(formatCard(reparsed), rendered) + assert.equal(reparsed.abilities.length, 2) + + const [triggered] = reparsed.abilities + assert.equal(triggered.kind, 'triggered') + if (triggered.kind !== 'triggered') return + assert.equal(triggered.effects[0].op, 'modal') + if (triggered.effects[0].op !== 'modal') return + assert.equal(triggered.effects[0].modes[0][1].op, 'schedule') + + const staticAbility = reparsed.abilities[1] + assert.equal(staticAbility.kind, 'static') + if (staticAbility.kind !== 'static') return + assert.equal(staticAbility.effects[0].op, 'grant_ability') + if (staticAbility.effects[0].op !== 'grant_ability') return + assert.equal(staticAbility.effects[0].ability.kind, 'triggered') +}) + +test('invalid pseudocode reports its line', () => { + assert.throws( + () => parsePseudoCard('spell:\n draw(you)'), + (error: unknown) => error instanceof PseudoParseError && error.line === 2, + ) +}) + +test('manual implementations persist one file per card', async (t) => { + const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-')) + const previous = process.env.CARD_OVERRIDES_DIR + process.env.CARD_OVERRIDES_DIR = dir + t.after(async () => { + if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR + else process.env.CARD_OVERRIDES_DIR = previous + await rm(dir, { recursive: true, force: true }) + }) + + await writeOverride(CARD.oracle_id, SOURCE) + const stored = await readOverride(CARD.oracle_id) + assert.equal(stored?.source, `${SOURCE}\n`) + assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`) + + const compiled = compileImplementation(CARD, stored!.source) + assert.equal(compiled.manual, true) + assert.equal(compiled.status, 'supported') + + await deleteOverride(CARD.oracle_id) + assert.equal(await readOverride(CARD.oracle_id), undefined) +}) diff --git a/backend/test/rooms.test.ts b/backend/test/rooms.test.ts new file mode 100644 index 0000000..d8fc4db --- /dev/null +++ b/backend/test/rooms.test.ts @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { findCardByName } from '../src/cards.js' +import { createMatch, getMatchView, joinMatch, leaveMatch, setDeck, startMatch } from '../src/game/rooms.js' + +function deck(commanderName: string) { + const commander = findCardByName(commanderName) + const forest = findCardByName('Forest') + assert.ok(commander && forest) + return { + commander: commander.oracle_id, + cards: Array.from({ length: 99 }, () => forest.oracle_id), + } +} + +test('lobby decks can be swapped and invalid decks are rejected', () => { + const first = deck("Atraxa, Praetors' Voice") + const second = deck('Kenrith, the Returned King') + const { matchId, token } = createMatch('Host', first, 2) + + setDeck(matchId, token, second) + assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King') + + assert.throws(() => setDeck(matchId, token, { ...second, cards: [] }), /100/) + assert.equal(getMatchView(matchId, token).players[0].commander?.name, 'Kenrith, the Returned King') +}) + +test('leaving a started game forfeits the seat instead of erroring', () => { + const host = createMatch('Host', deck("Atraxa, Praetors' Voice"), 2) + const guest = joinMatch(host.matchId, 'Guest', deck('Kenrith, the Returned King')) + startMatch(host.matchId, host.token) + + leaveMatch(host.matchId, host.token) + + const view = getMatchView(host.matchId, guest.token) + assert.equal(view.status, 'finished') + assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true) +}) diff --git a/backend/test/translate.test.ts b/backend/test/translate.test.ts new file mode 100644 index 0000000..88d8907 --- /dev/null +++ b/backend/test/translate.test.ts @@ -0,0 +1,117 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import type { Card } from '../src/cards.js' +import { cleanTranslation, TranslationError, translateCard } from '../src/effects/translate.js' + +const CARD: Card = { + oracle_id: '00000000-0000-4000-8000-000000000002', + name: 'Test Spell', + layout: 'normal', + cmc: 2, + type_line: 'Sorcery', + colors: ['U'], + color_identity: ['U'], + keywords: [], + oracle_text: 'Draw two cards.', +} + +interface RequestBody { + model: string + messages: Array<{ role: string; content: string }> + temperature: number + max_tokens: number +} + +function fakeOpenRouter(content: string) { + let body: RequestBody | undefined + let headers: Record | undefined + const fetchImpl = async (_input: Parameters[0], init?: Parameters[1]) => { + body = JSON.parse(String(init?.body)) as RequestBody + headers = init?.headers as Record + return new Response(JSON.stringify({ choices: [{ message: { content } }] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + } + return { + fetchImpl: fetchImpl as typeof fetch, + get body() { + assert.ok(body) + return body + }, + get headers() { + assert.ok(headers) + return headers + }, + } +} + +test('translation asks for pseudocode only and validates the answer', async () => { + const fake = fakeOpenRouter('spell:\n draw(you, 2)') + const source = await translateCard(CARD, { + apiKey: 'test-key', + model: 'test/model', + fetch: fake.fetchImpl, + }) + + assert.equal(source, 'spell:\n draw(you, 2)') + assert.equal(fake.body.model, 'test/model') + assert.equal(fake.body.temperature, 0) + assert.equal(fake.body.max_tokens, 700) + assert.equal(fake.headers.Authorization, 'Bearer test-key') + assert.match(fake.body.messages[0].content, /pseudocode only/i) + assert.match(fake.body.messages[0].content, /Never invent an operation/) + assert.match(fake.body.messages[1].content, /Draw two cards\./) +}) + +test('a model code fence is removed before saving', async () => { + const fake = fakeOpenRouter('```\nspell:\n draw(you, 2)\n```') + const source = await translateCard(CARD, { + apiKey: 'test-key', + model: 'test/model', + fetch: fake.fetchImpl, + }) + assert.equal(source, 'spell:\n draw(you, 2)') + assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)') +}) + +test('prose instead of pseudocode is rejected', async () => { + const fake = fakeOpenRouter('Here is the translated card. It draws two cards.') + await assert.rejects( + translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }), + (error: unknown) => error instanceof TranslationError && /valid pseudocode/.test(error.message), + ) +}) + +test('missing API key is reported before any request', async () => { + let called = false + const fetchImpl = async () => { + called = true + return new Response('{}') + } + await assert.rejects( + translateCard(CARD, { apiKey: '', fetch: fetchImpl as typeof fetch }), + (error: unknown) => error instanceof TranslationError && error.status === 503, + ) + assert.equal(called, false) +}) + +test('multi-face cards receive their face names in the prompt', async () => { + const faces: Card = { + ...CARD, + layout: 'transform', + card_faces: [ + { name: 'Front', type_line: 'Creature', oracle_text: 'When this enters, draw a card.', colors: [] }, + { name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] }, + ], + } + const fake = fakeOpenRouter('## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying') + const source = await translateCard(faces, { + apiKey: 'test-key', + model: 'test/model', + fetch: fake.fetchImpl, + }) + assert.equal(source, '## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying') + assert.match(fake.body.messages[1].content, /## Front/) + assert.match(fake.body.messages[1].content, /## Back/) +}) diff --git a/backend/tsconfig.json b/backend/tsconfig.json new file mode 100644 index 0000000..b11afd4 --- /dev/null +++ b/backend/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src"] +} diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..bfca993 --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,40 @@ +name: commander-dev + +services: + backend: + build: + context: ./backend + target: dev + command: sh -c "npm install --no-audit --no-fund && npm run dev" + volumes: + - ./backend:/app + - backend_node_modules:/app/node_modules + # Host networking lets the container reach a MongoDB bound to 127.0.0.1. + network_mode: host + environment: + PORT: ${PORT:-4000} + CORS_ORIGIN: ${CORS_ORIGIN:-http://localhost:3000} + MONGODB_URI: ${MONGODB_URI:-mongodb://localhost:27017/commander} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-2.5-flash-lite} + + frontend: + build: + context: ./frontend + target: dev + command: sh -c "npm install --no-audit --no-fund && npm run dev -- --host 0.0.0.0" + volumes: + - ./frontend:/app + - frontend_node_modules:/app/node_modules + - frontend_nuxt:/app/.nuxt + ports: + - "${FRONTEND_PORT:-3000}:3000" + environment: + NUXT_PUBLIC_API_BASE: ${NUXT_PUBLIC_API_BASE:-http://localhost:4000} + depends_on: + - backend + +volumes: + backend_node_modules: + frontend_node_modules: + frontend_nuxt: diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..492736d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,44 @@ +name: commander + +services: + backend: + build: + context: ./backend + target: production + # Host networking lets the container reach a MongoDB bound to 127.0.0.1. + network_mode: host + environment: + PORT: 4000 + CORS_ORIGIN: ${CORS_ORIGIN:-http://localhost:3000} + MONGODB_URI: ${MONGODB_URI:-mongodb://localhost:27017/commander} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-2.5-flash-lite} + volumes: + - card_images:/app/data/images + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "wget -qO /dev/null http://127.0.0.1:4000/health"] + interval: 30s + timeout: 5s + retries: 3 + + frontend: + build: + context: ./frontend + target: production + ports: + - "${FRONTEND_PORT:-3000}:3000" + environment: + NUXT_PUBLIC_API_BASE: ${NUXT_PUBLIC_API_BASE:-http://localhost:4000} + depends_on: + backend: + condition: service_healthy + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "wget -qO /dev/null http://127.0.0.1:3000/"] + interval: 30s + timeout: 5s + retries: 3 + +volumes: + card_images: diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..0efa34b --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,6 @@ +node_modules +.nuxt +.output +.env +Dockerfile +.dockerignore diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..4a7f73a --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,24 @@ +# Nuxt dev/build outputs +.output +.data +.nuxt +.nitro +.cache +dist + +# Node dependencies +node_modules + +# Logs +logs +*.log + +# Misc +.DS_Store +.fleet +.idea + +# Local env files +.env +.env.* +!.env.example diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..5529881 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,22 @@ +FROM node:24-alpine AS base +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci + +FROM base AS dev +COPY . . +EXPOSE 3000 +CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"] + +FROM base AS build +COPY . . +RUN npm run build + +FROM node:24-alpine AS production +WORKDIR /app +ENV NODE_ENV=production +ENV HOST=0.0.0.0 +ENV PORT=3000 +COPY --from=build /app/.output ./.output +EXPOSE 3000 +CMD ["node", ".output/server/index.mjs"] diff --git a/frontend/app/app.vue b/frontend/app/app.vue new file mode 100644 index 0000000..a445681 --- /dev/null +++ b/frontend/app/app.vue @@ -0,0 +1,71 @@ + + + diff --git a/frontend/app/assets/main.css b/frontend/app/assets/main.css new file mode 100644 index 0000000..06ebba6 --- /dev/null +++ b/frontend/app/assets/main.css @@ -0,0 +1,411 @@ +:root { + color-scheme: dark; + --bg: #0f1117; + --panel: #171a23; + --panel-2: #11151d; + --line: #2a2f3d; + --text: #e8e6e3; + --muted: #9aa2b1; + --accent: #7aa2f7; + --ok: #7dd3a0; + --warn: #e8c07d; + --bad: #e07a7a; +} + +* { + box-sizing: border-box; +} + +html, +body, +#__nuxt { + min-height: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: system-ui, sans-serif; +} + +h1, h2, h3, p { + margin: 0; +} + +h1 { + font-size: 1.35rem; +} + +h2 { + font-size: 1.15rem; +} + +h3 { + font-size: 1rem; +} + +a { + color: var(--accent); +} + +.app-nav { + height: 3rem; + display: flex; + align-items: center; + gap: 1rem; + padding: 0 1.25rem; + border-bottom: 1px solid var(--line); + background: #12151d; +} + +.app-nav strong { + margin-right: 0.5rem; +} + +.app-nav a { + color: var(--muted); + text-decoration: none; + font-size: 0.9rem; + padding: 0.25rem 0; +} + +.app-nav a.router-link-active { + color: var(--text); + border-bottom: 2px solid var(--accent); +} + +.nav-games { + display: flex; + gap: 1rem; + margin-left: auto; + min-width: 0; + overflow-x: auto; +} + +.nav-games a { + white-space: nowrap; +} + +.head-actions { + display: flex; + align-items: center; + gap: 0.75rem; +} + +.tabs { + display: flex; + gap: 0.25rem; +} + +.tabs button { + padding: 0.3rem 0.6rem; + background: transparent; + border-color: transparent; + color: var(--muted); +} + +.tabs button.active { + color: var(--text); + border-color: var(--accent); +} + +main.fill-page { + height: calc(100vh - 3rem); + display: flex; + flex-direction: column; + padding: 1rem 1.25rem; + gap: 1rem; +} + +main.page { + max-width: 1200px; + margin: 0 auto; + padding: 1.25rem; + display: flex; + flex-direction: column; + gap: 1rem; +} + +main > header { + display: flex; + align-items: start; + justify-content: space-between; + flex-wrap: wrap; + gap: 1rem; +} + +.muted { + color: var(--muted); + font-size: 0.85rem; +} + +.error { + color: var(--bad); + font-size: 0.85rem; + white-space: pre-wrap; +} + +.ok { + color: var(--ok); +} + +.warn { + color: var(--warn); +} + +.layout { + display: grid; + grid-template-columns: minmax(18rem, 26rem) 1fr; + gap: 1rem; + min-height: 0; + flex: 1; +} + +.list-panel, +.detail-panel, +.panel { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 8px; + padding: 0.85rem; + min-height: 0; + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.search { + display: flex; + gap: 0.5rem; +} + +.filters { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +.filters select { + flex: 1 1 8rem; + min-width: 0; +} + +input, select, textarea, button { + font: inherit; + color: var(--text); + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; + padding: 0.45rem 0.6rem; +} + +input { + flex: 1; + min-width: 0; +} + +button { + cursor: pointer; +} + +button:disabled { + opacity: 0.45; + cursor: default; +} + +button:not(:disabled):hover { + border-color: var(--accent); +} + +button.primary { + border-color: var(--accent); +} + +button.danger { + border-color: var(--bad); + color: var(--bad); +} + +.list { + list-style: none; + margin: 0; + padding: 0; + overflow-y: auto; + flex: 1; + display: flex; + flex-direction: column; + gap: 2px; +} + +.card-list { + list-style: none; + margin: 0; + padding: 0; + overflow-y: auto; + flex: 1; + display: flex; + flex-direction: column; + gap: 2px; +} + +.detail-head { + display: flex; + align-items: start; + justify-content: space-between; + gap: 1rem; +} + +.card-row { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + text-align: left; + background: transparent; + border-color: transparent; + padding: 0.45rem 0.5rem; +} + +.card-row.selected { + background: #202636; + border-color: var(--accent); +} + +.card-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.card-main { + display: flex; + align-items: center; + gap: 0.5rem; + min-width: 0; +} + +.card-main .card-name { + min-width: 0; +} + +.badges { + display: flex; + align-items: center; + gap: 0.3rem; + flex-shrink: 0; +} + +.badge { + font-size: 0.7rem; + text-transform: uppercase; + letter-spacing: 0.03em; + border-radius: 99px; + padding: 0.1rem 0.45rem; + border: 1px solid currentColor; + color: var(--muted); +} + +.badge.supported { + color: var(--ok); +} + +.badge.partial { + color: var(--warn); +} + +.badge.unsupported { + color: var(--bad); +} + +.badge.manual { + color: var(--accent); +} + +.pager { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.oracle { + display: flex; + flex-direction: column; + gap: 0.25rem; + border-left: 2px solid var(--line); + padding-left: 0.75rem; + font-size: 0.9rem; + white-space: pre-wrap; +} + +textarea { + min-height: 12rem; + resize: vertical; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 0.85rem; + line-height: 1.45; +} + +.actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.6rem; +} + +.saved-at { + margin-left: auto; +} + +.row { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.wrap { + flex-wrap: wrap; +} + +.grow { + flex: 1; +} + +.tag { + font-size: 0.75rem; + border: 1px solid var(--line); + border-radius: 99px; + padding: 0.1rem 0.45rem; + color: var(--muted); +} + +.tag.good { + color: var(--ok); + border-color: currentColor; +} + +.tag.bad { + color: var(--bad); + border-color: currentColor; +} + +@media (max-width: 800px) { + main.fill-page { + height: auto; + min-height: calc(100vh - 3rem); + } + + .layout { + grid-template-columns: 1fr; + } + + .list { + max-height: 40vh; + } + + .detail-panel { + min-height: 60vh; + } +} diff --git a/frontend/app/components/CardGraphEditor.vue b/frontend/app/components/CardGraphEditor.vue new file mode 100644 index 0000000..46ac072 --- /dev/null +++ b/frontend/app/components/CardGraphEditor.vue @@ -0,0 +1,1094 @@ + + + + + diff --git a/frontend/app/components/CardHover.vue b/frontend/app/components/CardHover.vue new file mode 100644 index 0000000..7abf89f --- /dev/null +++ b/frontend/app/components/CardHover.vue @@ -0,0 +1,77 @@ + + + + + diff --git a/frontend/app/components/GameCard.vue b/frontend/app/components/GameCard.vue new file mode 100644 index 0000000..9d88c02 --- /dev/null +++ b/frontend/app/components/GameCard.vue @@ -0,0 +1,98 @@ + + + + + diff --git a/frontend/app/components/ManaCost.vue b/frontend/app/components/ManaCost.vue new file mode 100644 index 0000000..499fc0d --- /dev/null +++ b/frontend/app/components/ManaCost.vue @@ -0,0 +1,54 @@ + + + + + diff --git a/frontend/app/components/PlaymatPicker.vue b/frontend/app/components/PlaymatPicker.vue new file mode 100644 index 0000000..901e2d0 --- /dev/null +++ b/frontend/app/components/PlaymatPicker.vue @@ -0,0 +1,199 @@ + + + + + diff --git a/frontend/app/components/PseudoGuide.vue b/frontend/app/components/PseudoGuide.vue new file mode 100644 index 0000000..69391cd --- /dev/null +++ b/frontend/app/components/PseudoGuide.vue @@ -0,0 +1,212 @@ + + + diff --git a/frontend/app/components/SymbolText.vue b/frontend/app/components/SymbolText.vue new file mode 100644 index 0000000..f729173 --- /dev/null +++ b/frontend/app/components/SymbolText.vue @@ -0,0 +1,27 @@ + + + + + diff --git a/frontend/app/middleware/auth.ts b/frontend/app/middleware/auth.ts new file mode 100644 index 0000000..e96815e --- /dev/null +++ b/frontend/app/middleware/auth.ts @@ -0,0 +1,7 @@ +import { authToken } from '~/utils/auth' + +export default defineNuxtRouteMiddleware(to => { + const token = import.meta.server ? useCookie('commander-auth-token').value : authToken() + if (token) return + return navigateTo({ path: '/account', query: { next: to.fullPath } }) +}) diff --git a/frontend/app/pages/account.vue b/frontend/app/pages/account.vue new file mode 100644 index 0000000..e617aaa --- /dev/null +++ b/frontend/app/pages/account.vue @@ -0,0 +1,370 @@ + + + + + diff --git a/frontend/app/pages/cards.vue b/frontend/app/pages/cards.vue new file mode 100644 index 0000000..26dd351 --- /dev/null +++ b/frontend/app/pages/cards.vue @@ -0,0 +1,445 @@ + + +