forked from WikiDeck/wikideck
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e6d597aef | ||
|
|
ff6c93c808 | ||
|
|
0f924b7732 | ||
|
|
848cfbbaf1 | ||
|
|
9c26b8d560 | ||
|
|
a57698a7e2 | ||
|
|
75ce8f5ba5 | ||
|
|
a7e46583fb | ||
|
|
4160086d16 | ||
|
|
0fcf0b0a73 | ||
|
|
0666b08829 | ||
|
|
2fe16a66c8 | ||
|
|
5a7cfba124 |
@@ -1,72 +0,0 @@
|
||||
# Polite Wikimedia client (Night 2, issue #62)
|
||||
|
||||
Every server-side Wikimedia request goes through one process-wide `WikimediaClient`
|
||||
(`server/wikimedia/client.ts`). The design comes from engineer review §4 and data review §5.
|
||||
|
||||
## What it does
|
||||
|
||||
| Behaviour | Default |
|
||||
|---|---|
|
||||
| Rate per upstream host (`en.wikipedia.org`, `wikimedia.org`, `www.wikidata.org`) | token bucket, 1 req/s, burst 3 |
|
||||
| Concurrency | 1 request in flight per host |
|
||||
| Priority lanes | `mint` → `interactive` → `background`; the queue holds 64 waiters, and background work is shed first |
|
||||
| Longest queue wait | mint 10 s, interactive 5 s, background 120 s |
|
||||
| `maxlag` | `maxlag=5` on every Action API request; a maxlag reply waits for `Retry-After` and retries up to 2 times |
|
||||
| 429 / 503 | honour `Retry-After` (seconds or HTTP date), else back off 2ⁿ s with jitter, capped at 10 min, by pausing the whole host |
|
||||
| Circuit breaker | 3 consecutive 429s stop that host for 10 min. Requests are refused at once without touching Wikimedia |
|
||||
| Daily cap | 20,000 requests a day per egress IP. Background work stops at 80 %, interactive at 100 %; mint has a 10 % reserve |
|
||||
| Disk cache | `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`: ETag / Last-Modified, `If-None-Match`, stale-while-revalidate on the background lane, stale copy served on refusal |
|
||||
| User-Agent | `WikiDeck/<version> (+https://gitea.eom.dev/WikiDeck/wikideck; <operator contact>) node/<version>` |
|
||||
|
||||
The rate is deliberately 1 req/s for **every** host, including the `wikimedia.org` REST (pageviews) host.
|
||||
The engineer review suggested 5 req/s there; we are stricter on purpose after the Night 1 rate limiting, because the
|
||||
budget is per egress IP. Raise it only with a reason and a per-host setting.
|
||||
|
||||
Cache lifetimes: article metadata 24 h, monthly pageviews 7 days (the URL names six closed
|
||||
months, which do not change). Random articles and all mint reads are never cached.
|
||||
|
||||
## Operator settings
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `WIKIDECK_OPERATOR_CONTACT` | **Set this.** An email address or URL, put in the User-Agent. Without it (and without `PUBLIC_ORIGIN`), the node logs a warning at start-up. Wikimedia policy requires a contact, and contact-less clients are the first to be blocked. |
|
||||
| `PUBLIC_ORIGIN` | Used as the contact when `WIKIDECK_OPERATOR_CONTACT` is unset. |
|
||||
| `WIKIDECK_USER_AGENT` | Overrides the whole User-Agent string (sanitized; kept from Night 1). |
|
||||
| `WIKIDECK_WIKIMEDIA_RPS` | Requests per second per host for the **whole egress IP** (default 1). |
|
||||
| `WIKIDECK_WIKIMEDIA_BURST` | Token-bucket burst (default 3). |
|
||||
| `WIKIDECK_WIKIMEDIA_CONCURRENCY` | In-flight requests per host (default 1). |
|
||||
| `WIKIDECK_WIKIMEDIA_DAILY_CAP` | Requests per UTC day for the whole egress IP (default 20000). |
|
||||
| `WIKIDECK_WIKIMEDIA_NODES_PER_IP` | How many nodes share this egress IP. The rate and the daily cap are divided by it. **The testnet runs several nodes behind one IP: set it to the node count** (e.g. 3 for `deploy/night/compose.lan.yaml`). |
|
||||
|
||||
The testnet's `WIKIDECK_USER_AGENT` already names the project URL, which satisfies the policy.
|
||||
|
||||
Counters (`lane.*`, `http.429`, `breaker.open`, `cache.hit`, `refused.*`, …), per-host pause state and the
|
||||
mint pool's state are in the private operations listener's `/status`, under `wikimedia`.
|
||||
|
||||
## Mint path: transport only
|
||||
|
||||
- `random()` (W1) and `getFresh()` (W2 and W3) keep their request parameters byte-identical. The only
|
||||
addition is `maxlag=5`, which changes only error behaviour. `tests/wikimedia-mint.test.ts` pins the exact URLs.
|
||||
- Mint reads use the `mint` lane and **never** read or write the disk cache, and never join a display read.
|
||||
- **Fixed:** a 429, 5xx, timeout, network error or non-JSON reply on the pageviews call used to mint a card with
|
||||
`attention: null` forever (`enrichment.ts`). Now `getFresh()` rejects, the template returns 503 and the miner
|
||||
retries. `unavailable` is minted only for a genuine 404 (no data) or missing months.
|
||||
- No block, transfer, trade or validation code changed. Validation never calls Wikimedia.
|
||||
|
||||
## Mining prefetch pool (`server/wikimedia/pool.ts`)
|
||||
|
||||
Each template used to cost 3+ requests, all in a burst at each new tip, so load scaled with the number of miners.
|
||||
Now every template on the same tip gets the same fresh article+snapshot pair (miners race for one block anyway),
|
||||
and a new tip takes the next prefetched pair. Load is about one pair, or 3 requests, per block, whatever the number
|
||||
of miners.
|
||||
|
||||
- Pairs come from the mint-path reads above, and the snapshot is stamped when the pair is fetched, so `capturedAt` is true.
|
||||
- Pairs older than 5 minutes are dropped, never served.
|
||||
- The pool (2 pairs) refills only after use, so an idle node makes no requests.
|
||||
|
||||
## Card faces
|
||||
|
||||
`/api/wikipedia/:id` → `get()`: memory LRU, then the disk cache (fresh, or stale with a background
|
||||
revalidation), and only then the interactive lane. A grid of cards therefore no longer means a burst
|
||||
of 2 upstream requests per card per render. `TrendCache` can use `getBackground()` to stay off the
|
||||
interactive lane.
|
||||
+27
-72
@@ -1,5 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { WikimediaClient, WikimediaUnavailable, wikimediaClient, type CachePolicy, type Lane } from './wikimedia/client.ts';
|
||||
import { ENRICHMENT_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
|
||||
import { deriveStats, type PageEnrichment } from '../shared/enrichment.ts';
|
||||
|
||||
const MAX_BYTES = 1024 * 1024;
|
||||
@@ -25,23 +25,7 @@ const viewsSchema = z.object({ items: z.array(z.object({
|
||||
})).max(6) });
|
||||
|
||||
type CacheEntry = { expires: number; value: PageEnrichment } | { expires: number; error: Error };
|
||||
type Options = { fetch?: typeof globalThis.fetch; client?: WikimediaClient; now?: () => Date; ttlMs?: number; maxEntries?: number };
|
||||
type Mode = 'mint' | 'display' | 'background';
|
||||
|
||||
/** Disk-cache lifetimes (engineer review §4). Mint reads never use the cache. */
|
||||
const METADATA_CACHE: CachePolicy = { ttlMs: 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES };
|
||||
// The URL names its six completed months, which are immutable; a week bounds late corrections.
|
||||
const PAGEVIEWS_CACHE: CachePolicy = { ttlMs: 7 * 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES };
|
||||
const NOT_FOUND = Symbol('not found');
|
||||
|
||||
/** The upstream did not answer properly (throttled, 5xx, timeout, network, non-JSON). Not "no data". */
|
||||
export class UpstreamFailure extends Error {
|
||||
constructor(message: string) { super(message); this.name = 'UpstreamFailure'; }
|
||||
}
|
||||
function transportFailure(error: unknown): boolean {
|
||||
return error instanceof WikimediaUnavailable || error instanceof UpstreamFailure ||
|
||||
(error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError'));
|
||||
}
|
||||
type Options = { fetch?: typeof globalThis.fetch; now?: () => Date; ttlMs?: number; maxEntries?: number };
|
||||
|
||||
function monthWindow(now: Date): string[] {
|
||||
return Array.from({ length: 6 }, (_, index) =>
|
||||
@@ -50,17 +34,16 @@ function monthWindow(now: Date): string[] {
|
||||
|
||||
/** Fixed-source read-only enrichment; no consensus, persistence, URL or header inputs. */
|
||||
export class WikipediaEnrichment {
|
||||
private readonly client: WikimediaClient;
|
||||
private readonly fetcher: typeof globalThis.fetch;
|
||||
private readonly now: () => Date;
|
||||
private readonly ttlMs: number;
|
||||
private readonly maxEntries: number;
|
||||
private readonly cache = new Map<number, CacheEntry>();
|
||||
private readonly pending = new Map<string, Promise<PageEnrichment>>();
|
||||
private readonly pending = new Map<number, Promise<PageEnrichment>>();
|
||||
private active = 0;
|
||||
private mintActive = 0;
|
||||
|
||||
constructor(options: Options = {}) {
|
||||
this.client = options.client ?? (options.fetch ? WikimediaClient.unthrottled(options.fetch) : wikimediaClient);
|
||||
this.fetcher = options.fetch ?? globalThis.fetch;
|
||||
this.now = options.now ?? (() => new Date());
|
||||
this.ttlMs = options.ttlMs ?? 6 * 60 * 60 * 1000;
|
||||
this.maxEntries = options.maxEntries ?? 128;
|
||||
@@ -70,27 +53,16 @@ export class WikipediaEnrichment {
|
||||
}
|
||||
}
|
||||
|
||||
/** Card faces (`/api/wikipedia/:id`): memory, then the disk cache, then the interactive lane. */
|
||||
async get(pageId: number): Promise<PageEnrichment> {
|
||||
return this.loadCached(pageId, 'display');
|
||||
return this.loadCached(pageId, false);
|
||||
}
|
||||
|
||||
/** Like get(), on the background lane: for trends and other work nobody is waiting on. */
|
||||
async getBackground(pageId: number): Promise<PageEnrichment> {
|
||||
return this.loadCached(pageId, 'background');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mint data: bypasses every cache and uses the mint lane. If pageviews fail in transport
|
||||
* (429, 5xx, timeout, throttled), this rejects so the template fails and the miner retries;
|
||||
* `unavailable` is recorded only for a genuine 404 or missing data.
|
||||
*/
|
||||
/** Bypass cached values when the result is being pinned into a newly minted block. */
|
||||
async getFresh(pageId: number): Promise<PageEnrichment> {
|
||||
return this.loadCached(pageId, 'mint');
|
||||
return this.loadCached(pageId, true);
|
||||
}
|
||||
|
||||
private async loadCached(pageId: number, mode: Mode): Promise<PageEnrichment> {
|
||||
const fresh = mode === 'mint';
|
||||
private async loadCached(pageId: number, fresh: boolean): Promise<PageEnrichment> {
|
||||
if (!Number.isSafeInteger(pageId) || pageId <= 0) throw new RangeError('Invalid Wikipedia page ID');
|
||||
const now = this.now();
|
||||
const cached = this.cache.get(pageId);
|
||||
@@ -101,29 +73,23 @@ export class WikipediaEnrichment {
|
||||
if ('error' in cached) throw cached.error;
|
||||
return structuredClone(cached.value);
|
||||
}
|
||||
if (!fresh) this.cache.delete(pageId);
|
||||
// Mint jobs never join a display job: that one may be served from the disk cache.
|
||||
const pendingKey = `${fresh ? 'mint' : 'cached'}:${pageId}`;
|
||||
const existing = this.pending.get(pendingKey);
|
||||
this.cache.delete(pageId);
|
||||
const existing = this.pending.get(pageId);
|
||||
if (existing) return structuredClone(await existing);
|
||||
// Reject immediately: no unbounded waiting queue. Four active jobs also keep
|
||||
// the pending-map ceiling of eight conservative (one upstream request/job).
|
||||
// Mint jobs have their own small allowance so card faces can never starve a template.
|
||||
if (fresh ? this.mintActive >= 2 : this.pending.size - this.mintActive >= 8 || this.active >= 4) {
|
||||
throw new Error('Wikipedia enrichment busy');
|
||||
}
|
||||
if (fresh) this.mintActive++; else this.active++;
|
||||
const job = this.load(pageId, now, mode).then(value => {
|
||||
if (this.pending.size >= 8 || this.active >= 4) throw new Error('Wikipedia enrichment busy');
|
||||
this.active++;
|
||||
const job = this.load(pageId, now).then(value => {
|
||||
const ttl = value.pageviews.status === 'available' ? this.ttlMs : Math.min(this.ttlMs, 5 * 60 * 1000);
|
||||
this.remember(pageId, { value, expires: this.now().getTime() + ttl });
|
||||
return value;
|
||||
}, () => {
|
||||
const error = new Error('Wikipedia page enrichment unavailable');
|
||||
// A failed mint read says nothing new about display data; keep any cached value.
|
||||
if (!fresh) this.remember(pageId, { error, expires: this.now().getTime() + 30_000 });
|
||||
this.remember(pageId, { error, expires: this.now().getTime() + 30_000 });
|
||||
throw error;
|
||||
}).finally(() => { if (fresh) this.mintActive--; else this.active--; this.pending.delete(pendingKey); });
|
||||
this.pending.set(pendingKey, job);
|
||||
}).finally(() => { this.active--; this.pending.delete(pageId); });
|
||||
this.pending.set(pageId, job);
|
||||
return structuredClone(await job);
|
||||
}
|
||||
|
||||
@@ -133,19 +99,16 @@ export class WikipediaEnrichment {
|
||||
while (this.cache.size > this.maxEntries) this.cache.delete(this.cache.keys().next().value!);
|
||||
}
|
||||
|
||||
private async json(url: URL, lane: Lane, cache: CachePolicy | undefined, allowNotFound = false): Promise<unknown> {
|
||||
const { response, signal } = await this.client.request(url, { lane, timeoutMs: 6000, cache });
|
||||
if (allowNotFound && response.status === 404) { await response.body?.cancel(); return NOT_FOUND; }
|
||||
if (!response.ok || response.redirected) {
|
||||
await response.body?.cancel();
|
||||
throw new UpstreamFailure(`Upstream HTTP ${response.status}`);
|
||||
}
|
||||
private async json(url: URL): Promise<unknown> {
|
||||
const signal = AbortSignal.timeout(6000);
|
||||
const response = await this.fetcher(url, { signal, redirect: 'error',
|
||||
headers: { Accept: 'application/json', 'User-Agent': wikimediaUserAgent(ENRICHMENT_USER_AGENT) } });
|
||||
const length = response.headers.get('content-length');
|
||||
if (
|
||||
if (!response.ok || response.redirected ||
|
||||
!/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '') ||
|
||||
(length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_BYTES)) || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new UpstreamFailure('Invalid upstream response');
|
||||
throw new Error('Invalid upstream response');
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
@@ -167,14 +130,12 @@ export class WikipediaEnrichment {
|
||||
}
|
||||
}
|
||||
|
||||
private async load(pageId: number, now: Date, mode: Mode): Promise<PageEnrichment> {
|
||||
const lane: Lane = mode === 'mint' ? 'mint' : mode === 'display' ? 'interactive' : 'background';
|
||||
const fresh = mode === 'mint';
|
||||
private async load(pageId: number, now: Date): Promise<PageEnrichment> {
|
||||
const url = new URL('https://en.wikipedia.org/w/api.php');
|
||||
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
|
||||
pageids: String(pageId), prop: 'info|categories|pageprops|description|langlinks',
|
||||
clshow: '!hidden', cllimit: '50', lllimit: '500', ppprop: 'wikibase_item' }).toString();
|
||||
const metadata = metadataSchema.parse(await this.json(url, lane, fresh ? undefined : METADATA_CACHE));
|
||||
const metadata = metadataSchema.parse(await this.json(url));
|
||||
const page = metadata.query.pages[0];
|
||||
if (page.pageid !== pageId) throw new Error('Wikipedia page ID mismatch');
|
||||
const months = monthWindow(now);
|
||||
@@ -185,9 +146,7 @@ export class WikipediaEnrichment {
|
||||
const title = encodeURIComponent(page.title.replace(/ /g, '_'));
|
||||
const stamp = (month: string) => `${month.replace('-', '')}0100`;
|
||||
const endpoint = new URL(`https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/${title}/monthly/${stamp(months[0])}/${stamp(latestMonth)}`);
|
||||
const raw = await this.json(endpoint, lane, fresh ? undefined : PAGEVIEWS_CACHE, true);
|
||||
if (raw === NOT_FOUND) throw new Error('No pageview data');
|
||||
const result = viewsSchema.parse(raw);
|
||||
const result = viewsSchema.parse(await this.json(endpoint));
|
||||
const byMonth = new Map<string, number>();
|
||||
for (const item of result.items) {
|
||||
const month = `${item.timestamp.slice(0, 4)}-${item.timestamp.slice(4, 6)}`;
|
||||
@@ -202,11 +161,7 @@ export class WikipediaEnrichment {
|
||||
const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)).getUTCDate();
|
||||
pageviews = { status: 'available', months: ordered, latestMonth, total,
|
||||
dailyAverage: latest / days, trendPercent: prior > 0 ? (latest - prior) / prior * 100 : null };
|
||||
} catch (error) {
|
||||
// Mint: a throttled or failed upstream must not pin `attention: null` into a block forever.
|
||||
if (fresh && transportFailure(error)) throw error;
|
||||
/* Metadata remains useful; unknown views must not become fake zeroes. */
|
||||
}
|
||||
} catch { /* Metadata remains useful; unknown views must not become fake zeroes. */ }
|
||||
return { pageId, title: page.title, description: page.description ?? null,
|
||||
wikidataId: page.pageprops?.wikibase_item ?? null, revisionId: page.lastrevid, pageBytes: page.length,
|
||||
languageCount: page.langlinks?.length ?? 0, languagesTruncated: metadata.continue?.llcontinue !== undefined,
|
||||
|
||||
@@ -11,7 +11,8 @@ import { RandomX } from './randomx.ts';
|
||||
import { Ledger } from './ledger.ts';
|
||||
import { PeerNetwork } from './peers.ts';
|
||||
import { wikipediaEnrichment } from '../enrichment.ts';
|
||||
import { configureWikimedia, mintPool, wikimediaStatus } from '../wikimedia/index.ts';
|
||||
import { snapshotStats } from '../../shared/enrichment.ts';
|
||||
import { wikipediaArticles } from '../wiki.ts';
|
||||
import { IS_MAINNET, PROFILE } from '../../shared/network.ts';
|
||||
import { assertLaunchAllowed, launchManifest } from '../launch.ts';
|
||||
import { resourceConfig, RpcBudget, RpcError } from '../resources.ts';
|
||||
@@ -27,7 +28,6 @@ const apiBudget = new RpcBudget(limits);
|
||||
const peerBudget = new RpcBudget({ ...limits, requestsPerSecond: 40, writesPerSecond: 10, active: 16 });
|
||||
const dataDir = process.env.WIKIDECK_DATA_DIR ?? resolve(root,'data');
|
||||
await mkdir(dataDir,{recursive:true});
|
||||
configureWikimedia({dataDir});
|
||||
// Never permit two processes to rewrite the same ledger. A stale lock requires operator review.
|
||||
const lockPath = resolve(dataDir,`${PROFILE}-node.lock`);
|
||||
const lock = await open(lockPath,'wx',0o600).catch(()=>{throw new Error('Data directory locked. Stop its other node; remove stale testnet-node.lock only after verifying no node is running.');});
|
||||
@@ -119,9 +119,9 @@ const templateLimit=rateLimit({windowMs:60000,limit:20,standardHeaders:'draft-8'
|
||||
app.post('/api/mining/template', templateLimit, async (req,res)=>{
|
||||
const body=z.object({owner:z.string().regex(/^[a-f0-9]{64}$/),publicKey:z.string().max(256)}).strict().parse(req.body);
|
||||
try {
|
||||
// One fresh article+snapshot per tip, shared by every miner (server/wikimedia/pool.ts).
|
||||
const {article,statsSnapshot}=await mintPool.take(ledger.summary().tip);
|
||||
res.json(ledger.template(body.owner,body.publicKey,article,statsSnapshot));
|
||||
const article=await wikipediaArticles.random();
|
||||
const metrics=await wikipediaEnrichment.getFresh(article.pageId);
|
||||
res.json(ledger.template(body.owner,body.publicKey,article,snapshotStats(metrics)));
|
||||
} catch {
|
||||
res.status(503).json({error:'Could not prepare a Wikipedia article and current statistics. Retry shortly.'});
|
||||
}
|
||||
@@ -170,7 +170,7 @@ const server=app.listen(port,host,()=>{
|
||||
const operations=startOperations(opsPort,()=>({network:NETWORK,
|
||||
ledger:ledger.diagnostics(),native:engine.diagnostics(),
|
||||
peers:{configured:peers.status().length,connected:peers.status().filter(p=>p.connected).length},
|
||||
rpc:{api:apiBudget.status(),p2p:peerBudget.status()},wikimedia:wikimediaStatus()}),resolve(dataDir,PROFILE));
|
||||
rpc:{api:apiBudget.status(),p2p:peerBudget.status()}}),resolve(dataDir,PROFILE));
|
||||
server.maxConnections=256;
|
||||
server.headersTimeout=10000;
|
||||
server.requestTimeout=15000;
|
||||
|
||||
+10
-22
@@ -1,6 +1,6 @@
|
||||
import { z } from 'zod';
|
||||
import type { Article } from '../shared/protocol.ts';
|
||||
import { WikimediaClient, WikimediaUnavailable, wikimediaClient } from './wikimedia/client.ts';
|
||||
import { ARTICLE_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
|
||||
|
||||
const pageSchema = z.object({
|
||||
pageid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), ns: z.literal(0),
|
||||
@@ -58,23 +58,11 @@ function pictureUrl(value: string | undefined): string | undefined {
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
/** The exact W1 request. Its parameters decide minted article content: keep them byte-identical. */
|
||||
export function randomArticlesUrl(): URL {
|
||||
const url = new URL('https://en.wikipedia.org/w/api.php');
|
||||
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
|
||||
generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories',
|
||||
exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString();
|
||||
return url;
|
||||
}
|
||||
|
||||
export class WikipediaArticleSource {
|
||||
private readonly client: WikimediaClient;
|
||||
private readonly fetcher: typeof globalThis.fetch;
|
||||
private active = 0;
|
||||
|
||||
/** A bare fetch (tests) gets an unthrottled pass-through client; production uses the shared client. */
|
||||
constructor(source: typeof globalThis.fetch | WikimediaClient = wikimediaClient) {
|
||||
this.client = source instanceof WikimediaClient ? source : WikimediaClient.unthrottled(source);
|
||||
}
|
||||
constructor(fetcher: typeof globalThis.fetch = globalThis.fetch) { this.fetcher = fetcher; }
|
||||
|
||||
async random(): Promise<Article> {
|
||||
if (this.active >= 4) throw new Error('Wikipedia article service is busy');
|
||||
@@ -82,8 +70,12 @@ export class WikipediaArticleSource {
|
||||
try {
|
||||
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
// Mint lane, never cached: random articles become immutable chain data.
|
||||
const { response } = await this.client.request(randomArticlesUrl(), { lane: 'mint', timeoutMs: 3500 });
|
||||
const url = new URL('https://en.wikipedia.org/w/api.php');
|
||||
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
|
||||
generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories',
|
||||
exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString();
|
||||
const response = await this.fetcher(url, { signal: AbortSignal.timeout(3500), redirect: 'error',
|
||||
headers: { 'User-Agent': wikimediaUserAgent(ARTICLE_USER_AGENT), Accept: 'application/json' } });
|
||||
const data = responseSchema.parse(await readJson(response));
|
||||
for (const rawPage of data.query.pages) {
|
||||
const parsedPage = pageSchema.safeParse(rawPage);
|
||||
@@ -96,11 +88,7 @@ export class WikipediaArticleSource {
|
||||
url: `https://en.wikipedia.org/?curid=${page.pageid}`, revisionId: page.lastrevid,
|
||||
source: 'live', category: category(page.title, page.categories?.map(c => c.title) ?? []) };
|
||||
}
|
||||
} catch (error) {
|
||||
// Throttled, paused or failing upstream: stop now rather than hammer it with retries.
|
||||
if (error instanceof WikimediaUnavailable) throw error;
|
||||
/* Otherwise try another random API response, but keep the number of attempts bounded. */
|
||||
}
|
||||
} catch { /* Try another random API response, but keep the number of attempts bounded. */ }
|
||||
}
|
||||
throw new Error('Wikipedia did not return an article with a picture after three attempts');
|
||||
} finally {
|
||||
|
||||
@@ -1,48 +1,13 @@
|
||||
// User-Agent for Wikimedia API requests. Wikimedia's User-Agent policy asks automated clients for a
|
||||
// descriptive agent with contact details: `Tool/version (+https://site; contact) lib/version`.
|
||||
// Operators set WIKIDECK_OPERATOR_CONTACT (an email address or URL); PUBLIC_ORIGIN is the fallback.
|
||||
// WIKIDECK_USER_AGENT still overrides the whole string.
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
export const PROJECT_URL = 'https://gitea.eom.dev/WikiDeck/wikideck';
|
||||
// User-Agent for Wikimedia API requests. Wikimedia asks automated clients to identify
|
||||
// themselves with contact information; operators can opt in with WIKIDECK_USER_AGENT.
|
||||
// Unset (or blank), each caller keeps its historical default string unchanged.
|
||||
export const ARTICLE_USER_AGENT = 'Wikideck/0.1 (experimental Wikipedia article cards)';
|
||||
export const ENRICHMENT_USER_AGENT = 'Wikideck/0.1 (Wikipedia off-chain page enrichment)';
|
||||
const MAX_LENGTH = 256;
|
||||
const SAFE = /^[\x20-\x7e]+$/;
|
||||
|
||||
function packageVersion(): string {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown };
|
||||
return typeof raw.version === 'string' && /^[\w.+-]{1,32}$/.test(raw.version) ? raw.version : '0';
|
||||
} catch { return '0'; }
|
||||
}
|
||||
const VERSION = packageVersion();
|
||||
|
||||
/** The operator contact, or undefined when none (or only an unsafe value) is configured. */
|
||||
export function operatorContact(env: Record<string, string | undefined> = process.env): string | undefined {
|
||||
for (const value of [env.WIKIDECK_OPERATOR_CONTACT, env.PUBLIC_ORIGIN]) {
|
||||
const trimmed = value?.trim();
|
||||
if (trimmed && trimmed.length <= 128 && SAFE.test(trimmed) && !/[();]/.test(trimmed)) return trimmed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** `WikiDeck/<version> (+<project URL>; <contact>) node/<version>`. */
|
||||
export function defaultUserAgent(env: Record<string, string | undefined> = process.env): string {
|
||||
const contact = operatorContact(env);
|
||||
return `WikiDeck/${VERSION} (+${PROJECT_URL}${contact ? `; ${contact}` : ''}) node/${process.versions.node}`;
|
||||
}
|
||||
|
||||
export function wikimediaUserAgent(fallback: string, env: Record<string, string | undefined> = process.env): string {
|
||||
const configured = env.WIKIDECK_USER_AGENT?.trim();
|
||||
// Reject header-injection/control characters and oversized values; fall back to the default.
|
||||
if (!configured || configured.length > MAX_LENGTH || !SAFE.test(configured)) return fallback;
|
||||
if (!configured || configured.length > MAX_LENGTH || !/^[\x20-\x7e]+$/.test(configured)) return fallback;
|
||||
return configured;
|
||||
}
|
||||
|
||||
/** Start-up check: Wikimedia throttles or blocks clients without contact details first. */
|
||||
export function warnIfNoContact(env: Record<string, string | undefined> = process.env,
|
||||
warn: (message: string) => void = console.warn): boolean {
|
||||
if (wikimediaUserAgent('', env) || operatorContact(env)) return false;
|
||||
warn('[wikimedia] WARNING: no operator contact in the Wikimedia User-Agent. Set WIKIDECK_OPERATOR_CONTACT '
|
||||
+ '(an email address or URL) or PUBLIC_ORIGIN; Wikimedia policy requires it and may block this node.');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
/**
|
||||
* On-disk HTTP cache for off-chain Wikimedia reads (`$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`).
|
||||
* It stores the raw body with its ETag / Last-Modified so stale entries can be revalidated with
|
||||
* conditional requests. Mint-path requests never use it (see client.ts).
|
||||
*/
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
export type StoredEntry = {
|
||||
status: number; body: Buffer; contentType: string; etag: string | null; lastModified: string | null;
|
||||
expiresAt: number; storedAt: number;
|
||||
};
|
||||
export type CacheEntry = StoredEntry & { toResponse(): Response };
|
||||
|
||||
/** Canonical key: origin + path + sorted query, without `maxlag` (it changes only error behaviour). */
|
||||
export function cacheKey(url: URL): string {
|
||||
const params = [...url.searchParams].filter(([name]) => name !== 'maxlag')
|
||||
.sort(([a, x], [b, y]) => a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0);
|
||||
return `${url.origin}${url.pathname}?${new URLSearchParams(params).toString()}`;
|
||||
}
|
||||
|
||||
function withResponse(entry: StoredEntry): CacheEntry {
|
||||
return { ...entry, toResponse: () => new Response(new Uint8Array(entry.body), { status: entry.status,
|
||||
headers: { 'Content-Type': entry.contentType, 'Content-Length': String(entry.body.byteLength),
|
||||
...(entry.etag ? { ETag: entry.etag } : {}) } }) };
|
||||
}
|
||||
|
||||
type Row = { status: number; body: Uint8Array; content_type: string; etag: string | null;
|
||||
last_modified: string | null; expires_at: number; stored_at: number };
|
||||
|
||||
export class WikimediaCache {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxRows: number;
|
||||
private writes = 0;
|
||||
|
||||
/** `path` may be ':memory:' (tests). */
|
||||
constructor(path: string, options: { maxRows?: number } = {}) {
|
||||
this.maxRows = options.maxRows ?? 100_000;
|
||||
this.db = new DatabaseSync(path);
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;
|
||||
CREATE TABLE IF NOT EXISTS http_cache (key TEXT PRIMARY KEY, status INTEGER NOT NULL, body BLOB NOT NULL,
|
||||
content_type TEXT NOT NULL, etag TEXT, last_modified TEXT, expires_at INTEGER NOT NULL, stored_at INTEGER NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS http_cache_stored ON http_cache(stored_at);`);
|
||||
}
|
||||
|
||||
get(key: string): CacheEntry | undefined {
|
||||
const row = this.db.prepare('SELECT * FROM http_cache WHERE key = ?').get(key) as Row | undefined;
|
||||
if (!row) return undefined;
|
||||
return withResponse({ status: row.status, body: Buffer.from(row.body), contentType: row.content_type,
|
||||
etag: row.etag, lastModified: row.last_modified, expiresAt: row.expires_at, storedAt: row.stored_at });
|
||||
}
|
||||
|
||||
put(key: string, entry: StoredEntry): CacheEntry {
|
||||
this.db.prepare(`INSERT OR REPLACE INTO http_cache (key, status, body, content_type, etag, last_modified, expires_at, stored_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(key, entry.status, entry.body, entry.contentType, entry.etag,
|
||||
entry.lastModified, entry.expiresAt, entry.storedAt);
|
||||
if (++this.writes % 500 === 0) this.prune();
|
||||
return withResponse(entry);
|
||||
}
|
||||
|
||||
touch(key: string, expiresAt: number): void {
|
||||
this.db.prepare('UPDATE http_cache SET expires_at = ? WHERE key = ?').run(expiresAt, key);
|
||||
}
|
||||
|
||||
delete(key: string): void { this.db.prepare('DELETE FROM http_cache WHERE key = ?').run(key); }
|
||||
|
||||
size(): number { return (this.db.prepare('SELECT COUNT(*) AS n FROM http_cache').get() as { n: number }).n; }
|
||||
|
||||
prune(): void {
|
||||
this.db.prepare(`DELETE FROM http_cache WHERE key IN (SELECT key FROM http_cache ORDER BY stored_at DESC LIMIT -1 OFFSET ?)`)
|
||||
.run(this.maxRows);
|
||||
}
|
||||
|
||||
close(): void { this.db.close(); }
|
||||
}
|
||||
@@ -1,441 +0,0 @@
|
||||
/**
|
||||
* One process-wide, polite Wikimedia HTTP client (engineer review §4, data review §5).
|
||||
*
|
||||
* Every server-side Wikimedia request goes through `WikimediaClient.request()`:
|
||||
* - a token bucket per upstream host (default 1 req/s, burst 3) and 1 request in flight per host;
|
||||
* - priority lanes: `mint` before `interactive` before `background`, with a bounded queue;
|
||||
* - `maxlag=5` on Action API requests (it changes only error behaviour, never content);
|
||||
* - `Retry-After` honoured on 429/503/maxlag by pausing the whole host, with exponential backoff;
|
||||
* - a circuit breaker: 3 consecutive 429s stop all requests to that host for 10 minutes;
|
||||
* - a daily request cap, and a budget shared by the nodes behind one egress IP;
|
||||
* - an optional on-disk cache (see cache.ts) with ETag / If-None-Match and stale-while-revalidate.
|
||||
*
|
||||
* The client is transport only. It never rewrites request parameters other than adding `maxlag`,
|
||||
* and requests made with `cache: undefined` (all mint-path requests) never read or write the cache.
|
||||
* Nothing here is reachable from block validation, so it cannot affect consensus.
|
||||
*/
|
||||
import { WikimediaCache, cacheKey } from './cache.ts';
|
||||
import { wikimediaUserAgent, defaultUserAgent } from '../wikimedia-user-agent.ts';
|
||||
|
||||
export type Lane = 'mint' | 'interactive' | 'background';
|
||||
const LANES: Lane[] = ['mint', 'interactive', 'background'];
|
||||
|
||||
export type Clock = {
|
||||
now(): number;
|
||||
setTimeout(fn: () => void, ms: number): unknown;
|
||||
clearTimeout(handle: unknown): void;
|
||||
};
|
||||
const realClock: Clock = {
|
||||
now: () => Date.now(),
|
||||
setTimeout: (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
|
||||
clearTimeout: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
};
|
||||
|
||||
export type ClientConfig = {
|
||||
/** Sustained requests per second per upstream host, for this whole egress IP. */
|
||||
requestsPerSecond: number;
|
||||
burst: number;
|
||||
concurrencyPerHost: number;
|
||||
/** Requests per UTC day for this whole egress IP. */
|
||||
dailyCap: number;
|
||||
/** Nodes sharing one egress IP; the rate and daily cap are divided between them. */
|
||||
nodesPerIp: number;
|
||||
queueLimit: number;
|
||||
/** Longest wait in the queue before a request fails, per lane. */
|
||||
maxWaitMs: Record<Lane, number>;
|
||||
breakerThreshold: number;
|
||||
breakerMs: number;
|
||||
maxBackoffMs: number;
|
||||
maxlag: number;
|
||||
/** Retries of a single request after a maxlag reply (HTTP 200/503 with MediaWiki-API-Error: maxlag). */
|
||||
maxlagRetries: number;
|
||||
};
|
||||
|
||||
export const DEFAULT_CONFIG: ClientConfig = {
|
||||
requestsPerSecond: 1, burst: 3, concurrencyPerHost: 1, dailyCap: 20_000, nodesPerIp: 1, queueLimit: 64,
|
||||
maxWaitMs: { mint: 10_000, interactive: 5_000, background: 120_000 },
|
||||
breakerThreshold: 3, breakerMs: 10 * 60_000, maxBackoffMs: 10 * 60_000, maxlag: 5, maxlagRetries: 2,
|
||||
};
|
||||
|
||||
/** Unthrottled settings for tests and tools that inject their own fetch. */
|
||||
export const UNTHROTTLED: Partial<ClientConfig> = {
|
||||
requestsPerSecond: 1e9, burst: 1e9, concurrencyPerHost: 1e9, dailyCap: Number.MAX_SAFE_INTEGER, queueLimit: 1e9,
|
||||
breakerThreshold: Number.MAX_SAFE_INTEGER, maxlagRetries: 0, maxBackoffMs: 0,
|
||||
};
|
||||
|
||||
function positive(value: string | undefined, fallback: number, integer = false): number {
|
||||
if (value === undefined || value.trim() === '') return fallback;
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isSafeInteger(n))) {
|
||||
console.warn(`[wikimedia] ignoring invalid setting ${JSON.stringify(value)}; using ${fallback}`);
|
||||
return fallback;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Operator settings. Documented in docs/night2/WIKIMEDIA.md. */
|
||||
export function configFromEnv(env: Record<string, string | undefined> = process.env): ClientConfig {
|
||||
return { ...DEFAULT_CONFIG,
|
||||
requestsPerSecond: positive(env.WIKIDECK_WIKIMEDIA_RPS, DEFAULT_CONFIG.requestsPerSecond),
|
||||
burst: positive(env.WIKIDECK_WIKIMEDIA_BURST, DEFAULT_CONFIG.burst),
|
||||
concurrencyPerHost: positive(env.WIKIDECK_WIKIMEDIA_CONCURRENCY, DEFAULT_CONFIG.concurrencyPerHost, true),
|
||||
dailyCap: positive(env.WIKIDECK_WIKIMEDIA_DAILY_CAP, DEFAULT_CONFIG.dailyCap, true),
|
||||
nodesPerIp: positive(env.WIKIDECK_WIKIMEDIA_NODES_PER_IP, DEFAULT_CONFIG.nodesPerIp, true),
|
||||
};
|
||||
}
|
||||
|
||||
/** Thrown for every refusal or transport failure: queue full, cap reached, circuit open, timeout, network. */
|
||||
export class WikimediaUnavailable extends Error {
|
||||
readonly reason: string;
|
||||
readonly status?: number;
|
||||
constructor(reason: string, status?: number) {
|
||||
super(`Wikimedia unavailable: ${reason}`);
|
||||
this.name = 'WikimediaUnavailable';
|
||||
this.reason = reason; this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export type CachePolicy = {
|
||||
ttlMs: number;
|
||||
/** Serve a stale entry at once and revalidate it on the background lane. */
|
||||
staleWhileRevalidate?: boolean;
|
||||
/** Largest body stored, in bytes. */
|
||||
maxBytes?: number;
|
||||
};
|
||||
|
||||
export type RequestOptions = {
|
||||
lane: Lane;
|
||||
/** Starts when the request is dispatched, not while it waits in the queue. */
|
||||
timeoutMs: number;
|
||||
headers?: Record<string, string>;
|
||||
/** Omit for mint data: the request then bypasses the cache completely. */
|
||||
cache?: CachePolicy;
|
||||
};
|
||||
|
||||
export type ClientResponse = { response: Response; signal: AbortSignal; fromCache: boolean };
|
||||
|
||||
type Waiter = {
|
||||
lane: Lane; host: string; enqueuedAt: number;
|
||||
run: () => void; fail: (error: Error) => void; timer?: unknown;
|
||||
};
|
||||
type HostState = {
|
||||
tokens: number; refilledAt: number; inFlight: number;
|
||||
pausedUntil: number; breakerUntil: number; consecutive429: number; backoffExponent: number;
|
||||
};
|
||||
|
||||
export type ClientStatus = {
|
||||
day: string; requestsToday: number; dailyCap: number; requestsPerSecond: number; queued: number;
|
||||
counters: Record<string, number>;
|
||||
hosts: Record<string, { inFlight: number; pausedForMs: number; circuitOpen: boolean; consecutive429: number }>;
|
||||
};
|
||||
|
||||
function parseRetryAfter(value: string | null, now: number): number | undefined {
|
||||
if (!value) return undefined;
|
||||
if (/^\d+$/.test(value.trim())) return Number(value.trim()) * 1000;
|
||||
const at = Date.parse(value);
|
||||
return Number.isNaN(at) ? undefined : Math.max(0, at - now);
|
||||
}
|
||||
|
||||
function isActionApi(url: URL): boolean {
|
||||
return url.pathname === '/w/api.php' && /(^|\.)(wikipedia|wikidata|wikimedia)\.org$/.test(url.hostname);
|
||||
}
|
||||
|
||||
export class WikimediaClient {
|
||||
readonly config: ClientConfig;
|
||||
private readonly fetcher: typeof globalThis.fetch;
|
||||
private readonly clock: Clock;
|
||||
private readonly userAgent: () => string;
|
||||
private cache: WikimediaCache | undefined;
|
||||
private readonly hosts = new Map<string, HostState>();
|
||||
private readonly queues = new Map<Lane, Waiter[]>(LANES.map(lane => [lane, []]));
|
||||
private readonly revalidating = new Set<string>();
|
||||
private pumpTimer: unknown;
|
||||
private pumpAt = Infinity;
|
||||
private day = '';
|
||||
private requestsToday = 0;
|
||||
readonly counters: Record<string, number> = {};
|
||||
|
||||
constructor(options: { fetch?: typeof globalThis.fetch; config?: Partial<ClientConfig>; clock?: Clock;
|
||||
cache?: WikimediaCache; userAgent?: () => string } = {}) {
|
||||
this.fetcher = options.fetch ?? ((...args) => globalThis.fetch(...args));
|
||||
this.config = { ...DEFAULT_CONFIG, ...options.config,
|
||||
maxWaitMs: { ...DEFAULT_CONFIG.maxWaitMs, ...options.config?.maxWaitMs } };
|
||||
this.clock = options.clock ?? realClock;
|
||||
this.userAgent = options.userAgent ?? (() => wikimediaUserAgent(defaultUserAgent()));
|
||||
this.cache = options.cache;
|
||||
}
|
||||
|
||||
/** A pass-through client for injected fetchers (tests): no rate limit, no breaker, no cache. */
|
||||
static unthrottled(fetcher: typeof globalThis.fetch): WikimediaClient {
|
||||
return new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED });
|
||||
}
|
||||
|
||||
attachCache(cache: WikimediaCache | undefined): void { this.cache = cache; }
|
||||
|
||||
private count(name: string): void { this.counters[name] = (this.counters[name] ?? 0) + 1; }
|
||||
|
||||
private get rate(): number { return this.config.requestsPerSecond / this.config.nodesPerIp; }
|
||||
private get cap(): number { return Math.max(1, Math.floor(this.config.dailyCap / this.config.nodesPerIp)); }
|
||||
|
||||
private host(name: string): HostState {
|
||||
let state = this.hosts.get(name);
|
||||
if (!state) {
|
||||
state = { tokens: this.config.burst, refilledAt: this.clock.now(), inFlight: 0,
|
||||
pausedUntil: 0, breakerUntil: 0, consecutive429: 0, backoffExponent: 0 };
|
||||
this.hosts.set(name, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private refill(state: HostState, now: number): void {
|
||||
state.tokens = Math.min(this.config.burst, state.tokens + (now - state.refilledAt) / 1000 * this.rate);
|
||||
state.refilledAt = now;
|
||||
}
|
||||
|
||||
/** Daily budget by lane: background stops at 80 %, interactive at 100 %, mint has a 10 % reserve. */
|
||||
private overCap(lane: Lane): boolean {
|
||||
const today = new Date(this.clock.now()).toISOString().slice(0, 10);
|
||||
if (today !== this.day) { this.day = today; this.requestsToday = 0; }
|
||||
const limit = lane === 'background' ? this.cap * 0.8 : lane === 'interactive' ? this.cap : this.cap * 1.1;
|
||||
return this.requestsToday >= limit;
|
||||
}
|
||||
|
||||
status(): ClientStatus {
|
||||
const now = this.clock.now();
|
||||
return { day: this.day, requestsToday: this.requestsToday, dailyCap: this.cap, requestsPerSecond: this.rate,
|
||||
queued: LANES.reduce((n, lane) => n + this.queues.get(lane)!.length, 0), counters: { ...this.counters },
|
||||
hosts: Object.fromEntries([...this.hosts].map(([name, s]) => [name,
|
||||
{ inFlight: s.inFlight, pausedForMs: Math.max(0, s.pausedUntil - now), circuitOpen: s.breakerUntil > now,
|
||||
consecutive429: s.consecutive429 }])) };
|
||||
}
|
||||
|
||||
async request(input: URL, options: RequestOptions): Promise<ClientResponse> {
|
||||
const url = new URL(input);
|
||||
if (url.protocol !== 'https:') throw new RangeError('Wikimedia requests must use HTTPS');
|
||||
if (isActionApi(url) && !url.searchParams.has('maxlag')) url.searchParams.append('maxlag', String(this.config.maxlag));
|
||||
const key = options.cache && this.cache ? cacheKey(url) : undefined;
|
||||
const entry = key ? this.cache?.get(key) : undefined;
|
||||
const now = this.clock.now();
|
||||
if (entry && entry.expiresAt > now) {
|
||||
this.count('cache.hit');
|
||||
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
|
||||
}
|
||||
if (entry && options.cache?.staleWhileRevalidate) {
|
||||
this.count('cache.stale');
|
||||
this.revalidate(url, key!, options);
|
||||
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
|
||||
}
|
||||
try {
|
||||
return await this.network(url, options, key);
|
||||
} catch (error) {
|
||||
// Prefer a stale copy over an error for anything that is allowed to use the cache.
|
||||
if (entry && error instanceof WikimediaUnavailable) {
|
||||
this.count('cache.staleOnError');
|
||||
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private revalidate(url: URL, key: string, options: RequestOptions): void {
|
||||
if (this.revalidating.has(key)) return;
|
||||
this.revalidating.add(key);
|
||||
void this.network(url, { ...options, lane: 'background' }, key)
|
||||
.then(({ response }) => response.body?.cancel(), () => this.count('cache.revalidateFailed'))
|
||||
.finally(() => this.revalidating.delete(key));
|
||||
}
|
||||
|
||||
private async network(url: URL, options: RequestOptions, key: string | undefined): Promise<ClientResponse> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const result = await this.dispatch(url, options, key);
|
||||
if (result !== 'maxlag') return result;
|
||||
if (attempt >= this.config.maxlagRetries) throw new WikimediaUnavailable('maxlag');
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for a slot, send one request, and classify the reply. */
|
||||
private async dispatch(url: URL, options: RequestOptions, key: string | undefined): Promise<ClientResponse | 'maxlag'> {
|
||||
const hostName = url.hostname;
|
||||
const wait = this.acquire(hostName, options.lane);
|
||||
if (wait) await wait; // No await on the fast path: an idle host dispatches synchronously.
|
||||
const state = this.host(hostName);
|
||||
const headers = new Headers({ Accept: 'application/json', 'Accept-Encoding': 'gzip', ...options.headers,
|
||||
'User-Agent': this.userAgent() });
|
||||
const entry = key ? this.cache?.get(key) : undefined;
|
||||
if (entry?.etag) headers.set('If-None-Match', entry.etag);
|
||||
if (entry?.lastModified) headers.set('If-Modified-Since', entry.lastModified);
|
||||
const signal = AbortSignal.timeout(options.timeoutMs);
|
||||
this.requestsToday++;
|
||||
this.count(`lane.${options.lane}`);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetcher(url, { signal, redirect: 'error', headers });
|
||||
} catch (error) {
|
||||
this.release(state);
|
||||
this.count('error.network');
|
||||
throw new WikimediaUnavailable(signal.aborted ? 'timeout' : `network: ${(error as Error).message}`);
|
||||
}
|
||||
const now = this.clock.now();
|
||||
const retryAfter = parseRetryAfter(response.headers.get('retry-after'), now);
|
||||
const apiError = response.headers.get('mediawiki-api-error');
|
||||
if (apiError === 'maxlag') {
|
||||
await response.body?.cancel();
|
||||
this.count('maxlag');
|
||||
this.pause(state, Math.min(this.config.maxBackoffMs, retryAfter ?? 5000), false);
|
||||
this.release(state);
|
||||
return 'maxlag';
|
||||
}
|
||||
if (response.status === 429 || response.status === 503) {
|
||||
await response.body?.cancel();
|
||||
this.count(`http.${response.status}`);
|
||||
if (response.status === 429) state.consecutive429++;
|
||||
const backoff = Math.min(this.config.maxBackoffMs, 2 ** state.backoffExponent * 1000 * (1 + Math.random() * 0.25));
|
||||
state.backoffExponent = Math.min(state.backoffExponent + 1, 20);
|
||||
if (state.consecutive429 >= this.config.breakerThreshold) {
|
||||
this.pause(state, this.config.breakerMs, true);
|
||||
this.count('breaker.open');
|
||||
} else {
|
||||
this.pause(state, Math.min(this.config.maxBackoffMs, Math.max(retryAfter ?? 0, backoff)), false);
|
||||
}
|
||||
this.release(state);
|
||||
throw new WikimediaUnavailable(`HTTP ${response.status}`, response.status);
|
||||
}
|
||||
state.consecutive429 = 0;
|
||||
state.backoffExponent = 0;
|
||||
this.release(state);
|
||||
if (response.status === 304 && entry && key) {
|
||||
this.count('cache.revalidated');
|
||||
this.cache?.touch(key, now + options.cache!.ttlMs);
|
||||
return { response: entry.toResponse(), signal, fromCache: true };
|
||||
}
|
||||
if (key && this.cache && response.status === 200 && !response.redirected && options.cache &&
|
||||
/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '')) {
|
||||
// Store the raw body; callers re-validate it exactly as they would a network reply.
|
||||
const body = await this.readLimited(response, options.cache.maxBytes ?? 1024 * 1024, signal);
|
||||
const stored = this.cache.put(key, { status: response.status, body,
|
||||
contentType: response.headers.get('content-type') ?? '', etag: response.headers.get('etag'),
|
||||
lastModified: response.headers.get('last-modified'), expiresAt: now + options.cache.ttlMs, storedAt: now });
|
||||
return { response: stored.toResponse(), signal, fromCache: false };
|
||||
}
|
||||
if (response.status >= 500) this.count(`http.${response.status}`);
|
||||
return { response, signal, fromCache: false };
|
||||
}
|
||||
|
||||
private async readLimited(response: Response, maxBytes: number, signal: AbortSignal): Promise<Buffer> {
|
||||
const length = response.headers.get('content-length');
|
||||
if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes) || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new WikimediaUnavailable('oversized or empty response');
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
if (signal.aborted) throw new WikimediaUnavailable('timeout');
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > maxBytes) throw new WikimediaUnavailable('oversized response');
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
} catch (error) {
|
||||
throw error instanceof WikimediaUnavailable ? error : new WikimediaUnavailable('read failed');
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {});
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
private pause(state: HostState, ms: number, breaker: boolean): void {
|
||||
const until = this.clock.now() + ms;
|
||||
if (until > state.pausedUntil) {
|
||||
if (state.pausedUntil <= this.clock.now()) {
|
||||
console.warn(`[wikimedia] ${breaker ? 'circuit open' : 'pausing'} for ${Math.ceil(ms / 1000)} s`);
|
||||
}
|
||||
state.pausedUntil = until;
|
||||
}
|
||||
if (breaker) { state.consecutive429 = 0; state.breakerUntil = until; }
|
||||
}
|
||||
|
||||
private release(state: HostState): void {
|
||||
state.inFlight--;
|
||||
this.pump();
|
||||
}
|
||||
|
||||
/** Undefined when a slot was taken at once; otherwise a promise for the slot. Throws on refusal. */
|
||||
private acquire(hostName: string, lane: Lane): Promise<void> | undefined {
|
||||
const state = this.host(hostName);
|
||||
const now = this.clock.now();
|
||||
if (this.overCap(lane)) { this.count('refused.cap'); throw new WikimediaUnavailable('daily cap reached'); }
|
||||
// A paused host refuses at once when the pause outlasts this lane's patience.
|
||||
if (state.pausedUntil - now > this.config.maxWaitMs[lane]) {
|
||||
this.count('refused.paused');
|
||||
throw new WikimediaUnavailable(state.breakerUntil > now ? 'circuit open' : 'host paused');
|
||||
}
|
||||
this.refill(state, now);
|
||||
if (state.pausedUntil <= now && state.inFlight < this.config.concurrencyPerHost && state.tokens >= 1 &&
|
||||
!LANES.some(l => this.queues.get(l)!.some(w => w.host === hostName))) {
|
||||
state.tokens -= 1;
|
||||
state.inFlight++;
|
||||
return undefined;
|
||||
}
|
||||
const queued = LANES.reduce((n, l) => n + this.queues.get(l)!.length, 0);
|
||||
if (queued >= this.config.queueLimit) {
|
||||
// Background work is shed first; a mint request evicts the newest background waiter.
|
||||
const background = this.queues.get('background')!;
|
||||
if (lane === 'background' || background.length === 0) {
|
||||
this.count('refused.queue');
|
||||
throw new WikimediaUnavailable('queue full');
|
||||
}
|
||||
const evicted = background.pop()!;
|
||||
this.clock.clearTimeout(evicted.timer);
|
||||
evicted.fail(new WikimediaUnavailable('queue full'));
|
||||
}
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const waiter: Waiter = { lane, host: hostName, enqueuedAt: now,
|
||||
run: () => { this.clock.clearTimeout(waiter.timer); resolve(); },
|
||||
fail: error => reject(error) };
|
||||
waiter.timer = this.clock.setTimeout(() => {
|
||||
const queue = this.queues.get(lane)!;
|
||||
const index = queue.indexOf(waiter);
|
||||
if (index >= 0) { queue.splice(index, 1); this.count('refused.wait'); reject(new WikimediaUnavailable('queue wait')); }
|
||||
}, this.config.maxWaitMs[lane]);
|
||||
this.queues.get(lane)!.push(waiter);
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
|
||||
/** Start every waiter that may run now, highest lane first; otherwise arm a timer for the next slot. */
|
||||
private pump(): void {
|
||||
const now = this.clock.now();
|
||||
let next = Infinity;
|
||||
for (const lane of LANES) {
|
||||
const queue = this.queues.get(lane)!;
|
||||
for (let i = 0; i < queue.length;) {
|
||||
const waiter = queue[i];
|
||||
// A host is served strictly by priority: lower lanes wait while a higher lane waits for the same host.
|
||||
if (LANES.slice(0, LANES.indexOf(lane)).some(l => this.queues.get(l)!.some(w => w.host === waiter.host))) { i++; continue; }
|
||||
const state = this.host(waiter.host);
|
||||
this.refill(state, now);
|
||||
if (state.pausedUntil > now) { next = Math.min(next, state.pausedUntil); i++; continue; }
|
||||
if (state.inFlight >= this.config.concurrencyPerHost) { i++; continue; }
|
||||
if (state.tokens < 1) { next = Math.min(next, now + (1 - state.tokens) / this.rate * 1000); i++; continue; }
|
||||
state.tokens -= 1;
|
||||
state.inFlight++;
|
||||
queue.splice(i, 1);
|
||||
waiter.run();
|
||||
}
|
||||
}
|
||||
if (next < Infinity && next < this.pumpAt) {
|
||||
if (this.pumpTimer !== undefined) this.clock.clearTimeout(this.pumpTimer);
|
||||
this.pumpAt = next;
|
||||
this.pumpTimer = this.clock.setTimeout(() => { this.pumpTimer = undefined; this.pumpAt = Infinity; this.pump(); },
|
||||
Math.max(1, Math.ceil(next - now)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The process-wide client. `configureWikimedia()` (server start-up) attaches the disk cache. */
|
||||
export const wikimediaClient = new WikimediaClient({ config: configFromEnv() });
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* Node start-up wiring for the polite Wikimedia client: the disk cache, the User-Agent warning,
|
||||
* the mining prefetch pool and an ops status snapshot. See docs/night2/WIKIMEDIA.md.
|
||||
*/
|
||||
import { resolve } from 'node:path';
|
||||
import { WikimediaCache } from './cache.ts';
|
||||
import { wikimediaClient } from './client.ts';
|
||||
import { MintTemplatePool } from './pool.ts';
|
||||
import { warnIfNoContact } from '../wikimedia-user-agent.ts';
|
||||
import { wikipediaArticles } from '../wiki.ts';
|
||||
import { wikipediaEnrichment } from '../enrichment.ts';
|
||||
|
||||
export { wikimediaClient } from './client.ts';
|
||||
|
||||
/** Serves every mining template; shared by all miners of this node. */
|
||||
export const mintPool = new MintTemplatePool({ articles: wikipediaArticles, enrichment: wikipediaEnrichment });
|
||||
|
||||
let cache: WikimediaCache | undefined;
|
||||
|
||||
/** Call once at start-up. Without it the client still works, with in-memory caching only. */
|
||||
export function configureWikimedia(options: { dataDir: string }): void {
|
||||
warnIfNoContact();
|
||||
if (cache) return;
|
||||
try {
|
||||
cache = new WikimediaCache(resolve(options.dataDir, 'wikimedia-cache.sqlite'));
|
||||
wikimediaClient.attachCache(cache);
|
||||
} catch (error) {
|
||||
console.warn(`[wikimedia] disk cache disabled: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function closeWikimedia(): void { wikimediaClient.attachCache(undefined); cache?.close(); cache = undefined; }
|
||||
|
||||
export function wikimediaStatus() {
|
||||
return { client: wikimediaClient.status(), cacheEntries: cache?.size() ?? null, mintPool: mintPool.status() };
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Mining-template prefetch pool (data review §5, "Mining load").
|
||||
*
|
||||
* Without it every miner costs 3+ Wikimedia requests per template, all in a burst at each new tip.
|
||||
* The pool keeps a few fresh article + stats snapshots ready, and serves the SAME pair to every
|
||||
* template built on the same tip (miners race for one block anyway). Wikimedia load is then about
|
||||
* one pair (3 requests) per block, whatever the number of miners.
|
||||
*
|
||||
* Mint data stays transport-only: each pair comes from the mint-path reads (`random()` and
|
||||
* `getFresh()`, byte-identical parameters, never the disk cache), and the snapshot is stamped when it
|
||||
* is fetched, so `capturedAt` stays true. Pairs older than `maxAgeMs` are discarded, never served.
|
||||
* The pool refills only after it is used, so an idle node makes no requests.
|
||||
*/
|
||||
import type { Article } from '../../shared/protocol.ts';
|
||||
import { snapshotStats, type MintStatsSnapshot, type PageEnrichment } from '../../shared/enrichment.ts';
|
||||
|
||||
export type MintPair = { article: Article; statsSnapshot: MintStatsSnapshot };
|
||||
type Entry = MintPair & { fetchedAt: number };
|
||||
type Sources = {
|
||||
articles: { random(): Promise<Article> };
|
||||
enrichment: { getFresh(pageId: number): Promise<PageEnrichment> };
|
||||
};
|
||||
|
||||
export class MintTemplatePool {
|
||||
private readonly sources: Sources;
|
||||
private readonly size: number;
|
||||
private readonly maxAgeMs: number;
|
||||
private readonly now: () => number;
|
||||
private readonly ready: Entry[] = [];
|
||||
private assigned: { tip: string; entry: Entry } | undefined;
|
||||
private filling: Promise<void> | undefined;
|
||||
private direct: Promise<Entry> | undefined;
|
||||
readonly counters = { served: 0, shared: 0, fetched: 0, expired: 0, failed: 0 };
|
||||
|
||||
constructor(sources: Sources, options: { size?: number; maxAgeMs?: number; now?: () => number } = {}) {
|
||||
this.sources = sources;
|
||||
this.size = options.size ?? 2;
|
||||
this.maxAgeMs = options.maxAgeMs ?? 5 * 60_000;
|
||||
this.now = options.now ?? Date.now;
|
||||
if (!Number.isSafeInteger(this.size) || this.size < 0 || this.size > 16 ||
|
||||
!Number.isFinite(this.maxAgeMs) || this.maxAgeMs <= 0) throw new RangeError('Invalid mint pool options');
|
||||
}
|
||||
|
||||
private fresh(entry: Entry): boolean { return this.now() - entry.fetchedAt < this.maxAgeMs; }
|
||||
|
||||
private async fetchOne(): Promise<Entry> {
|
||||
const article = await this.sources.articles.random();
|
||||
const metrics = await this.sources.enrichment.getFresh(article.pageId);
|
||||
this.counters.fetched++;
|
||||
return { article, statsSnapshot: snapshotStats(metrics), fetchedAt: this.now() };
|
||||
}
|
||||
|
||||
/** The article and snapshot for a template on `tip`. Rejects when Wikimedia is unavailable. */
|
||||
async take(tip: string): Promise<MintPair> {
|
||||
let entry: Entry | undefined;
|
||||
if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) {
|
||||
entry = this.assigned.entry;
|
||||
this.counters.shared++;
|
||||
} else {
|
||||
while (this.ready.length && !this.fresh(this.ready[0])) { this.ready.shift(); this.counters.expired++; }
|
||||
entry = this.ready.shift();
|
||||
if (!entry) {
|
||||
// Cold: fetch directly, and let concurrent templates share that one fetch.
|
||||
this.direct ??= this.fetchOne().finally(() => { this.direct = undefined; });
|
||||
try { entry = await this.direct; }
|
||||
catch (error) { this.counters.failed++; throw error; }
|
||||
if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) entry = this.assigned.entry;
|
||||
}
|
||||
this.assigned = { tip, entry };
|
||||
}
|
||||
this.counters.served++;
|
||||
this.refill();
|
||||
return structuredClone({ article: entry.article, statsSnapshot: entry.statsSnapshot });
|
||||
}
|
||||
|
||||
/** Top the pool up one pair at a time, in the background. Exposed for tests. */
|
||||
refill(): Promise<void> {
|
||||
this.filling ??= (async () => {
|
||||
while (this.ready.filter(e => this.fresh(e)).length < this.size) {
|
||||
try { this.ready.push(await this.fetchOne()); }
|
||||
catch { this.counters.failed++; break; } // The next take() tries again; no retry loop.
|
||||
}
|
||||
})().finally(() => { this.filling = undefined; });
|
||||
return this.filling;
|
||||
}
|
||||
|
||||
status() { return { ready: this.ready.length, size: this.size, maxAgeMs: this.maxAgeMs, ...this.counters }; }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { DuelAction, LogEvent, PlayerView } from './contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog, type Articles } from './adapter.ts';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
/**
|
||||
* The duel board on duel-core's types, for any controller (ui-pvp's OnlinePlay, the local bot match).
|
||||
* One board intent can be several atomic actions (toggleAttacker × N, confirmAttack): they go out
|
||||
* through `onAct` in order, each awaited, each an element of `legal` or legal once the previous ones apply.
|
||||
*/
|
||||
export function DuelBoard({ view, legal, onAct, opponentName, playerName = 'You', error, busy, log, logEvents, articles, clock, onExit, onRecap }: {
|
||||
view: PlayerView; legal: DuelAction[]; onAct: (a: DuelAction) => void | Promise<void>;
|
||||
opponentName: string; playerName?: string; error?: string; busy?: boolean;
|
||||
/** Rendered log lines (duel-design's story renderer). If absent, `logEvents` are shown with plain templates. */
|
||||
log?: string[]; logEvents?: LogEvent[];
|
||||
/** cardId → article image/url, from the chain. */
|
||||
articles?: Articles;
|
||||
clock?: { turn: number; bank: number };
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sending, setSending] = useState(false);
|
||||
const [sendError, setSendError] = useState<string>();
|
||||
const names = useMemo<[string, string]>(() => (view.seat === 0 ? [playerName, opponentName] : [opponentName, playerName]), [view.seat, playerName, opponentName]);
|
||||
const lines = useMemo(() => log ?? plainLog(logEvents ?? [], names), [log, logEvents, names]);
|
||||
const board = useMemo(() => boardFromView(view, names, lines, articles, clock), [view, names, lines, articles, clock]);
|
||||
const boardLegal = useMemo(() => legalFromActions(legal), [legal]);
|
||||
|
||||
const act = async (ui: DuelUIAction) => {
|
||||
const seq = expand(ui, legal);
|
||||
setSending(true); setSendError(undefined);
|
||||
try { for (const a of seq) await onAct(a); }
|
||||
catch (e) { setSendError(e instanceof Error ? e.message : 'That move was not accepted.'); }
|
||||
finally { setSending(false); }
|
||||
};
|
||||
|
||||
return <DuelTable view={board} legal={boardLegal} onAct={ui => { void act(ui); }} busy={busy || sending}
|
||||
error={error ?? sendError} onExit={onExit} onRecap={onRecap} />;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { DuelAction, DuelCard, DuelEngineLike, DuelRulesetLike, Seat } from './contract.ts';
|
||||
import type { Articles } from './adapter.ts';
|
||||
import { DuelBoard } from './DuelBoard.tsx';
|
||||
import { DuelGate } from './DuelGate.tsx';
|
||||
import { botDeck, hash, mulberry, playerDeck, type BotMatchCard, type DuelBot } from './decks.ts';
|
||||
|
||||
export type { BotMatchCard, DuelBot };
|
||||
|
||||
const HUMAN: Seat = 0, BOT: Seat = 1;
|
||||
const BOT_STEP_MS = 300;
|
||||
|
||||
/**
|
||||
* A bot match in the browser, for eligible players only (BRIEF decisions 2–3): the deck must be
|
||||
* exactly `deckSize` cards the player owns. Off-chain; nothing moves or burns.
|
||||
* Unrated by design: the whole DuelState (bot hand, library order) lives in the page, so `onFinish` never
|
||||
* gets a match id and a browser-hosted result must never feed Elo or the ladder (night-review, #79).
|
||||
*/
|
||||
export function DuelBotMatch<S, R extends DuelRulesetLike>({ deck, cards, onExit, onFinish, engine, bot, botPool, rules, playerName = 'You', onMine }: {
|
||||
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
|
||||
engine: DuelEngineLike<S, R>; bot: DuelBot; botPool: readonly DuelCard[]; rules: R; playerName?: string; onMine?: () => void;
|
||||
}) {
|
||||
const mine = useMemo(() => playerDeck(deck, cards, rules.deckSize), [deck, cards, rules.deckSize]);
|
||||
const [seed] = useState(() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
|
||||
const [state, setState] = useState<S | null>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
const rng = useRef(mulberry(hash(seed)));
|
||||
const current = useRef<S | null>(null);
|
||||
current.current = state;
|
||||
|
||||
useEffect(() => {
|
||||
if (!mine.cards.length) return;
|
||||
try { setState(engine.createDuel(rules, [mine.cards, botDeck(botPool, rules.deckSize, seed)], seed)); }
|
||||
catch (e) { setError(e instanceof Error ? e.message : 'This deck can’t be played.'); }
|
||||
}, [engine, rules, mine.cards, botPool, seed]);
|
||||
|
||||
// The bot moves one atomic action at a time, so the board shows its plays and declarations.
|
||||
useEffect(() => {
|
||||
if (!state || engine.toAct(state) !== BOT) return;
|
||||
const t = setTimeout(() => {
|
||||
const legal = engine.legalActions(state, BOT);
|
||||
if (!legal.length) return;
|
||||
let a: DuelAction;
|
||||
try { a = bot.choose(engine.viewFor(state, BOT), legal, rng.current); } catch { a = legal[0]; }
|
||||
if (!legal.some(l => JSON.stringify(l) === JSON.stringify(a))) a = legal[0];
|
||||
if (current.current !== state) return;
|
||||
const next = engine.applyAction(state, BOT, a);
|
||||
current.current = next;
|
||||
setState(next);
|
||||
}, BOT_STEP_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [state, engine, bot]);
|
||||
|
||||
// Applied synchronously through a ref, so a confirmed declaration (toggleAttacker × N, confirmAttack)
|
||||
// sees each previous action, and an illegal action throws back to DuelBoard, which shows the error.
|
||||
const onAct = useCallback((a: DuelAction) => {
|
||||
const s = current.current;
|
||||
if (!s) return;
|
||||
const next = engine.applyAction(s, HUMAN, a);
|
||||
current.current = next;
|
||||
setError(undefined);
|
||||
setState(next);
|
||||
}, [engine]);
|
||||
|
||||
const articles = useMemo<Articles>(() => Object.fromEntries(cards.map(c => [c.tokenId, { image: c.imageUrl, url: c.url, extract: c.extract }])), [cards]);
|
||||
|
||||
if (!mine.cards.length) {
|
||||
if (deck.length < rules.deckSize || mine.missing.length) return <DuelGate owned={deck.length - mine.missing.length} deckSize={rules.deckSize} onExit={onExit} onMine={onMine} />;
|
||||
return <section className="duel-gate"><h2>Card profiles pending</h2>
|
||||
<p className="muted">These cards don’t have a duel profile yet, so they can’t be played: {mine.pending.join(', ')}. Pick other cards for your deck, or try again shortly.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section>;
|
||||
}
|
||||
if (!state) return error ? <section className="duel-gate"><h2>Can’t start this match</h2><p className="muted">{error}</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section> : null;
|
||||
|
||||
const view = engine.viewFor(state, HUMAN);
|
||||
return <DuelBoard view={view} legal={engine.legalActions(state, HUMAN)} onAct={onAct} opponentName={`Bot (${bot.name})`} playerName={playerName}
|
||||
logEvents={engine.logFor(state, HUMAN)} articles={articles} busy={engine.toAct(state) === BOT} error={error}
|
||||
onExit={engine.isOver(state) ? () => onFinish() : onExit} />;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { BookMarked, BookOpen, Building2, CalendarClock, Globe2, Home, Hourglass, Languages, Link2, MapPin, Shield, ShieldCheck, Sparkles, Sprout, Star, Swords, TrendingUp, UserRound } from 'lucide-react';
|
||||
import type { BoardCard, DuelCardType } from './model.ts';
|
||||
import { cardSummary, typeLine } from './model.ts';
|
||||
|
||||
const TYPE_ICONS: Record<DuelCardType, typeof UserRound> = {
|
||||
Figure: UserRound, Location: MapPin, Event: CalendarClock, Institution: Building2, Doctrine: BookOpen,
|
||||
};
|
||||
export const TypeIcon = ({ type, size = 12 }: { type: DuelCardType; size?: number }) => {
|
||||
const Icon = TYPE_ICONS[type] ?? BookOpen;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
/** Keyword icons for the board face, where a word doesn't fit 62 px. The words are in the label and the zoom face. */
|
||||
const KEYWORD_ICONS: Record<string, typeof Star> = {
|
||||
protected: ShieldCheck, featured: Star, translated: Languages, legacy: Hourglass, stub: Sprout,
|
||||
'well-sourced': BookMarked, multilingual: Globe2, local: Home, trending: TrendingUp, connected: Link2,
|
||||
};
|
||||
export const KeywordIcon = ({ keyword, size = 11 }: { keyword: string; size?: number }) => {
|
||||
const Icon = KEYWORD_ICONS[keyword.toLowerCase()] ?? Sparkles;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
export type FaceSize = 'board' | 'hand' | 'zoom';
|
||||
export type FaceState = { selected?: boolean; attacking?: boolean; blocking?: boolean; target?: boolean; dim?: boolean; fresh?: boolean };
|
||||
|
||||
const statClass = (now?: number, base?: number) => (now === undefined || base === undefined ? '' : now > base ? 'up' : now < base ? 'down' : '');
|
||||
|
||||
function Stats({ card }: { card: BoardCard }) {
|
||||
if (card.power === undefined) return null;
|
||||
const tough = (card.toughness ?? 0) - (card.damage ?? 0);
|
||||
return <span className="dface-pt" aria-hidden="true">
|
||||
<b className={statClass(card.power, card.basePower)}>{card.power}</b>/<b className={card.damage ? 'down' : statClass(card.toughness, card.baseToughness)}>{tough}</b>
|
||||
</span>;
|
||||
}
|
||||
|
||||
function Art({ card, iconSize }: { card: BoardCard; iconSize: number }) {
|
||||
return <span className="dface-art" aria-hidden="true">
|
||||
{card.image ? <img src={card.image} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer"
|
||||
onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
|
||||
<TypeIcon type={card.type} size={iconSize} />
|
||||
</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel card face (MTG layout). Board and hand faces show only what fits a phone: title (2-line
|
||||
* clamp), cost, type icon, P/T and keyword chips. Rules text and flavour live in the zoom face,
|
||||
* which the tap-to-zoom sheet shows (critic S4).
|
||||
*/
|
||||
export function DuelCardFace({ card, size = 'hand', state = {}, onClick, label, refNumber }: {
|
||||
card: BoardCard; size?: FaceSize; state?: FaceState; onClick?: () => void; label?: string; refNumber?: number;
|
||||
}) {
|
||||
const cls = ['dface', `dface-${size}`, `portal-${card.portal.toLowerCase()}`,
|
||||
card.tapped && 'is-tapped', card.pending && 'is-pending', state.selected && 'is-selected', state.attacking && 'is-attacking',
|
||||
state.blocking && 'is-blocking', state.target && 'is-target', state.dim && 'is-dim', state.fresh && 'is-fresh', card.token && 'is-token']
|
||||
.filter(Boolean).join(' ');
|
||||
|
||||
if (size === 'zoom') return <article className={cls} aria-label={cardSummary(card)}>
|
||||
<div className="dface-namebar"><h3 className="dface-name">{card.title}</h3><span className="dface-cost" aria-label={`Cost ${card.cost} Citations`}>{card.cost}</span></div>
|
||||
<Art card={card} iconSize={34} />
|
||||
<p className="dface-typeline"><TypeIcon type={card.type} size={13} /> {typeLine(card)}<span className="dface-portal">{card.portal}</span></p>
|
||||
<div className="dface-textbox">
|
||||
{card.keywords.length > 0 && !card.keywords.every(k => card.rulesText.includes(k)) && <p className="dface-keywords">{card.keywords.join('. ')}.</p>}
|
||||
{card.rulesText && <p className="dface-rules">{card.rulesText}</p>}
|
||||
{card.flavour && <p className="dface-flavour">{card.flavour}{card.url
|
||||
? <sup><a href={card.url} target="_blank" rel="noopener noreferrer" aria-label={`Wikipedia article: ${card.title}`}>[{refNumber ?? 1}]</a></sup>
|
||||
: null}</p>}
|
||||
</div>
|
||||
<div className="dface-footer">
|
||||
<span className="dface-rev">{card.revisionId ? `rev. ${card.revisionId}` : card.token ? 'Token' : ''}</span>
|
||||
<Stats card={card} />
|
||||
</div>
|
||||
</article>;
|
||||
|
||||
const kwShown = card.keywords.slice(0, 2);
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': state.selected || state.attacking || state.blocking || undefined } : { role: 'img' })}
|
||||
className={cls} aria-label={label ?? cardSummary(card)}>
|
||||
<Art card={card} iconSize={size === 'board' ? 14 : 18} />
|
||||
<span className="dface-cost" aria-hidden="true">{card.cost}</span>
|
||||
{state.attacking && <span className="dface-flag attack" aria-hidden="true"><Swords size={11} /></span>}
|
||||
{state.blocking && <span className="dface-flag block" aria-hidden="true"><Shield size={11} /></span>}
|
||||
<span className="dface-title">{card.title}</span>
|
||||
<span className="dface-bottom">
|
||||
{size === 'board' || kwShown.length > 1
|
||||
? kwShown.map(k => <span key={k} className="dface-kwicon" title={k}><KeywordIcon keyword={k} size={10} /></span>)
|
||||
: kwShown.map(k => <span key={k} className="dface-chip">{k}</span>)}
|
||||
<Stats card={card} />
|
||||
</span>
|
||||
</Tag>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Pickaxe } from 'lucide-react';
|
||||
import { eligibility } from './model.ts';
|
||||
import './duel.css';
|
||||
|
||||
/**
|
||||
* Shown instead of a board when the player doesn't own a full deck (BRIEF decisions 1–2). There is
|
||||
* no practice with borrowed cards: the only way forward is mining (or trading) for real cards.
|
||||
*/
|
||||
export function DuelGate({ owned, deckSize, onMine, onExit }: { owned: number; deckSize: number; onMine?: () => void; onExit?: () => void }) {
|
||||
const e = eligibility(owned, deckSize);
|
||||
const pct = Math.round((Math.min(owned, deckSize) / deckSize) * 100);
|
||||
return <section className="duel-gate" aria-labelledby="duel-gate-title">
|
||||
<div className="section-eyebrow">DUEL · {deckSize}-CARD DECKS</div>
|
||||
<h2 id="duel-gate-title">{e.label}</h2>
|
||||
<div className="duel-gate-bar" role="progressbar" aria-valuemin={0} aria-valuemax={deckSize} aria-valuenow={Math.min(owned, deckSize)} aria-label="Cards owned"><i style={{ width: `${pct}%` }} /></div>
|
||||
<p className="muted">A duel deck is exactly {deckSize} cards, and every one is an NFT you own. You need {e.needed} more.
|
||||
Each block you mine is a new card: a random Wikipedia article, frozen with its stats at the moment it was mined.
|
||||
Trades with other players count too. Matches never move or burn your cards.</p>
|
||||
<div className="play-actions">
|
||||
{onExit && <button className="button outline" onClick={onExit}>Back</button>}
|
||||
{onMine && <button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import { PREVIEW_POOL, previewView } from './mock.ts';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
type Scene = 'main' | 'attack' | 'block' | 'over' | 'cards';
|
||||
const SCENES: Scene[] = ['main', 'attack', 'block', 'over', 'cards'];
|
||||
const ZOOM = ['Jess Harnell', 'Agda (programming language)', "April 2021 nor'easter", 'Pathrail Mosque', 'Hiroshima Electric Railway', 'Heart rot'];
|
||||
|
||||
/** Static board scenes from card-sample.json, for screenshots and review (`#duel-preview/<scene>`). Not a match. */
|
||||
export function DuelPreview() {
|
||||
const initial = (location.hash.split('/')[1] as Scene) || 'main';
|
||||
const [scene, setScene] = useState<Scene>(SCENES.includes(initial) ? initial : 'main');
|
||||
const [acted, setActed] = useState<string[]>([]);
|
||||
const { view, legal } = previewView(scene === 'cards' ? 'main' : scene);
|
||||
const onAct = (a: DuelUIAction) => setActed(l => [...l, JSON.stringify(a)]);
|
||||
return <div className="duel-preview-page" style={{ padding: 0 }}>
|
||||
<nav className="category-tabs" aria-label="Preview scene" style={{ padding: '4px 8px', display: location.hash.includes('clean') ? 'none' : undefined }}>
|
||||
{SCENES.map(s => <button key={s} className={s === scene ? 'selected' : ''} onClick={() => { setScene(s); location.hash = `duel-preview/${s}`; }}>{s}</button>)}
|
||||
{acted.length > 0 && <small style={{ marginLeft: 8 }}>last action: {acted.at(-1)}</small>}
|
||||
</nav>
|
||||
{scene === 'cards' ? <div className="duel" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16, padding: 12 }}>
|
||||
{ZOOM.map(t => PREVIEW_POOL.find(c => c.title === t)).filter(c => !!c).map((c, i) => <DuelCardFace key={c.id} card={c} size="zoom" refNumber={i + 1} />)}
|
||||
</div> : <DuelTable key={scene} view={{ ...view, log: [...view.log, ...acted.map(a => `(preview) ${a}`)] }} legal={legal} onAct={onAct} />}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Award, Flag, Hand, Library, LoaderCircle, Quote, ScrollText, Shield, Swords, Timer, X } from 'lucide-react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import '../play.css';
|
||||
import './duel.css';
|
||||
import {
|
||||
EMPTY_DECL, blockList, isMyTurn, nextTargets, playerTarget, previewCombat, targetsComplete, tapAttacker, tapBlocker, toggleAttacker,
|
||||
type Attack, type BoardCard, type Seat, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
|
||||
} from './model.ts';
|
||||
|
||||
type Sheet =
|
||||
| { kind: 'card'; card: BoardCard; where: 'hand' | 'mine' | 'theirs' }
|
||||
| { kind: 'combat'; attacks: Attack[]; mode: 'attack' | 'block' }
|
||||
| { kind: 'log' } | { kind: 'concede' } | null;
|
||||
|
||||
const PHASE_LABEL: Record<BoardView['phase'], string> = {
|
||||
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
|
||||
};
|
||||
|
||||
function SideBar({ side, who, active, target, onTarget }: { side: SideView; who: 'me' | 'opponent'; active: boolean; target?: boolean; onTarget?: () => void }) {
|
||||
const label = `${who === 'me' ? 'You' : side.name}: ${side.notability} Notability, ${side.citations} of ${side.maxCitations} Citations, ${side.library} in library, ${side.hand} in hand`;
|
||||
const Tag = target ? 'button' : 'div';
|
||||
return <Tag className={`duel-side ${who} ${active ? 'is-active' : ''} ${target ? 'is-target' : ''}`} {...(target ? { type: 'button' as const, onClick: onTarget } : { role: 'group' })} aria-label={target ? `Target ${who === 'me' ? 'yourself' : side.name}. ${label}` : label}>
|
||||
<span className="duel-side-name">{who === 'me' ? 'You' : side.name}</span>
|
||||
<span className={`duel-stat life ${side.notability <= 5 ? 'low' : ''}`} title="Notability"><Award size={14} aria-hidden="true" /><b>{side.notability}</b></span>
|
||||
<span className="duel-stat cites" title="Citations"><Quote size={13} aria-hidden="true" /><b>{side.citations}</b><small>/{side.maxCitations}</small></span>
|
||||
<span className="duel-stat" title="Library"><Library size={13} aria-hidden="true" />{side.library}</span>
|
||||
<span className="duel-stat" title="Hand"><Hand size={13} aria-hidden="true" />{side.hand}</span>
|
||||
</Tag>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel table (presentational), 360 × 740 first. Controllers (local bot, PvP host) feed it a BoardView and the
|
||||
* legal moves, and get DuelUIActions back. Attack: tap a Figure (1 tap). Block: tap your Figure,
|
||||
* then the attacker (2 taps). Both go through a preview → confirm sheet; no drawn arrows.
|
||||
*/
|
||||
export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }: {
|
||||
view: BoardView; legal: Legal; onAct: (a: DuelUIAction) => void; busy?: boolean; error?: string;
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sheet, setSheet] = useState<Sheet>(null);
|
||||
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
|
||||
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
|
||||
const logRef = useRef<HTMLOListElement>(null);
|
||||
// Hand overflow cue (QA #58): how many hand cards are past the right edge.
|
||||
const handRef = useRef<HTMLDivElement>(null);
|
||||
const [hiddenRight, setHiddenRight] = useState(0);
|
||||
useEffect(() => {
|
||||
const el = handRef.current;
|
||||
if (!el) return;
|
||||
const measure = () => {
|
||||
const edge = el.getBoundingClientRect().right;
|
||||
setHiddenRight([...el.children].filter(c => c.getBoundingClientRect().left > edge - 24).length);
|
||||
};
|
||||
measure();
|
||||
el.addEventListener('scroll', measure, { passive: true });
|
||||
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
|
||||
ro?.observe(el);
|
||||
return () => { el.removeEventListener('scroll', measure); ro?.disconnect(); };
|
||||
}, [view.hand.length]);
|
||||
|
||||
const mine = isMyTurn(view);
|
||||
const oppSeat = (1 - view.seat) as Seat;
|
||||
const attackMode = mine && view.phase === 'attack' && !busy;
|
||||
const blockMode = !mine && view.phase === 'block' && view.combat.length > 0 && !busy;
|
||||
const stepKey = `${view.turn}:${view.active}:${view.phase}`;
|
||||
useEffect(() => { setDecl(EMPTY_DECL); setTargeting(undefined); }, [stepKey]);
|
||||
useEffect(() => { logRef.current?.lastElementChild?.scrollIntoView?.({ block: 'nearest' }); }, [view.log.length]);
|
||||
|
||||
const cards = useMemo(() => new Map([...view.me.battlefield, ...view.opponent.battlefield, ...view.hand].map(c => [c.id, c])), [view]);
|
||||
const attackingIds = new Set(view.combat.map(a => a.attackerId));
|
||||
const targets = targeting ? nextTargets(legal.plays[targeting.cardId], targeting.chosen) : null;
|
||||
const refs = useMemo(() => { const m = new Map<string, number>(); for (const c of cards.values()) if (c.url && !m.has(c.url)) m.set(c.url, m.size + 1); return m; }, [cards]);
|
||||
|
||||
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
|
||||
const startPlay = (card: BoardCard) => {
|
||||
const seqs = legal.plays[card.id];
|
||||
if (!seqs) return;
|
||||
if (targetsComplete(seqs, [])) play(card.id, []); else { setTargeting({ cardId: card.id, chosen: [] }); setSheet(null); }
|
||||
};
|
||||
const chooseTarget = (id: string) => {
|
||||
if (!targeting || !targets?.has(id)) return;
|
||||
const chosen = [...targeting.chosen, id];
|
||||
if (targetsComplete(legal.plays[targeting.cardId], chosen) && !nextTargets(legal.plays[targeting.cardId], chosen).size) play(targeting.cardId, chosen);
|
||||
else setTargeting({ ...targeting, chosen });
|
||||
};
|
||||
|
||||
const tapMine = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (attackMode && legal.attackers.includes(c.id)) { setDecl(d => toggleAttacker(d, c.id, legal)); return; }
|
||||
if (blockMode && (legal.blockers[c.id]?.length || decl.blocks[c.id])) { setDecl(d => tapBlocker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'mine' });
|
||||
};
|
||||
const tapTheirs = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (blockMode && attackingIds.has(c.id) && (decl.picked || Object.values(decl.blocks).includes(c.id))) { setDecl(d => tapAttacker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'theirs' });
|
||||
};
|
||||
|
||||
const blockedBy = (attackerId: string) => Object.entries(decl.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
const pendingAttacks: Attack[] = attackMode ? decl.attackers.map(attackerId => ({ attackerId }))
|
||||
: blockMode ? view.combat.map(a => ({ attackerId: a.attackerId, blockerId: blockedBy(a.attackerId) })) : view.combat;
|
||||
|
||||
const stateFor = (c: BoardCard, side: 'mine' | 'theirs') => {
|
||||
const t = targets?.has(c.id);
|
||||
if (side === 'mine') return {
|
||||
attacking: attackMode ? decl.attackers.includes(c.id) : attackingIds.has(c.id),
|
||||
blocking: !!decl.blocks[c.id] || view.combat.some(a => a.blockerId === c.id),
|
||||
selected: decl.picked === c.id,
|
||||
target: t,
|
||||
dim: (targets && !t) || (attackMode && c.type === 'Figure' && !legal.attackers.includes(c.id)) || (blockMode && !legal.blockers[c.id]?.length && !decl.blocks[c.id]),
|
||||
};
|
||||
const canBeBlocked = !!decl.picked && !!legal.blockers[decl.picked]?.includes(c.id);
|
||||
return { attacking: attackingIds.has(c.id), target: t || canBeBlocked, blocking: view.combat.some(a => a.blockerId === c.id), dim: (targets && !t) || (!!decl.picked && !canBeBlocked) };
|
||||
};
|
||||
|
||||
const row = (list: BoardCard[], side: 'mine' | 'theirs') => {
|
||||
const top = list.filter(c => !c.attachedTo);
|
||||
return <div className={`duel-row ${side}`} aria-label={side === 'mine' ? 'Your battlefield' : 'Opponent battlefield'}>
|
||||
{top.length ? top.map(c => <div key={c.id} className="duel-slot">
|
||||
<DuelCardFace card={c} size="board" state={stateFor(c, side)} onClick={() => (side === 'mine' ? tapMine(c) : tapTheirs(c))} />
|
||||
{!!c.attachments?.length && <span className="duel-attach" aria-label={`${c.attachments.length} Doctrine attached`}>+{c.attachments.length}</span>}
|
||||
{blockMode && side === 'theirs' && blockedBy(c.id) && <span className="duel-pair" aria-hidden="true">{cards.get(blockedBy(c.id)!)?.title}</span>}
|
||||
</div>) : <span className="duel-empty">No permanents</span>}
|
||||
</div>;
|
||||
};
|
||||
|
||||
// ---------- primary action ----------
|
||||
const nAtt = decl.attackers.length, nBlk = Object.keys(decl.blocks).length;
|
||||
let note: ReactNode = view.log.at(-1) ?? '';
|
||||
let primary: { label: string; run: () => void; disabled?: boolean } | null = null;
|
||||
let secondary: { label: string; run: () => void } | null = null;
|
||||
if (view.phase === 'over') {
|
||||
// The engine's own game-over sentence (DUEL_DESIGN §8.2); the board never writes story text itself.
|
||||
note = <span><b>{view.winner === 'draw' ? 'Draw.' : view.winner === view.seat ? 'You won.' : 'You lost.'}</b> {view.log.at(-1)}</span>;
|
||||
primary = onRecap ? { label: 'Battle recap', run: onRecap } : onExit ? { label: 'Done', run: onExit } : null;
|
||||
if (onRecap && onExit) secondary = { label: 'Done', run: onExit };
|
||||
} else if (busy) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {mine ? 'Resolving…' : `${view.opponent.name} is choosing…`}</>;
|
||||
} else if (legal.mulligan) {
|
||||
note = 'Keep this hand, or mulligan once: shuffle, draw 7, put 1 on the bottom.';
|
||||
primary = { label: 'Keep hand', run: () => onAct({ type: 'mulligan', keep: true }) };
|
||||
secondary = { label: 'Mulligan', run: () => onAct({ type: 'mulligan', keep: false }) };
|
||||
} else if (targeting) {
|
||||
const c = cards.get(targeting.cardId);
|
||||
note = <>{targeting.chosen.length ? 'Now choose the next target' : 'Choose a target'} for <b>{c?.title}</b>.</>;
|
||||
secondary = { label: 'Cancel', run: () => setTargeting(undefined) };
|
||||
} else if (attackMode) {
|
||||
note = nAtt ? `${nAtt} attacking. Tap a Figure to add or remove it.` : legal.attackers.length ? 'Tap Figures to attack with them.' : 'No Figure can attack.';
|
||||
primary = { label: nAtt ? `Attack with ${nAtt}` : 'No attack', run: () => (nAtt ? setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'attack' }) : onAct({ type: 'attack', attackerIds: [] })) };
|
||||
} else if (blockMode) {
|
||||
note = decl.picked ? <>Now tap the attacker <b>{cards.get(decl.picked)?.title}</b> blocks.</> : `${view.combat.length} attacking. Tap your Figure, then the attacker it blocks.`;
|
||||
primary = { label: nBlk ? `Review ${nBlk} block${nBlk > 1 ? 's' : ''}` : 'Review: no blocks', run: () => setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'block' }) };
|
||||
} else if (mine && view.phase === 'main') {
|
||||
note = Object.keys(legal.plays).length ? 'Tap a card in your hand to read or play it.' : note;
|
||||
if (legal.canGoToCombat && legal.attackers.length) { primary = { label: 'Combat', run: () => onAct({ type: 'toCombat' }) }; secondary = legal.canEndTurn ? { label: 'End turn', run: () => onAct({ type: 'endTurn' }) } : null; }
|
||||
else if (legal.canEndTurn) primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (mine && legal.canEndTurn) {
|
||||
primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (!mine) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {view.opponent.name}’s turn.</>;
|
||||
}
|
||||
|
||||
const outcome = sheet?.kind === 'combat' ? previewCombat(sheet.attacks, cards) : null;
|
||||
|
||||
return <section className="duel" aria-label={`Duel against ${view.opponent.name}`}>
|
||||
<header className="duel-bar">
|
||||
<span className="duel-turn">Turn <b>{view.turn}</b> · {PHASE_LABEL[view.phase]}{view.active !== view.seat && view.phase !== 'over' ? ` · ${view.opponent.name}` : ''}</span>
|
||||
{view.clock && view.phase !== 'over' && <span className={`duel-clock ${view.clock.turn <= 10 ? 'low' : ''}`} aria-label={`${view.clock.turn} seconds left this turn, ${view.clock.bank} in the bank`}><Timer size={13} aria-hidden="true" />{view.clock.turn}s<small>+{Math.floor(view.clock.bank / 60)}:{String(view.clock.bank % 60).padStart(2, '0')}</small></span>}
|
||||
<button className="icon-button duel-log-button" onClick={() => setSheet({ kind: 'log' })} aria-label="Match log"><ScrollText size={16} /></button>
|
||||
{view.phase !== 'over' && <button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>}
|
||||
</header>
|
||||
|
||||
<div className="duel-main">
|
||||
<div className="duel-field">
|
||||
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} target={targets?.has(playerTarget(oppSeat))} onTarget={() => chooseTarget(playerTarget(oppSeat))} />
|
||||
{row(view.opponent.battlefield, 'theirs')}
|
||||
<button className="duel-ticker" onClick={() => setSheet({ kind: 'log' })} aria-label="Open match log">
|
||||
{(attackMode || blockMode) && <span className="duel-ticker-phase">{attackMode ? <Swords size={12} /> : <Shield size={12} />}</span>}
|
||||
<span>{view.log.at(-1) ?? 'The match began.'}</span>
|
||||
</button>
|
||||
{row(view.me.battlefield, 'mine')}
|
||||
<SideBar side={view.me} who="me" active={view.active === view.seat} target={targets?.has(playerTarget(view.seat))} onTarget={() => chooseTarget(playerTarget(view.seat))} />
|
||||
</div>
|
||||
<aside className="duel-log-aside" aria-label="Match log">
|
||||
<h3>Log</h3>
|
||||
<ol ref={logRef} className="duel-log">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div className="duel-dock">
|
||||
<div className="duel-hand-wrap">
|
||||
<div ref={handRef} className={`duel-hand ${hiddenRight ? 'has-more' : ''}`} aria-label={`Your hand, ${view.hand.length} cards`}>
|
||||
{view.hand.length ? view.hand.map(c => {
|
||||
const playable = !!legal.plays[c.id] && !busy;
|
||||
return <DuelCardFace key={c.id} card={c} size="hand" state={{ dim: !playable || !!targeting, selected: targeting?.cardId === c.id }}
|
||||
onClick={() => setSheet({ kind: 'card', card: c, where: 'hand' })} />;
|
||||
}) : <span className="duel-empty">No cards in hand.</span>}
|
||||
</div>
|
||||
{hiddenRight > 0 && <button type="button" className="duel-hand-more" aria-label={`${hiddenRight} more cards in hand: scroll right`} onClick={() => handRef.current?.scrollBy({ left: handRef.current.clientWidth * 0.8, behavior: 'smooth' })}>+{hiddenRight}</button>}
|
||||
</div>
|
||||
<p className="duel-note" role="status" aria-live="polite">{error ? <span className="dock-error">{error}</span> : note}</p>
|
||||
<div className="duel-actions">
|
||||
{secondary && <button className="button outline" onClick={secondary.run}>{secondary.label}</button>}
|
||||
{primary && <button className="button dark duel-primary" onClick={primary.run} disabled={primary.disabled}>{primary.label}</button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
|
||||
<div className={`sheet duel-sheet ${sheet.kind}`} role="dialog" aria-modal="true" aria-label={sheet.kind === 'card' ? sheet.card.title : sheet.kind === 'log' ? 'Match log' : sheet.kind === 'combat' ? 'Combat preview' : 'Concede'}>
|
||||
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
|
||||
{sheet.kind === 'card' && <>
|
||||
<DuelCardFace card={sheet.card} size="zoom" refNumber={sheet.card.url ? refs.get(sheet.card.url) : undefined} />
|
||||
<p className="muted small duel-sheet-meta">{sheet.where === 'theirs' ? `${view.opponent.name}’s card` : sheet.where === 'hand' ? 'In your hand' : 'Your card'}
|
||||
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
|
||||
{sheet.card.connectedNote && <p className="small duel-sheet-meta">Connected: {sheet.card.connectedNote}</p>}
|
||||
{sheet.where === 'hand' && <div className="play-actions">
|
||||
{legal.plays[sheet.card.id] && !busy
|
||||
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{targetsComplete(legal.plays[sheet.card.id], []) ? `Play for ${sheet.card.cost}` : `Play for ${sheet.card.cost}, then choose a target`}</button>
|
||||
: <p className="muted small">{!mine ? 'You can play cards on your turn.' : view.phase !== 'main' ? 'Cards are played in your main phase.' : sheet.card.cost > view.me.citations ? `Needs ${sheet.card.cost} Citations; you have ${view.me.citations}.` : 'No legal target.'}</p>}
|
||||
</div>}
|
||||
</>}
|
||||
{sheet.kind === 'combat' && outcome && <>
|
||||
<h3>{sheet.mode === 'attack' ? 'Declare attackers' : 'Declare blockers'}</h3>
|
||||
<ul className="duel-preview">
|
||||
{outcome.rows.map(r => <li key={r.attacker.id}>
|
||||
<span className={r.attackerDies ? 'gone' : ''}>{r.attacker.title} <small>{r.attacker.power}/{r.attacker.toughness}</small></span>
|
||||
<span className="vs">{r.blocker ? 'blocked by' : sheet.mode === 'attack' ? '→' : 'unblocked →'}</span>
|
||||
{r.blocker ? <span className={r.blockerDies ? 'gone' : ''}>{r.blocker.title} <small>{r.blocker.power}/{r.blocker.toughness}</small></span>
|
||||
: <span>{sheet.mode === 'attack' ? view.opponent.name : 'you'} −{r.attacker.power ?? 0}</span>}
|
||||
</li>)}
|
||||
</ul>
|
||||
<p className="muted small">{sheet.mode === 'attack'
|
||||
? `If unblocked: ${outcome.toPlayer} damage to ${view.opponent.name} (${view.opponent.notability} → ${Math.max(0, view.opponent.notability - outcome.toPlayer)}). ${view.opponent.name} chooses blocks next.`
|
||||
: `You take ${outcome.toPlayer} (${view.me.notability} → ${Math.max(0, view.me.notability - outcome.toPlayer)}).${outcome.destroyed.length ? ` Struck through: destroyed.` : ''}`}</p>
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={() => setSheet(null)}>Change</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct(sheet.mode === 'attack' ? { type: 'attack', attackerIds: decl.attackers } : { type: 'block', blocks: blockList(decl) }); }}>
|
||||
{sheet.mode === 'attack' ? <><Swords size={15} /> Confirm attack</> : <><Shield size={15} /> Confirm blocks</>}
|
||||
</button>
|
||||
</div>
|
||||
</>}
|
||||
{sheet.kind === 'log' && <><h3>Match log</h3>
|
||||
<ol className="duel-log full">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol></>}
|
||||
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
|
||||
</div>
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// duel-core (shared/duel) ↔ the board's view model. The only file that knows engine shapes.
|
||||
import type { DuelAction, LogEvent, PermanentView, PlayerView, Seat, TargetRef } from './contract.ts';
|
||||
import { boardCard, type ArticleBits } from './cards.ts';
|
||||
import type { Attack, BoardCard, BoardView, DuelUIAction, Legal, SideView } from './model.ts';
|
||||
import { NO_LEGAL } from './model.ts';
|
||||
|
||||
export const targetId = (t: TargetRef) => (t.kind === 'card' ? t.uid : `player:${t.seat}`);
|
||||
const targetRef = (id: string): TargetRef => (id.startsWith('player:') ? { kind: 'player', seat: Number(id.slice(7)) as Seat } : { kind: 'card', uid: id });
|
||||
|
||||
export type Articles = Record<string, ArticleBits | undefined>;
|
||||
|
||||
function permanentCard(p: PermanentView, all: PermanentView[], articles: Articles): BoardCard {
|
||||
const keywords: string[] = [...p.keywords];
|
||||
if (p.connected) keywords.push('Connected');
|
||||
return boardCard(p.card, articles[p.card.cardId], {
|
||||
id: p.uid, power: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.power : undefined,
|
||||
toughness: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.toughness : undefined,
|
||||
keywords, tapped: p.tapped, pending: p.card.type === 'Figure' && p.sick, damage: p.damage || undefined,
|
||||
attachedTo: p.attachedTo, attachments: all.filter(x => x.attachedTo === p.uid).map(x => x.uid), token: p.card.token,
|
||||
connectedNote: p.connected ? `${p.connected.tier} (${p.connected.via}): +${p.connected.bonus}/+${p.connected.bonus}` : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export function boardFromView(v: PlayerView, names: [string, string], log: string[], articles: Articles = {}, clock?: BoardView['clock']): BoardView {
|
||||
const opp = (1 - v.seat) as Seat;
|
||||
const side = (s: PlayerView['opponent'], name: string, seat: Seat): SideView => ({
|
||||
name, notability: s.life, citations: s.citations, maxCitations: s.maxCitations, library: s.librarySize, hand: s.handSize,
|
||||
battlefield: v.battlefield.filter(p => p.controller === seat).map(p => permanentCard(p, v.battlefield, articles)), graveyard: s.graveyard.length,
|
||||
});
|
||||
const blockerOf = Object.fromEntries(Object.entries(v.combat.blocks).map(([b, a]) => [a, b]));
|
||||
const combat: Attack[] = v.combat.attackers.map(a => ({ attackerId: a, blockerId: blockerOf[a] }));
|
||||
return {
|
||||
seat: v.seat, turn: v.turn, active: v.active, phase: v.phase,
|
||||
me: side(v.you, names[v.seat], v.seat), opponent: side(v.opponent, names[opp], opp),
|
||||
hand: v.you.hand.map(i => boardCard(i.card, articles[i.card.cardId], { id: i.uid })),
|
||||
combat, log, winner: v.result ? (v.result.winner ?? 'draw') : undefined, clock,
|
||||
};
|
||||
}
|
||||
|
||||
export function legalFromActions(actions: DuelAction[]): Legal {
|
||||
if (!actions.length) return NO_LEGAL;
|
||||
const legal: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
for (const a of actions) {
|
||||
switch (a.type) {
|
||||
case 'play': (legal.plays[a.uid] ??= []).push((a.targets ?? []).map(targetId)); break;
|
||||
case 'endPhase': legal.canGoToCombat = true; legal.canEndTurn = true; break;
|
||||
case 'toggleAttacker': legal.attackers.push(a.uid); break;
|
||||
case 'confirmAttack': legal.canEndTurn = true; break;
|
||||
case 'block': (legal.blockers[a.blocker] ??= []).push(a.attacker); break;
|
||||
case 'keep': case 'mulligan': legal.mulligan = true; break;
|
||||
}
|
||||
}
|
||||
return legal;
|
||||
}
|
||||
|
||||
/**
|
||||
* One board intent → duel-core's atomic actions, in send order. Single-step intents return the exact
|
||||
* element of `legal` (so the host's deep-equal check passes); declarations are staged on the board and
|
||||
* sent here as toggle/block × N then confirm (DUEL_API: declarations are monotonic).
|
||||
*/
|
||||
export function expand(ui: DuelUIAction, legal: DuelAction[]): DuelAction[] {
|
||||
const find = (pred: (a: DuelAction) => boolean) => legal.find(pred);
|
||||
switch (ui.type) {
|
||||
case 'mulligan': return [ui.keep ? { type: 'keep' } : { type: 'mulligan' }];
|
||||
case 'play': {
|
||||
const want = ui.targetIds.join('|');
|
||||
const a = find(x => x.type === 'play' && x.uid === ui.cardId && (x.targets ?? []).map(targetId).join('|') === want);
|
||||
return a ? [a] : [{ type: 'play', uid: ui.cardId, ...(ui.targetIds.length ? { targets: ui.targetIds.map(targetRef) } : {}) }];
|
||||
}
|
||||
case 'toCombat': return [{ type: 'endPhase' }];
|
||||
case 'endTurn': return find(x => x.type === 'endPhase') ? [{ type: 'endPhase' }, { type: 'confirmAttack' }] : [{ type: 'confirmAttack' }];
|
||||
case 'attack': return [...ui.attackerIds.map(uid => ({ type: 'toggleAttacker', uid }) as DuelAction), { type: 'confirmAttack' }];
|
||||
case 'block': return [...ui.blocks.map(b => ({ type: 'block', blocker: b.blockerId, attacker: b.attackerId }) as DuelAction), { type: 'confirmBlocks' }];
|
||||
case 'concede': return [{ type: 'concede' }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback log text, used only until duel-design's story renderer (shared/duel/story, DUEL_DESIGN §8.2)
|
||||
* can read engine events. First variant of each §8.2 template, real card and match data only.
|
||||
*/
|
||||
export function plainLog(events: LogEvent[], names: [string, string]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const e of events) {
|
||||
const n = (s: Seat) => names[s];
|
||||
switch (e.kind) {
|
||||
case 'turnStart': out.push(`Turn ${e.turn}.`); break;
|
||||
case 'mulligan': out.push(`${n(e.seat)} took a mulligan.`); break;
|
||||
case 'deploy': out.push(`${n(e.seat)} deployed ${e.card.title}.`); break;
|
||||
case 'cast': out.push(`${n(e.seat)} cited ${e.card.title}.`); break;
|
||||
case 'adopt': out.push(`${e.to.title} adopted ${e.card.title}.`); break;
|
||||
case 'tokenCreated': out.push(`${e.source.title} created ${e.card.title}.`); break;
|
||||
case 'attack': out.push(`${e.attackers.map(a => `${a.title} (${a.power}/${a.toughness})`).join(', ')} attacked.`); break;
|
||||
case 'block': for (const b of e.blocks) out.push(`${b.blocker.title} blocked ${b.attacker.title}.`); break;
|
||||
case 'playerDamage': out.push(`${n(e.seat)} lost ${e.amount} Notability (${e.life} remaining).`); break;
|
||||
case 'lifeGain': out.push(`${n(e.seat)} gained ${e.amount} Notability (${e.life}).`); break;
|
||||
case 'destroyed': out.push(`${e.card.title} was moved to Deleted.`); break;
|
||||
case 'bounced': out.push(`${e.card.title} was returned to ${n(e.owner)}'s hand.`); break;
|
||||
case 'connected': out.push(`${e.card.title} was Connected to ${e.with.title} (${e.tier}).`); break;
|
||||
case 'concede': out.push(`${n(e.seat)} withdrew.`); break;
|
||||
case 'gameOver': out.push(e.winner === null ? `The match ended in a draw on turn ${e.turn}.`
|
||||
: e.reason === 'life' ? `${n((1 - e.winner) as Seat)} was nominated for deletion. The result was delete.`
|
||||
: e.reason === 'library' ? `${n((1 - e.winner) as Seat)} could not draw a card and lost.`
|
||||
: `${n(e.winner)} won on turn ${e.turn}.`); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// View-only fallback duel bots for the browser bot match. They see only `viewFor` output (Night 1 rule, #5).
|
||||
// sim-balance owns the real duel bots (shared/bots/duel-bots.ts); these are swapped for its heuristic
|
||||
// once a PlayerView lens exists (#64). Deterministic given the rng.
|
||||
import type { DuelAction, PermanentView, PlayerView, Seat } from './contract.ts';
|
||||
import type { DuelBot } from './decks.ts';
|
||||
|
||||
const value = (p: PermanentView) => p.power + p.toughness + p.keywords.length;
|
||||
const opp = (s: Seat) => (1 - s) as Seat;
|
||||
|
||||
function chooseNormal(v: PlayerView, legal: DuelAction[], rng: () => number): DuelAction {
|
||||
const me = v.seat, them = opp(me);
|
||||
const mine = v.battlefield.filter(p => p.controller === me), theirs = v.battlefield.filter(p => p.controller === them);
|
||||
const find = <T extends DuelAction['type']>(t: T) => legal.filter((a): a is Extract<DuelAction, { type: T }> => a.type === t);
|
||||
|
||||
if (find('keep').length) return find('keep')[0];
|
||||
|
||||
const plays = find('play');
|
||||
if (plays.length) {
|
||||
const hand = new Map(v.you.hand.map(i => [i.uid, i.card]));
|
||||
// Prefer the most expensive card. Targets: harmful effects (damage, destroy, bounce, tap, fight, a
|
||||
// negative pump) aim at the opponent's side; everything else (pumps, Adopt) at ours.
|
||||
const owner = (uid: string) => v.battlefield.find(p => p.uid === uid)?.controller;
|
||||
const harmful = (effects: unknown[]) => effects.some(e => {
|
||||
const x = e as { op?: string; power?: number; amount?: number };
|
||||
return ['damage', 'damageEach', 'destroy', 'bounce', 'tap', 'fight', 'drain'].includes(x.op ?? '') || (x.op === 'pump' && ((x.power ?? x.amount ?? 0) < 0));
|
||||
});
|
||||
const score = (a: Extract<DuelAction, { type: 'play' }>) => {
|
||||
const c = hand.get(a.uid);
|
||||
if (!c) return -1;
|
||||
const hostile = harmful(c.effects);
|
||||
let s = c.cost * 10 + rng();
|
||||
for (const t of a.targets ?? []) s += ((t.kind === 'card' ? owner(t.uid) : t.seat) === them) === hostile ? 3 : -3;
|
||||
return s;
|
||||
};
|
||||
return plays.reduce((b, a) => (score(a) > score(b) ? a : b));
|
||||
}
|
||||
|
||||
const toggles = find('toggleAttacker');
|
||||
if (toggles.length || find('confirmAttack').length) {
|
||||
const blockers = theirs.filter(p => !p.tapped && (p.card.type === 'Figure' || p.toughness > 0));
|
||||
const ready = mine.filter(p => v.combat.attackers.includes(p.uid) || toggles.some(t => t.uid === p.uid));
|
||||
const lethal = ready.map(p => p.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, x) => t + x, 0) >= v.opponent.life;
|
||||
const want = toggles.find(t => {
|
||||
const c = mine.find(p => p.uid === t.uid)!;
|
||||
if (v.combat.attackers.includes(c.uid)) return false;
|
||||
if (lethal) return true;
|
||||
return c.power > 0 && !blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
|
||||
});
|
||||
return want ?? find('confirmAttack')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
const blocks = find('block');
|
||||
if (blocks.length || find('confirmBlocks').length) {
|
||||
const used = new Set(Object.keys(v.combat.blocks)), covered = new Set(Object.values(v.combat.blocks));
|
||||
const incoming = v.combat.attackers.filter(a => !covered.has(a)).reduce((t, a) => t + (theirs.find(p => p.uid === a)?.power ?? 0), 0);
|
||||
const lethal = incoming >= v.you.life;
|
||||
let best: DuelAction | undefined, bestScore = 0;
|
||||
for (const b of blocks) {
|
||||
if (used.has(b.blocker) || covered.has(b.attacker)) continue;
|
||||
const B = mine.find(p => p.uid === b.blocker), A = theirs.find(p => p.uid === b.attacker);
|
||||
if (!A || !B) continue;
|
||||
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
|
||||
const s = kills && !dies ? 10 + value(A) : kills ? (value(A) > value(B) ? 5 : lethal ? 3 : 0) : !dies ? 2 : lethal ? 1 : 0;
|
||||
if (s > bestScore) { bestScore = s; best = b; }
|
||||
}
|
||||
return best ?? find('confirmBlocks')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
return find('endPhase')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
/** Chance that Easy makes a random legal move (never concede) instead of Normal's. */
|
||||
export const EASY_BLUNDER_RATE = 0.3;
|
||||
|
||||
export const NORMAL_BOT: DuelBot = { name: 'Normal', choose: chooseNormal };
|
||||
export const EASY_BOT: DuelBot = {
|
||||
name: 'Easy',
|
||||
choose(v, legal, rng) {
|
||||
if (rng() < EASY_BLUNDER_RATE) return legal[Math.floor(rng() * legal.length)];
|
||||
return chooseNormal(v, legal, rng);
|
||||
},
|
||||
};
|
||||
export const DUEL_BOTS: DuelBot[] = [EASY_BOT, NORMAL_BOT];
|
||||
@@ -0,0 +1,50 @@
|
||||
// DuelCard (duel-cards, shared/duel/derive.ts) → BoardCard. Declared structurally so this file doesn't
|
||||
// depend on an unmerged branch; once shared/duel/derive.ts is on the integration branch, `DuelCardLike`
|
||||
// can become `DuelCard` with no other change.
|
||||
import type { BoardCard, DuelCardType, Portal } from './model.ts';
|
||||
import { firstSentence } from './model.ts';
|
||||
|
||||
export type DuelCardLike = {
|
||||
cardId: string; pageId: number | null; revisionId?: number; title: string; type: DuelCardType; subtype?: string | null;
|
||||
description?: string; token?: boolean;
|
||||
portal: Portal; cost: number; power: number | null; toughness: number | null; keywords: readonly string[];
|
||||
rulesText: string; flavor: string;
|
||||
};
|
||||
|
||||
/** What the chain (not the derivation) knows about the card's article: art and link. */
|
||||
export type ArticleBits = { image?: string; url?: string; extract?: string };
|
||||
|
||||
export const articleUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
|
||||
|
||||
const SUBTYPE_LABEL: Record<string, string> = {
|
||||
organisation: 'Organisation', work: 'Work', sport: 'Sport', election: 'Election', conflict: 'Conflict', disaster: 'Disaster',
|
||||
period: 'Period', mathematics: 'Mathematics', pathology: 'Pathology', language: 'Language', ideology: 'Ideology', team: 'Team', vehicle: 'Vehicle',
|
||||
};
|
||||
/** "(1909–1994)", "(born 1963)", "(c.1872–1919)" in the description → "1909–1994", "1963–", "1872–1919". */
|
||||
export function lifespan(text: string | undefined): string | undefined {
|
||||
const m = text?.match(/\((?:c\.\s?)?(\d{3,4})\s?[–-]\s?(?:c\.\s?)?(\d{3,4})(?!\d)[^)]*\)|\(born (\d{3,4})\)/);
|
||||
if (!m) return undefined;
|
||||
return m[3] ? `${m[3]}–` : `${m[1]}–${m[2]}`;
|
||||
}
|
||||
|
||||
/** The part after the em dash: "History · 1530–1537", "Society · Election". */
|
||||
export function subtypeLine(card: Pick<DuelCardLike, 'type' | 'subtype' | 'portal' | 'flavor'>): string {
|
||||
const extra = card.type === 'Figure' ? lifespan(card.flavor) : card.subtype ? SUBTYPE_LABEL[card.subtype] : undefined;
|
||||
return extra ? `${card.portal} · ${extra}` : card.portal;
|
||||
}
|
||||
|
||||
export function boardCard(card: DuelCardLike, article: ArticleBits = {}, live: Partial<BoardCard> = {}): BoardCard {
|
||||
// Figures show P/T; Locations only when they have a Garrison (0/T); other types never.
|
||||
const body = card.type === 'Figure' || (card.type === 'Location' && (card.toughness ?? 0) > 0);
|
||||
const power = body ? card.power ?? 0 : undefined, toughness = body ? card.toughness ?? 0 : undefined;
|
||||
return {
|
||||
id: card.cardId, title: card.title, type: card.type,
|
||||
subtype: subtypeLine(card),
|
||||
portal: card.portal, cost: card.cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: [...card.keywords], rulesText: card.rulesText,
|
||||
flavour: firstSentence(card.flavor || article.extract || card.description),
|
||||
// Tokens are not articles: no link.
|
||||
image: article.image, url: card.token ? undefined : article.url ?? articleUrl(card.title), revisionId: card.revisionId, token: card.token,
|
||||
...live,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* The part of duel-core's contract (shared/duel/types.ts and index.ts, PR #72 at 7904199) that the
|
||||
* board uses, mirrored so this PR doesn't stack on #72 (HANDBOOK: stub the interface). Field names
|
||||
* and unions are copied verbatim; engine-only details are widened to `unknown`, so real engine values
|
||||
* are assignable here. When #72 is on night/2026-11-17 this file becomes re-exports of shared/duel.
|
||||
*/
|
||||
export type Seat = 0 | 1;
|
||||
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
|
||||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
|
||||
|
||||
export interface DuelCard {
|
||||
cardId: string;
|
||||
pageId: number | null;
|
||||
revisionId?: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
type: CardType;
|
||||
subtype?: string | null;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power: number | null;
|
||||
toughness: number | null;
|
||||
keywords: Keyword[];
|
||||
territory?: number;
|
||||
effects: unknown[];
|
||||
rulesText: string;
|
||||
flavor: string;
|
||||
connect?: unknown;
|
||||
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
deriveVersion?: string;
|
||||
token?: boolean;
|
||||
}
|
||||
|
||||
/** Only deckSize is read here; the engine validates the rest. */
|
||||
export interface DuelRulesetLike { deckSize: number }
|
||||
|
||||
export interface CardInstance { uid: string; owner: Seat; card: DuelCard }
|
||||
export interface CombatState { attackers: string[]; blocks: Record<string, string> }
|
||||
export interface DuelResult { winner: Seat | null; reason: EndReason }
|
||||
|
||||
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
|
||||
|
||||
export type DuelAction =
|
||||
| { type: 'keep' }
|
||||
| { type: 'mulligan' }
|
||||
| { type: 'play'; uid: string; targets?: TargetRef[] }
|
||||
| { type: 'endPhase' }
|
||||
| { type: 'toggleAttacker'; uid: string }
|
||||
| { type: 'confirmAttack' }
|
||||
| { type: 'block'; blocker: string; attacker: string }
|
||||
| { type: 'confirmBlocks' }
|
||||
| { type: 'concede' }
|
||||
| { type: 'timeout' };
|
||||
|
||||
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number }
|
||||
|
||||
export type LogEvent = { seq: number; turn: number } & (
|
||||
| { kind: 'start'; firstSeat: Seat }
|
||||
| { kind: 'mulligan'; seat: Seat }
|
||||
| { kind: 'keep'; seat: Seat; handSize: number }
|
||||
| { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
|
||||
| { kind: 'draw'; seat: Seat; card?: CardRef }
|
||||
| { kind: 'deploy'; seat: Seat; card: CardRef }
|
||||
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
|
||||
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
|
||||
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
|
||||
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
|
||||
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
|
||||
| { kind: 'effect'; seat: Seat; source: CardRef; op: string; template?: string; targets: TargetRef[] }
|
||||
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
|
||||
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
|
||||
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean }
|
||||
| { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number }
|
||||
| { kind: 'destroyed'; card: CardRef; owner: Seat }
|
||||
| { kind: 'bounced'; card: CardRef; owner: Seat }
|
||||
| { kind: 'discard'; seat: Seat; card: CardRef }
|
||||
| { kind: 'fatigue'; seat: Seat; amount: number }
|
||||
| { kind: 'concede'; seat: Seat }
|
||||
| { kind: 'timeout'; seat: Seat }
|
||||
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
|
||||
);
|
||||
|
||||
export interface PermanentView {
|
||||
uid: string;
|
||||
owner: Seat;
|
||||
controller: Seat;
|
||||
card: DuelCard;
|
||||
tapped: boolean;
|
||||
sick: boolean;
|
||||
damage: number;
|
||||
counters: number;
|
||||
attachedTo?: string;
|
||||
power: number;
|
||||
toughness: number;
|
||||
keywords: Keyword[];
|
||||
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
|
||||
}
|
||||
|
||||
export interface SideView {
|
||||
seat: Seat;
|
||||
life: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
handSize: number;
|
||||
librarySize: number;
|
||||
graveyard: CardInstance[];
|
||||
bankSeconds: number;
|
||||
ready: boolean;
|
||||
mulligansTaken: number;
|
||||
}
|
||||
|
||||
export interface PlayerView {
|
||||
engine: 'duel';
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
toAct: Seat | null;
|
||||
you: SideView & { hand: CardInstance[] };
|
||||
opponent: SideView;
|
||||
battlefield: PermanentView[];
|
||||
combat: CombatState;
|
||||
result: DuelResult | null;
|
||||
version: number;
|
||||
rules: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The slice of `DuelEngineApi` (shared/duel/index.ts) the bot match calls. Method syntax on purpose:
|
||||
* the real engine (typed on the full DuelState/DuelRuleset/DuelCard) is assignable to it.
|
||||
*/
|
||||
export interface DuelEngineLike<S = unknown, R = unknown> {
|
||||
createDuel(rules: R, decks: [DuelCard[], DuelCard[]], seed: string): S;
|
||||
legalActions(state: S, seat: Seat): DuelAction[];
|
||||
applyAction(state: S, seat: Seat, action: DuelAction): S;
|
||||
toAct(state: S): Seat | null;
|
||||
isOver(state: S): boolean;
|
||||
viewFor(state: S, seat: Seat): PlayerView;
|
||||
logFor(state: S, seat: Seat): LogEvent[];
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Local (in-browser) match driver, engine-agnostic. ./adapter.ts binds it to duel-core's shared/duel.
|
||||
// The bot gets only its own seat's view (viewFor), never the full state (Night 1 rule, #5).
|
||||
import type { BoardView, DuelUIAction, Legal, Seat } from './model.ts';
|
||||
|
||||
/** The engine as the board needs it. `A` is the engine's atomic action; `S` its state. */
|
||||
export interface DuelEnginePort<S, A> {
|
||||
legal(s: S, seat: Seat): A[];
|
||||
apply(s: S, seat: Seat, a: A): S;
|
||||
/** Whose input the engine is waiting for, or null when the match is over. */
|
||||
toAct(s: S): Seat | null;
|
||||
board(s: S, seat: Seat, names: [string, string]): BoardView;
|
||||
legalForBoard(actions: A[], view: BoardView): Legal;
|
||||
/** One board-level intent → the engine's atomic actions, in order. Each must be legal when sent. */
|
||||
expand(ui: DuelUIAction, actions: A[], view: BoardView): A[];
|
||||
}
|
||||
|
||||
export type BotChoose<S, A> = (s: S, seat: Seat, legal: A[], rng: () => number) => A;
|
||||
|
||||
/** Applies a sequence for one seat, re-checking legality at every step. Throws on the first illegal action. */
|
||||
export function applySequence<S, A>(port: DuelEnginePort<S, A>, s: S, seat: Seat, seq: A[], same: (a: A, b: A) => boolean): S {
|
||||
for (const a of seq) {
|
||||
const legal = port.legal(s, seat);
|
||||
if (!legal.some(l => same(l, a))) throw new Error('That move is no longer legal.');
|
||||
s = port.apply(s, seat, a);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Runs bot moves until the human must act or the match ends. Bounded, so a broken bot can't hang the tab. */
|
||||
export function runBot<S, A>(port: DuelEnginePort<S, A>, s: S, human: Seat, choose: BotChoose<S, A>, rng: () => number, maxSteps = 500): S {
|
||||
const bot = (human === 0 ? 1 : 0) as Seat;
|
||||
for (let i = 0; i < maxSteps; i++) {
|
||||
if (port.toAct(s) !== bot) return s;
|
||||
const legal = port.legal(s, bot);
|
||||
if (!legal.length) return s;
|
||||
s = port.apply(s, bot, choose(s, bot, legal, rng));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Stable structural equality for plain JSON actions. */
|
||||
export const sameAction = (a: unknown, b: unknown): boolean => stable(a) === stable(b);
|
||||
const stable = (v: unknown): string => JSON.stringify(v, (_k, x) =>
|
||||
x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => p.localeCompare(q))) : x);
|
||||
@@ -0,0 +1,40 @@
|
||||
// Pure deck helpers for the bot match (no React, no CSS), so they are unit-tested under Node.
|
||||
import type { DuelAction, DuelCard, PlayerView } from './contract.ts';
|
||||
|
||||
/** A collection card as ui-pvp passes it (ownership's ChainCard satisfies this). `duel` is the server-derived frozen profile. */
|
||||
export type BotMatchCard = { tokenId: string; title: string; url?: string; imageUrl?: string; extract?: string; duel?: unknown };
|
||||
|
||||
const TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
|
||||
/** Shape check for a profile that arrives untyped over the wire (the engine's validateDeck does the rest). */
|
||||
export function isDuelCard(v: unknown): v is DuelCard {
|
||||
const c = v as Partial<DuelCard> | null;
|
||||
return !!c && typeof c === 'object' && typeof c.title === 'string' && TYPES.includes(c.type as string) && typeof c.cost === 'number'
|
||||
&& Array.isArray(c.keywords) && Array.isArray(c.effects) && typeof c.rulesText === 'string';
|
||||
}
|
||||
/** The bot sees only its own seat's view (Night 1 rule, #5). */
|
||||
export type DuelBot = { name: string; choose(view: PlayerView, legal: DuelAction[], rng: () => number): DuelAction };
|
||||
|
||||
export function mulberry(seed: number) {
|
||||
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
}
|
||||
export const hash = (s: string) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
|
||||
|
||||
/** The bot's own deck: `size` distinct cards from a pool (the 236 real sample cards), seeded, within the copy limit. */
|
||||
export function botDeck(pool: readonly DuelCard[], size: number, seed: string): DuelCard[] {
|
||||
const rng = mulberry(hash(`bot-deck:${seed}`));
|
||||
const shuffled = [...pool].sort((a, b) => a.cardId.localeCompare(b.cardId));
|
||||
for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
|
||||
return shuffled.slice(0, size).map(c => ({ ...c, cardId: `bot:${c.cardId}` }));
|
||||
}
|
||||
|
||||
/** Resolves the player's deck: exactly `deckSize` owned cards, each with a frozen profile. Returns problems instead of a partial deck. */
|
||||
export function playerDeck(deck: string[], cards: BotMatchCard[], deckSize: number): { cards: DuelCard[]; pending: string[]; missing: string[] } {
|
||||
const byId = new Map(cards.map(c => [c.tokenId, c]));
|
||||
const out: DuelCard[] = [], pending: string[] = [], missing: string[] = [];
|
||||
for (const id of deck) {
|
||||
const c = byId.get(id);
|
||||
if (!c) missing.push(id); else if (!isDuelCard(c.duel)) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
|
||||
}
|
||||
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* Duel board (ui-duel, #58). Mobile-first: everything must read at 360 × 740 with a full 5 + 5 board.
|
||||
Portals take MTG colour analogues: Arts red, Earth green, History black, Science blue, Society white. */
|
||||
.duel{--gap:6px;display:flex;flex-direction:column;gap:var(--gap);max-width:1180px;margin:0 auto;padding:6px 8px 0;color:var(--ctp-text);background:var(--ctp-mantle);border:1px solid var(--theme-border);border-radius:12px;min-height:min(100dvh,980px);font-size:13px}
|
||||
.duel button{font:inherit;color:inherit;cursor:pointer}
|
||||
.duel-bar{display:flex;align-items:center;gap:6px;min-height:36px}
|
||||
.duel-turn{font-size:12px;color:var(--ctp-subtext1);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.duel-clock{display:inline-flex;align-items:center;gap:3px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--ctp-subtext1)}
|
||||
.duel-clock small{color:var(--ctp-overlay1);font-size:10px}
|
||||
.duel-clock.low{color:var(--ctp-red)}
|
||||
.duel .icon-button{min-width:36px;min-height:36px}
|
||||
|
||||
.duel-main{display:flex;gap:10px;flex:1 1 auto;min-height:0}
|
||||
.duel-field{display:flex;flex-direction:column;gap:var(--gap);flex:1 1 auto;min-width:0}
|
||||
|
||||
/* Player bars: Notability, Citations, library and hand are always visible. */
|
||||
.duel-side{display:flex;align-items:center;gap:10px;padding:5px 8px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--ctp-surface0);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.duel-side.is-target{width:100%;text-align:left;box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.duel-side.is-active{border-color:var(--theme-accent);box-shadow:inset 3px 0 0 var(--theme-accent)}
|
||||
.duel-side-name{font-weight:700;margin-right:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.duel-stat{display:inline-flex;align-items:center;gap:3px;color:var(--ctp-subtext1)}
|
||||
.duel-stat b{font-size:15px;color:var(--ctp-text)}
|
||||
.duel-stat small{color:var(--ctp-overlay1)}
|
||||
.duel-stat.life svg{color:var(--ctp-yellow)}
|
||||
.duel-stat.life.low b{color:var(--ctp-red)}
|
||||
.duel-stat.cites svg{color:var(--ctp-blue)}
|
||||
|
||||
/* Battlefields: one scrollable row per side; 5 cards fit 344 px without scrolling. */
|
||||
.duel-row{display:flex;gap:4px;overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:none;min-height:102px;padding:4px 0;align-items:flex-start}
|
||||
.duel-zoomgrid .dface-zoom{align-self:start}
|
||||
.duel-row::-webkit-scrollbar{display:none}
|
||||
.duel-row.theirs{align-items:flex-end}
|
||||
.duel-slot{position:relative;display:flex;flex-direction:column;align-items:stretch;flex:1 1 0;min-width:62px;max-width:110px}
|
||||
.duel-empty{flex:1;align-self:center;text-align:center;font-size:12px;color:var(--ctp-overlay1);padding:8px}
|
||||
.duel-attach{position:absolute;top:-5px;right:-3px;z-index:3;font-size:12px;font-weight:800;padding:1px 5px;border-radius:8px;background:var(--ctp-mauve);color:var(--ctp-crust)}
|
||||
.duel-pair{font-size:9px;line-height:1.2;color:var(--ctp-green);text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px}
|
||||
|
||||
.duel-ticker{display:flex;align-items:center;gap:6px;width:100%;min-height:36px;padding:6px 10px;border-radius:8px;background:var(--ctp-crust);border:1px dashed var(--ctp-surface1);text-align:left;font-size:12px;line-height:1.35;color:var(--ctp-subtext1)}
|
||||
.duel-ticker>span:last-child{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.duel-ticker-phase{display:inline-flex;color:var(--theme-accent);flex:0 0 auto}
|
||||
|
||||
.duel-log-aside{display:none}
|
||||
.duel-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:13px;line-height:1.5;color:var(--ctp-subtext1)}
|
||||
.duel-log li{padding-left:10px;border-left:2px solid var(--ctp-surface1)}
|
||||
.duel-log li:last-child{border-left-color:var(--theme-accent);color:var(--ctp-text)}
|
||||
.duel-log.full{max-height:60vh;overflow:auto}
|
||||
|
||||
/* Dock: hand, status line, actions. Sticky so the thumb always reaches it. */
|
||||
.duel-dock{position:sticky;bottom:0;z-index:5;margin:0 -8px;padding:6px 8px calc(8px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 12px 12px;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-hand{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:6px 0 2px;min-height:112px}
|
||||
.duel-hand::-webkit-scrollbar{display:none}
|
||||
.duel-hand-wrap{position:relative}
|
||||
.duel-hand.has-more{-webkit-mask-image:linear-gradient(to right,#000 78%,transparent);mask-image:linear-gradient(to right,#000 78%,transparent)}
|
||||
.duel-hand-more{position:absolute;right:0;top:50%;transform:translateY(-50%);min-width:40px;min-height:40px;border-radius:20px;background:var(--ctp-surface1);color:var(--ctp-text);font-weight:800;font-size:13px;box-shadow:0 2px 8px rgb(0 0 0/.4)}
|
||||
.duel-note{margin:0;min-height:18px;font-size:12px;line-height:1.35;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px}
|
||||
.duel-actions{display:flex;gap:8px;justify-content:flex-end}
|
||||
.duel-actions .button{min-height:46px;font-size:13px;padding:10px 16px}
|
||||
.duel-actions .duel-primary{flex:1 1 auto;max-width:280px}
|
||||
|
||||
/* ---------- card faces ---------- */
|
||||
.dface{--portal:var(--ctp-overlay1);--portal-ink:var(--ctp-crust);position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:0;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid color-mix(in srgb,var(--portal) 65%,var(--ctp-surface1));border-radius:8px;overflow:hidden;transition:transform .15s ease,box-shadow .15s ease,opacity .15s ease}
|
||||
.dface.portal-arts{--portal:var(--ctp-red)}
|
||||
.dface.portal-earth{--portal:var(--ctp-green)}
|
||||
.dface.portal-history{--portal:var(--ctp-surface2);--portal-ink:var(--ctp-text)}
|
||||
.dface.portal-science{--portal:var(--ctp-blue)}
|
||||
.dface.portal-society{--portal:var(--ctp-rosewater)}
|
||||
.dface.portal-neutral{--portal:var(--ctp-overlay0);--portal-ink:var(--ctp-text)}
|
||||
.dface-art{position:relative;display:flex;align-items:center;justify-content:center;height:32px;overflow:hidden;color:var(--portal);background:color-mix(in srgb,var(--portal) 25%,var(--ctp-surface0))}
|
||||
.dface-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
|
||||
.dface-art svg{position:relative;opacity:.9}
|
||||
.dface-art:has(img:not([style*="none"])) svg{position:absolute;right:3px;bottom:3px;width:14px;height:14px;padding:2px;border-radius:4px;background:rgb(0 0 0/.55);color:#fff;box-sizing:content-box}
|
||||
.dface-cost{position:absolute;top:3px;left:3px;z-index:2;min-width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:var(--ctp-blue);color:var(--ctp-crust);box-shadow:0 1px 3px rgb(0 0 0/.4)}
|
||||
.dface-title{font-size:10.5px;font-weight:700;line-height:1.2;padding:3px 4px 0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em;overflow-wrap:break-word;hyphens:auto}
|
||||
.dface-bottom{display:flex;align-items:center;gap:2px;padding:2px 2px 3px;margin-top:auto;min-width:0}
|
||||
.dface-type{display:inline-flex;color:var(--portal);flex:0 0 auto}
|
||||
.dface-kwicon{display:inline-flex;align-items:center;justify-content:center;width:15px;height:16px;border-radius:4px;flex:0 0 auto;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text)}
|
||||
.dface-chip{font-size:9px;font-weight:700;padding:1px 3px;border-radius:3px;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
|
||||
.dface-pt{margin-left:auto;flex:0 0 auto;font-size:12px;font-weight:800;padding:0 3px;letter-spacing:-.3px;border-radius:4px;background:var(--ctp-surface0);font-variant-numeric:tabular-nums}
|
||||
.dface-pt .up{color:var(--ctp-green)}.dface-pt .down{color:var(--ctp-red)}
|
||||
.dface-flag{position:absolute;top:3px;right:3px;z-index:2;display:flex;padding:3px;border-radius:50%}
|
||||
.dface-flag.attack{background:var(--ctp-red);color:var(--ctp-crust)}
|
||||
.dface-flag.block{background:var(--ctp-green);color:var(--ctp-crust)}
|
||||
|
||||
.dface-board{width:100%;min-height:90px}
|
||||
.dface-hand{flex:0 0 80px;width:80px;min-height:106px}
|
||||
.dface-hand .dface-art{height:42px}
|
||||
.dface-hand .dface-title{font-size:11px}
|
||||
|
||||
.dface.is-tapped{opacity:.62;filter:saturate(.6)}
|
||||
.dface.is-tapped::after{content:'';position:absolute;inset:0;background:repeating-linear-gradient(135deg,transparent 0 6px,rgb(0 0 0/.12) 6px 8px);pointer-events:none}
|
||||
.dface.is-pending .dface-art{filter:grayscale(.7)}
|
||||
.dface.is-selected{box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-4px)}
|
||||
.dface.is-attacking{box-shadow:0 0 0 2px var(--ctp-red);transform:translateY(-4px)}
|
||||
.duel-row.theirs .dface.is-attacking{transform:translateY(4px)}
|
||||
.dface.is-blocking{box-shadow:0 0 0 2px var(--ctp-green)}
|
||||
.dface.is-target{box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.dface.is-dim{opacity:.42}
|
||||
.dface.is-token{border-style:dashed}
|
||||
.dface.is-fresh{animation:dface-in .4s ease-out}
|
||||
.dface:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
|
||||
@keyframes dface-pulse{50%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ctp-yellow) 55%,transparent)}}
|
||||
@keyframes dface-in{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
|
||||
@media (prefers-reduced-motion:reduce){.dface{transition:none}.dface.is-target,.dface.is-fresh{animation:none}}
|
||||
|
||||
/* Zoom face: the full MTG layout, in the tap-to-zoom sheet. */
|
||||
.dface-zoom{width:min(300px,100%);margin:0 auto;border-width:3px;border-radius:14px;background:color-mix(in srgb,var(--portal) 10%,var(--ctp-base));padding:8px;gap:6px}
|
||||
.dface-namebar{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0)}
|
||||
.dface-name{font-family:Georgia,'Times New Roman',serif;font-size:17px !important;font-weight:700;line-height:1.2;margin:0 !important;flex:1 1 auto;min-width:0}
|
||||
.dface-zoom .dface-cost{position:static;min-width:26px;height:26px;font-size:15px}
|
||||
.dface-zoom .dface-art{height:150px;border-radius:6px}
|
||||
.dface-typeline{display:flex;align-items:center;gap:6px;margin:0;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0);font-size:13px !important;font-weight:600}
|
||||
.dface-portal{margin-left:auto;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:4px;background:var(--portal);color:var(--portal-ink)}
|
||||
.dface-textbox{padding:8px 10px;border-radius:7px;background:var(--ctp-crust);display:flex;flex-direction:column;gap:6px;min-height:88px}
|
||||
.dface-textbox p{margin:0;font-size:13.5px !important;line-height:1.45 !important}
|
||||
.dface-keywords{font-weight:700}
|
||||
.dface-flavour{font-family:Georgia,'Times New Roman',serif;font-style:italic;color:var(--ctp-subtext0);border-top:1px solid var(--ctp-surface0);padding-top:6px}
|
||||
.dface-flavour sup a{font-style:normal;font-family:inherit;color:var(--ctp-blue);text-decoration:none;margin-left:1px;padding:4px 2px}
|
||||
.dface-footer{display:flex;align-items:center;gap:6px}
|
||||
.dface-rev{font-size:10px;color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.dface-zoom .dface-pt{font-size:18px;padding:2px 10px;border:2px solid var(--portal);background:var(--ctp-base)}
|
||||
|
||||
.duel-sheet .duel-sheet-meta{text-align:center;margin:8px 0}
|
||||
.duel-preview{list-style:none;padding:0;margin:8px 0;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-preview li{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;font-size:14px;padding:8px 10px;border-radius:8px;background:var(--ctp-base)}
|
||||
.duel-preview small{color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.duel-preview .vs{color:var(--ctp-subtext0);font-size:12px}
|
||||
.duel-preview .gone{text-decoration:line-through;color:var(--ctp-red)}
|
||||
|
||||
/* Eligibility gate */
|
||||
.duel-gate{max-width:560px;margin:0 auto;padding:22px 16px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle);color:var(--ctp-text)}
|
||||
.duel-gate h2{font-size:22px;margin:0 0 8px}
|
||||
.duel-gate-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin:12px 0 6px}
|
||||
.duel-gate-bar i{display:block;height:100%;background:var(--theme-accent)}
|
||||
|
||||
/* Tall phones (≥ 720 px): give the spare height to the cards, with 3-line titles (QA #58). */
|
||||
@media (max-width:899px) and (min-height:720px){
|
||||
.dface-board{min-height:112px}
|
||||
.dface-board .dface-art{height:42px}
|
||||
.dface-board .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.dface-hand{min-height:128px}
|
||||
.dface-hand .dface-art{height:52px}
|
||||
.dface-hand .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.duel-hand{min-height:134px}
|
||||
}
|
||||
|
||||
/* Desktop: bigger cards, log always visible beside the field. */
|
||||
@media (min-width:900px){
|
||||
.duel{padding:10px 14px 0;font-size:14px}
|
||||
.duel-log-button{display:none}
|
||||
.duel-log-aside{display:flex;flex-direction:column;flex:0 0 300px;max-height:calc(100dvh - 240px);min-height:380px;padding:10px 12px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--ctp-surface0)}
|
||||
.duel-log-aside h3{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:0 0 8px}
|
||||
.duel-log-aside .duel-log{overflow:auto}
|
||||
.duel-ticker{display:none}
|
||||
.duel-row{justify-content:center;min-height:150px;gap:8px}
|
||||
.duel-slot{min-width:96px;max-width:120px}
|
||||
.dface-board{min-height:140px}
|
||||
.dface-board .dface-art{height:62px}
|
||||
.dface-board .dface-title{font-size:12.5px}
|
||||
.dface-board .dface-chip{font-size:9px}
|
||||
.dface-board .dface-kwicon{width:20px;height:20px}
|
||||
.dface-board .dface-pt{font-size:14px}
|
||||
.dface-board .dface-cost{min-width:24px;height:24px;font-size:13px}
|
||||
.dface-hand{flex-basis:104px;width:104px;min-height:138px}
|
||||
.dface-hand .dface-art{height:60px}
|
||||
.dface-hand .dface-title{font-size:12.5px}
|
||||
.duel-hand{justify-content:center;min-height:146px}
|
||||
.duel-dock{margin:0 -14px;padding:8px 14px 12px}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Preview data for the duel board: real cards from docs/game/card-sample.json, with a deliberately
|
||||
// crude stand-in derivation so the board can be built and screenshotted before duel-cards' real
|
||||
// shared/duel/derive.ts lands. Never used for real matches. No network calls.
|
||||
import sample from '../../../docs/game/card-sample.json';
|
||||
import type { BoardCard, BoardView, DuelCardType, Legal, Portal } from './model.ts';
|
||||
|
||||
type SampleCard = {
|
||||
pageId: number; title: string; description?: string | null; revisionId: number; pageBytes: number; languageCount: number;
|
||||
categories: string[]; instanceOf?: { id: string; label: string }[]; tiers: { attention: number; depth: number; reach: number };
|
||||
};
|
||||
const CARDS = (sample as unknown as { cards: SampleCard[] }).cards;
|
||||
|
||||
function previewType(c: SampleCard): DuelCardType {
|
||||
const labels = (c.instanceOf ?? []).map(i => i.label).join(' ');
|
||||
const d = c.description ?? '';
|
||||
if (c.instanceOf?.some(i => i.id === 'Q5') || /\btaxon\b/.test(labels) || /^(Species|Genus) of/.test(d)) return 'Figure';
|
||||
if (/commune|municipality|village|town|river|settlement|mosque|parish|area/i.test(labels + d)) return 'Location';
|
||||
if (/election|storm|nor.easter|battle|match|final|season|war/i.test(labels + d)) return 'Event';
|
||||
if (/company|band|group|film|team|organi[sz]ation|party/i.test(labels + d)) return 'Institution';
|
||||
return 'Doctrine';
|
||||
}
|
||||
function previewPortal(c: SampleCard, t: DuelCardType): Portal {
|
||||
const s = `${c.description ?? ''} ${c.categories.join(' ')}`;
|
||||
if (/century|deaths|sultan|empire|medieval|monarch|queen|king/i.test(s)) return 'History';
|
||||
if (/mathemat|algebra|programming|gene|disease|scientist|botanist|archaeolog/i.test(s)) return 'Science';
|
||||
if (/actor|singer|film|band|music|novel|television/i.test(s)) return 'Arts';
|
||||
if (/species|genus|river|fungus|plant|orchid|commune|village/i.test(s)) return 'Earth';
|
||||
if (/politic|election|protest|footballer|team|government/i.test(s)) return 'Society';
|
||||
return t === 'Figure' ? 'Society' : t === 'Location' ? 'Earth' : 'Neutral';
|
||||
}
|
||||
const years = (d?: string | null) => d?.match(/\(([^)]*\d{3,4}[^)]*)\)/)?.[1]?.replace(/^(c\.|born )/, '').replace('born ', '');
|
||||
|
||||
export function previewCard(c: SampleCard, suffix = ''): BoardCard {
|
||||
const type = previewType(c), portal = previewPortal(c, type);
|
||||
const fame = Math.round((c.tiers.attention * 2 + c.tiers.depth + c.tiers.reach) / 4);
|
||||
const cost = Math.max(1, Math.min(6, Math.ceil(fame * 0.6)));
|
||||
const keywords: string[] = [];
|
||||
if (c.categories.includes('Living people')) keywords.push('Protected');
|
||||
if (c.tiers.attention >= 9) keywords.push('Featured');
|
||||
if (c.languageCount >= 20 && keywords.length < 2) keywords.push('Translated');
|
||||
if (c.categories.some(x => /\d+ deaths/.test(x)) && keywords.length < 2) keywords.push('Legacy');
|
||||
if ((c.pageBytes < 3000 || c.categories.some(x => /stubs/.test(x))) && keywords.length < 2) keywords.push('Stub');
|
||||
const k = Math.ceil(cost / 2);
|
||||
let power: number | undefined, toughness: number | undefined, rulesText = '';
|
||||
if (type === 'Figure') {
|
||||
const b = 2 * cost + 1, s = Math.min(0.7, Math.max(0.3, c.tiers.attention / (c.tiers.attention + c.tiers.depth || 1)));
|
||||
power = Math.max(1, Math.round(b * s)) - (keywords.length > 1 ? 1 : 0); toughness = Math.max(1, b - Math.round(b * s));
|
||||
} else if (type === 'Location') {
|
||||
power = 0; toughness = 1 + Math.floor(c.tiers.depth / 3);
|
||||
rulesText = `Territory. Garrison 0/${toughness}.`;
|
||||
} else if (type === 'Event') {
|
||||
rulesText = /storm|nor.easter/i.test(c.description ?? '') ? `Deal ${Math.max(1, k - 1)} damage to each Figure and each Location.`
|
||||
: /election/i.test(c.description ?? '') ? `Create ${k} 1/1 Society Figure tokens named Elected Member.`
|
||||
: `Target Figure you control gets +${k}/+0 until end of turn, then fights target Figure you don't control.`;
|
||||
} else if (type === 'Institution') {
|
||||
rulesText = cost >= 4 ? 'At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.' : 'Figures you control with power 2 or less get +1/+0.';
|
||||
} else {
|
||||
rulesText = /disease/i.test(c.description ?? '') ? `Attach to target Figure. It gets −${k}/−${k}.` : `Adopt. Adopted Figure gets +${k}/+${k}.`;
|
||||
}
|
||||
const sub = type === 'Figure' ? [portal, years(c.description)].filter(Boolean).join(' · ') : portal;
|
||||
return {
|
||||
id: `${c.pageId}${suffix}`, title: c.title, type, subtype: sub, portal, cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: type === 'Figure' ? keywords.slice(0, 2) : [], rulesText, flavour: c.description ? `${c.description}.` : undefined,
|
||||
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, revisionId: c.revisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export const PREVIEW_POOL: BoardCard[] = CARDS.map(c => previewCard(c));
|
||||
const byTitle = (t: string) => PREVIEW_POOL.find(c => c.title === t) ?? PREVIEW_POOL[0];
|
||||
const figures = PREVIEW_POOL.filter(c => c.type === 'Figure');
|
||||
|
||||
/** A full 5 + 5 board for screenshots and tests. `scene` picks whose step it is. */
|
||||
export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'): { view: BoardView; legal: Legal } {
|
||||
const mine = [byTitle('Jess Harnell'), byTitle('Dichromorpha viridis'), byTitle('Salahuddin of Aceh'), byTitle('Pathrail Mosque'), byTitle('Hiroshima Electric Railway')]
|
||||
.map((c, i) => ({ ...c, pending: i === 1 && scene === 'main' }));
|
||||
const theirs = [byTitle('Isabella of Aragon, Queen of Portugal'), byTitle('Miloje Vasić'), figures[12], byTitle('Topusko'), byTitle('Zbyszek Godlewski')]
|
||||
.map((c, i) => ({ ...c, id: `${c.id}-o`, damage: i === 1 ? 1 : 0 }));
|
||||
mine[0] = { ...mine[0], attachments: ['doc-1'], power: (mine[0].power ?? 0) + 2, toughness: (mine[0].toughness ?? 0) + 2 };
|
||||
const hand = [byTitle('Agda (programming language)'), byTitle('April 2021 nor\'easter'), byTitle('Mary Sophie Young'), byTitle('Charmont-en-Beauce'), byTitle('Heart rot'), byTitle('Joseph Ujlaki')];
|
||||
const log = [
|
||||
'Turn 1. Bot (Normal) kept a hand of seven.',
|
||||
'Turn 3. You cited Pathrail Mosque. Maximum Citations rose to 4.',
|
||||
'Turn 4. Isabella of Aragon, Queen of Portugal (6/5) attacked. Dichromorpha viridis (4/2) blocked and was reverted.[2]',
|
||||
'Turn 5. You deployed Jess Harnell. Bot (Normal) lost 3 Notability.',
|
||||
'Turn 6. Miloje Vasić was assigned 1 damage.',
|
||||
];
|
||||
const view: BoardView = {
|
||||
seat: 0, turn: 6, active: scene === 'block' ? 1 : 0, phase: scene === 'main' ? 'main' : scene === 'attack' ? 'attack' : scene === 'block' ? 'block' : 'over',
|
||||
me: { name: 'You', notability: 14, citations: scene === 'main' ? 4 : 1, maxCitations: 6, library: 27, hand: hand.length, battlefield: mine, graveyard: 3 },
|
||||
opponent: { name: 'Bot (Normal)', notability: scene === 'over' ? 0 : 11, citations: 0, maxCitations: 6, library: 26, hand: 4, battlefield: theirs, graveyard: 2 },
|
||||
hand, combat: scene === 'block' ? [{ attackerId: theirs[0].id }, { attackerId: theirs[1].id }, { attackerId: theirs[2].id }] : [],
|
||||
log, winner: scene === 'over' ? 0 : undefined, clock: { turn: 42, bank: 251 },
|
||||
};
|
||||
const myFigs = mine.filter(c => c.type === 'Figure' && !c.pending).map(c => c.id);
|
||||
const legal: Legal = scene === 'main' ? {
|
||||
...emptyLegal(), canGoToCombat: true, canEndTurn: true, attackers: myFigs,
|
||||
plays: Object.fromEntries(hand.filter(c => c.cost <= 4).map(c => [c.id,
|
||||
c.type === 'Doctrine' ? mine.filter(m => m.type === 'Figure').map(m => [m.id])
|
||||
: c.type === 'Event' ? mine.filter(m => m.type === 'Figure').flatMap(m => theirs.filter(t => t.type === 'Figure').map(t => [m.id, t.id])) : [[]]])),
|
||||
} : scene === 'attack' ? { ...emptyLegal(), attackers: myFigs, canEndTurn: true }
|
||||
: scene === 'block' ? { ...emptyLegal(), blockers: Object.fromEntries(mine.filter(c => c.type === 'Figure' || c.type === 'Location').map(c => [c.id, view.combat.map(a => a.attackerId)])) }
|
||||
: emptyLegal();
|
||||
return { view, legal };
|
||||
}
|
||||
const emptyLegal = (): Legal => ({ plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false });
|
||||
@@ -0,0 +1,235 @@
|
||||
// ui-duel (#58): the duel board's own view model. Board components read only these types, so the
|
||||
// engine contract (duel-core, mirrored in ./contract.ts) is mapped in exactly one place: ./adapter.ts.
|
||||
// Nothing here moves cards on-chain; matches are off-chain and never burn or transfer.
|
||||
|
||||
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Seat = 0 | 1;
|
||||
/** duel-core's phases (refresh, draw, damage and end are automatic). */
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
|
||||
/** One card as the board shows it. Hidden cards never reach the board (opponent's hand is a count). */
|
||||
export type BoardCard = {
|
||||
id: string;
|
||||
title: string;
|
||||
type: DuelCardType;
|
||||
/** The line after the em dash, e.g. "People · 1961–". */
|
||||
subtype?: string;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power?: number;
|
||||
toughness?: number;
|
||||
/** Base stats, to colour buffs and debuffs. */
|
||||
basePower?: number;
|
||||
baseToughness?: number;
|
||||
/** Damage marked this turn. */
|
||||
damage?: number;
|
||||
keywords: string[];
|
||||
rulesText: string;
|
||||
/** First sentence of the on-chain extract. */
|
||||
flavour?: string;
|
||||
image?: string;
|
||||
url?: string;
|
||||
revisionId?: number;
|
||||
tapped?: boolean;
|
||||
/** "Pending review": entered this turn, can't attack. */
|
||||
pending?: boolean;
|
||||
/** Doctrine attached to this card (ids), or the Figure a Doctrine is attached to. */
|
||||
attachments?: string[];
|
||||
attachedTo?: string;
|
||||
token?: boolean;
|
||||
/** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */
|
||||
connectedNote?: string;
|
||||
};
|
||||
|
||||
export type SideView = {
|
||||
name: string;
|
||||
notability: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
library: number;
|
||||
hand: number;
|
||||
battlefield: BoardCard[];
|
||||
graveyard: number;
|
||||
};
|
||||
|
||||
export type Attack = { attackerId: string; blockerId?: string };
|
||||
|
||||
export type BoardView = {
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
/** Whose turn it is. */
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
me: SideView;
|
||||
opponent: SideView;
|
||||
hand: BoardCard[];
|
||||
/** Current combat: attackers (opponent's when I'm blocking) and any blocks already declared. */
|
||||
combat: Attack[];
|
||||
log: string[];
|
||||
winner?: Seat | 'draw';
|
||||
/** Seconds left this turn, and in the bank, for the player to act. */
|
||||
clock?: { turn: number; bank: number };
|
||||
};
|
||||
|
||||
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
|
||||
export type DuelUIAction =
|
||||
| { type: 'mulligan'; keep: boolean }
|
||||
/** targetIds: card uids or `player:<seat>`, one per chosen-target effect, in order. */
|
||||
| { type: 'play'; cardId: string; targetIds: string[] }
|
||||
| { type: 'toCombat' }
|
||||
| { type: 'attack'; attackerIds: string[] }
|
||||
| { type: 'block'; blocks: { blockerId: string; attackerId: string }[] }
|
||||
| { type: 'endTurn' }
|
||||
| { type: 'concede' };
|
||||
|
||||
/** What the engine says is legal right now, in board terms. */
|
||||
export type Legal = {
|
||||
/** Hand card id → every legal target sequence ([[]] = needs no target). Absent = can't be played now. */
|
||||
plays: Record<string, string[][]>;
|
||||
canGoToCombat: boolean;
|
||||
/** Figures that may be declared as attackers. */
|
||||
attackers: string[];
|
||||
/** blocker id → attacker ids it may block (Featured, Translated and Garrison are the engine's call). */
|
||||
blockers: Record<string, string[]>;
|
||||
canEndTurn: boolean;
|
||||
mulligan: boolean;
|
||||
};
|
||||
|
||||
export const NO_LEGAL: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
|
||||
// ---------- targeting (multi-step: e.g. a sport Event picks your Figure, then theirs) ----------
|
||||
|
||||
export const playerTarget = (seat: Seat) => `player:${seat}`;
|
||||
|
||||
/** Ids that may be chosen next, given the targets already chosen for this card. */
|
||||
export function nextTargets(seqs: string[][] | undefined, chosen: string[]): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const q of seqs ?? []) if (q.length > chosen.length && chosen.every((t, i) => q[i] === t)) out.add(q[chosen.length]);
|
||||
return out;
|
||||
}
|
||||
/** True when `chosen` is a complete legal sequence. */
|
||||
export const targetsComplete = (seqs: string[][] | undefined, chosen: string[]) =>
|
||||
!!seqs?.some(q => q.length === chosen.length && q.every((t, i) => t === chosen[i]));
|
||||
|
||||
// ---------- combat declaration (pure, so it is unit-tested) ----------
|
||||
|
||||
/**
|
||||
* Attack: one tap toggles a Figure in or out. Block: tap your blocker (1), then the attacker it
|
||||
* blocks (2). Tapping an assigned blocker again removes it. At most one blocker per attacker and
|
||||
* one attacker per blocker (BRIEF: single blocks).
|
||||
*/
|
||||
export type Declaration = { attackers: string[]; blocks: Record<string, string>; picked?: string };
|
||||
export const EMPTY_DECL: Declaration = { attackers: [], blocks: {} };
|
||||
|
||||
export function toggleAttacker(d: Declaration, id: string, legal: Legal): Declaration {
|
||||
if (!legal.attackers.includes(id)) return d;
|
||||
const attackers = d.attackers.includes(id) ? d.attackers.filter(a => a !== id) : [...d.attackers, id];
|
||||
return { ...d, attackers };
|
||||
}
|
||||
|
||||
/** Tap on one of my cards during blocks. */
|
||||
export function tapBlocker(d: Declaration, blockerId: string, legal: Legal): Declaration {
|
||||
if (d.blocks[blockerId]) { const blocks = { ...d.blocks }; delete blocks[blockerId]; return { ...d, blocks, picked: undefined }; }
|
||||
if (!legal.blockers[blockerId]?.length) return d;
|
||||
return { ...d, picked: d.picked === blockerId ? undefined : blockerId };
|
||||
}
|
||||
|
||||
/** Tap on an attacker during blocks. With a blocker picked, assign it; the attacker's old blocker is freed. */
|
||||
export function tapAttacker(d: Declaration, attackerId: string, legal: Legal): Declaration {
|
||||
const picked = d.picked;
|
||||
if (!picked) {
|
||||
// No blocker picked: tapping a blocked attacker clears its block.
|
||||
const owner = Object.entries(d.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
if (!owner) return d;
|
||||
const blocks = { ...d.blocks }; delete blocks[owner]; return { ...d, blocks };
|
||||
}
|
||||
if (!legal.blockers[picked]?.includes(attackerId)) return d;
|
||||
const blocks = Object.fromEntries(Object.entries(d.blocks).filter(([, a]) => a !== attackerId));
|
||||
blocks[picked] = attackerId;
|
||||
return { ...d, blocks, picked: undefined };
|
||||
}
|
||||
|
||||
export const blockList = (d: Declaration) => Object.entries(d.blocks).map(([blockerId, attackerId]) => ({ blockerId, attackerId }));
|
||||
|
||||
// ---------- combat preview ----------
|
||||
|
||||
export type CombatOutcome = {
|
||||
/** Damage the defending player takes. */
|
||||
toPlayer: number;
|
||||
/** Card ids that would be destroyed. */
|
||||
destroyed: string[];
|
||||
rows: { attacker: BoardCard; blocker?: BoardCard; attackerDies: boolean; blockerDies: boolean }[];
|
||||
};
|
||||
|
||||
const has = (c: BoardCard | undefined, kw: string) => !!c?.keywords.some(k => k.toLowerCase() === kw.toLowerCase());
|
||||
/** Damage a card takes from one source, after Well-sourced (prevent the first 1 each turn). */
|
||||
const taken = (c: BoardCard, dmg: number) => Math.max(0, dmg - (has(c, 'Well-sourced') && !(c.damage ?? 0) ? 1 : 0));
|
||||
const dies = (c: BoardCard, dmg: number) => c.toughness !== undefined && (c.damage ?? 0) + taken(c, dmg) >= c.toughness && dmg > 0;
|
||||
|
||||
/**
|
||||
* A preview for the confirm sheet: simultaneous damage, single blocks, no trample or first strike
|
||||
* (BRIEF). The engine resolves for real; this is only so the player sees what they are confirming.
|
||||
*/
|
||||
export function previewCombat(attacks: Attack[], cards: Map<string, BoardCard>): CombatOutcome {
|
||||
const out: CombatOutcome = { toPlayer: 0, destroyed: [], rows: [] };
|
||||
for (const { attackerId, blockerId } of attacks) {
|
||||
const attacker = cards.get(attackerId);
|
||||
if (!attacker) continue;
|
||||
const blocker = blockerId ? cards.get(blockerId) : undefined;
|
||||
if (!blocker) { out.toPlayer += attacker.power ?? 0; out.rows.push({ attacker, attackerDies: false, blockerDies: false }); continue; }
|
||||
const attackerDies = dies(attacker, blocker.power ?? 0);
|
||||
const blockerDies = dies(blocker, attacker.power ?? 0);
|
||||
if (attackerDies) out.destroyed.push(attacker.id);
|
||||
if (blockerDies) out.destroyed.push(blocker.id);
|
||||
out.rows.push({ attacker, blocker, attackerDies, blockerDies });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- eligibility (BRIEF decisions 1–3) ----------
|
||||
|
||||
export const DEFAULT_DECK_SIZE = 40;
|
||||
|
||||
export type Eligibility = { eligible: boolean; owned: number; needed: number; label: string };
|
||||
|
||||
/** Bot and PvP matches are only for players who own a full deck. There is no borrowed-card play. */
|
||||
export function eligibility(owned: number, deckSize = DEFAULT_DECK_SIZE): Eligibility {
|
||||
const needed = Math.max(0, deckSize - owned);
|
||||
return { eligible: needed === 0, owned, needed, label: `${Math.min(owned, deckSize)} / ${deckSize} cards` };
|
||||
}
|
||||
|
||||
// ---------- text helpers ----------
|
||||
|
||||
/**
|
||||
* First sentence of an extract, for flavour text. Doesn't split on initials ("J. R. R."), common
|
||||
* abbreviations or decimals. Falls back to the whole (trimmed) text.
|
||||
*/
|
||||
export function firstSentence(text: string | undefined, max = 220): string | undefined {
|
||||
const t = text?.replace(/\s+/g, ' ').trim();
|
||||
if (!t) return undefined;
|
||||
const re = /[.!?](?=\s+[A-Z0-9"“(])/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(t))) {
|
||||
const before = t.slice(0, m.index);
|
||||
const word = before.split(' ').at(-1) ?? '';
|
||||
if (/^[A-Z]$/.test(word) || /^(Mr|Mrs|Ms|Dr|St|Jr|Sr|No|Mt|Ft|vs|c|ca|approx|e\.g|i\.e|U\.S|U\.K)$/i.test(word)) continue;
|
||||
return clip(t.slice(0, m.index + 1), max);
|
||||
}
|
||||
return clip(t, max);
|
||||
}
|
||||
const clip = (s: string, max: number) => (s.length <= max ? s : `${s.slice(0, max - 1).replace(/\s+\S*$/, '')}…`);
|
||||
|
||||
/** "Figure — People · 1961–" */
|
||||
export const typeLine = (c: Pick<BoardCard, 'type' | 'subtype' | 'portal'>) =>
|
||||
`${c.type} — ${c.subtype ?? c.portal}`;
|
||||
|
||||
/** Accessible one-line summary of a card. */
|
||||
export function cardSummary(c: BoardCard): string {
|
||||
const stats = c.power !== undefined ? `, ${c.power}/${c.toughness ?? 0}` : '';
|
||||
const kw = c.keywords.length ? `, ${c.keywords.join(', ')}` : '';
|
||||
const state = `${c.tapped ? ', tapped' : ''}${c.pending ? ', pending review' : ''}${c.damage ? `, ${c.damage} damage` : ''}`;
|
||||
return `${c.title}, ${typeLine(c)}, cost ${c.cost}${stats}${kw}${state}`;
|
||||
}
|
||||
|
||||
export const isMyTurn = (v: BoardView) => v.active === v.seat && v.phase !== 'over';
|
||||
+11
-8
@@ -1,8 +1,11 @@
|
||||
import './native.ts';
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
|
||||
import './native.ts';
|
||||
import React, { Suspense, lazy } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
// ui-duel review aid: `#duel-preview` renders static duel board scenes from card-sample.json.
|
||||
const DuelPreview = lazy(() => import('./game/duel/DuelPreview.tsx').then(m => ({ default: m.DuelPreview })));
|
||||
const root = location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
|
||||
|
||||
@@ -54,7 +54,7 @@ test('fixed HTTPS sources, encoded title, hidden categories, lower bounds and pl
|
||||
assert.equal(init.redirect, 'error');
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
assert.equal(new Headers(init.headers).get('accept'), 'application/json');
|
||||
assert.match(new Headers(init.headers).get('user-agent')!, /WikiDeck/i);
|
||||
assert.match(new Headers(init.headers).get('user-agent')!, /Wikideck/);
|
||||
assert.equal(new Headers(init.headers).has('origin'), false); // Server-side requests need no CORS workaround.
|
||||
}
|
||||
assert.equal(result.title, title);
|
||||
|
||||
@@ -2,7 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WikipediaArticleSource } from '../server/wiki.ts';
|
||||
import { WikipediaEnrichment } from '../server/enrichment.ts';
|
||||
import { PROJECT_URL, defaultUserAgent, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts';
|
||||
import { ARTICLE_USER_AGENT, ENRICHMENT_USER_AGENT, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts';
|
||||
|
||||
function capture() {
|
||||
const agents: string[] = [];
|
||||
@@ -12,10 +12,9 @@ function capture() {
|
||||
};
|
||||
return { agents, fetcher };
|
||||
}
|
||||
async function agentsFor(env: string | undefined, contact?: string) {
|
||||
const previous = process.env.WIKIDECK_USER_AGENT, previousContact = process.env.WIKIDECK_OPERATOR_CONTACT;
|
||||
async function agentsFor(env: string | undefined) {
|
||||
const previous = process.env.WIKIDECK_USER_AGENT;
|
||||
if (env === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = env;
|
||||
if (contact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT; else process.env.WIKIDECK_OPERATOR_CONTACT = contact;
|
||||
try {
|
||||
const article = capture(), enrichment = capture();
|
||||
await assert.rejects(new WikipediaArticleSource(article.fetcher).random());
|
||||
@@ -23,22 +22,15 @@ async function agentsFor(env: string | undefined, contact?: string) {
|
||||
return { article: article.agents, enrichment: enrichment.agents };
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = previous;
|
||||
if (previousContact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT;
|
||||
else process.env.WIKIDECK_OPERATOR_CONTACT = previousContact;
|
||||
}
|
||||
}
|
||||
|
||||
test('default Wikimedia user agent names the project, the operator contact and node', async () => {
|
||||
const { article, enrichment } = await agentsFor(undefined, 'ops@example.org');
|
||||
const expected = `WikiDeck/0.1.0 (+${PROJECT_URL}; ops@example.org) node/${process.versions.node}`;
|
||||
assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }), expected);
|
||||
assert.ok(article.length > 0 && article.every(a => a === expected));
|
||||
assert.ok(enrichment.length > 0 && enrichment.every(a => a === expected));
|
||||
assert.equal(defaultUserAgent({ PUBLIC_ORIGIN: 'https://node.example' }),
|
||||
`WikiDeck/0.1.0 (+${PROJECT_URL}; https://node.example) node/${process.versions.node}`);
|
||||
assert.equal(defaultUserAgent({}), `WikiDeck/0.1.0 (+${PROJECT_URL}) node/${process.versions.node}`);
|
||||
// Unsafe contacts are dropped rather than breaking the header's comment syntax.
|
||||
assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'a); evil(' }), defaultUserAgent({}));
|
||||
test('default Wikimedia user agents are unchanged when WIKIDECK_USER_AGENT is unset', async () => {
|
||||
assert.equal(ARTICLE_USER_AGENT, 'Wikideck/0.1 (experimental Wikipedia article cards)');
|
||||
assert.equal(ENRICHMENT_USER_AGENT, 'Wikideck/0.1 (Wikipedia off-chain page enrichment)');
|
||||
const { article, enrichment } = await agentsFor(undefined);
|
||||
assert.ok(article.length > 0 && article.every(a => a === ARTICLE_USER_AGENT));
|
||||
assert.ok(enrichment.length > 0 && enrichment.every(a => a === ENRICHMENT_USER_AGENT));
|
||||
});
|
||||
|
||||
test('WIKIDECK_USER_AGENT overrides both Wikimedia clients', async () => {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
|
||||
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
|
||||
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
|
||||
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
|
||||
});
|
||||
|
||||
function view(): PlayerView {
|
||||
const fig = card('fig', { keywords: ['Legacy'] });
|
||||
return {
|
||||
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
|
||||
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
|
||||
opponent: side(0, { life: 12 }),
|
||||
battlefield: [
|
||||
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
|
||||
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
|
||||
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
|
||||
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
|
||||
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
|
||||
],
|
||||
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
|
||||
};
|
||||
}
|
||||
|
||||
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
|
||||
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
|
||||
assert.equal(b.me.name, 'bob');
|
||||
assert.equal(b.opponent.name, 'alice');
|
||||
assert.equal(b.opponent.notability, 12);
|
||||
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
|
||||
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
|
||||
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
|
||||
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
|
||||
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
|
||||
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
|
||||
assert.deepEqual(mine.attachments, ['1:5']);
|
||||
assert.ok(mine.keywords.includes('Connected'));
|
||||
assert.equal(mine.pending, true);
|
||||
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
|
||||
assert.equal(b.hand[0].id, '1:7');
|
||||
assert.equal(b.hand[0].flavour, 'A thing.');
|
||||
});
|
||||
|
||||
test('legal actions → board legality, and board intents → atomic action sequences', () => {
|
||||
const legal: DuelAction[] = [
|
||||
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
|
||||
];
|
||||
const l = legalFromActions(legal);
|
||||
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
|
||||
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
|
||||
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
|
||||
|
||||
const main: DuelAction[] = [
|
||||
{ type: 'play', uid: 'h1' },
|
||||
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
|
||||
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
|
||||
{ type: 'endPhase' },
|
||||
];
|
||||
const m = legalFromActions(main);
|
||||
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
|
||||
assert.equal(m.canGoToCombat, true);
|
||||
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
|
||||
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
|
||||
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
|
||||
assert.equal(legalFromActions([]).canEndTurn, false);
|
||||
});
|
||||
|
||||
test('fallback log: real names and titles only, no adjectives', () => {
|
||||
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
|
||||
const events: LogEvent[] = [
|
||||
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
|
||||
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
|
||||
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
|
||||
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
|
||||
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
|
||||
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
|
||||
];
|
||||
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
|
||||
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
|
||||
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
|
||||
]);
|
||||
});
|
||||
|
||||
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
|
||||
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
|
||||
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
|
||||
const ids = cards.slice(0, 40).map(c => c.tokenId);
|
||||
const ok = playerDeck(ids, cards, 40);
|
||||
assert.equal(ok.cards.length, 40);
|
||||
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
|
||||
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
|
||||
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
|
||||
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
|
||||
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
|
||||
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
|
||||
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
|
||||
assert.deepEqual(a, b);
|
||||
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
|
||||
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
|
||||
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
|
||||
});
|
||||
|
||||
test('bot match: untyped profiles from the wire are shape-checked', async () => {
|
||||
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
|
||||
assert.equal(isDuelCard(card('x')), true);
|
||||
assert.equal(isDuelCard({ title: 'x' }), false);
|
||||
assert.equal(isDuelCard(null), false);
|
||||
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
|
||||
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EASY_BOT, NORMAL_BOT } from '../src/game/duel/bots.ts';
|
||||
import type { DuelAction, DuelCard, PermanentView, PlayerView } from '../src/game/duel/contract.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2, keywords: [], effects: [], rulesText: '', flavor: '', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, power: number, toughness: number, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: card(uid, { power, toughness }), tapped: false, sick: false, damage: 0, counters: 0, power, toughness, keywords: [], ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, life = 20) => ({ seat, life, citations: 3, maxCitations: 3, handSize: 0, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0 });
|
||||
const view = (p: Partial<PlayerView>): PlayerView => ({
|
||||
engine: 'duel', seat: 1, turn: 4, active: 1, phase: 'main', toAct: 1, you: { ...side(1), hand: [] }, opponent: side(0),
|
||||
battlefield: [], combat: { attackers: [], blocks: {} }, result: null, version: 1, rules: {}, ...p,
|
||||
});
|
||||
const rng = () => 0.5;
|
||||
|
||||
test('normal bot: plays the priciest card, harmful effects at the opponent', () => {
|
||||
const hand = [{ uid: '1:1', owner: 1 as const, card: card('cheap', { cost: 1 }) },
|
||||
{ uid: '1:2', owner: 1 as const, card: card('bolt', { type: 'Event', cost: 3, power: null, toughness: null, effects: [{ op: 'damage', amount: 3 }] }) }];
|
||||
const v = view({ you: { ...side(1), hand }, battlefield: [perm('0:9', 0, 3, 3), perm('1:8', 1, 2, 2)] });
|
||||
const legal: DuelAction[] = [{ type: 'play', uid: '1:1' },
|
||||
{ type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '1:8' }] }, { type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '0:9' }] }, { type: 'endPhase' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[2]);
|
||||
});
|
||||
|
||||
test('normal bot: attacks unless a blocker eats it, all-in on lethal, then confirms', () => {
|
||||
const bf = [perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1), perm('0:1', 0, 2, 4)];
|
||||
const legal: DuelAction[] = [{ type: 'toggleAttacker', uid: '1:1' }, { type: 'toggleAttacker', uid: '1:2' }, { type: 'confirmAttack' }];
|
||||
// 1:1 (3/3) faces a 2/4 that survives but doesn't kill: attack. 1:2 (1/1) would die to it for nothing.
|
||||
const v = view({ phase: 'attack', battlefield: bf });
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
const after = view({ phase: 'attack', battlefield: bf, combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(after, legal.slice(1), rng), { type: 'confirmAttack' });
|
||||
const lethal = view({ phase: 'attack', battlefield: bf, opponent: side(0, 1), combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(lethal, legal.slice(1), rng), legal[1]);
|
||||
});
|
||||
|
||||
test('normal bot: takes the kill-and-survive block, otherwise no block', () => {
|
||||
const bf = [perm('0:1', 0, 2, 2), perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1)];
|
||||
const v = view({ phase: 'block', active: 0, battlefield: bf, combat: { attackers: ['0:1'], blocks: {} } });
|
||||
const legal: DuelAction[] = [{ type: 'block', blocker: '1:1', attacker: '0:1' }, { type: 'block', blocker: '1:2', attacker: '0:1' }, { type: 'confirmBlocks' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal.slice(1), rng), { type: 'confirmBlocks' });
|
||||
});
|
||||
|
||||
test('bots always return a listed action and keep their opening hand', () => {
|
||||
const legal: DuelAction[] = [{ type: 'keep' }, { type: 'mulligan' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(view({ phase: 'mulligan' }), legal, rng), { type: 'keep' });
|
||||
let x = 1; const r = () => ((x = (x * 48271) % 2147483647) / 2147483647);
|
||||
for (let i = 0; i < 50; i++) assert.ok(legal.includes(EASY_BOT.choose(view({ phase: 'mulligan' }), legal, r)));
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
EMPTY_DECL, NO_LEGAL, blockList, cardSummary, eligibility, firstSentence, previewCombat, tapAttacker, tapBlocker, toggleAttacker, typeLine,
|
||||
type BoardCard, type Legal,
|
||||
} from '../src/game/duel/model.ts';
|
||||
import { PREVIEW_POOL, previewView } from '../src/game/duel/mock.ts';
|
||||
|
||||
const fig = (id: string, power: number, toughness: number, extra: Partial<BoardCard> = {}): BoardCard =>
|
||||
({ id, title: id, type: 'Figure', portal: 'Society', cost: 2, power, toughness, keywords: [], rulesText: '', ...extra });
|
||||
|
||||
test('attack declaration: one tap toggles a legal attacker, illegal ones are ignored', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, attackers: ['a', 'b'] };
|
||||
let d = toggleAttacker(EMPTY_DECL, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'z', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'b', legal);
|
||||
d = toggleAttacker(d, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['b']);
|
||||
});
|
||||
|
||||
test('block declaration: two taps per blocker, single blocks, re-tap clears', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, blockers: { x: ['A', 'B'], y: ['A'], z: [] } };
|
||||
let d = tapBlocker(EMPTY_DECL, 'x', legal);
|
||||
assert.equal(d.picked, 'x');
|
||||
d = tapAttacker(d, 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'x', attackerId: 'A' }]);
|
||||
assert.equal(d.picked, undefined);
|
||||
// y takes over A; x is freed (at most one blocker per attacker).
|
||||
d = tapAttacker(tapBlocker(d, 'y', legal), 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'y', attackerId: 'A' }]);
|
||||
// y can't block B: the tap is ignored and y stays picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'y', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(d), []);
|
||||
// A blocker with no legal attacker can't be picked.
|
||||
assert.equal(tapBlocker(EMPTY_DECL, 'z', legal).picked, undefined);
|
||||
// Re-tapping an assigned blocker removes the block; so does tapping its attacker with nothing picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'x', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(tapBlocker(d, 'x', legal)), []);
|
||||
assert.deepEqual(blockList(tapAttacker(d, 'B', legal)), []);
|
||||
// One blocker per attacker, and one attacker per blocker.
|
||||
d = tapAttacker(tapBlocker(d, 'x', legal), 'A', legal);
|
||||
assert.equal(blockList(d).length <= 1, true);
|
||||
});
|
||||
|
||||
test('combat preview: simultaneous damage, single blocks, Well-sourced, marked damage', () => {
|
||||
const cards = new Map([fig('a', 3, 3), fig('b', 2, 2), fig('c', 4, 1), fig('w', 1, 3, { keywords: ['Well-sourced'] }), fig('d', 2, 3, { damage: 1 })].map(c => [c.id, c]));
|
||||
const out = previewCombat([{ attackerId: 'a', blockerId: 'b' }, { attackerId: 'c' }], cards);
|
||||
assert.equal(out.toPlayer, 4);
|
||||
assert.deepEqual(out.destroyed.sort(), ['b']);
|
||||
// Well-sourced prevents the first 1: a 3-power attacker deals 2 to a 1/3, which survives.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'a', blockerId: 'w' }], cards).destroyed, []);
|
||||
// Damage already marked counts: 2 more kills a 2/3 with 1 damage.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'b', blockerId: 'd' }], cards).destroyed.sort(), ['b', 'd']);
|
||||
});
|
||||
|
||||
test('eligibility: exactly the deck size, no borrowed cards, progress label', () => {
|
||||
assert.deepEqual(eligibility(23), { eligible: false, owned: 23, needed: 17, label: '23 / 40 cards' });
|
||||
assert.equal(eligibility(40).eligible, true);
|
||||
assert.equal(eligibility(57).label, '40 / 40 cards');
|
||||
assert.equal(eligibility(12, 12).eligible, true); // testnet mode file may lower deckSize
|
||||
});
|
||||
|
||||
test('flavour: first sentence of the extract, not split on initials or abbreviations', () => {
|
||||
assert.equal(firstSentence('J. R. R. Tolkien was an English writer. He wrote books.'), 'J. R. R. Tolkien was an English writer.');
|
||||
assert.equal(firstSentence('St. Georgen am Längsee is a town. It is in Austria.'), 'St. Georgen am Längsee is a town.');
|
||||
assert.equal(firstSentence('Pi is about 3.14 in value. More.'), 'Pi is about 3.14 in value.');
|
||||
assert.equal(firstSentence('No full stop here'), 'No full stop here');
|
||||
assert.equal(firstSentence(''), undefined);
|
||||
assert.ok((firstSentence('word '.repeat(100)) ?? '').length <= 220);
|
||||
});
|
||||
|
||||
test('type line and accessible summary', () => {
|
||||
const c = fig('Barack Obama', 3, 4, { subtype: 'People · 1961–', keywords: ['Protected'], tapped: true });
|
||||
assert.equal(typeLine(c), 'Figure — People · 1961–');
|
||||
assert.equal(cardSummary(c), 'Barack Obama, Figure — People · 1961–, cost 2, 3/4, Protected, tapped');
|
||||
});
|
||||
|
||||
test('preview scenes: a full 5 + 5 board with every card from the real sample', () => {
|
||||
assert.equal(PREVIEW_POOL.length, 236);
|
||||
for (const scene of ['main', 'attack', 'block', 'over'] as const) {
|
||||
const { view } = previewView(scene);
|
||||
assert.equal(view.me.battlefield.length, 5);
|
||||
assert.equal(view.opponent.battlefield.length, 5);
|
||||
}
|
||||
for (const c of PREVIEW_POOL) {
|
||||
assert.ok(c.keywords.length <= 2, c.title);
|
||||
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
|
||||
}
|
||||
});
|
||||
|
||||
test('DuelCard → board card: type line from real data only, flavour is one sentence', async () => {
|
||||
const { boardCard, lifespan } = await import('../src/game/duel/cards.ts');
|
||||
assert.equal(lifespan('Sultan of Aceh (1530–1537/9)'), '1530–1537');
|
||||
assert.equal(lifespan('American voice actor and singer (born 1963)'), '1963–');
|
||||
assert.equal(lifespan('American botanist (c.1872–1919)'), '1872–1919');
|
||||
assert.equal(lifespan('Species of grasshopper'), undefined);
|
||||
const c = boardCard({ cardId: 't', pageId: 1, revisionId: 9, title: 'Salahuddin of Aceh', type: 'Figure', subtype: null, portal: 'History',
|
||||
cost: 4, power: 4, toughness: 3, keywords: ['Legacy'], rulesText: 'Legacy.', flavor: 'Sultan of Aceh (1530–1537/9). Second sentence.' });
|
||||
assert.equal(typeLine(c), 'Figure — History · 1530–1537');
|
||||
assert.equal(c.flavour, 'Sultan of Aceh (1530–1537/9).');
|
||||
assert.equal(c.url, 'https://en.wikipedia.org/wiki/Salahuddin_of_Aceh');
|
||||
const e = boardCard({ cardId: 'e', pageId: 2, revisionId: 9, title: '1954 Gold Coast general election', type: 'Event', subtype: 'election', portal: 'Society',
|
||||
cost: 4, power: null, toughness: null, keywords: [], rulesText: 'x', flavor: '' });
|
||||
assert.equal(typeLine(e), 'Event — Society · Election');
|
||||
assert.equal(e.power, undefined);
|
||||
});
|
||||
|
||||
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
|
||||
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
|
||||
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
|
||||
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
|
||||
assert.equal(targetsComplete(seqs, ['a']), false);
|
||||
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
|
||||
assert.equal(targetsComplete([[]], []), true);
|
||||
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
|
||||
});
|
||||
+1
-4
@@ -56,16 +56,13 @@ test('random article fetch rejects unsafe response types, redirects, and oversiz
|
||||
() => new Response('{}', { headers: { 'Content-Type': 'text/html' } }),
|
||||
() => new Response(null, { status: 302, headers: { Location: 'https://evil.example' } }),
|
||||
() => new Response(' '.repeat(512 * 1024 + 1), { headers: { 'Content-Type': 'application/json' } }),
|
||||
() => { throw new Error('offline'); },
|
||||
];
|
||||
for (const fail of failures) {
|
||||
const { fetcher, calls } = mockFetch(() => fail());
|
||||
await assert.rejects(new WikipediaArticleSource(fetcher).random());
|
||||
assert.equal(calls.length, 3);
|
||||
}
|
||||
// A network failure (or throttling) stops at once instead of retrying against an unreachable upstream.
|
||||
const { fetcher, calls } = mockFetch(() => { throw new Error('offline'); });
|
||||
await assert.rejects(new WikipediaArticleSource(fetcher).random(), /Wikimedia unavailable/);
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test('bad page records are skipped while later valid candidates are considered', async () => {
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WikimediaClient, WikimediaUnavailable, configFromEnv, type ClientConfig } from '../server/wikimedia/client.ts';
|
||||
import { WikimediaCache, cacheKey } from '../server/wikimedia/cache.ts';
|
||||
import { warnIfNoContact } from '../server/wikimedia-user-agent.ts';
|
||||
import { FakeClock, flush, json, recorder } from './wikimedia-helpers.ts';
|
||||
|
||||
const API = 'https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1';
|
||||
const REST = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/x';
|
||||
|
||||
function setup(handler: Parameters<typeof recorder>[1] = () => json({ ok: true }), config: Partial<ClientConfig> = {},
|
||||
cache?: WikimediaCache) {
|
||||
const clock = new FakeClock();
|
||||
const rec = recorder(clock, handler);
|
||||
const client = new WikimediaClient({ fetch: rec.fetcher, clock, config, cache, userAgent: () => 'Test/1 (+x; y)' });
|
||||
return { clock, client, ...rec };
|
||||
}
|
||||
|
||||
test('token bucket: burst of 3, then 1 request per second, one in flight per host', async () => {
|
||||
const { clock, client, calls } = setup();
|
||||
const jobs = Array.from({ length: 6 }, () => client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 })
|
||||
.then(r => r.response.body?.cancel()));
|
||||
await clock.advance(0);
|
||||
assert.equal(calls.length, 3);
|
||||
await clock.advance(999);
|
||||
assert.equal(calls.length, 3);
|
||||
await clock.advance(1);
|
||||
assert.equal(calls.length, 4);
|
||||
await clock.advance(2000);
|
||||
await Promise.all(jobs);
|
||||
assert.deepEqual(calls.map(c => c.at - calls[0].at), [0, 0, 0, 1000, 2000, 3000]);
|
||||
// Different hosts have separate buckets.
|
||||
await client.request(new URL(REST), { lane: 'interactive', timeoutMs: 1000 });
|
||||
assert.equal(calls.at(-1)!.url.hostname, 'wikimedia.org');
|
||||
});
|
||||
|
||||
test('only one request is in flight per host, even with tokens to spare', async () => {
|
||||
const releases: (() => void)[] = [];
|
||||
const { clock, client, calls } = setup(() => new Promise(resolve => releases.push(() => resolve(json({})))));
|
||||
const a = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
|
||||
const b = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
|
||||
await clock.advance(0);
|
||||
assert.equal(calls.length, 1);
|
||||
releases.shift()!();
|
||||
await a;
|
||||
await clock.advance(0);
|
||||
assert.equal(calls.length, 2);
|
||||
releases.shift()!();
|
||||
await b;
|
||||
});
|
||||
|
||||
test('priority lanes: mint, then interactive, then background', async () => {
|
||||
const { clock, client, calls } = setup(url => json({ lane: url.searchParams.get('n') }), { burst: 1 });
|
||||
await client.request(new URL(`${API}&n=warm`), { lane: 'background', timeoutMs: 1000 }); // Uses the only token.
|
||||
const order: string[] = [];
|
||||
const go = (lane: 'mint' | 'interactive' | 'background', n: string) =>
|
||||
client.request(new URL(`${API}&n=${n}`), { lane, timeoutMs: 1000 }).then(() => order.push(n));
|
||||
const jobs = [go('background', 'b1'), go('interactive', 'i1'), go('background', 'b2'), go('mint', 'm1'), go('interactive', 'i2')];
|
||||
await clock.advance(5000);
|
||||
await Promise.all(jobs);
|
||||
assert.deepEqual(order, ['m1', 'i1', 'i2', 'b1', 'b2']);
|
||||
assert.equal(calls.length, 6);
|
||||
});
|
||||
|
||||
test('maxlag=5 is added to Action API requests only, and a maxlag reply waits for Retry-After', async () => {
|
||||
let lagged = 1;
|
||||
const { clock, client, calls } = setup(url => url.pathname === '/w/api.php' && lagged-- > 0
|
||||
? json({ error: { code: 'maxlag' } }, { 'MediaWiki-API-Error': 'maxlag', 'Retry-After': '5' })
|
||||
: json({ ok: true }));
|
||||
const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 });
|
||||
await clock.advance(0);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].url.searchParams.get('maxlag'), '5');
|
||||
await clock.advance(4999);
|
||||
assert.equal(calls.length, 1);
|
||||
await clock.advance(1);
|
||||
const { response } = await job;
|
||||
assert.deepEqual(await response.json(), { ok: true });
|
||||
assert.equal(calls.length, 2);
|
||||
await client.request(new URL(REST), { lane: 'background', timeoutMs: 1000 });
|
||||
assert.equal(calls[2].url.searchParams.has('maxlag'), false);
|
||||
assert.equal(calls[0].headers.get('user-agent'), 'Test/1 (+x; y)');
|
||||
});
|
||||
|
||||
test('429 honours Retry-After by pausing the host; three in a row open the circuit for 10 minutes', async () => {
|
||||
let status = 429;
|
||||
const { clock, client, calls } = setup(() => status === 200 ? json({}) : new Response('slow down',
|
||||
{ status, headers: { 'Retry-After': '2' } }));
|
||||
const req = (lane: 'mint' | 'background' = 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 });
|
||||
await assert.rejects(req(), (e: unknown) => e instanceof WikimediaUnavailable && e.status === 429);
|
||||
// The next request waits out Retry-After (2 s) instead of going straight back.
|
||||
const second = req().catch(e => e);
|
||||
await clock.advance(1999);
|
||||
assert.equal(calls.length, 1);
|
||||
await clock.advance(1);
|
||||
assert.equal(((await second) as WikimediaUnavailable).status, 429);
|
||||
const third = req().catch(e => e);
|
||||
await clock.advance(10_000);
|
||||
assert.equal(((await third) as WikimediaUnavailable).status, 429);
|
||||
assert.equal(calls.length, 3);
|
||||
assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, true);
|
||||
// Open circuit: refused at once without touching Wikimedia, even on the mint lane.
|
||||
status = 200;
|
||||
await assert.rejects(req('mint'), /circuit open/);
|
||||
assert.equal(calls.length, 3);
|
||||
await clock.advance(10 * 60_000);
|
||||
await req('mint');
|
||||
assert.equal(calls.length, 4);
|
||||
assert.equal(client.status().counters['breaker.open'], 1);
|
||||
});
|
||||
|
||||
test('a success resets the consecutive-429 count', async () => {
|
||||
const replies = [429, 200, 429, 200, 429];
|
||||
const { clock, client } = setup(() => {
|
||||
const status = replies.shift()!;
|
||||
return status === 200 ? json({}) : new Response('', { status });
|
||||
});
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).catch(() => {});
|
||||
await clock.advance(60_000);
|
||||
await job;
|
||||
}
|
||||
assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, false);
|
||||
});
|
||||
|
||||
test('daily cap: background stops at 80 %, interactive at 100 %, mint keeps a 10 % reserve; resets at UTC midnight', async () => {
|
||||
const { clock, client } = setup(() => json({}), { dailyCap: 10, requestsPerSecond: 1000, burst: 1000 });
|
||||
const req = (lane: 'mint' | 'interactive' | 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 });
|
||||
for (let i = 0; i < 8; i++) await req('background');
|
||||
await assert.rejects(req('background'), /daily cap/);
|
||||
await req('interactive'); await req('interactive');
|
||||
await assert.rejects(req('interactive'), /daily cap/);
|
||||
await req('mint');
|
||||
await assert.rejects(req('mint'), /daily cap/);
|
||||
await clock.advance(24 * 3600_000);
|
||||
await req('background');
|
||||
});
|
||||
|
||||
test('nodes sharing one egress IP split the rate and the daily cap', () => {
|
||||
const config = configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: '0.9', WIKIDECK_WIKIMEDIA_NODES_PER_IP: '3',
|
||||
WIKIDECK_WIKIMEDIA_DAILY_CAP: '3000' });
|
||||
const client = new WikimediaClient({ fetch: async () => json({}), config });
|
||||
assert.ok(Math.abs(client.status().requestsPerSecond - 0.3) < 1e-9);
|
||||
assert.equal(client.status().dailyCap, 1000);
|
||||
assert.equal(configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: 'abc' }).requestsPerSecond, 1);
|
||||
});
|
||||
|
||||
test('a full queue sheds background work first and a mint request evicts a background waiter', async () => {
|
||||
const { clock, client } = setup(() => json({}), { queueLimit: 2, burst: 1 });
|
||||
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
|
||||
const b1 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message);
|
||||
const b2 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message);
|
||||
await assert.rejects(client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }), /queue full/);
|
||||
const mint = client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 });
|
||||
await clock.advance(5000);
|
||||
await mint;
|
||||
assert.deepEqual([await b1, await b2], ['ok', 'Wikimedia unavailable: queue full']);
|
||||
});
|
||||
|
||||
test('waiting longer than the lane allows fails instead of queueing forever', async () => {
|
||||
const { clock, client } = setup(() => json({}), { burst: 1, requestsPerSecond: 0.01, maxWaitMs: { interactive: 3000 } as ClientConfig['maxWaitMs'] });
|
||||
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
|
||||
const late = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }).catch(e => e);
|
||||
await clock.advance(3000);
|
||||
assert.match(String(await late), /queue wait/);
|
||||
});
|
||||
|
||||
test('disk cache: ETag revalidation with If-None-Match, 304 refresh, stale-while-revalidate on the background lane', async () => {
|
||||
const cache = new WikimediaCache(':memory:');
|
||||
let body = { v: 1 };
|
||||
const { clock, client, calls } = setup((_url, headers) => headers.get('if-none-match') === '"v1"' && body.v === 1
|
||||
? new Response(null, { status: 304 }) : json(body, { ETag: `"v${body.v}"` }), {}, cache);
|
||||
const policy = { ttlMs: 1000, staleWhileRevalidate: false };
|
||||
const read = async (lane: 'interactive' | 'background' = 'interactive', cachePolicy = policy) =>
|
||||
(await (await client.request(new URL(API), { lane, timeoutMs: 1000, cache: cachePolicy })).response.json());
|
||||
assert.deepEqual(await read(), { v: 1 });
|
||||
assert.deepEqual(await read(), { v: 1 });
|
||||
assert.equal(calls.length, 1); // Fresh hit.
|
||||
await clock.advance(1000);
|
||||
assert.deepEqual(await read(), { v: 1 });
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[1].headers.get('if-none-match'), '"v1"'); // Conditional request, answered 304.
|
||||
assert.equal(client.status().counters['cache.revalidated'], 1);
|
||||
// Stale-while-revalidate: the stale copy is served at once; the refresh happens on the background lane.
|
||||
await clock.advance(1000);
|
||||
body = { v: 2 };
|
||||
assert.deepEqual(await read('interactive', { ttlMs: 1000, staleWhileRevalidate: true }), { v: 1 });
|
||||
await clock.advance(0); await flush();
|
||||
assert.equal(calls.length, 3);
|
||||
assert.equal(client.status().counters['lane.background'], 1);
|
||||
assert.deepEqual(await read(), { v: 2 });
|
||||
assert.equal(calls.length, 3);
|
||||
// The key ignores maxlag and parameter order.
|
||||
assert.equal(cacheKey(new URL('https://h.org/p?b=2&a=1&maxlag=5')), cacheKey(new URL('https://h.org/p?a=1&b=2')));
|
||||
});
|
||||
|
||||
test('requests without a cache policy (mint) neither read nor write the cache', async () => {
|
||||
const cache = new WikimediaCache(':memory:');
|
||||
const { client, calls } = setup(() => json({ n: calls.length }), {}, cache);
|
||||
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: { ttlMs: 60_000 } });
|
||||
const minted = await client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 });
|
||||
assert.equal(minted.fromCache, false);
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(cache.size(), 1);
|
||||
});
|
||||
|
||||
test('a stale copy is served when the upstream refuses, and non-JSON replies are never cached', async () => {
|
||||
const cache = new WikimediaCache(':memory:');
|
||||
let fail = false, html = false;
|
||||
const { clock, client } = setup(() => fail ? new Response('', { status: 429 })
|
||||
: html ? new Response('<html>', { headers: { 'Content-Type': 'text/html' } }) : json({ v: 1 }), {}, cache);
|
||||
const policy = { ttlMs: 1000 };
|
||||
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy });
|
||||
await clock.advance(2000);
|
||||
fail = true;
|
||||
const stale = await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy });
|
||||
assert.equal(stale.fromCache, true);
|
||||
fail = false; html = true;
|
||||
await clock.advance(60_000);
|
||||
await client.request(new URL(`${API}&other=1`), { lane: 'interactive', timeoutMs: 1000, cache: policy });
|
||||
assert.equal(cache.size(), 1);
|
||||
});
|
||||
|
||||
test('start-up warns when there is no operator contact', () => {
|
||||
const messages: string[] = [];
|
||||
assert.equal(warnIfNoContact({}, m => messages.push(m)), true);
|
||||
assert.match(messages[0], /WIKIDECK_OPERATOR_CONTACT/);
|
||||
assert.equal(warnIfNoContact({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }, m => messages.push(m)), false);
|
||||
assert.equal(warnIfNoContact({ WIKIDECK_USER_AGENT: 'X/1 (+https://x; y)' }, m => messages.push(m)), false);
|
||||
assert.equal(messages.length, 1);
|
||||
});
|
||||
|
||||
test('only HTTPS is allowed', async () => {
|
||||
const { client } = setup();
|
||||
await assert.rejects(client.request(new URL('http://en.wikipedia.org/w/api.php'), { lane: 'mint', timeoutMs: 1 }), RangeError);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
// Shared fakes for tests/wikimedia-*.test.ts: a manual clock and a recording fetch. Zero network.
|
||||
import type { Clock } from '../server/wikimedia/client.ts';
|
||||
|
||||
export class FakeClock implements Clock {
|
||||
time: number;
|
||||
private timers: { at: number; fn: () => void; id: number }[] = [];
|
||||
private nextId = 1;
|
||||
constructor(start = Date.parse('2026-11-17T12:00:00Z')) { this.time = start; }
|
||||
now(): number { return this.time; }
|
||||
setTimeout(fn: () => void, ms: number): unknown {
|
||||
const id = this.nextId++;
|
||||
this.timers.push({ at: this.time + Math.max(0, ms), fn, id });
|
||||
return id;
|
||||
}
|
||||
clearTimeout(handle: unknown): void { this.timers = this.timers.filter(t => t.id !== handle); }
|
||||
/** Advance time, firing due timers in order and letting promise chains settle between them. */
|
||||
async advance(ms: number): Promise<void> {
|
||||
const target = this.time + ms;
|
||||
await flush();
|
||||
for (;;) {
|
||||
this.timers.sort((a, b) => a.at - b.at || a.id - b.id);
|
||||
const next = this.timers[0];
|
||||
if (!next || next.at > target) break;
|
||||
this.timers.shift();
|
||||
this.time = Math.max(this.time, next.at);
|
||||
next.fn();
|
||||
await flush();
|
||||
}
|
||||
this.time = target;
|
||||
await flush();
|
||||
}
|
||||
}
|
||||
|
||||
export async function flush(): Promise<void> {
|
||||
for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
|
||||
export function json(value: unknown, headers: Record<string, string> = {}, status = 200): Response {
|
||||
return new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', ...headers } });
|
||||
}
|
||||
|
||||
export type Call = { url: URL; headers: Headers; at: number };
|
||||
export function recorder(clock: { now(): number }, handler: (url: URL, headers: Headers) => Response | Promise<Response>) {
|
||||
const calls: Call[] = [];
|
||||
const fetcher: typeof fetch = async (input, init) => {
|
||||
const url = new URL(String(input));
|
||||
const headers = new Headers(init?.headers);
|
||||
calls.push({ url, headers, at: clock.now() });
|
||||
return handler(url, headers);
|
||||
};
|
||||
return { calls, fetcher };
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WikipediaEnrichment } from '../server/enrichment.ts';
|
||||
import { WikipediaArticleSource, randomArticlesUrl } from '../server/wiki.ts';
|
||||
import { WikimediaClient } from '../server/wikimedia/client.ts';
|
||||
import { WikimediaCache } from '../server/wikimedia/cache.ts';
|
||||
import { UNTHROTTLED } from '../server/wikimedia/client.ts';
|
||||
import { json } from './wikimedia-helpers.ts';
|
||||
|
||||
const JANUARY = new Date('2025-01-15T23:59:59Z');
|
||||
const MONTHS = ['2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12'];
|
||||
const metadata = (pageId = 736) => ({ query: { pages: [{ pageid: pageId, ns: 0, title: 'Albert Einstein', lastrevid: 1234,
|
||||
length: 100_000, pageprops: { wikibase_item: 'Q937' }, categories: [], langlinks: [{ lang: 'de' }] }] } });
|
||||
const views = (counts = [10, 20, 30, 40, 50, 100]) => ({ items: MONTHS.map((month, i) => ({ timestamp: `${month.replace('-', '')}0100`,
|
||||
views: counts[i], project: 'en.wikipedia', access: 'all-access', agent: 'user', granularity: 'monthly' })) });
|
||||
|
||||
function service(viewsReply: () => Response | Promise<Response>, cache?: WikimediaCache) {
|
||||
const urls: URL[] = [];
|
||||
const fetcher: typeof fetch = async input => {
|
||||
const url = new URL(String(input));
|
||||
urls.push(url);
|
||||
return url.hostname === 'en.wikipedia.org' ? json(metadata(Number(url.searchParams.get('pageids')))) : viewsReply();
|
||||
};
|
||||
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED, cache });
|
||||
return { urls, client, enrichment: new WikipediaEnrichment({ client, now: () => JANUARY }) };
|
||||
}
|
||||
|
||||
test('mint fix: a 429, 5xx, timeout or network failure on pageviews fails the mint read instead of pinning attention: null', async () => {
|
||||
const failures: (() => Response | Promise<Response>)[] = [
|
||||
() => new Response('', { status: 429, headers: { 'Retry-After': '0' } }),
|
||||
() => new Response('', { status: 503 }),
|
||||
() => new Response('', { status: 500 }),
|
||||
() => new Response('<html>busy</html>', { headers: { 'Content-Type': 'text/html' } }),
|
||||
() => { throw new TypeError('fetch failed'); },
|
||||
() => Promise.reject(new DOMException('The operation timed out.', 'TimeoutError')),
|
||||
];
|
||||
for (const failure of failures) {
|
||||
const { enrichment } = service(failure);
|
||||
await assert.rejects(enrichment.getFresh(736), /unavailable/);
|
||||
// Display reads keep their old behaviour: metadata with unavailable views.
|
||||
const shown = await enrichment.get(736);
|
||||
assert.equal(shown.pageviews.status, 'unavailable');
|
||||
assert.equal(shown.stats.attention, null);
|
||||
}
|
||||
});
|
||||
|
||||
test('mint records unavailable views only for a genuine 404 or missing data', async () => {
|
||||
for (const reply of [() => json({ type: 'not found' }, {}, 404), () => json({ items: [] }), () => json({ items: views().items.slice(1) })]) {
|
||||
const { enrichment } = service(reply);
|
||||
const minted = await enrichment.getFresh(736);
|
||||
assert.equal(minted.pageviews.status, 'unavailable');
|
||||
assert.equal(minted.stats.attention, null);
|
||||
}
|
||||
const { enrichment } = service(() => json(views()));
|
||||
assert.equal((await enrichment.getFresh(736)).stats.attention, 33);
|
||||
});
|
||||
|
||||
test('mint reads never use the disk cache or join a display read', async () => {
|
||||
const cache = new WikimediaCache(':memory:');
|
||||
let count = 100;
|
||||
const { enrichment, urls } = service(() => json(views([1, 1, 1, 1, 1, count++])), cache);
|
||||
const shown = await enrichment.get(736);
|
||||
assert.equal(cache.size(), 2);
|
||||
const [display, minted] = await Promise.all([enrichment.get(736), enrichment.getFresh(736)]);
|
||||
assert.equal(display.pageviews.months[5].views, shown.pageviews.months[5].views);
|
||||
assert.equal(minted.pageviews.months[5].views, 101); // Fetched again, not the cached 100.
|
||||
assert.equal(urls.length, 4);
|
||||
// A later display read (memory cache cleared by a new service) is served from disk: no upstream call.
|
||||
const second = new WikipediaEnrichment({ client: new WikimediaClient({ fetch: async () => { throw new Error('no network'); },
|
||||
config: UNTHROTTLED, cache }), now: () => JANUARY });
|
||||
assert.equal((await second.get(736)).pageviews.months[5].views, 100);
|
||||
});
|
||||
|
||||
test('golden mint URLs: request parameters are byte-identical apart from the added maxlag', async () => {
|
||||
assert.equal(randomArticlesUrl().toString(), 'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2'
|
||||
+ '&generator=random&grnnamespace=0&grnlimit=10&prop=extracts%7Cpageimages%7Cinfo%7Ccategories&exintro=1&explaintext=1'
|
||||
+ '&exchars=900&piprop=thumbnail&pithumbsize=800&cllimit=20');
|
||||
const urls: string[] = [];
|
||||
const fetcher: typeof fetch = async input => {
|
||||
const url = new URL(String(input));
|
||||
urls.push(url.toString());
|
||||
if (url.searchParams.get('generator') === 'random') return json({ query: { pages: [{ pageid: 9, ns: 0, title: 'T',
|
||||
extract: 'An extract that is comfortably longer than forty characters.', lastrevid: 2,
|
||||
thumbnail: { source: 'https://upload.wikimedia.org/a.jpg' } }] } });
|
||||
return url.hostname === 'en.wikipedia.org' ? json(metadata(9)) : json(views());
|
||||
};
|
||||
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED });
|
||||
const article = await new WikipediaArticleSource(client).random();
|
||||
await new WikipediaEnrichment({ client, now: () => JANUARY }).getFresh(article.pageId);
|
||||
assert.deepEqual(urls, [
|
||||
`${randomArticlesUrl()}&maxlag=5`,
|
||||
'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&pageids=9'
|
||||
+ '&prop=info%7Ccategories%7Cpageprops%7Cdescription%7Clanglinks&clshow=%21hidden&cllimit=50&lllimit=500'
|
||||
+ '&ppprop=wikibase_item&maxlag=5',
|
||||
'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/Albert_Einstein/monthly/2024070100/2024120100',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a throttled upstream stops random() at once instead of retrying three times', async () => {
|
||||
let calls = 0;
|
||||
const source = new WikipediaArticleSource(async () => { calls++; return new Response('', { status: 429 }); });
|
||||
await assert.rejects(source.random(), /HTTP 429/);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MintTemplatePool } from '../server/wikimedia/pool.ts';
|
||||
import type { Article } from '../shared/protocol.ts';
|
||||
import type { PageEnrichment } from '../shared/enrichment.ts';
|
||||
|
||||
function article(pageId: number): Article {
|
||||
return { pageId, title: `Page ${pageId}`, extract: 'An extract that is comfortably longer than forty characters.',
|
||||
image: 'https://upload.wikimedia.org/a.jpg', url: `https://en.wikipedia.org/?curid=${pageId}`, revisionId: pageId + 1,
|
||||
source: 'live', category: 'Culture' };
|
||||
}
|
||||
function enrichment(pageId: number): PageEnrichment {
|
||||
return { pageId, title: `Page ${pageId}`, description: null, wikidataId: null, revisionId: pageId + 1, pageBytes: 10,
|
||||
languageCount: 1, languagesTruncated: false, categories: [], categoriesTruncated: false, fetchedAt: '2026-11-17T00:00:00Z',
|
||||
pageviews: { status: 'available', months: [], latestMonth: '2026-10', total: 1, dailyAverage: 1, trendPercent: null },
|
||||
stats: { attention: 1, depth: 1, reach: 1 } };
|
||||
}
|
||||
|
||||
function fixture(options: { size?: number; maxAgeMs?: number } = {}) {
|
||||
let next = 1, now = 0, fail = false;
|
||||
const log: string[] = [];
|
||||
const sources = {
|
||||
articles: { random: async () => { log.push('random'); if (fail) throw new Error('Wikimedia unavailable: HTTP 429'); return article(next++); } },
|
||||
enrichment: { getFresh: async (id: number) => { log.push(`fresh:${id}`); return enrichment(id); } },
|
||||
};
|
||||
const pool = new MintTemplatePool(sources, { now: () => now, ...options });
|
||||
return { pool, log, advance: (ms: number) => { now += ms; }, setFail: (value: boolean) => { fail = value; } };
|
||||
}
|
||||
|
||||
test('every template on one tip shares one article; a new tip gets a different one', async () => {
|
||||
const { pool, log } = fixture({ size: 1 });
|
||||
const first = await Promise.all(Array.from({ length: 20 }, () => pool.take('tip-a')));
|
||||
assert.ok(first.every(pair => pair.article.pageId === first[0].article.pageId));
|
||||
await pool.refill();
|
||||
const requestsForTwentyMiners = log.length;
|
||||
assert.equal(requestsForTwentyMiners, 4); // One direct pair, one prefetched pair: 2 calls each.
|
||||
const second = await pool.take('tip-b');
|
||||
assert.notEqual(second.article.pageId, first[0].article.pageId);
|
||||
assert.equal(second.article.pageId, 2); // Served from the prefetched pair, no wait.
|
||||
await pool.refill();
|
||||
assert.equal(log.length, 6); // ...and that use alone triggers the next prefetch.
|
||||
// The stats snapshot comes from a mint-path read of the same page.
|
||||
assert.equal(second.statsSnapshot.revisionId, second.article.pageId + 1);
|
||||
});
|
||||
|
||||
test('pairs older than maxAge are dropped, never served', async () => {
|
||||
const { pool, advance } = fixture({ size: 1, maxAgeMs: 1000 });
|
||||
const a = await pool.take('t1');
|
||||
await pool.refill();
|
||||
advance(1000);
|
||||
const b = await pool.take('t1'); // Same tip, but its pair expired; the ready pair expired too.
|
||||
assert.notEqual(b.article.pageId, a.article.pageId);
|
||||
assert.equal(pool.status().expired, 1);
|
||||
});
|
||||
|
||||
test('an idle pool makes no requests, and a failure rejects the template without a retry loop', async () => {
|
||||
const { pool, log, setFail } = fixture({ size: 2 });
|
||||
assert.equal(log.length, 0);
|
||||
setFail(true);
|
||||
await assert.rejects(pool.take('t1'), /429/);
|
||||
await pool.refill();
|
||||
assert.equal(log.filter(entry => entry === 'random').length, 2); // The direct attempt and one refill attempt.
|
||||
setFail(false);
|
||||
assert.ok((await pool.take('t1')).article.pageId > 0);
|
||||
});
|
||||
|
||||
test('callers get copies they cannot mutate', async () => {
|
||||
const { pool } = fixture();
|
||||
const a = await pool.take('t');
|
||||
a.article.title = 'changed';
|
||||
assert.equal((await pool.take('t')).article.title.startsWith('Page'), true);
|
||||
assert.throws(() => new MintTemplatePool({ articles: { random: async () => article(1) },
|
||||
enrichment: { getFresh: async () => enrichment(1) } }, { size: 99 }), RangeError);
|
||||
});
|
||||
Reference in New Issue
Block a user