The list predates multiple campaigns: it didn't say which campaign a room plays, and headed the clock column with Dead Channel's "until contact".
200 lines
12 KiB
JavaScript
200 lines
12 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');
|
|
});
|
|
test('the room list names the campaign each room plays', async () => {
|
|
const env = environment();
|
|
env.context.setInterval = () => 0; env.context.window.addEventListener = () => {};
|
|
const room = { code: 'ABC234', phase: 'ACTIVE', crew: 2, round: 3, pressure: 9, campaign: 'Hollow Point', campaignId: 'hollow-point', campaignHash: '' };
|
|
env.context.fetch = async () => ({ ok: true, status: 200, json: async () => ({ serverName: 'Relay', uptimeSeconds: 5, narrator: 'SCRIPTED',
|
|
narration: { completed: 0, fallbacks: 0 }, javaVersion: '21', rooms: [room] }) });
|
|
env.script('app.js');
|
|
env.run('unlocked = true; token = "key"');
|
|
await env.run('refreshStatus()');
|
|
assert.deepEqual(env.$('rooms').children[0].children.map(cell => cell.textContent), ['ABC234', 'Hollow Point', 'ACTIVE', '2', '03', '9']);
|
|
});
|
|
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('a campaign opened from the library stays offered when saved', async () => {
|
|
const e = studio();
|
|
const listing = e.run('refreshOpen()');
|
|
e.requests.find(r => r.path === 'studio/templates').resolve([]); await tick();
|
|
e.requests.find(r => r.path === 'campaigns').resolve([{ id: 'lighthouse', title: 'Lighthouse', version: '1.0.0', builtIn: false, enabled: true }]);
|
|
await listing;
|
|
const opening = e.run('openCampaign("lighthouse")');
|
|
e.requests.find(r => r.path === 'campaigns/lighthouse/source').resolve({ text: async () => e.source });
|
|
await opening;
|
|
void e.$('save').fire('click');
|
|
assert.equal(e.requests.find(r => r.path === 'studio/save').data.enable, true);
|
|
});
|
|
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)'), '[]');
|
|
});
|
|
test('hidden campaigns show the cover placeholder, since the relay only serves offered covers', async () => {
|
|
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('campaigns.js');
|
|
const entry = { title: 'Lighthouse', tagline: '', authors: ['you'], license: 'CC0-1.0', version: '1.0.0', builtIn: false, isDefault: false, hasCover: true, rooms: 0 };
|
|
const loading = env.run('refresh()');
|
|
requests[0].resolve([{ ...entry, id: 'shown', enabled: true }, { ...entry, id: 'hidden', enabled: false }]);
|
|
await loading;
|
|
const covers = env.$('campaigns').children.map(row => row.children[0].children[0].children[0]);
|
|
assert.deepEqual(covers.map(c => c.tagName), ['img', 'span']);
|
|
assert.equal(covers[0].src, '/campaigns/shown/cover.png');
|
|
});
|