Files
de-praxis/scripts/admin.test.cjs
T
juli d8bd6d3a80 Find the latest round whatever its header says, and keep empty content warnings
The app found the latest round by looking for a log line starting with
'ROUND ', the default wording of text.resolving. A campaign that reworded
it made the transcript show the whole history and jump back to the
intro every round. The round now starts at the line just before its
first player action, which holds for any wording.

The Studio removed meta.warnings when the field was cleared, and the
blank template had none, but catalogs require the field ([] for none),
so such campaigns always failed the catalog check.
2026-10-25 14:56:37 +01:00

160 lines
8.9 KiB
JavaScript

'use strict';
// Exercise the shipped browser scripts with controlled requests and timers (no external packages).
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const vm = require('node:vm');
const root = join(__dirname, '..');
const tick = () => new Promise(resolve => setImmediate(resolve));
function deferred() { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }
class Element {
constructor(tag = 'div') { this.tagName = tag; this.children = []; this.events = {}; this.value = ''; this.hidden = true; this.dataset = {}; this.style = {}; this.classList = { add() {}, remove() {}, toggle() {} }; }
addEventListener(type, fn) { (this.events[type] ||= []).push(fn); }
async fire(type) { for (const fn of this.events[type] || []) await fn({ preventDefault() {}, target: this }); }
append(...children) { this.children.push(...children); }
replaceChildren(...children) { this.children = children; }
setAttribute(key, value) { if (key === 'value') this.value = value; else this[key] = value; }
}
function environment() {
const nodes = new Map(), timers = new Map(), storage = new Map(); let timer = 0;
const $ = id => { if (!nodes.has(id)) nodes.set(id, new Element()); return nodes.get(id); };
const context = vm.createContext({
document: { getElementById: $, createElement: tag => new Element(tag), body: new Element(), documentElement: new Element(), querySelectorAll: () => [], activeElement: null },
window: { matchMedia: () => ({ matches: true, addEventListener() {} }) },
sessionStorage: { getItem: k => storage.get(k), setItem: (k, v) => storage.set(k, v), removeItem: k => storage.delete(k) },
localStorage: { getItem: () => null, setItem() {} },
setTimeout: fn => { timers.set(++timer, fn); return timer; }, clearTimeout: id => timers.delete(id),
AbortController, location: { hash: '' }, console,
});
const run = code => vm.runInContext(code, context);
const script = name => run(readFileSync(join(root, 'server/src/main/resources/admin', name), 'utf8'));
return { $, context, run, script, storage };
}
function auth() {
const env = environment(), requests = [];
env.context.fetch = (_url, options) => { const request = deferred(); requests.push({ ...request, options }); return request.promise; };
env.script('common.js');
env.run('let loads = 0; Console.start(() => { loads++; });');
const reply = (i, status = 200) => requests[i].resolve({ ok: status === 200, status, json: async () => ({}) });
return { ...env, requests, reply };
}
test('a delayed sign-in cannot reopen the console after logout', async () => {
const e = auth();
e.$('admin-key').value = 'first-token'; await e.$('login-form').fire('submit');
e.run('Console.lock()'); e.reply(0); await tick();
assert.equal(e.$('sidebar').hidden, true);
assert.equal(e.run('loads'), 0);
});
test('a rejected old login cannot lock a newer authenticated session', async () => {
const e = auth();
e.$('admin-key').value = 'first-token'; await e.$('login-form').fire('submit');
e.$('admin-key').value = 'second-token'; await e.$('login-form').fire('submit');
e.reply(1); await tick(); e.reply(0, 401); await tick();
assert.equal(e.$('sidebar').hidden, false);
assert.equal(e.storage.get('de-praxis-admin'), 'second-token');
});
function studio() {
const env = environment(), requests = [];
env.context.$ = env.$;
env.context.Console = {
start() {}, notice() {},
api: (path, data) => { const request = deferred(); requests.push({ ...request, path, data }); return request.promise; },
el: (tag, attrs = {}, ...children) => { const e = new Element(tag); for (const [k, v] of Object.entries(attrs)) { if (k.startsWith('on')) e.addEventListener(k.slice(2), v); else e.setAttribute(k, v); } e.append(...children); return e; },
};
env.script('studio.js');
const source = readFileSync(join(root, 'server/src/main/resources/campaigns/templates/blank.json'), 'utf8');
env.run(`load(${JSON.stringify(source)})`);
return { ...env, requests, source };
}
test('typing source and immediately saving sends the current document', async () => {
const e = studio(), current = e.source.replace('My Campaign', 'Latest title');
e.$('source').value = current; await e.$('source').fire('input');
void e.$('save').fire('click');
assert.equal(e.requests.find(r => r.path === 'studio/save').data.source, current);
});
test('invalid source cannot silently save the previous valid document', async () => {
const e = studio();
e.$('source').value = '{'; await e.$('source').fire('input');
void e.$('save').fire('click');
assert.equal(e.requests.some(r => r.path === 'studio/save'), false);
});
test('an older validation response cannot overwrite the current result', async () => {
const e = studio();
const first = e.run('check()');
e.run('doc.meta.title = "Latest"; changed()');
const second = e.run('check()');
const result = { valid: true, issues: [], counts: {}, nodes: [], edges: [] };
e.requests[1].resolve(result); await second;
e.requests[0].resolve({ ...result, valid: false, issues: [{ severity: 'error', path: '$', message: 'Old draft' }] }); await first;
assert.equal(e.$('valid-heading').textContent, 'Valid');
});
test('an invalid admin key still displays a sign-in error', async () => {
const e = auth();
e.$('admin-key').value = 'bad-token'; await e.$('login-form').fire('submit');
e.reply(0, 401); await tick();
assert.equal(e.$('sidebar').hidden, true);
assert.ok(e.$('login-error').textContent);
});
function descendants(node) { return [node, ...(node.children || []).filter(c => c instanceof Element).flatMap(descendants)]; }
function actionEditor(e) {
e.run('open.add("actions:0"); renderSections()');
return descendants(e.$('sections')).find(n => n.tagName === 'textarea' && n.children.some(c => typeof c === 'string' && c.includes('"id": "try"')));
}
test('section JSON edits are included when saving immediately', async () => {
const e = studio(), area = actionEditor(e);
area.value = JSON.stringify({ id: 'try', label: 'Changed immediately', effects: [] });
await area.fire('input'); void e.$('save').fire('click');
assert.equal(JSON.parse(e.requests.find(r => r.path === 'studio/save').data.source).actions[0].label, 'Changed immediately');
});
test('invalid section JSON blocks stale saves and can be corrected', async () => {
const e = studio(), area = actionEditor(e);
area.value = '{'; await area.fire('input'); void e.$('save').fire('click');
assert.equal(e.requests.some(r => r.path === 'studio/save'), false);
area.value = JSON.stringify({ id: 'try', label: 'Repaired', effects: [] });
await area.fire('input'); void e.$('save').fire('click');
assert.equal(JSON.parse(e.requests.find(r => r.path === 'studio/save').data.source).actions[0].label, 'Repaired');
});
test('unfinished raw JSON is preserved when restoring a browser draft', () => {
const e = studio(); e.run('load("{\\n", { remember: false })');
assert.equal(e.$('source').value, '{\n');
assert.equal(e.$('source-state').textContent, 'JSON ERROR');
assert.equal(e.run('sourceValid'), false);
});
function selection(e, value) {
e.context.Event = class { constructor(type) { this.type = type; } };
e.run(`var field = { value: ${JSON.stringify(value)}, isConnected: true, dispatched: 0,
setRangeText(text, start, end) { this.value = this.value.slice(0, start) + text + this.value.slice(end); },
dispatchEvent() { this.dispatched++; } };
lastSelection = { field, start: 4, end: 12, kind: 'line' }; suggest();`);
const request = e.requests.find(r => r.path === 'studio/suggest');
assert.equal(request.data.text, 'old line');
return request;
}
const firstSuggestion = e => e.$('suggestions').children[0].children[0];
test('a suggestion replaces the selected text when it is unchanged', async () => {
const e = studio(), request = selection(e, 'The old line here.');
request.resolve(['new words']); await tick();
await firstSuggestion(e).fire('click');
assert.equal(e.run('field.value'), 'The new words here.');
assert.equal(e.run('field.dispatched'), 1);
});
test('a suggestion never overwrites text edited while the model answered', async () => {
const e = studio(), request = selection(e, 'The old line here.');
e.run('field.value = "Edited meanwhile, all of it."');
request.resolve(['new words']); await tick();
await firstSuggestion(e).fire('click');
assert.equal(e.run('field.value'), 'Edited meanwhile, all of it.');
assert.equal(e.run('field.dispatched'), 0);
});
test('clearing content warnings keeps an explicit empty list', async () => {
const e = studio();
const input = descendants(e.$('details')).find(n => n['data-path'] === 'meta.warnings');
input.value = 'dread, isolation'; await input.fire('input');
assert.deepEqual(JSON.parse(e.run('JSON.stringify(doc.meta.warnings)')), ['dread', 'isolation']);
input.value = ''; await input.fire('input');
assert.equal(e.run('JSON.stringify(doc.meta.warnings)'), '[]');
});