'use strict'; const test = require('node:test'); const assert = require('node:assert'); const { createApi, ApiError } = require('../public/js/api.js'); // A scripted fetch: each call takes the next response (or throws when given an Error). function harness(script, extra) { const calls = []; const sleeps = []; let t = 1000; const store = new Map(); const api = createApi(Object.assign({ fetch: async (url, init) => { calls.push({ url, init }); const step = script.shift(); if (step instanceof Error) throw step; t += step.rtt || 0; return { ok: step.status >= 200 && step.status < 300, status: step.status, headers: { get: (k) => (step.headers || {})[k] || null }, json: async () => step.body, }; }, now: () => t, sleep: async (ms) => { sleeps.push(ms); t += ms; }, jitter: () => 0.5, storage: { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => store.set(k, v), removeItem: (k) => store.delete(k) }, randomHex: (() => { let n = 0; return () => 'abcdef' + String(++n).padStart(6, '0'); })(), }, extra)); return { api, calls, sleeps, store, tick: (ms) => { t += ms; } }; } const ok = (body, more) => Object.assign({ status: 200, body: Object.assign({ serverTime: 5000 }, body) }, more); const err = (status, code, more) => Object.assign({ status, body: { serverTime: 5000, error: { code, message: code, details: {} } } }, more); test('bearer token, JSON body and Idempotency-Key on authenticated POST', async () => { const h = harness([ok({ a: 1 })]); h.api.setToken('tok'); assert.strictEqual(h.store.get('upstream.token'), 'tok'); await h.api.post('/towns/1/build', { key: 'f1' }); const { url, init } = h.calls[0]; assert.strictEqual(url, 'api/v1/towns/1/build'); assert.strictEqual(init.headers.Authorization, 'Bearer tok'); assert.strictEqual(init.headers['Content-Type'], 'application/json'); assert.ok(h.api.isValidKey(init.headers['Idempotency-Key'])); assert.strictEqual(init.body, '{"key":"f1"}'); }); test('login POST carries no token and no idempotency key; GET carries no key', async () => { const h = harness([ok({}), ok({})]); await h.api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false }); assert.strictEqual(h.calls[0].init.headers['Idempotency-Key'], undefined); assert.strictEqual(h.calls[0].init.headers.Authorization, undefined); h.api.setToken('t'); await h.api.get('/me'); assert.strictEqual(h.calls[1].init.headers['Idempotency-Key'], undefined); }); test('query string is encoded and skips undefined values', async () => { const h = harness([ok({})]); await h.api.get('/map', { x: -3, y: 4, r: 20, worldId: undefined }); assert.strictEqual(h.calls[0].url, 'api/v1/map?x=-3&y=4&r=20'); }); test('error envelope becomes ApiError with code, status and details', async () => { const h = harness([{ status: 409, body: { serverTime: 1, error: { code: 'not_enough_resources', message: 'no', details: { key: 'f1' } } } }]); h.api.setToken('t'); await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }), (e) => e instanceof ApiError && e.code === 'not_enough_resources' && e.status === 409 && e.details.key === 'f1'); }); test('401 clears the token and emits unauthorized', async () => { const h = harness([err(401, 'unauthorized')]); h.api.setToken('t'); let fired = 0; h.api.on('unauthorized', () => fired++); await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'unauthorized'); assert.strictEqual(fired, 1); assert.strictEqual(h.api.hasToken(), false); assert.strictEqual(h.store.has('upstream.token'), false); }); test('network errors on GET retry with growing backoff, then succeed', async () => { const h = harness([new TypeError('fail'), new TypeError('fail'), ok({ fine: true })]); const events = []; h.api.on('offline', () => events.push('offline')); h.api.on('online', () => events.push('online')); const r = await h.api.get('/me'); assert.strictEqual(r.fine, true); assert.deepStrictEqual(h.sleeps, [400, 800]); assert.deepStrictEqual(events, ['offline', 'online']); }); test('network errors give up as network_error after the retry budget', async () => { const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x')], { maxRetries: 2 }); await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'network_error' && e.status === 0); assert.strictEqual(h.calls.length, 3); }); test('unkeyed POST (login) is NOT retried on a network error', async () => { const h = harness([new TypeError('x'), ok({})]); await assert.rejects(() => h.api.post('/auth/signup', { username: 'a' }, { auth: false }), (e) => e.code === 'network_error'); assert.strictEqual(h.calls.length, 1); }); test('429 honours Retry-After (seconds) and is retried even for unkeyed POSTs', async () => { const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '3' } }), ok({ done: 1 })]); const r = await h.api.post('/auth/login', {}, { auth: false }); assert.strictEqual(r.done, 1); assert.deepStrictEqual(h.sleeps, [3000]); }); test('a Retry-After beyond the cap is handed to the caller instead of blocking', async () => { const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '120' } })]); await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'rate_limited' && e.retryAfter === 120); assert.deepStrictEqual(h.sleeps, []); }); test('retries of one call reuse its Idempotency-Key; the next call gets a new one', async () => { const h = harness([new TypeError('x'), ok({}), ok({})]); h.api.setToken('t'); await h.api.post('/towns/1/build', { key: 'f1' }); await h.api.post('/towns/1/build', { key: 'f1' }); const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']); assert.strictEqual(keys[0], keys[1]); assert.notStrictEqual(keys[1], keys[2]); }); test('an intent keeps its key across failed attempts until the server answers', async () => { const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x'), err(409, 'not_enough_resources'), ok({})], { maxRetries: 0 }); h.api.setToken('t'); for (let i = 0; i < 3; i++) await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'network_error'); assert.deepStrictEqual(h.api.pendingIntents(), ['build:1:f1']); await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'not_enough_resources'); assert.deepStrictEqual(h.api.pendingIntents(), []); // definite answer: the intent is over await h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }); const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']); assert.strictEqual(new Set(keys.slice(0, 4)).size, 1); assert.notStrictEqual(keys[4], keys[3]); }); test('request_in_progress is retried after a short delay', async () => { const h = harness([err(409, 'request_in_progress'), ok({ x: 1 })]); h.api.setToken('t'); const r = await h.api.post('/towns/1/build', { key: 'f1' }); assert.strictEqual(r.x, 1); assert.strictEqual(h.sleeps.length, 1); }); test('503 on GET is retried, on unkeyed POST is not', async () => { const a = harness([err(503, 'internal_error'), ok({ y: 1 })]); assert.strictEqual((await a.api.get('/me')).y, 1); const b = harness([err(503, 'internal_error'), ok({})]); await assert.rejects(() => b.api.post('/auth/login', {}, { auth: false }), (e) => e.status === 503); assert.strictEqual(b.calls.length, 1); }); test('server clock offset comes from the lowest-latency sample; replayed responses are ignored', async () => { // t0=1000, rtt 400, serverTime 5000 -> offset 5000 - 1200 = 3800 const h = harness([ok({}, { rtt: 400 }), ok({ serverTime: 99999 }, { rtt: 100 }), ok({ serverTime: 1 }, { rtt: 900 }), ok({ serverTime: 99999 }, { rtt: 1, headers: { 'Idempotent-Replay': 'true' } })]); await h.api.get('/me'); assert.strictEqual(h.api.serverOffset(), 3800); await h.api.get('/me'); // better rtt (100): adopted. t0 was 1400 -> mid 1450 -> offset 99999-1450 assert.strictEqual(h.api.serverOffset(), 99999 - 1450); const before = h.api.serverOffset(); await h.api.get('/me'); // worse rtt: kept assert.strictEqual(h.api.serverOffset(), before); await h.api.get('/me'); // replay: ignored assert.strictEqual(h.api.serverOffset(), before); }); test('push events can be emitted and unsubscribed; a throwing listener does not break others', () => { const h = harness([]); const got = []; const off = h.api.on('push', (m) => got.push(m)); h.api.on('push', () => { throw new Error('boom'); }); h.api.on('push', (m) => got.push('2:' + m.type)); h.api.emit('push', { type: 'town', id: 1 }); off(); h.api.emit('push', { type: 'x' }); assert.deepStrictEqual(got, [{ type: 'town', id: 1 }, '2:town', '2:x']); }); test('storage failures fall back to memory', () => { const api = createApi({ fetch: async () => { throw new Error('unused'); }, storage: { getItem() { throw new Error('denied'); }, setItem() { throw new Error('denied'); }, removeItem() { throw new Error('denied'); } } }); api.setToken('abc'); assert.strictEqual(api.getToken(), 'abc'); api.clearToken(); assert.strictEqual(api.getToken(), null); });