Files
wikideck/server/game/collection.ts
claudeandClaude Opus 5.5 9943de3b53 [ownership] collectionRouter: optional injected duelCard hook (#57)
Attaches duel: DuelCard to collection cards when the server has a frozen
profile (requested by ui-duel); omitted while pending, never fetches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:02:50 -05:00

77 lines
3.4 KiB
TypeScript

/**
* GET /api/game/collection Authorization: Bearer <Dex ID token> [?minConfirmations=N]
*
* Every card the account's linked wallets own (no 128-block cap) and whether that is enough to
* build a deck. Eligibility counts the copy limit: 40 copies of one article is 4 playable cards.
*/
import { Router, type Request, type Response } from 'express';
import { DeckError, collectionAt, ownershipRules, playableCount, verifyAccount,
type ChainCard, type OwnershipDeps, type OwnershipRules } from './ownership.ts';
export type CollectionResponse = {
tip: string;
wallets: string[];
deckSize: number;
/** Max copies per pageId. `maxCopiesPerPage` is the same value under the ruleset's name. */
copyLimit: number;
maxCopiesPerPage: number;
minConfirmations: number;
/** Confirmed cards across all linked wallets. */
owned: number;
/** Σ min(copies, copyLimit) per pageId: the most cards a legal deck can draw from. */
playable: number;
/** max(0, deckSize - playable). */
needed: number;
/** playable >= deckSize. */
eligible: boolean;
/** `duel` is present when the server has a frozen profile for the card (see collectionRouter's `duelCard`). */
cards: (ChainCard & { duel?: unknown })[];
};
export function collectionResponse(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, sub: string,
rules?: Partial<OwnershipRules>): CollectionResponse {
const r = ownershipRules(rules);
const { tip, wallets, cards } = collectionAt(deps, { sub }, { minConfirmations: r.minConfirmations });
const playable = playableCount(cards, r.maxCopiesPerPage);
return { tip, wallets, deckSize: r.deckSize, copyLimit: r.maxCopiesPerPage, maxCopiesPerPage: r.maxCopiesPerPage,
minConfirmations: r.minConfirmations, owned: cards.length, playable, needed: Math.max(0, r.deckSize - playable),
eligible: playable >= r.deckSize, cards };
}
export type CollectionRouterDeps = OwnershipDeps & {
rules?: Partial<OwnershipRules>;
/**
* Optional: the same chain card → duel card function the PvP host uses, so the browser shows and
* plays exactly what PvP would. Return undefined while a card's profile is pending; it must not fetch.
*/
duelCard?: (card: ChainCard) => unknown;
};
export function collectionRouter(deps: CollectionRouterDeps): Router {
const router = Router();
router.get('/', async (req: Request, res: Response) => {
res.setHeader('Cache-Control', 'no-store');
const q = req.query.minConfirmations;
if (q !== undefined && (typeof q !== 'string' || !/^[1-9]\d{0,3}$/.test(q))) { res.status(400).json({ error: 'Invalid minConfirmations' }); return; }
const m = /^Bearer ([A-Za-z0-9_.-]{1,8192})$/.exec(req.get('authorization') ?? '');
try {
const account = await verifyAccount(deps, m?.[1]);
const body = collectionResponse(deps, account.sub, { ...deps.rules, ...(q ? { minConfirmations: Number(q) } : {}) });
if (deps.duelCard) {
const toDuel = deps.duelCard;
body.cards = body.cards.map(c => {
let duel: unknown;
try { duel = toDuel(c); } catch { duel = undefined; }
return duel === undefined ? c : { ...c, duel };
});
}
res.json(body);
} catch (e) {
const err = e as Error & { status?: number };
const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500;
res.status(status).json({ error: status === 500 ? 'Collection unavailable' : err.message });
}
});
return router;
}