/** * How the UI reacts to Starfleet API errors. * * The API's own `message` is already player-readable ("The ship is docked: orbit first."), * so we show it as-is. This module only adds: * - a retry policy for the transient errors every endpoint may answer, and * - the action that usually fixes a refusal, so the UI can offer it. * Codes are from https://starfleet.glo.quebec/docs (API v1, the "captain" revision). */ /** Longest we are willing to wait before the single automatic retry. */ export const MAX_RETRY_WAIT_MS = 5_000; /** * Milliseconds to wait before retrying once, or null if the error is not worth retrying. * - `409 contended`: a concurrent change; the docs say to retry (we wait a beat). * - `429 rate_limited` / `503 busy`: wait `Retry-After` seconds, if that is short enough. */ export function retryDelayMs(status: number, code: string, retryAfter: string | null): number | null { if (status === 409 && code === 'contended') return 250; if (status !== 429 && status !== 503) return null; const seconds = retryAfter === null || retryAfter.trim() === '' ? NaN : Number(retryAfter); const ms = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : 1000; return ms <= MAX_RETRY_WAIT_MS ? ms : null; } /** Error code → name of the ship action that resolves it. */ const FIXES: Record = { ship_docked: 'orbit', ship_in_orbit: 'dock', no_market: 'dock', not_enough_fuel: 'refuel', tank_full: 'navigate', trade_unsettled: 'settle', ship_disabled: 'distress', hold_full: 'sell' }; export function fixFor(code: string): string | null { return FIXES[code] ?? null; } /** `$.waypoint` → `waypoint`; anything deeper or malformed → null. */ export function fieldFromPath(path: string | undefined): string | null { const m = path?.match(/^\$\.([A-Za-z_][A-Za-z0-9_]*)$/); return m ? m[1] : null; } /** * Actions the API refuses to rehearse with `?dry_run=1` (422 `no_dry_run`: * "Extractions, trades and purchases cannot be rehearsed"). Anything else that * answers `no_dry_run` at runtime is remembered by the caller. */ export const NO_DRY_RUN = new Set(['extract', 'buy', 'sell', 'buy_ship']); /** * Message for an error response that carries no API error envelope: a proxy, firewall or * CDN answered instead of the game server (an HTML 403 page, a bare 502…). */ export function unexplainedMessage(status: number, statusText: string): string { const what = statusText ? `${status} ${statusText}` : String(status); return `The game server answered ${what} without an explanation. Try again in a moment.`; } /** * HTTP status for a page whose load failed on an API error. The API's 4xx answers are * meaningful to the player (401 key refused, 404 not found…) and pass through; anything * else is the upstream failing, which is a 502 from our side, not a crash of ours. */ export function pageStatusFor(apiStatus: number): number { return apiStatus >= 400 && apiStatus < 500 ? apiStatus : 502; }