Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
CHANGELOG.md: upstream's released sections as they are; main's 11 Unreleased bullets kept under Unreleased. scripts/lib/route-fuzz.js: upstream's skip of dashboard tabs the base lacks, plus main's trimming of args the base's buttons lack. src/game/10-catalog/40-ports.js: upstream's one-pass portsAt(); an express still takes ports per channel at its ends. src/game/10-catalog/60-reach-and-subsea.js: upstream's dfLit/dfCap0/dfOn (managed waves carved out); capOf() keeps xp and sat. src/game/60-features/80-new-game.js: upstream's vol and cm in a new game, with main's ip4, rgen, mp and saved-shape fields. src/game/60-features/95-standing-orders.js: upstream's portsAt, cachePlan and promiseCheck, inside main's build-standard routers order, optup marks, opsDarkPre and decom gone list; opsPairs still leaves satellites out. src/game/80-simulation/30-compute.js: upstream's routing core; main's satellite edges (SATN) pass into it, express risks and sat/ip4 money stay. src/game/80-simulation/29-route-core.js: main's satellite latency note moved into the core, where upstream moved the flow loop. src/game/80-simulation/40-billing.js: main's linkCut() and xp/sat in linkDown(), with upstream's dfOn(). src/game/80-simulation/50-sanitize.js: upstream's cmClean listings and cmFix/volFix; main keeps the xp/sat kinds, mpSanitize, ip4Fix and satSanitize. src/game/80-simulation/60-requirements.js: upstream's shared diversity graph; an express link carries the list of trenches it rides. src/game/91-save.js: upstream's saves in the worker, except a multiplayer session network, whose text is made on the page (mpSave) so the server gets the very save the slot holds; bootNotes() kept. src/game/91-slots.js: upstream's slot text and day, with main's mp badge on a slot. src/game/93-ui/70-link-panels.js: a fiber says both its managed waves and the expresses it carries. src/game/94-dashboard/60-dashboard.js: upstream's carried tile, main's themed demand line. src/game/95-modals/70-link-modal.js: main's Express tab, then upstream's hint for a coast no cable lands on (#321). After the merge: - Moving a circuit: a path over an express shares the trenches of the fibers it rides, so it is never called fully diverse from a path along them (test in express-fiber). - The capacity market and moving customers leave the slots expresses hold (test in express-fiber; no code change needed). - The NOC log keeps only the kinds a reload keeps: the market's info/warn news is a plain line, live as after a reload. - New acts classified for server-run play: market and path moves sent, marketOpen and pathOpen local; pathPin's path may be longer than 64 characters. - Server-play fixtures written again (new cm and vol fields); the dark-mode test reads mapStill()'s three states. - A big multiplayer network that moved on still pushes its save to the server (test in multiplayer). - The full suite ran on jsdom 31.0.0 and playwright-core 1.65.0, the versions the merged lockfile pins.
209 lines
15 KiB
JavaScript
209 lines
15 KiB
JavaScript
// Loads the game page in jsdom with the animation loop disabled, so tests can drive the simulation
|
|
// directly through the game's globals (ACT, S, R, dayTick…). The page is assembled from src/ once per
|
|
// test process (scripts/lib/page.js), so tests always run what is in src/, never a stale build.
|
|
// It is the page players get; {agent: true} loads the development page instead, with the agent facade
|
|
// (src/agent/) the MCP server drives. Only the tests of that facade ask for it, so core code that leans on
|
|
// it fails here rather than in production.
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const vm = require('node:vm');
|
|
const { JSDOM, VirtualConsole } = require('jsdom');
|
|
const { assemble, simId } = require('../scripts/lib/page');
|
|
|
|
const PAGE = {};
|
|
const page = (dev, mp) => PAGE[dev + '|' + mp] || (PAGE[dev + '|' + mp] = assemble({ dev, mp }).html);
|
|
// The build id an MP page carries (scripts/lib/page.js simId()), worked out once per test process.
|
|
let SIM;
|
|
const simOf = () => SIM || (SIM = simId(assemble({ mp: true }).html));
|
|
|
|
// The page's inline scripts, taken out of the HTML once per process and compiled once. jsdom's HTML parser is slow
|
|
// on 2 MB of script text (it was more than half of every load()), so the DOM is built from the rest of the page and
|
|
// the scripts then run in its window, in order, the same way jsdom runs them (vm.Script.runInContext). Only plain
|
|
// <script> tags run, as in the browser here; data blocks (ld+json) stay in the page untouched.
|
|
const SPLIT = new Map();
|
|
function split(html) {
|
|
let s = SPLIT.get(html);
|
|
if (s) return s;
|
|
const code = [];
|
|
const shell = html.replace(/<script>([\s\S]*?)<\/script\b[^>]*>/gi, (m, src) => {
|
|
code.push(new vm.Script(src, { filename: `page-script-${code.length}.js` }));
|
|
return '<script></script>';
|
|
});
|
|
// With scripting on, the parser keeps a <noscript>'s content as text; with scripts run from outside it builds those
|
|
// elements (an extra <h1>, <p>, <div>). Escaped, the content stays one text node, as players' browsers have it.
|
|
const page = shell.replace(/(<noscript>)([\s\S]*?)(<\/noscript>)/g, (m, a, body, b) => a + body.replace(/&/g, '&').replace(/</g, '<') + b);
|
|
SPLIT.set(html, s = { shell: page, code });
|
|
return s;
|
|
}
|
|
|
|
// opts.file: a built or older page to load instead (the perf bench, the release build test).
|
|
// opts.agent: the development page, with src/agent/.
|
|
// opts.mp: the page with multiplayer on, as MP_API=… npm run build makes it: the server-play client in it, MP_API
|
|
// stamped (opts.mp's path, or '/api/mp' for true) and SIM_ID too; opts.fetch: the page's fetch, from the start
|
|
// (fakeFetch() below fakes the session server, streams included).
|
|
function load(opts = {}) {
|
|
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent, !!opts.mp);
|
|
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp === true ? '/api/mp' : opts.mp)).replace("/*__SIM_ID__*/''", () => JSON.stringify(simOf()));
|
|
const errors = [];
|
|
const vc = new VirtualConsole();
|
|
vc.on('jsdomError', (e) => {
|
|
// jsdom has no canvas; drawing calls are expected to be unimplemented.
|
|
if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message);
|
|
});
|
|
const { shell, code } = split(html);
|
|
const dom = new JSDOM(shell, {
|
|
// opts.url: the origin the page is "served" from. Tests that dial the agent relay pass the relay's own host, so
|
|
// the page's WebSocket Origin matches (the relay refuses a cross-site one); everything else stays on a made-up
|
|
// https origin nothing can reach.
|
|
url: opts.url || 'https://tests.invalid/',
|
|
runScripts: 'outside-only',
|
|
pretendToBeVisual: true,
|
|
virtualConsole: vc,
|
|
beforeParse(window) {
|
|
window.__TUBES_TEST__ = true;
|
|
// Seed before the game script runs, so nothing random happens at load time either.
|
|
if (opts.seed !== false) { let r = opts.seed || 12345; window.Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; window.__reseed = (n) => { r = n; }; }
|
|
// opts.browser (from browser()): windows of one browser share localStorage, its storage events, a broadcast
|
|
// channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload.
|
|
if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts);
|
|
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
|
|
if (opts.fetch) window.fetch = opts.fetch;
|
|
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
|
|
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
|
|
// (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.)
|
|
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
|
|
// jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176).
|
|
if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k];
|
|
// An MP page reads its server's stream through fetch: the decoder and streams it needs, Node's (as browsers have them).
|
|
if (opts.mp) for (const k of ['TextEncoder', 'TextDecoder', 'ReadableStream']) if (!window[k]) window[k] = globalThis[k];
|
|
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
|
|
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
|
|
const fake = () => { const calls = { n: 0 };
|
|
const grad = { addColorStop() {} };
|
|
return new Proxy({ calls }, { get(t, k) {
|
|
if (k in t) return t[k];
|
|
if (k === 'measureText') return (s) => ({ width: String(s).length * 7 });
|
|
if (k === 'createLinearGradient' || k === 'createRadialGradient' || k === 'createPattern') return () => grad;
|
|
if (k === 'getImageData') return () => ({ data: new Uint8ClampedArray(4) });
|
|
if (k === 'canvas') return null;
|
|
return (...a) => { calls.n++; };
|
|
}, set(t, k, v) { t[k] = v; return true; } }); };
|
|
window.HTMLCanvasElement.prototype.getContext = function () { return this.__ctx || (this.__ctx = fake()); };
|
|
window.HTMLCanvasElement.prototype.toDataURL = () => 'data:image/png;base64,';
|
|
window.HTMLCanvasElement.prototype.toBlob = (cb) => cb(null);
|
|
},
|
|
});
|
|
// The language picker document.write()s a dictionary <script src> for a non-English player. jsdom fetched nothing
|
|
// for it anyway (opts.lang registers the dictionary), and after parsing a real write would wipe the page.
|
|
const doc = dom.window.document, ctx = dom.getInternalVMContext();
|
|
doc.write = () => {};
|
|
for (const sc of code) {
|
|
try { sc.runInContext(ctx); } catch (e) { vc.emit('jsdomError', Object.assign(new Error(`Uncaught [${e}]`), { detail: e })); }
|
|
}
|
|
delete doc.write;
|
|
const ev = (src) => dom.window.eval(src);
|
|
// Deterministic by default so a test never passes or fails by luck; pass {seed:false} to opt out.
|
|
// (Seeded in beforeParse, so the game's own seeded-games wrapper around Math.random stays in place.)
|
|
return { dom, ev, errors };
|
|
}
|
|
|
|
// Deterministic Math.random so failures are reproducible.
|
|
function seed(ev, n) {
|
|
ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
|
|
}
|
|
|
|
// A fake browser for several windows at once (see opts.browser). Storage events, broadcast messages and lock
|
|
// hand-overs arrive asynchronously, as in browsers: await settle() or flush() before checking them.
|
|
function browser({ locks = true, channel = true } = {}) {
|
|
const ls = new Map(), wins = new Set(), held = new Map(), log = [];
|
|
const later = (f) => setTimeout(f, 0);
|
|
const store = (map, win, shared) => {
|
|
const fire = (key, oldValue, newValue) => { if (shared) for (const w of wins) if (w !== win && !w.closed) later(() => { try { w.dispatchEvent(new w.StorageEvent('storage', { key, oldValue, newValue })); } catch (e) {} }); };
|
|
return {
|
|
getItem: (k) => { if (shared) log.push(['get', String(k)]); return map.has(String(k)) ? map.get(String(k)) : null; },
|
|
setItem: (k, v) => { if (win.closed) return; k = String(k); v = String(v); if (shared && b.quota && k.startsWith('sot-save-v1:') && v.length > b.quota) { const e = new win.Error('full'); e.name = 'QuotaExceededError'; throw e; } const o = map.has(k) ? map.get(k) : null; map.set(k, v); if (shared) { log.push(['set', k]); fire(k, o, v); } },
|
|
removeItem: (k) => { k = String(k); if (!map.has(k)) return; const o = map.get(k); map.delete(k); if (shared) fire(k, o, null); },
|
|
key: (i) => [...map.keys()][i] ?? null,
|
|
get length() { return map.size; },
|
|
clear: () => map.clear(),
|
|
};
|
|
};
|
|
const b = { ls, wins, log, quota: 0,
|
|
attach(win, tab, opts) {
|
|
wins.add(win);
|
|
Object.defineProperty(win, 'localStorage', { configurable: true, get: () => store(ls, win, true) });
|
|
Object.defineProperty(win, 'sessionStorage', { configurable: true, get: () => store(tab, win, false) });
|
|
if (channel) win.BroadcastChannel = class { constructor(name) { this.name = name; (b.chans = b.chans || []).push({ c: this, win }); }
|
|
postMessage(data) { const msg = JSON.parse(JSON.stringify(data)); for (const o of b.chans) if (o.c !== this && o.c.name === this.name && !o.win.closed && o.c.onmessage) later(() => o.c.onmessage({ data: msg })); }
|
|
close() {} };
|
|
if (locks) Object.defineProperty(win.navigator, 'locks', { configurable: true, value: {
|
|
request(name, o, cb) {
|
|
const cur = held.get(name);
|
|
if (cur && !cur.win.closed && !o.steal) { if (o.ifAvailable) return win.Promise.resolve().then(() => cb(null)); return win.Promise.reject(new win.Error('busy')); }
|
|
if (cur) { held.delete(name); cur.reject(new win.DOMException('stolen', 'AbortError')); }
|
|
return new win.Promise((res, rej) => { const me = { win, reject: rej }; held.set(name, me);
|
|
win.Promise.resolve().then(() => cb({ name })).then((v) => { if (held.get(name) === me) held.delete(name); res(v); }, rej); });
|
|
} } });
|
|
},
|
|
// A tab closing: its locks go with it.
|
|
close(win) { win.closed = true; for (const [k, v] of held) if (v.win === win) held.delete(k); wins.delete(win); },
|
|
};
|
|
return b;
|
|
}
|
|
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
|
|
|
|
/* One server-sent event as it goes over the wire (section 5.1 of the server-sim design): event, optional id, one line
|
|
of JSON data. */
|
|
const sse = (event, data, id) => `event: ${event}\n${id === undefined ? '' : `id: ${id}\n`}data: ${JSON.stringify(data)}\n\n`;
|
|
|
|
/* A fake session server for an MP page (load({mp: true, fetch: f})). routes: [regexp on "METHOD url", reply |
|
|
(call) => reply], where a reply is {status, json, headers?}, an Error (the network failed) or a promise of either (an
|
|
answer still on its way; the page aborting meanwhile rejects it, as fetch does). A GET of …/stream that no route
|
|
answers opens an event stream the test writes to:
|
|
f.streams every stream opened, in order; await f.stream(i) the i-th one (0 first), once the page opens it
|
|
s.send(event, data, id) one event (sse() above); s.comment('hb'); s.close(); s.fail(err)
|
|
s.aborted the page aborted it (its AbortSignal); s.closed it ended either way; s.call its request
|
|
Every request is in f.calls: {url, method, path (without MP_API's base), query, headers, raw, body (parsed JSON),
|
|
keepalive, signal}. Responses are Node's own Headers and ReadableStream, which is what browsers hand a page. */
|
|
function fakeFetch(routes = [], { base = '/api/mp' } = {}) {
|
|
const calls = [], streams = [], waiting = [], enc = new TextEncoder();
|
|
const aborted = () => { const e = new Error('aborted'); e.name = 'AbortError'; return e; };
|
|
const res = (r) => (r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, headers: new Headers(r.headers || { 'content-type': 'application/json' }),
|
|
body: null, json: () => (r.json === undefined ? Promise.reject(new SyntaxError('no body')) : Promise.resolve(r.json)), text: () => Promise.resolve(r.json === undefined ? '' : JSON.stringify(r.json)) }));
|
|
function open(c) {
|
|
let ctl;
|
|
const s = { call: c, closed: false, aborted: false, sent: [],
|
|
write(t) { if (!s.closed) ctl.enqueue(enc.encode(t)); return s; },
|
|
send(event, data, id) { const t = sse(event, data, id); s.sent.push({ event, data, id }); return s.write(t); },
|
|
comment(text = 'hb') { return s.write(`: ${text}\n\n`); },
|
|
close() { if (!s.closed) { s.closed = true; ctl.close(); } return s; },
|
|
fail(e = new Error('network')) { if (!s.closed) { s.closed = true; ctl.error(e); } return s; } };
|
|
const body = new ReadableStream({ start(k) { ctl = k; }, cancel() { s.closed = true; } });
|
|
if (c.signal) c.signal.addEventListener('abort', () => { s.aborted = true; s.fail(aborted()); });
|
|
streams.push(s);
|
|
for (const w of waiting.filter((x) => x.i < streams.length)) { waiting.splice(waiting.indexOf(w), 1); w.ok(streams[w.i]); }
|
|
return Promise.resolve({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/event-stream; charset=utf-8' }), body,
|
|
json: () => Promise.reject(new SyntaxError('an event stream')), text: () => Promise.reject(new TypeError('an event stream')) });
|
|
}
|
|
const f = (url, o = {}) => {
|
|
const u = new URL(String(url), 'https://tests.invalid/'), method = (o.method || 'GET').toUpperCase();
|
|
const headers = {}; for (const [k, v] of Object.entries(o.headers || {})) headers[k.toLowerCase()] = v;
|
|
let body; try { body = typeof o.body === 'string' ? JSON.parse(o.body) : undefined; } catch (e) { body = undefined; }
|
|
const c = { url: String(url), method, path: u.pathname.startsWith(base) ? u.pathname.slice(base.length) : u.pathname, query: Object.fromEntries(u.searchParams),
|
|
headers, raw: o.body, body, keepalive: !!o.keepalive, signal: o.signal };
|
|
calls.push(c);
|
|
if (o.signal && o.signal.aborted) return Promise.reject(aborted());
|
|
for (const [re, h] of f.routes) if (re.test(`${method} ${c.url}`)) {
|
|
const r = typeof h === 'function' ? h(c) : h;
|
|
if (!r || typeof r.then !== 'function') return res(r);
|
|
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(aborted())); r.then((x) => res(x).then(ok, no), no); });
|
|
}
|
|
if (method === 'GET' && /\/stream$/.test(c.path)) return open(c);
|
|
return res({ status: 404, json: { error: 'not here' } });
|
|
};
|
|
f.routes = routes; f.calls = calls; f.streams = streams;
|
|
f.stream = (i = 0) => (streams[i] ? Promise.resolve(streams[i]) : new Promise((ok) => waiting.push({ i, ok })));
|
|
return f;
|
|
}
|
|
|
|
module.exports = { load, seed, browser, flush, sse, fakeFetch };
|