import { STARFLEET_API_URL } from '$app/env/private'; import { retryDelayMs, unexplainedMessage } from '$lib/game/errors'; import type { Envelope, ErrorEnvelope } from '$lib/types'; export const API_BASE = STARFLEET_API_URL; export class ApiError extends Error { constructor( public status: number, public code: string, message: string, public payload: ErrorEnvelope | null ) { super(message); this.name = 'ApiError'; } } interface ApiOptions { body?: unknown; query?: Record; headers?: Record; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** * Server-side call to the Starfleet API. Throws ApiError on non-2xx. * Transient errors (contended, rate_limited, busy) are retried once — see `retryDelayMs`. */ export async function api( token: string, method: string, path: string, opts: ApiOptions = {} ): Promise> { const url = new URL(`${API_BASE}${path.startsWith('/') ? path : `/${path}`}`); for (const [k, v] of Object.entries(opts.query ?? {})) { if (v !== undefined) url.searchParams.set(k, String(v)); } const init: RequestInit = { method, headers: { authorization: `Bearer ${token}`, accept: 'application/json', ...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}), ...opts.headers }, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined }; for (let attempt = 0; ; attempt++) { let res: Response; try { res = await fetch(url, init); } catch (e) { console.error(`[api] ${method} ${url.pathname}: game server unreachable`, e); throw new ApiError(502, 'unreachable', 'Could not reach the game server. Try again in a moment.', null); } const text = await res.text(); const json = parseJson(text) as Envelope | ErrorEnvelope | null; const err = json && 'error' in json ? json.error : undefined; if (res.ok && json && !err) return json as Envelope; const wait = !res.ok && attempt === 0 ? retryDelayMs(res.status, err?.code ?? '', res.headers.get('retry-after')) : null; if (wait !== null) { await sleep(wait); continue; } if (err) throw new ApiError(res.status, err.code, err.message, json as ErrorEnvelope); // Not the game API speaking (a proxy or firewall page, an empty body): log who did, // so the host's logs explain it. Never log the request headers: they carry the key. console.error( `[api] ${method} ${url.pathname} -> ${res.status} without an API envelope` + ` (server: ${res.headers.get('server') ?? '?'}, cf-ray: ${res.headers.get('cf-ray') ?? '-'},` + ` content-type: ${res.headers.get('content-type') ?? '?'}): ${text.slice(0, 200)}` ); throw new ApiError(res.ok ? 502 : res.status, 'unexplained', unexplainedMessage(res.status, res.statusText), null); } } function parseJson(text: string): unknown { try { return JSON.parse(text); } catch { return null; } } export const get = (token: string, path: string, query?: ApiOptions['query']) => api(token, 'GET', path, { query });