Stage 0-2 server spine: db, scheduler, REST, auth, economy, map

Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event
scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt
passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map +
spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused.
Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet.
NOT done: military, expansion, social, client, push, deploy docs, bots/admin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:07:42 +02:00
parent 9fa76d53a8
commit b56b13880e
39 changed files with 4450 additions and 0 deletions

80
tools/gen-openapi.js Normal file
View file

@ -0,0 +1,80 @@
'use strict';
/*
* Builds docs/openapi.json from the route table (server/routes/*) and the error table (server/errors.js).
* node tools/gen-openapi.js write docs/openapi.json
* node tools/gen-openapi.js --check exit 1 if the file on disk differs (test/openapi.test.js does the same)
*/
const fs = require('fs');
const path = require('path');
const { Router } = require('../server/http');
const routes = require('../server/routes');
const { schemas } = require('../server/routes/schemas');
const { CODES } = require('../server/errors');
const FILE = path.join(__dirname, '..', 'docs', 'openapi.json');
// $ref: 'Name' -> '#/components/schemas/Name'; type: ['x','null'] -> nullable
function conv(s) {
if (Array.isArray(s)) return s.map(conv);
if (!s || typeof s !== 'object') return s;
if (s.$ref) return { $ref: '#/components/schemas/' + s.$ref };
const out = {};
for (const k of Object.keys(s)) {
if (k === 'type' && Array.isArray(s.type)) { out.type = s.type.find((t) => t !== 'null'); out.nullable = true; }
else if (k === 'additionalProperties' && s[k] === true) out[k] = true;
else out[k] = conv(s[k]);
}
return out;
}
function build() {
const router = new Router();
routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) }));
const paths = {};
for (const r of router.routes) {
const p = r.path.replace(/:([A-Za-z]+)/g, '{$1}');
const m = r.meta;
const op = { summary: m.summary, tags: [m.tag || 'misc'], operationId: r.method.toLowerCase() + r.path.replace(/[/:]+([a-zA-Z])/g, (x, c) => c.toUpperCase()).replace(/[^a-zA-Z0-9]/g, '') };
op.parameters = r.names.map((n) => ({ name: n, in: 'path', required: true, schema: { type: /id$/i.test(n) ? 'integer' : 'string' } }));
if (m.query) for (const [k, sch] of Object.entries(m.query.properties || {})) op.parameters.push({ name: k, in: 'query', required: (m.query.required || []).includes(k), schema: conv(sch) });
if (m.body) op.requestBody = { required: true, content: { 'application/json': { schema: conv(m.body) } } };
op.security = m.auth === false ? [] : [{ bearer: [] }];
const okStatus = String(m.status || 200);
op.responses = { [okStatus]: { description: 'OK', content: { 'application/json': { schema: conv(m.response || { $ref: 'Ok' }) } } } };
const errs = new Set(['internal_error'].concat(m.errors || []));
if (m.auth !== false) errs.add('unauthorized');
if (r.method === 'POST') errs.add('idempotency_key_reuse');
const byStatus = {};
for (const code of errs) { const def = CODES[code]; if (!def) throw new Error('route ' + r.method + ' ' + r.path + ' lists unknown error code ' + code); (byStatus[def[0]] = byStatus[def[0]] || []).push(code); }
for (const st of Object.keys(byStatus).sort()) {
op.responses[st] = { description: 'Error codes: ' + byStatus[st].sort().join(', '), content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } } };
}
(paths[p] = paths[p] || {})[r.method.toLowerCase()] = op;
}
const components = { schemas: {}, securitySchemes: { bearer: { type: 'http', scheme: 'bearer', description: 'Opaque device token from /auth/login or /auth/signup' } } };
for (const k of Object.keys(schemas)) components.schemas[k] = conv(schemas[k]);
return {
openapi: '3.0.3',
info: { title: 'UPSTREAM API', version: '1.0.0', description: 'Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: ' + Object.keys(CODES).join(', ') },
servers: [{ url: '/api/v1' }],
paths: Object.fromEntries(Object.keys(paths).sort().map((k) => [k, paths[k]])),
components,
'x-error-codes': Object.fromEntries(Object.entries(CODES).map(([c, [status, msg]]) => [c, { status, description: msg }])),
};
}
function render() { return JSON.stringify(build(), null, 2) + '\n'; }
if (require.main === module) {
const text = render();
if (process.argv.includes('--check')) {
const cur = fs.existsSync(FILE) ? fs.readFileSync(FILE, 'utf8') : '';
if (cur !== text) { console.error('docs/openapi.json is out of date: run npm run openapi'); process.exit(1); }
console.log('openapi.json is up to date');
} else {
fs.writeFileSync(FILE, text);
console.log('wrote ' + FILE);
}
}
module.exports = { build, render, FILE };