cards/docs/marketplace/archive/code/lib/credits.ts
Till JS 7dbbf63523 Phase 12 R2: Marketplace-Backend α + β — Authors + Deck-Init + Publish
Routes (additiv unter /api/v1/marketplace/*):
- POST/GET /authors/me — eigenes Author-Profil anlegen/updaten/lesen
- GET /authors/:slug — public Profile-Lookup (banned-reason gestrippt)
- POST /decks — Deck-Init (Slug-Validation + Pflicht-Author-Profil +
  CHECK auf paid + Pro-License)
- POST /decks/:slug/publish — Versions-Snapshot mit per-Karte
  cardContentHash aus @cards/domain, per-Version-Hash, AI-Mod-Stub-Log,
  atomarer latest_version_id-Bump in Drizzle-Transaction
- PATCH /decks/:slug — Metadaten-Update (Owner-Only)
- GET /decks/:slug — Public-Detail mit optional-auth-Middleware

Geport aus cards-decommission-base:services/cards-server/, mit
Greenfield-Anpassungen:
- Hashing über @cards/domain.cardContentHash (gemeinsame SoT
  zwischen privatem cards.cards und marketplace.deck_cards), per-
  Version-Hash als SHA-256 über sortierte Karten-Hashes mit Ord-Prefix
- AI-Moderation als R2-Stub (pass+rationale+model='stub'),
  echte mana-llm-Anbindung in späterer Welle
- Auth-Middleware-Shape an Greenfield (userId/tier/authMode in
  c.get(...) statt user-Object), optional-auth als Schwester für
  anonymen Public-Read
- Hono-typing: outer Marketplace-Decks-Router ist Partial<AuthVars>
  weil Public-GET kein JWT braucht; Auth-Subroute ist strict

Lese-Referenz:
- 3331 LOC altes cards-server-Code (routes, services, middleware,
  lib) unter docs/marketplace/archive/code/ archiviert. Read-only,
  nicht im Build-Path.

Verifikation:
- 16 neue Vitest-Tests (Slug + Version-Hash), 72 gesamt grün
- type-check 0 errors
- E2E-Smoke gegen lokale cards-api: Cardecky-Author + Deck
  r2-stoische-ethik mit 3 Karten v1.0.0 (basic + basic + cloze),
  per-Karten-Hashes geschrieben, ai_moderation_log-Row da, semver-409
  + paid-422-Errors verifiziert. Smoke-Daten danach aufgeräumt.

Verbleibend für R3+: Discovery (explore + search), Engagement (stars/
subscribe/fork), Smart-Merge mit FSRS-State-Erhalt; danach R4 PRs +
Card-Discussions, R5 Frontend-Routes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:13:58 +02:00

80 lines
2.5 KiB
TypeScript

/**
* Thin client for mana-credits internal API. Cards-server is a
* service-to-service caller — the buyer's JWT does not flow through
* here; we use the X-Service-Key channel instead so we can reserve
* credits on a user's behalf, commit them after the purchase row is
* written, and grant the author share in one server-side flow.
*
* Errors propagate as Error subclasses so the purchase service can
* branch on `InsufficientCredits` vs. infra failures.
*/
export class CreditsClientError extends Error {
constructor(
public readonly status: number,
public readonly code: string,
message: string
) {
super(message);
this.name = 'CreditsClientError';
}
}
export class InsufficientCreditsError extends CreditsClientError {
constructor(message: string) {
super(402, 'insufficient_credits', message);
this.name = 'InsufficientCreditsError';
}
}
export interface CreditsClient {
reserve(input: { userId: string; amount: number; reason: string }): Promise<{
reservationId: string;
balance: number;
}>;
commit(input: { reservationId: string; description?: string }): Promise<unknown>;
refundReservation(input: { reservationId: string }): Promise<unknown>;
grant(input: {
userId: string;
amount: number;
reason: string;
referenceId: string;
description?: string;
}): Promise<{ transactionId?: string; grantId?: string } | unknown>;
}
export function createCreditsClient(opts: { url: string; serviceKey: string }): CreditsClient {
async function call<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${opts.url}/api/v1/internal${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Service-Key': opts.serviceKey,
},
body: JSON.stringify(body),
});
if (!res.ok) {
let msg = `${res.status} ${res.statusText}`;
let code = 'credits_error';
try {
const j = (await res.json()) as { code?: string; message?: string };
if (j.message) msg = j.message;
if (j.code) code = j.code;
} catch {
/* keep default */
}
if (res.status === 402 || code === 'insufficient_credits') {
throw new InsufficientCreditsError(msg);
}
throw new CreditsClientError(res.status, code, msg);
}
return (await res.json()) as T;
}
return {
reserve: (input) => call('/credits/reserve', input),
commit: (input) => call('/credits/commit', input),
refundReservation: (input) => call('/credits/refund-reservation', input),
grant: (input) => call('/credits/grant', input),
};
}