feat(combat): add first-class undo and redo controls Add undo and redo controls to the combat UI so the DM can recover from recent actions without leaving the encounter view. Undo and redo operate on the current encounter's combat history. Empty stacks produce clear feedback instead of failing silently. Redo order follows normal stack behavior after multiple undos. This makes combat history actionable during play, not just visible in the log. feat(logs): make combat logs replayable Replace plain combat log messages with structured combat events that can be used by the UI, exported as JSON, replayed, and verified. Each new log entry records the action type, encounter identity, participant identity, a small action delta, undo intent, and a turn snapshot. Download and copy now export the event stream as JSON so a saved combat log is useful for offline analysis and debugging. Legacy logs remain viewable, but new logs use the structured event format. feat(logs): make undo and redo transactional Apply undo and redo as single storage operations so the encounter state and log state cannot drift apart. Server storage applies the encounter update and the log undone flag inside one SQLite transaction. Firebase storage uses a batch write for the same behavior. The storage contract now includes undo/redo semantics. This replaces fragile multi-write undo behavior where a failure could update the encounter without marking the log, or mark the log without updating the encounter. feat(combat): add unified replay and verification tool Add one combat CLI for replaying live combat and verifying combat logs. Replay drives the live backend through the same shared combat logic used by the app, writes a JSON event log to an explicit output path, and automatically verifies the result. Verification checks for DM-visible combat problems such as skipped turns, double actions, bad round changes, and unexpected turn order changes. The tool uses the same JSON event stream produced by log downloads, supports verbose turn output, and handles Ctrl-C by ending the encounter, writing the partial log, and verifying what was captured. fix(perf): keep long combat logging fast Remove the combat-time log query bottleneck that made long replays slow as log volume grew. Combat controls no longer subscribe to the log collection just to keep undo and redo state warm. Undo and redo now query the latest matching encounter log only when clicked. Server collection queries support exact filters, ordering, limits, and offsets, and SQLite indexes keep latest-log and per-encounter log lookups fast. Also fix duplicate WebSocket handler registration so realtime updates do not double-fire under write load. fix(turns): make toggle active a status change Make toggle active a roster/status edit instead of a turn advance. Deactivating the current participant no longer passes the turn or increments the round. The current turn stays where it is until the DM explicitly clicks Next Turn, and Next Turn skips inactive participants during normal rotation. This matches the initiative design: slot order is stable, toggle active does not move participants, and round changes only come from explicit turn advance. chore(ci): make warnings and hangs fail fast Tighten test and build checks so failures are visible instead of noisy or silent. Builds run with CI enabled so warnings fail production builds. The full test command runs app, shared, and server suites with hard timeouts so hangs fail quickly. Static eslint coverage fails on warnings as well as errors. Tests were updated around the new async combat logging flow, structured log events, transactional undo, replay verification, and toggle-active semantics.
191 lines
7.1 KiB
JavaScript
191 lines
7.1 KiB
JavaScript
// server/index.js — generic KV document store over HTTP + WebSocket.
|
|
// firebase mirror: doc-tree model. Thin REST, path-based WS push.
|
|
// Adapter (src/storage/server.js) = passthrough, no shape translation.
|
|
|
|
'use strict';
|
|
|
|
const express = require('express');
|
|
const cors = require('cors');
|
|
const http = require('http');
|
|
const crypto = require('crypto');
|
|
const { WebSocketServer } = require('ws');
|
|
const { openDb, makeStore } = require('./db');
|
|
|
|
function createServer({ dbPath, port, corsOrigin } = {}) {
|
|
const db = openDb(dbPath || './data/tracker.sqlite');
|
|
const app = express();
|
|
app.use(cors({ origin: corsOrigin || '*' }));
|
|
app.use(express.json({ limit: '1mb' }));
|
|
|
|
// WS subscribers: path -> Set<ws>.
|
|
// Subscribers register a path (doc or collection). On change, notify:
|
|
// - doc subscribers at the changed path
|
|
// - collection subscribers at the changed doc's parent path
|
|
const docSubscribers = new Map(); // path -> Set<ws>
|
|
const collSubscribers = new Map(); // collPath -> Set<ws>
|
|
|
|
function addSub(map, key, ws) {
|
|
if (!map.has(key)) map.set(key, new Set());
|
|
map.get(key).add(ws);
|
|
}
|
|
function removeSub(map, key, ws) {
|
|
const set = map.get(key);
|
|
if (set) { set.delete(ws); if (set.size === 0) map.delete(key); }
|
|
}
|
|
function dropWs(ws) {
|
|
for (const [key, set] of docSubscribers) { set.delete(ws); if (set.size === 0) docSubscribers.delete(key); }
|
|
for (const [key, set] of collSubscribers) { set.delete(ws); if (set.size === 0) collSubscribers.delete(key); }
|
|
}
|
|
|
|
function broadcast(change) {
|
|
const payload = JSON.stringify({ type: 'change', change });
|
|
// doc subscriber at exact path
|
|
const docSet = docSubscribers.get(change.path);
|
|
if (docSet) [...docSet].forEach(ws => ws.readyState === ws.OPEN && ws.send(payload));
|
|
// collection subscribers at parent path (collection contains this doc)
|
|
if (change.parent) {
|
|
const collSet = collSubscribers.get(change.parent);
|
|
if (collSet) [...collSet].forEach(ws => ws.readyState === ws.OPEN && ws.send(payload));
|
|
}
|
|
}
|
|
|
|
const store = makeStore(db, broadcast);
|
|
|
|
// --- generic REST ---
|
|
|
|
app.get('/health', (req, res) => res.json({ ok: true }));
|
|
|
|
// GET /api/doc?path=campaigns/abc/encounters/xyz
|
|
app.get('/api/doc', (req, res) => {
|
|
const { path: p } = req.query;
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
res.json({ path: p, data: store.getDoc(p) });
|
|
});
|
|
|
|
// GET /api/collection?path=campaigns/abc/encounters
|
|
app.get('/api/collection', (req, res) => {
|
|
const { path: p, whereField, whereOp, whereValue, orderBy, dir, limit, offset } = req.query;
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
const opts = {};
|
|
if (whereField) opts.where = { field: whereField, op: whereOp || '==', value: whereValue };
|
|
if (orderBy) opts.orderBy = orderBy;
|
|
if (dir) opts.dir = dir;
|
|
if (limit) opts.limit = limit;
|
|
if (offset) opts.offset = offset;
|
|
res.json(store.getCollection(p, opts));
|
|
});
|
|
|
|
app.get('/api/collection/count', (req, res) => {
|
|
const { path: p } = req.query;
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
res.json({ count: store.countCollection(p) });
|
|
});
|
|
|
|
// PUT /api/doc body: { path, data } (replace)
|
|
app.put('/api/doc', (req, res) => {
|
|
const { path: p, data } = req.body || {};
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
res.json({ path: p, data: store.setDoc(p, data) });
|
|
});
|
|
|
|
// PATCH /api/doc body: { path, patch } (shallow merge, create-on-miss)
|
|
app.patch('/api/doc', (req, res) => {
|
|
const { path: p, patch } = req.body || {};
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
res.json({ path: p, data: store.updateDoc(p, patch) });
|
|
});
|
|
|
|
// DELETE /api/doc?path=...
|
|
app.delete('/api/doc', (req, res) => {
|
|
const { path: p } = req.query;
|
|
if (!p) return res.status(400).json({ error: 'path required' });
|
|
store.deleteDoc(p);
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
// POST /api/collection body: { path, data } (addDoc: auto-id under collection)
|
|
app.post('/api/collection', (req, res) => {
|
|
const { path: collPath, data } = req.body || {};
|
|
if (!collPath) return res.status(400).json({ error: 'path required' });
|
|
const id = crypto.randomUUID();
|
|
const docPath = `${collPath}/${id}`;
|
|
res.json({ id, path: docPath, data: store.setDoc(docPath, data) });
|
|
});
|
|
|
|
// POST /api/batch body: { ops: [{type:'set'|'update'|'delete', path, data?}] }
|
|
app.post('/api/batch', (req, res) => {
|
|
const { ops } = req.body || {};
|
|
if (!Array.isArray(ops)) return res.status(400).json({ error: 'ops array required' });
|
|
store.batchWrite(ops);
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
// POST /api/undo body: { logPath, undo } where undo={encounterPath, updates, redo}
|
|
// Transactional: apply updates + flip undone in one SQLite tx.
|
|
// If `redo` true, applies redo patch instead + flips undone:false.
|
|
app.post('/api/undo', (req, res) => {
|
|
const { logPath, undo } = req.body || {};
|
|
if (!logPath || !undo || !undo.encounterPath) {
|
|
return res.status(400).json({ error: 'logPath + undo.encounterPath required' });
|
|
}
|
|
if (!store.transactionalUndo) {
|
|
return res.status(501).json({ error: 'transactionalUndo not supported by store' });
|
|
}
|
|
try {
|
|
const isRedo = !!req.body.redo;
|
|
const updates = isRedo ? (undo.redo || undo.updates) : undo.updates;
|
|
const result = store.transactionalUndo({
|
|
logPath,
|
|
encounterPath: undo.encounterPath,
|
|
updates,
|
|
undoneFlag: !isRedo,
|
|
});
|
|
res.json({ ok: true, ...result });
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
// --- WebSocket: subscribe by path ---
|
|
const server = http.createServer(app);
|
|
const wss = new WebSocketServer({ server, path: '/ws' });
|
|
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (raw) => {
|
|
let msg;
|
|
try { msg = JSON.parse(raw.toString()); } catch { ws.send(JSON.stringify({ type: 'error', error: 'bad json' })); return; }
|
|
if (msg.type === 'subscribe' && msg.path) {
|
|
if (msg.kind === 'collection') addSub(collSubscribers, msg.path, ws);
|
|
else addSub(docSubscribers, msg.path, ws);
|
|
ws.send(JSON.stringify({ type: 'subscribed', path: msg.path, kind: msg.kind || 'doc' }));
|
|
} else if (msg.type === 'unsubscribe' && msg.path) {
|
|
if (msg.kind === 'collection') removeSub(collSubscribers, msg.path, ws);
|
|
else removeSub(docSubscribers, msg.path, ws);
|
|
}
|
|
});
|
|
ws.on('close', () => dropWs(ws));
|
|
ws.on('error', () => {});
|
|
});
|
|
|
|
return {
|
|
app, server, wss, store, db,
|
|
close(done) {
|
|
wss.clients.forEach(c => { try { c.terminate(); } catch {} });
|
|
wss.close();
|
|
server.close(() => { db.close(); if (done) done(); });
|
|
},
|
|
};
|
|
}
|
|
|
|
// Boot standalone if run directly.
|
|
if (require.main === module) {
|
|
const port = parseInt(process.env.PORT, 10) || 4001;
|
|
const dbPath = process.env.DB_PATH || './data/tracker.sqlite';
|
|
const { server } = createServer({ dbPath, port });
|
|
server.listen(port, () => {
|
|
console.log(`ttrpg backend listening on :${port} (db: ${dbPath})`);
|
|
});
|
|
}
|
|
|
|
module.exports = { createServer };
|