// src/lib/server-registry.ts import { AuthStore } from './auth.js'; export interface ServerAddresses { lobbyUrl: string; gameServerUrl: string | null; wsUrl: string | null; } function normalizeGameServerUrl(url: string): string { return url .replace(/^wss:/, 'https:') .replace(/^ws:/, 'http:') .replace(/\/api\/v1\/game\/sync\/?(?:\?.*)?$/, '') .replace(/\/game\/sync\/?(?:\?.*)?$/, '') .replace(/\/$/, ''); } export class ServerRegistry { private lobbyUrl: string; private _gameServerUrl: string | null; private _gatewayWsUrl: string | null; private agentName: string | undefined; /** True when gameServerUrl was pre-configured (e.g. from auth) — prevents * discoverGameServer() from clearing it during queue status polling. */ private _urlPreconfigured: boolean; constructor(opts: { lobbyUrl: string; gameServerUrl?: string; agentName?: string }) { this.lobbyUrl = opts.lobbyUrl.replace(/\/$/, ''); this._gatewayWsUrl = null; if (opts.gameServerUrl) { const raw = opts.gameServerUrl.replace(/\/$/, ''); try { const u = new URL(raw); if (u.pathname && u.pathname !== '/') { // Gateway URL — restore _gatewayWsUrl so wsUrl path prefix is preserved this._gatewayWsUrl = raw; this._gameServerUrl = raw; } else { this._gameServerUrl = raw.replace(/^https:\/\//, 'http://'); } } catch { this._gameServerUrl = raw.replace(/^https:\/\//, 'http://'); } this._urlPreconfigured = true; } else { this._gameServerUrl = null; this._urlPreconfigured = false; } this.agentName = opts.agentName; } get addresses(): ServerAddresses { return { lobbyUrl: this.lobbyUrl, gameServerUrl: this._gameServerUrl, wsUrl: this.wsUrl, }; } get gameServerUrl(): string | null { return this._gameServerUrl; } get lobbyAgentWsUrl(): string { const u = new URL(this.lobbyUrl); const protocol = u.protocol === 'https:' || u.protocol === 'wss:' ? 'wss:' : 'ws:'; const basePath = u.pathname && u.pathname !== '/' ? u.pathname.replace(/\/$/, '') : ''; return `${protocol}//${u.host}${basePath}/api/v1/agent/ws`; } /** * Determine the correct base URL for a given API path. * * Game Server routes retained by the v2 client: acknowledged Action and leave. * Other dynamic observations use GameSync WebSocket; map geometry and paths * remain local CCL capabilities. * Lobby routes: everything else (/api/v1/agents/*, /api/v1/queue/*, etc.) */ baseUrlFor(path: string): string { if ( path.startsWith('/api/v1/game/action') || path.startsWith('/api/v1/game/leave') ) { const base = this._gatewayWsUrl ?? this._gameServerUrl; if (!base) throw new Error('No game server allocated'); return base; } return this.lobbyUrl; } /** * Extract game server address from a queue response and update gameServerUrl. * Prefers ws_url (Gateway route) over raw address:port. * Returns true if the address changed. */ updateFromQueueResponse(data: any): boolean { if (!data || typeof data !== 'object') return false; const qs = data.data ?? data; if (qs.status && qs.status !== 'allocated') { // Never clear a pre-configured URL just because queue status changed — // the game may already be in progress. Only clear if the URL was // originally discovered via queue (not pre-set from auth). if (this._urlPreconfigured) return false; if (this._gameServerUrl !== null || this._gatewayWsUrl !== null) { this._gameServerUrl = null; this._gatewayWsUrl = null; this.persistGameServerUrl(); return true; } return false; } const wsUrl = qs.ws_url; if (wsUrl && typeof wsUrl === 'string') { const httpUrl = normalizeGameServerUrl(wsUrl); if (this._gatewayWsUrl !== httpUrl) { this._gatewayWsUrl = httpUrl; this._gameServerUrl = httpUrl; this.persistGameServerUrl(); return true; } return false; } const addr = qs.address ?? qs.game_server?.address; const port = qs.port ?? qs.game_server?.port; if (addr && port) { const url = `http://${addr}:${port}`; if (this._gameServerUrl !== url) { this._gameServerUrl = url; this._gatewayWsUrl = null; this.persistGameServerUrl(); return true; } } return false; } /** Manually set the game server URL. */ setGameServerUrl(url: string): void { const normalized = normalizeGameServerUrl(url); this._gameServerUrl = normalized; try { const parsed = new URL(normalized); this._gatewayWsUrl = parsed.pathname && parsed.pathname !== '/' ? normalized : null; } catch { this._gatewayWsUrl = null; } this._urlPreconfigured = true; this.persistGameServerUrl(); } /** Set the game server URL via the public lobby gateway route. */ setGatewayGameServerName(gameServerName: string): void { const cleanName = gameServerName.replace(/^\/+|\/+$/g, ''); const route = `${this.lobbyUrl}/gs/${encodeURIComponent(cleanName)}`; this._gatewayWsUrl = route; this._gameServerUrl = route; this._urlPreconfigured = true; this.persistGameServerUrl(); } /** GameSync v2 WS URL derived from gameServerUrl (Gateway or direct). */ get wsUrl(): string | null { if (!this._gameServerUrl) return null; try { const u = new URL(this._gameServerUrl); const protocol = u.protocol === 'https:' || u.protocol === 'wss:' ? 'wss:' : 'ws:'; const basePath = this._gatewayWsUrl ? u.pathname.replace(/\/$/, '') : ''; return `${protocol}//${u.host}${basePath}/api/v1/game/sync`; } catch { return null; } } /** Persist gameServerUrl to runtime auth state (best-effort). */ private persistGameServerUrl(): void { if (!this.agentName) return; try { new AuthStore().updateGameServerUrl(this._gameServerUrl ?? undefined, this.agentName); } catch { /* non-critical */ } } }