// The browser's side of the game server: a few JSON calls, and the seats this // browser holds, remembered so a shared link never has to carry a token. import type { SeatId, TableOptions } from '$lib/game/spec'; import type { Report, RoomView, Tally } from './view'; export interface HeldSeat { seat: SeatId; token: string; } const SEATS_KEY = 'hnefatafl:seats'; function heldSeats(): Record { try { return JSON.parse(localStorage.getItem(SEATS_KEY) ?? '{}') as Record; } catch { return {}; } } /** A seat the keeper sent in a link, `#seat=.`: a fragment stays in the browser, out of every log. */ export function seatInLink(hash: string): HeldSeat | null { const m = /^#seat=([^.]+)\.([A-Za-z0-9_-]+)$/.exec(hash); return m ? { seat: m[1], token: m[2] } : null; } export function seatFor(roomId: string): HeldSeat | null { return heldSeats()[roomId] ?? null; } /** Every seat this browser holds, newest last. */ export function allSeats(): { roomId: string; seat: SeatId; token: string }[] { return Object.entries(heldSeats()).map(([roomId, h]) => ({ roomId, ...h })); } export function forgetSeat(roomId: string): void { try { const seats = heldSeats(); delete seats[roomId]; localStorage.setItem(SEATS_KEY, JSON.stringify(seats)); } catch { // Nothing to forget without storage. } void bankSeats([roomId]).catch(() => {}); } /** * The seats this browser holds are banked with the server as well, in a cookie it sets and the browser keeps for * it alone. A browser whose storage is cleared, or that Safari clears for it after a week away, still has the * cookie, and gets its seats back from it. The answer is every seat the bank holds that still opens. */ export async function bankSeats(forget: string[] = []): Promise<{ roomId: string; seat: SeatId; token: string }[]> { const seats = allSeats().map(({ roomId, token }) => ({ roomId, token })); const { seats: banked } = await call<{ seats: { roomId: string; seat: SeatId; token: string }[] }>('POST', '/api/seats', { seats, forget }); return banked; } /** The seats the bank holds that this browser does not, taken into storage; true when there were any. */ export async function restoreSeats(): Promise { let found = false; for (const s of await bankSeats()) { if (seatFor(s.roomId)) continue; store(s.roomId, { seat: s.seat, token: s.token }); found = true; } return found; } /** * A seat the server refused is doubted, not dropped: a restarting server, a * stale answer or the wrong backend all answer with ignorance, and ignorance * is not deletion. Only the second refusal in a row costs the seat. */ const DOUBT_KEY = 'hnefatafl:doubted'; function doubted(): Record { try { return JSON.parse(localStorage.getItem(DOUBT_KEY) ?? '{}') as Record; } catch { return {}; } } /** Note a refusal; true when it is the second in a row and the seat is forgotten. */ export function doubtSeat(roomId: string): boolean { const all = doubted(); if (all[roomId]) { forgetSeat(roomId); delete all[roomId]; try { localStorage.setItem(DOUBT_KEY, JSON.stringify(all)); } catch { // Nothing to note without storage. } return true; } try { localStorage.setItem(DOUBT_KEY, JSON.stringify({ ...all, [roomId]: true })); } catch { // Nothing to note without storage. } return false; } /** The server answered for this seat: any doubt is cleared. */ export function trustSeat(roomId: string): void { const all = doubted(); if (!all[roomId]) return; delete all[roomId]; try { localStorage.setItem(DOUBT_KEY, JSON.stringify(all)); } catch { // Nothing to clear without storage. } } function store(roomId: string, held: HeldSeat): void { try { localStorage.setItem(SEATS_KEY, JSON.stringify({ ...heldSeats(), [roomId]: held })); } catch { // Without storage the seat lasts for this page only. } } /** A seat taken is kept here and banked with the server, each time, so the two agree. */ export function rememberSeat(roomId: string, held: HeldSeat): void { store(roomId, held); void bankSeats().catch(() => {}); } export class ServerError extends Error { constructor( message: string, public status: number ) { super(message); } } /** The server's answer as JSON, or its refusal as a ServerError with the reason it gave. */ async function fetchJson(path: string, init: RequestInit): Promise { const res = await fetch(path, init); const data = (await res.json().catch(() => ({}))) as { error?: string }; if (!res.ok) throw new ServerError(data.error ?? `The server answered ${res.status}.`, res.status); return data as T; } function call(method: string, path: string, body?: unknown): Promise { return fetchJson(path, { method, headers: body ? { 'content-type': 'application/json' } : undefined, body: body ? JSON.stringify(body) : undefined }); } export function makeApi() { type Seated = { seat: SeatId; token: string; view: RoomView }; type View = RoomView; return { create: (name: string, size: number, options?: TableOptions) => call('POST', '/api/rooms', { name, size, options }), join: (roomId: string, name: string) => call('POST', `/api/rooms/${roomId}/join`, { name }), addBot: (roomId: string, token: string) => call('POST', `/api/rooms/${roomId}/bot`, { token }), begin: (roomId: string, token: string) => call('POST', `/api/rooms/${roomId}/begin`, { token }), unseat: (roomId: string, token: string, seat: SeatId) => call('POST', `/api/rooms/${roomId}/unseat`, { token, seat }), view: (roomId: string, token: string) => call('GET', `/api/rooms/${roomId}?token=${encodeURIComponent(token)}`), /** The gallery's view: no token, no seat, nothing any player could not see. */ watch: (roomId: string) => call('GET', `/api/rooms/${roomId}`), turn: (roomId: string, token: string, input: Input, resolved: number) => call('POST', `/api/rooms/${roomId}/turn`, { token, input, resolved }), say: (roomId: string, token: string, text: string) => call('POST', `/api/rooms/${roomId}/say`, { token, text }), /** A word from the gallery, signed with a name, when the host allows it. */ sayFromGallery: (roomId: string, name: string, text: string) => call('POST', `/api/rooms/${roomId}/say`, { name, text }), setGalleryTalk: (roomId: string, token: string, on: boolean) => call('POST', `/api/rooms/${roomId}/gallery`, { token, on }), challenge: (roomId: string, token: string) => call('POST', `/api/rooms/${roomId}/challenge`, { token }), rematch: (roomId: string, token: string) => call<{ roomId: string; seat: SeatId | null; token: string | null; created: boolean }>('POST', `/api/rooms/${roomId}/rematch`, { token }), transfer: (roomId: string, token: string) => call<{ phrase: string; expiresAt: number }>('POST', `/api/rooms/${roomId}/transfer`, { token }), /** The host's phrase for another person's seat; claimed, it re-seats them. */ hostPhrase: (roomId: string, token: string, seat: SeatId) => call<{ phrase: string; expiresAt: number }>('POST', `/api/rooms/${roomId}/phrase`, { token, seat }), standIn: (roomId: string, token: string, seat: SeatId) => call('POST', `/api/rooms/${roomId}/standin`, { token, seat }), claim: (phrase: string) => call<{ roomId: string; seat: SeatId; token: string }>('POST', '/api/transfer', { phrase }), /** The seats a name holds at tables not over: those last used from this address come back seated; the rest are only counted. */ findSeats: (name: string, roomId?: string) => call<{ seated: { roomId: string; seat: SeatId; token: string }[]; elsewhere: number }>('POST', '/api/seats/find', { name, ...(roomId ? { roomId } : {}) }), report: (roomId: string, token: string, happened: string, expected: string) => call<{ id: string }>('POST', `/api/rooms/${roomId}/report`, { token, happened, expected }), reportImage: (id: string, file: File) => fetchJson(`/api/reports/${id}/image`, { method: 'POST', headers: { 'content-type': file.type || 'application/octet-stream' }, body: file }), tally: () => call('GET', '/api/tally'), myReports: (seats: { roomId: string; token: string }[]) => call<{ reports: Report[] }>('POST', '/api/reports/mine', { seats }), answerReport: (id: string, roomId: string, token: string, text: string) => call<{ ok: true }>('POST', `/api/reports/${id}/answer`, { roomId, token, text }) }; } /** A socket that only ever says "fetch the view again"; reconnects on its own. An empty token sits in the gallery. */ export function watchRoom(roomId: string, token: string, onUpdate: () => void, onStatus: (open: boolean) => void): () => void { let socket: WebSocket | null = null; let closed = false; let delay = 1000; const open = () => { if (closed) return; const protocol = location.protocol === 'https:' ? 'wss' : 'ws'; const seat = token ? `&token=${encodeURIComponent(token)}` : ''; socket = new WebSocket(`${protocol}://${location.host}/ws?room=${encodeURIComponent(roomId)}${seat}`); socket.onopen = () => { delay = 1000; onStatus(true); onUpdate(); }; socket.onmessage = (e) => { try { if (JSON.parse(String(e.data)).type === 'update') onUpdate(); } catch { // Not a message this client understands. } }; socket.onclose = () => { onStatus(false); if (!closed) setTimeout(open, delay); delay = Math.min(delay * 2, 30000); }; }; open(); return () => { closed = true; socket?.close(); }; }