'use strict'; /* * REST client for /api/v1. No DOM; fetch, storage, clock and sleep are injected so Node tests can drive it * (test/client-api.test.js). Loads as a browser script (window.UpstreamApi) and as a Node module. * * const api = UpstreamApi.createApi({ fetch, storage: localStorage }); * const me = await api.get('/me'); * await api.post('/towns/3/build', { key: 'f1' }, { intent: 'build:3:f1' }); * api.serverNow(); // server clock estimate in ms: use this for every countdown * api.on('unauthorized', fn); // token rejected: the shell drops to the login screen * api.on('push', fn); // reserved: the WebSocket client (stage 6) calls api.emit('push', msg) * * Rules it follows (docs/API.md): * - every response carries serverTime; the offset is kept from the lowest-latency sample (replayed idempotent * responses carry the ORIGINAL serverTime and are ignored for this) * - errors are { error: { code, message, details } } and become ApiError with .code; callers switch on code * - mutating POSTs of a logged-in user carry an Idempotency-Key. An "intent" (a stable string like * 'build:3:f1') keeps the same key across calls until the server has given a definite answer, so a tap that * died on a flaky network and is tapped again cannot build twice. Without an intent, one key per call, reused * by that call's retries. * - retries with backoff: network errors, 429 (Retry-After honoured, seconds), 502/503/504 and request_in_progress. * Network errors and 5xx are only retried when repeating is safe (GET, a keyed POST). 429 is always safe. */ (function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(); else root.UpstreamApi = factory(); }(typeof self !== 'undefined' ? self : this, function () { class ApiError extends Error { constructor(code, message, status, details, retryAfter) { super(message || code); this.name = 'ApiError'; this.code = code; this.status = status || 0; this.details = details || {}; this.retryAfter = retryAfter || 0; } } const KEY_RE = /^[A-Za-z0-9_.:-]{8,64}$/; function defaultHex() { const c = typeof globalThis !== 'undefined' && globalThis.crypto; if (c && c.getRandomValues) { const a = new Uint8Array(12); c.getRandomValues(a); return Array.prototype.map.call(a, (b) => (b < 16 ? '0' : '') + b.toString(16)).join(''); } let s = ''; for (let i = 0; i < 24; i++) s += Math.floor(Math.random() * 16).toString(16); return s; } function createApi(opts) { opts = opts || {}; const doFetch = opts.fetch; const now = opts.now || Date.now; const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))); const base = (opts.base || 'api/v1').replace(/\/$/, ''); const tokenKey = opts.tokenKey || 'upstream.token'; const maxRetries = opts.maxRetries === undefined ? 4 : opts.maxRetries; const maxWaitMs = opts.maxWaitMs || 15000; // a Retry-After longer than this is given to the caller instead const hex = opts.randomHex || defaultHex; const jitter = opts.jitter || (() => Math.random()); // ---- token (storage can throw or be empty in private windows: stay usable from memory) let memToken = null; const store = opts.storage; function getToken() { if (memToken) return memToken; try { return (store && store.getItem(tokenKey)) || null; } catch (e) { return null; } } function setToken(t) { memToken = t || null; try { if (store) { if (t) store.setItem(tokenKey, t); else store.removeItem(tokenKey); } } catch (e) { /* memory only */ } } const clearToken = () => setToken(null); // ---- events const handlers = {}; function on(evt, fn) { (handlers[evt] = handlers[evt] || new Set()).add(fn); return () => off(evt, fn); } function off(evt, fn) { if (handlers[evt]) handlers[evt].delete(fn); } function emit(evt, data) { if (!handlers[evt]) return; for (const fn of Array.from(handlers[evt])) { try { fn(data); } catch (e) { /* a listener must not break the client */ } } } // ---- server clock let offset = 0, bestRtt = null, bestAt = 0, haveOffset = false; function observeServerTime(serverTime, t0, t1) { if (!Number.isFinite(serverTime)) return; const rtt = Math.max(0, t1 - t0); if (bestRtt === null || rtt <= bestRtt || t1 - bestAt > 5 * 60 * 1000) { offset = serverTime - (t0 + t1) / 2; bestRtt = rtt; bestAt = t1; haveOffset = true; emit('offset', offset); } } const serverNow = () => now() + offset; // ---- idempotency keys const intents = new Map(); const newKey = () => 'u' + hex(); function keyFor(intent) { if (!intent) return newKey(); let k = intents.get(intent); if (!k) { k = newKey(); intents.set(intent, k); } return k; } function backoff(attempt) { return Math.round(400 * Math.pow(2, attempt) * (0.75 + jitter() * 0.5)); } let offline = false; function setOffline(v) { if (v !== offline) { offline = v; emit(v ? 'offline' : 'online'); } } function buildUrl(path, query) { let u = base + (path[0] === '/' ? path : '/' + path); if (query) { const p = []; for (const k of Object.keys(query)) if (query[k] !== undefined && query[k] !== null) p.push(encodeURIComponent(k) + '=' + encodeURIComponent(query[k])); if (p.length) u += '?' + p.join('&'); } return u; } async function request(method, path, o) { o = o || {}; const authed = o.auth !== false; const token = authed ? getToken() : null; const hasBody = o.body !== undefined && method !== 'GET'; const keyed = method === 'POST' && !!token; const key = keyed ? keyFor(o.intent) : null; const safeToRepeat = method === 'GET' || keyed; const headers = { Accept: 'application/json' }; if (token) headers.Authorization = 'Bearer ' + token; if (hasBody) headers['Content-Type'] = 'application/json'; if (key) headers['Idempotency-Key'] = key; const init = { method, headers, cache: 'no-store' }; if (hasBody) init.body = JSON.stringify(o.body); const url = buildUrl(path, o.query); const retries = o.retries === undefined ? maxRetries : o.retries; for (let attempt = 0; ; attempt++) { const t0 = now(); let res; try { res = await doFetch(url, init); } catch (e) { setOffline(true); if (attempt < retries && (safeToRepeat || method === 'DELETE')) { await sleep(backoff(attempt)); continue; } throw new ApiError('network_error', String(e && e.message || e), 0); // intent key is kept: same tap, same key } const t1 = now(); let body = null; try { body = await res.json(); } catch (e) { body = null; } const replay = res.headers && res.headers.get && res.headers.get('Idempotent-Replay'); if (body && !replay) observeServerTime(body.serverTime, t0, t1); if (res.ok) { setOffline(false); if (o.intent) intents.delete(o.intent); return body || {}; } const err = body && body.error ? body.error : {}; const code = err.code || (res.status === 429 ? 'rate_limited' : 'http_' + res.status); let retryAfter = 0; const ra = res.headers && res.headers.get ? Number(res.headers.get('Retry-After')) : NaN; if (Number.isFinite(ra) && ra > 0) retryAfter = ra; else if (err.details && Number(err.details.retryAfter) > 0) retryAfter = Number(err.details.retryAfter); // 429 was refused before doing anything, so it is always safe to repeat. if (res.status === 429 && attempt < retries) { const wait = retryAfter ? retryAfter * 1000 : backoff(attempt); if (wait <= maxWaitMs) { await sleep(wait); continue; } } if ([502, 503, 504].includes(res.status) && attempt < retries && safeToRepeat) { await sleep(backoff(attempt)); continue; } if (code === 'request_in_progress' && attempt < retries) { await sleep(500 + backoff(attempt)); continue; } setOffline(false); // the server answered: the network is fine if (o.intent && res.status !== 429 && res.status < 500) intents.delete(o.intent); // a definite answer ends the intent if (res.status === 401 && token && code === 'unauthorized') { clearToken(); emit('unauthorized', {}); } throw new ApiError(code, err.message, res.status, err.details, retryAfter); } } return { request, get: (path, query, o) => request('GET', path, Object.assign({ query }, o)), post: (path, body, o) => request('POST', path, Object.assign({ body: body === undefined ? {} : body }, o)), del: (path, o) => request('DELETE', path, o), getToken, setToken, clearToken, hasToken: () => !!getToken(), on, off, emit, serverNow, hasServerTime: () => haveOffset, serverOffset: () => offset, pendingIntents: () => Array.from(intents.keys()), isValidKey: (k) => KEY_RE.test(k), }; } return { createApi, ApiError }; }));