12 Companion server.js (4/13)
function readJson(file, fallback) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; }
}
function writeJson(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(value));
fs.renameSync(tmp, file);
}
function activeGame(sid, requested) {
const all = games();
const file = path.join(sessionDir(sid), 'active.json');
if (requested && all.has(requested)) {
writeJson(file, { game: requested });
return requested;
}
const saved = readJson(file, {}).game;
if (saved && all.has(saved)) return saved;
return all.keys().next().value || null;
}
// One request per session at a time: a turn is load -> run -> save.
const locks = new Map();
function withLock(key, fn) {
const prev = locks.get(key) || Promise.resolve();
const next = prev.then(fn, fn);
locks.set(key, next.catch(() => {}));
return next;
}
function machineFor(game, state) {
const m = ZMachine.restore(game.story, state.snap);
m.undoState = state.undo || null;
m.saveSlot = state.slot || null;
return m;
}
function cleanOutput(text) {
return text.replace(/\r/g, '').replace(/\n?>\s*$/, '').replace(/^\n+/, '').replace(/\s+$/, '');
}
function location(m) {
try {
const loc = m.rw(m.globals); // global 0: the location in Infocom and Inform games
if (loc > 0 && m.objectName(loc)) return loc;
} catch { /* not an object */ }
return 0;
}