Phase 3: trade/end-game client, bot simulator, first balance pass

Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 20:24:41 +02:00
parent d84b0c9d12
commit 931f59e11e
49 changed files with 4750 additions and 59 deletions

75
test/bot-run.test.js Normal file
View file

@ -0,0 +1,75 @@
'use strict';
/* tools/bot.js: short deterministic runs of the bot harness against the real server. Asserts the invariants (conservation of
* resources and units, no negative stock, no failed events, no unexpected error codes), that the same seed gives identical stats
* (wall-clock `perf` excepted), that the harness parses its options, and that the data.js override mechanism restores what it
* changed. Keep it fast: it is part of `npm test`. */
const test = require('node:test');
const assert = require('node:assert');
const { runBot, parseArgs, applyOverrides } = require('../tools/bot.js');
const D = require('../public/js/data.js');
const strip = (s) => { const c = JSON.parse(JSON.stringify(s)); delete c.perf; return c; };
test('bot run: invariants hold and the same seed gives identical stats', async () => {
const t0 = Date.now();
const a = await runBot({ players: 12, days: 6, seed: 7 }); // long enough for scans, raids and battle losses
const b = await runBot({ players: 12, days: 6, seed: 7 });
assert.equal(a.invariants.ok, true, JSON.stringify(a.invariants).slice(0, 800));
assert.equal(a.invariants.resources.ok, true);
assert.equal(a.invariants.units.ok, true);
assert.equal(a.invariants.negativeStock.ok, true);
assert.equal(a.invariants.failedEvents.n, 0);
assert.equal(a.invariants.unexpectedErrors.n, 0);
assert.deepStrictEqual(strip(a), strip(b), 'same options and seed, different stats');
assert.ok(a.perf.commands > 50 && a.botLogs.builds > 20 && a.botLogs.trains > 0, 'the bots built and trained');
assert.ok(a.days.length === 6 && a.meta.players === 12);
assert.ok(a.combat.scans.n > 0, 'and scouted (the military paths ran, so determinism covers them)');
const c = await runBot({ players: 12, days: 6, seed: 8 });
assert.notDeepStrictEqual(strip(a).days, strip(c).days, 'a different seed should change the world');
assert.ok(Date.now() - t0 < 15000, 'the harness must stay fast (took ' + (Date.now() - t0) + ' ms)');
});
test('bot run: a fast world reaches the landing sites, an alliance takes one and ships; conservation holds with backbone sinks', async () => {
// 20 bots, 12 sittings a day, a world at speed 15: day 100 of world time is day 6.7; takes ~5 s
const s = await runBot({ players: 20, days: 8, speed: 15, seed: 3, sessionsPerDay: 12, endgameStepMin: 60 });
assert.equal(s.invariants.ok, true, JSON.stringify(s.invariants).slice(0, 800));
assert.equal(s.endgame.open, true, 'age 120 world days: the sites are open');
assert.ok(s.endgame.strikes >= 1 && s.combat.landing.taken >= 1, 'an alliance took a landing site');
assert.ok(s.endgame.shipments > 0 && s.endgame.bestLevel >= 1, 'and its members shipped enough for Backbone node levels');
assert.ok(s.endgame.sites.some((x) => x.holder && x.contributors >= 1));
assert.equal(s.invariants.resources.final.fiber.backbone > 0, true, 'the ledger booked the node levels as a sink');
});
test('bot options: parsing, overrides and restore', () => {
const o = parseArgs(['--players', '12', '--days', '5', '--speed', '2', '--seed', '9', '--set', 'FORMULAS.costGrowth=1.3', '--set', 'UNITS.script_crew.cost.fiber=70', '--always-on']);
assert.equal(o.players, 12); assert.equal(o.speed, 2); assert.equal(o.seed, 9); assert.equal(o.alwaysOn, true); assert.equal(o.set.length, 2);
assert.throws(() => parseArgs(['--nope']), /unknown option/);
assert.throws(() => parseArgs(['--players']), /missing value/);
const before = [D.FORMULAS.costGrowth, D.UNITS.script_crew.cost.fiber];
const restore = applyOverrides(o.set);
assert.equal(D.FORMULAS.costGrowth, 1.3);
assert.equal(D.UNITS.script_crew.cost.fiber, 70);
restore();
assert.deepEqual([D.FORMULAS.costGrowth, D.UNITS.script_crew.cost.fiber], before);
assert.throws(() => applyOverrides(['FORMULAS.nope=1']), /no such path/);
});
test('bot invariants catch tampering: created resources, vanished units, negative stock and failed events', async () => {
// tamper on the last day boundary: the final checkpoint follows at the same instant, nothing settles the damage away
const tamper = (fn, o) => runBot(Object.assign({ players: 6, days: 3, seed: 2, onDay: (sim, day) => { if (day === (o && o.days || 3)) fn(sim.db); } }, o));
const a = await tamper((db) => db.run('UPDATE towns SET fiber = fiber + 500 WHERE id = 1'));
assert.equal(a.invariants.ok, false);
assert.equal(a.invariants.resources.ok, false, 'conjured Fiber must show as drift');
assert.ok(a.invariants.resources.worstDrift >= 400);
let vanished = null;
const b = await tamper((db) => { const u = db.get('SELECT town_id, unit, count FROM town_units ORDER BY count DESC LIMIT 1'); if (u) { vanished = u; db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', u.town_id, u.unit); } }, { players: 12, days: 6 });
assert.ok(vanished, 'the bots trained some units by day 6');
assert.equal(b.invariants.units.ok, false, 'units that vanish must show as drift');
assert.equal(b.invariants.ok, false);
const c = await tamper((db) => db.run('UPDATE towns SET hardware = -5 WHERE id = 2'));
assert.equal(c.invariants.negativeStock.ok, false);
assert.equal(c.invariants.ok, false);
const d = await tamper((db) => db.run("INSERT INTO events (world_id, due_at, type, payload, status, created_at) VALUES (1, 0, 'nope', '{}', 'pending', 0)"));
assert.ok(d.invariants.failedEvents.n >= 1, 'an event without a handler fails and is counted');
assert.equal(d.invariants.ok, false);
});

View file

@ -0,0 +1,47 @@
'use strict';
/* Small server fixes found by the bot harness (tools/bot.js), each with the test that failed before the fix. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const M = require('../server/military/movements');
const { R, D } = T;
// The conservation ledger of the harness found it: a shipment that comes home (a landing site changed hands, a POP vanished) rides
// back on a `link` return leg. Cargo above the Rack hall cap is dropped on arrival, but the return handler stayed silent for link
// legs, so the loss was invisible to the player and to every audit that sums the `cargoLost` notifications.
test('a bounced shipment that does not fit the Rack hall reports the overflow (link return legs with cargo are no longer silent)', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice', { infra: { rack_hall: 1 } });
const cap = R.storageCap(require('../server/state').loadTown(h.db, a.townId));
h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', cap - 100, a.townId);
const row = T.town(h, a.townId);
const ctx = h.ctx();
M.launchReturn(ctx, { worldId: h.worldId, ownerId: a.opId, fromTownId: null, at: { x: row.x + 5, y: row.y }, to: row, units: {}, cargo: { fiber: 400 }, arriveAt: h.clock.now() + 60 * 1000, parentId: null, extra: { link: 1 } });
h.advance(2 * 60 * 1000);
const n = T.notes(h, a.userId, 'movement_returned');
assert.equal(n.length, 1, 'the bounced shipment is announced');
assert.ok(Math.abs(n[0].cargoLost.fiber - 300) <= 2, 'and says how much did not fit (400 sent, 100 of room, a minute of production on top): ' + n[0].cargoLost.fiber);
assert.ok(Math.abs(T.town(h, a.townId).fiber - cap) < 1e-6, 'the store is full, not above the cap');
});
test('empty carriers coming home on a link leg stay silent (no notification spam)', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice');
const row = T.town(h, a.townId);
M.launchReturn(h.ctx(), { worldId: h.worldId, ownerId: a.opId, fromTownId: null, at: { x: row.x + 5, y: row.y }, to: row, units: {}, cargo: {}, arriveAt: h.clock.now() + 60 * 1000, parentId: null, extra: { link: 1 } });
h.advance(2 * 60 * 1000);
assert.equal(T.notes(h, a.userId, 'movement_returned').length, 0);
});
// Balance pass B1 (docs/BALANCE.md): the second build slot opens at Core router 3; FORMULAS.extraQueueCores (default none) can open more.
test('build slots follow the Core router: one, a second from FORMULAS.secondQueueCoreLevel, more from FORMULAS.extraQueueCores', () => {
const F = D.FORMULAS;
const at = (core) => R.queueSlots({ buildings: { core_router: { type: 'core_router', level: core } } });
assert.equal(F.secondQueueCoreLevel, 3, 'the tuned value (B1)');
assert.deepEqual([0, 1, 2, 3, 10, 20].map(at), [1, 1, 1, 2, 2, 2], 'default: two slots from the second-slot level, no extra ones');
const saved = F.extraQueueCores;
try {
F.extraQueueCores = [6, 10];
assert.deepEqual([2, 3, 5, 6, 9, 10, 20].map(at), [1, 2, 2, 3, 3, 4, 4]);
} finally { F.extraQueueCores = saved; }
});

114
test/client-alerts.test.js Normal file
View file

@ -0,0 +1,114 @@
'use strict';
/* The Alerts feed: every notification type the server writes has a describer, and each describer turns the real payload shapes
* into a readable title (no raw keys, no "undefined", no "[object Object]"). The browser files cannot be loaded here, so the pure
* describers (public/js/alertkinds.js) are run directly and the others are found by reading the sources. */
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const I = require('../public/js/i18n.js');
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
const AK = require('../public/js/alertkinds.js');
const ROOT = path.join(__dirname, '..');
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : []));
// every notification type the server writes: notify(uid, worldId, 'type', ...), A.notifyAlliance(ctx, id, 'type', ...), notifyWorld(...)
function serverTypes() {
const out = new Set();
for (const f of walk(path.join(ROOT, 'server'))) {
const src = fs.readFileSync(f, 'utf8');
for (const m of src.matchAll(/\bnotify(?:Alliance|Operator|World)?\(([^'`\n]*?)'([a-z_]+)'/g)) out.add(m[2]);
}
return out;
}
const lang = { en: 'en', nb: 'nb' };
function ctxFor(l) {
return {
t: (k, v) => I.t(l, k, v), num: (n) => I.fmtNum(l, n), resName: (r) => I.t(l, 'res.' + r),
townName: (id) => (id === 1 ? 'Home POP' : null), clockTime: () => '12:00', dayTime: () => '1 Jan, 12:00',
};
}
const T = { resource: 'fiber', amount: 400 }, W = { resource: 'hardware', amount: 300 };
const alliance = { id: 7, tag: 'NSP', name: 'North Sea Peering' };
// payloads in the shapes the server writes them (grep the notify calls)
const SAMPLES = {
trade_accepted: { offerId: 3, townId: 1, byTownId: 2, give: T, want: W },
trade_completed: { offerId: 3, give: T, want: W },
trade_expired: { offerId: 3, townId: 1, returned: T },
trade_void: { offerId: 3, townId: 1 },
backbone_open: { sites: [{ siteId: 1, index: 0, x: 3, y: 4 }, { siteId: 2, index: 1, x: 5, y: 6 }] },
backbone_taken: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' }, from: { allianceId: 8, tag: 'FTC', name: 'Fjord' } },
backbone_lost: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 8, tag: 'FTC', name: 'Fjord' }, from: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' } },
backbone_level: { siteId: 1, index: 2, level: 20 },
backbone_delivered: { movementId: 5, siteId: 1, cargo: { fiber: 500, hardware: 0, capital: 120 } },
backbone_ship_bounced: { movementId: 5, siteId: 1, cargo: { fiber: 500 } },
backbone_won: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, endsAt: 1767225600000 },
world_ended: { winner: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, wonAt: 1 }, endedAt: 1767225600000 },
alliance_invite: { inviteId: 1, allianceId: 7, tag: 'NSP', name: 'North Sea Peering', by: 'Alice', expiresAt: 1767225600000 },
alliance_invite_declined: { inviteId: 1, allianceId: 7, by: 'Bob' },
alliance_member_joined: { allianceId: 7, operatorId: 3, name: 'Bob' },
alliance_member_left: { allianceId: 7, operatorId: 3, name: 'Bob', kicked: false },
alliance_kicked: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' },
alliance_role: { allianceId: 7, tag: 'NSP', from: 'member', role: 'officer' },
alliance_leader: { allianceId: 7, operatorId: 3, name: 'Bob', from: 'Alice' },
alliance_disbanded: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering', reason: 'disbanded' },
diplomacy_proposal: { proposalId: 1, from: alliance, state: 'nap', expiresAt: 1767225600000 },
diplomacy_declined: { proposalId: 1, by: alliance, state: 'nap' },
diplomacy_changed: { allianceId: 8, other: alliance, from: 'neutral', to: 'war' },
diplomacy_cancel_pending: { allianceId: 8, other: alliance, from: 'nap', to: 'neutral', effectiveAt: 1767225600000, startedBy: 7 },
diplomacy_cancel_revoked: { allianceId: 8, other: alliance, state: 'nap' },
message: { messageId: 4, from: { operatorId: 3, name: 'Bob' } },
alliance_message: { messageId: 4, allianceId: 7, tag: 'NSP', from: 'Alice' },
};
const KNOWN_ELSEWHERE = new Set(['build_done']); // screens/alerts.js
test('every notification type the server writes has a describer (alertkinds.js, milstate.js or alerts.js)', () => {
const have = new Set(Object.keys(AK.make(ctxFor('en'))));
const mil = fs.readFileSync(path.join(ROOT, 'public', 'js', 'milstate.js'), 'utf8');
for (const m of mil.matchAll(/\bkinds\.([a-z_]+) =/g)) have.add(m[1]);
for (const k of KNOWN_ELSEWHERE) have.add(k);
const types = serverTypes();
assert.ok(types.size >= 40, 'the notify calls were found (' + types.size + ')');
const missing = Array.from(types).filter((t) => !have.has(t)).sort();
assert.deepStrictEqual(missing, [], 'notification types without an Alerts describer (they would read "Event: <type>")');
});
test('each new describer renders its server payload as readable text in en and nb, with an icon and a jump target', () => {
const icons = new Set(fs.readFileSync(path.join(ROOT, 'public', 'icons', 'sprite.svg'), 'utf8').match(/id="i-([a-z_-]+)"/g).map((s) => s.slice(6, -1)));
for (const l of Object.keys(lang)) {
const kinds = AK.make(ctxFor(l));
for (const [type, p] of Object.entries(SAMPLES)) {
assert.ok(kinds[type], 'describer for ' + type);
const d = kinds[type]({ id: 1, type, payload: p, createdAt: 0 }, p);
const text = d.title + ' | ' + d.detail;
assert.ok(d.title && d.title.length > 3, l + ' ' + type + ' has a title');
assert.ok(!/undefined|\[object|NaN|\{\w+\}|alerts\./.test(text), l + ' ' + type + ' looks raw: ' + text);
assert.ok(icons.has(d.icon), type + ' icon ' + d.icon + ' exists in the sprite');
assert.ok(typeof d.go === 'string', type + ' jumps somewhere');
}
}
});
test('describers survive an empty payload (a newer server field never breaks the feed)', () => {
const kinds = AK.make(ctxFor('en'));
for (const type of Object.keys(SAMPLES)) assert.doesNotThrow(() => kinds[type]({ id: 1, type, payload: {} }, {}), type);
});
test('diplomacy_changed has two payload shapes and both read well', () => {
const k = AK.make(ctxFor('en')).diplomacy_changed;
assert.match(k({}, { allianceId: 8, other: alliance, from: 'nap', to: 'neutral' }).title, /\[NSP\].*Neutral/);
const d = k({}, { allianceId: 8, otherId: 7, otherTag: 'NSP', from: 'war', to: 'neutral', reason: 'disbanded' });
assert.match(d.title, /\[NSP\]/);
assert.match(d.detail, /disbanded/);
});
test('backbone alerts jump to the world screen, to the right site when the payload has one', () => {
const k = AK.make(ctxFor('en'));
assert.deepStrictEqual([k.backbone_taken({}, SAMPLES.backbone_taken).go, k.backbone_taken({}, SAMPLES.backbone_taken).params], ['world', { site: 2 }]);
assert.strictEqual(k.backbone_won({}, SAMPLES.backbone_won).go, 'world');
assert.strictEqual(k.trade_accepted({}, SAMPLES.trade_accepted).go, 'trade');
assert.deepStrictEqual(k.trade_accepted({}, SAMPLES.trade_accepted).params, { tab: 'mine' });
});

View file

@ -28,12 +28,15 @@ test('every building, resource and tile type has a player-facing name in both la
}
});
test('every error code the client can meet is translated', () => {
// codes the current screens can see (auth, build, cancel, rename, map, notifications, tokens) + client-side ones
const codes = ['bad_request', 'validation_failed', 'unauthorized', 'invalid_credentials', 'forbidden', 'not_found', 'conflict', 'request_in_progress',
'idempotency_key_reuse', 'payload_too_large', 'rate_limited', 'internal_error', 'signup_closed', 'username_taken', 'world_full', 'unknown_building',
'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources', 'network_error', 'unknown', 'method_not_allowed'];
for (const l of I.LANGS) for (const c of codes) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
test('every error code the server can send is translated in en and nb (iterates server/errors.js CODES)', () => {
const { CODES } = require('../server/errors');
// client-side codes (api.js ApiError) come on top of the server's table
const codes = Object.keys(CODES).concat(['network_error', 'unknown']);
assert.ok(codes.length > 50, 'the CODES table was read');
for (const l of I.LANGS) {
const missing = codes.filter((c) => !I.strings[l]['err.' + c]);
assert.deepStrictEqual(missing, [], l + ' is missing err.<code> translations');
}
});
test('t() fills placeholders, falls back to en then to the key', () => {

159
test/client-world.test.js Normal file
View file

@ -0,0 +1,159 @@
'use strict';
/* Client side of the end game and trade: pure helpers (endcore.js), the send-dialog options for landing sites and transports (milcore.js),
* string coverage of the new screens, and no HTML injection sinks. Browser behaviour was looked at in headless Chromium, not here. */
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const I = require('../public/js/i18n.js');
const D = require('../public/js/data.js');
const E = require('../public/js/endcore.js');
const M = require('../public/js/milcore.js');
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
const ROOT = path.join(__dirname, '..', 'public', 'js');
const site = (o) => Object.assign({ id: 1, index: 0, x: 1, y: 2, holder: null, takenBy: null, takenAt: null, level: 0, maxLevel: 100, progress: 0, pool: { fiber: 0, hardware: 0, capital: 0 }, build: null, next: { toLevel: 1, cost: { fiber: 100, hardware: 100, capital: 100 }, durationMs: 1000 } }, o || {});
const holder = (id, tag) => ({ allianceId: id, tag, name: 'Alliance ' + tag });
test('leading: highest node level, then more sites, then the earlier takeover', () => {
assert.strictEqual(E.leading([]), null);
assert.strictEqual(E.leading([site(), site({ index: 1 })]), null, 'nobody holds a site');
const a = site({ index: 0, holder: holder(1, 'AAA'), level: 10, takenAt: 500 });
const b = site({ index: 1, holder: holder(2, 'BBB'), level: 12, takenAt: 900 });
assert.strictEqual(E.leading([a, b]).tag, 'BBB');
assert.strictEqual(E.leading([a, b]).siteIndex, 1);
const a2 = site({ index: 2, holder: holder(1, 'AAA'), level: 12, takenAt: 700 });
assert.strictEqual(E.leading([a, b, a2]).tag, 'AAA', 'same level: two sites beat one');
assert.strictEqual(E.leading([a, b, a2]).sites, 2);
const c = site({ index: 3, holder: holder(3, 'CCC'), level: 12, takenAt: 100 });
assert.strictEqual(E.leading([b, c]).tag, 'CCC', 'same level and sites: the earlier takeover');
});
test('buildProgress, missing and holderKind', () => {
assert.strictEqual(E.buildProgress(site(), 5), null);
const s = site({ build: { toLevel: 2, startedAt: 1000, dueAt: 3000 } });
assert.strictEqual(E.buildProgress(s, 2000), 0.5);
assert.strictEqual(E.buildProgress(s, 9000), 1);
assert.strictEqual(E.buildProgress(s, 0), 0);
assert.deepStrictEqual(E.missing({ fiber: 100, hardware: 50, capital: 0 }, { fiber: 40, hardware: 50, capital: 9 }), { fiber: 60 });
assert.deepStrictEqual(E.missing({ fiber: 1 }, null), { fiber: 1 });
assert.strictEqual(E.holderKind(site(), 5), 'incumbent');
assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), 5), 'mine');
assert.strictEqual(E.holderKind(site({ holder: holder(6, 'Y') }), 5), 'rival');
assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), null), 'rival');
});
test('buildCheck explains why the node cannot be built, in the order the server checks it', () => {
const rich = { fiber: 1e6, hardware: 1e6, capital: 1e6 };
const ok = site({ pool: rich });
const you = { holder: true, canBuild: true, canShip: true, canAttack: false };
assert.deepStrictEqual(E.buildCheck(ok, you, false), { ok: true, reason: null });
assert.strictEqual(E.buildCheck(ok, you, true).reason, 'ended');
assert.strictEqual(E.buildCheck(ok, { holder: true, canBuild: false }, false).reason, 'forbidden');
assert.strictEqual(E.buildCheck(ok, { holder: false, canBuild: false }, false).reason, 'forbidden');
assert.strictEqual(E.buildCheck(site({ pool: rich, next: null, level: 100 }), you, false).reason, 'max_level');
assert.strictEqual(E.buildCheck(site({ pool: rich, build: { toLevel: 2, startedAt: 0, dueAt: 9 } }), you, false).reason, 'already_queued');
assert.strictEqual(E.buildCheck(site(), you, false).reason, 'not_enough_resources');
});
test('phaseNow flips to backbone_open at opensAt even before the status is refetched; ended wins', () => {
const st = { phase: 'running', opensAt: 1000, ageDays: 40, openDay: 100 };
assert.strictEqual(E.phaseNow(st, 999), 'running');
assert.strictEqual(E.phaseNow(st, 1000), 'backbone_open');
assert.strictEqual(E.phaseNow({ phase: 'ended', opensAt: 1 }, 0), 'ended');
assert.strictEqual(E.phaseNow(null, 0), 'running');
assert.strictEqual(E.openProgress(st), 0.4);
assert.strictEqual(E.openProgress({ ageDays: 500, openDay: 100 }), 1);
assert.strictEqual(E.sumCargo({ fiber: 3, capital: 4 }), 7);
assert.strictEqual(E.topRows([1, 2, 3], 2).length, 2);
});
test('moveOptions on a landing site: scan, attack (needs an alliance, not your own site)', () => {
const tile = (b) => ({ type: 'backbone', backbone: Object.assign({ siteId: 1, index: 0, mine: false, canAttack: true }, b) });
const home = { port_scanner: 2, script_crew: 10 };
const types = (o) => o.map((x) => x.type + (x.ok ? '' : '!'));
assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home, allianceId: 5 })), ['scan', 'attack']);
const noAll = M.moveOptions({ tile: tile(), home, allianceId: null });
assert.deepStrictEqual(types(noAll), ['scan', 'attack!']);
assert.strictEqual(noAll[1].reason, 'no_alliance');
const own = M.moveOptions({ tile: tile({ mine: true }), home, allianceId: 5 });
assert.strictEqual(own[1].reason, 'own_site');
assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home: {}, allianceId: 5 })), ['scan!', 'attack!']);
assert.ok(!M.moveOptions({ tile: tile(), home, allianceId: 5 }).some((o) => ['raid', 'takeover', 'settle', 'reinforce', 'transport'].includes(o.type)));
});
test('moveOptions transportOnly: any POP takes a transport (a rival\'s too), nothing else is offered, links decide ok', () => {
const rival = { type: 'pop', town: { id: 9, mine: false, owner: { id: 2, protected: true } } };
const mine = { type: 'pop', town: { id: 3, mine: true, owner: { id: 1 } } };
const home = { script_crew: 10, port_scanner: 3 };
const o = M.moveOptions({ tile: rival, home, transport: { links: 2, active: 1 }, transportOnly: true });
assert.deepStrictEqual(o, [{ type: 'transport', ok: true, reason: null }]);
assert.strictEqual(M.moveOptions({ tile: rival, home, transport: { links: 2, active: 2 }, transportOnly: true })[0].reason, 'links_busy');
assert.strictEqual(M.moveOptions({ tile: mine, home, transport: { links: 0, active: 0 }, transportOnly: true })[0].reason, 'no_link');
assert.deepStrictEqual(M.moveOptions({ tile: { type: 'land', settle: { possible: true } }, home, transportOnly: true }), [], 'empty land takes no transport');
// without the flag a rival POP still gets the hostile types only
assert.ok(!M.moveOptions({ tile: rival, home, transport: { links: 2, active: 0 } }).some((x) => x.type === 'transport'));
});
// ------------------------------------------------------------------ strings of the new screens
const files = ['screens/trade.js', 'screens/world.js', 'screens/cargo-ui.js', 'screens/reports.js', 'screens/map.js', 'screens/send.js', 'screens/movements.js', 'alertkinds.js'];
const SRC = files.map((f) => fs.readFileSync(path.join(ROOT, f), 'utf8')).join('\n');
test('every static string key the trade / world / report / map / send screens use exists in en and nb', () => {
const used = new Set();
for (const m of SRC.matchAll(/\b(?:App\.)?t\('([a-zA-Z0-9_.]+)'/g)) if (!m[1].endsWith('.')) used.add(m[1]);
for (const m of SRC.matchAll(/\bt\([^()']*\? '([a-z0-9_]+\.[a-zA-Z0-9_.]+)' : '([a-z0-9_]+\.[a-zA-Z0-9_.]+)'/g)) { used.add(m[1]); used.add(m[2]); }
assert.ok(used.size > 150, 'found the keys (' + used.size + ')');
const missing = [];
for (const l of I.LANGS) for (const k of used) if (!I.strings[l][k]) missing.push(l + ' ' + k);
assert.deepStrictEqual(missing, []);
});
test('dynamic string keys: tabs, statuses, roles, validation codes, ranking tabs, build refusals, send reasons', () => {
const want = ['trd.tab.offers', 'trd.tab.new', 'trd.tab.mine', 'trd.tab.send', 'trd.role.poster', 'trd.role.acceptor', 'wld.rank.operators', 'wld.rank.alliances', 'wld.rank.attackers', 'wld.rank.defenders',
'wld.build.why.ended', 'wld.build.why.forbidden', 'send.reason.no_alliance', 'send.reason.own_site', 'send.invalid.no_alliance', 'send.invalid.own_site', 'send.invalid.landing_scan_or_attack_only',
'tile.backbone', 'report.type.landing', 'rep.attackerWon', 'rep.defenderWon', 'rep.tab.mine', 'rep.tab.alliance', 'rep.folder.empty', 'rep.share.done', 'rep.share.already', 'nav.trade', 'nav.world', 'screen.trade', 'screen.world']
.concat(['all', 'open', 'accepted', 'completed', 'cancelled', 'expired', 'void'].map((s) => 'trd.status.' + s))
.concat(['giveRes', 'wantRes', 'giveAmount', 'wantAmount', 'maxDistance', 'terms'].map((s) => 'trd.v.' + s));
for (const l of I.LANGS) for (const k of want) assert.ok(I.strings[l][k], l + ' ' + k);
// trade_terms paths the rules can report all have a message
const R = require('../public/js/rules.js');
for (const bad of [{ giveRes: 'x' }, { wantRes: 'x' }, { wantRes: 'fiber' }, { giveAmount: 0 }, { wantAmount: 0 }, { maxDistance: 0 }]) {
const r = R.tradeTermsCheck(Object.assign({ giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: 30 }, bad));
assert.ok(!r.ok);
assert.ok(I.strings.en['trd.v.' + r.errors[0].path], 'message for ' + r.errors[0].path);
}
});
test('the new screens put no player-controlled text through HTML sinks', () => {
const code = SRC.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(code), 'no HTML injection sinks');
});
test('every screen file of the new screens is loaded by index.html, strings before screens', () => {
const html = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
const order = (f) => html.indexOf('js/' + f + '"');
for (const f of ['strings/alerts.js', 'strings/trade.js', 'strings/world.js', 'endcore.js', 'alertkinds.js', 'screens/cargo-ui.js', 'screens/trade.js', 'screens/world.js']) assert.ok(order(f) > 0, f + ' is in index.html');
assert.ok(order('strings/world.js') < order('main.js'), 'strings before the shell');
assert.ok(order('endcore.js') < order('screens/world.js'));
assert.ok(order('milstate.js') < order('alertkinds.js') && order('main.js') < order('alertkinds.js'), 'alert kinds need App and App.mil');
assert.ok(order('screens/cargo-ui.js') < order('screens/trade.js') && order('screens/cargo-ui.js') < order('screens/world.js'));
});
test('icons used by the new screens exist in the sprite', () => {
const sprite = fs.readFileSync(path.join(__dirname, '..', 'public', 'icons', 'sprite.svg'), 'utf8');
const have = new Set((sprite.match(/id="i-([a-z_-]+)"/g) || []).map((s) => s.slice(6, -1)));
const used = new Set();
for (const f of ['screens/trade.js', 'screens/world.js']) for (const m of fs.readFileSync(path.join(ROOT, f), 'utf8').matchAll(/\bicon\('([a-z_-]+)'/g)) used.add(m[1]);
used.delete('b-'); // icon('b-' + building): the building icons
used.add('b-' + D.TRANSPORT.building);
for (const i of used) assert.ok(have.has(i), 'icon ' + i);
});
test('every browser script under public/js parses (a syntax error in one file kills every screen after it)', () => {
const vm = require('vm');
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : []));
const files = walk(ROOT);
assert.ok(files.length > 30, 'found the scripts (' + files.length + ')');
for (const f of files) assert.doesNotThrow(() => new vm.Script(fs.readFileSync(f, 'utf8'), { filename: f }), f);
});

View file

@ -177,7 +177,7 @@ test('shipping: members feed the stockpile by transport; strangers cannot; a shi
assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden');
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP");
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 501 } })).code, 'capacity_exceeded');
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: D.TRANSPORT.capacityPerLink + 1 } })).code, 'capacity_exceeded');
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found');
const before = stock(a2.townId);

View file

@ -13,9 +13,9 @@ test('transport: capacity and links come from the Internet exchange; cargo arriv
const seen = [];
M.hooks.transportArrived.push((ctx, mv, r) => seen.push({ id: mv.id, added: r.added, extra: mv.extra }));
const send = (cargo) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo });
assert.throws(() => send({ fiber: 600 }), (e) => e.code === 'capacity_exceeded');
assert.throws(() => send({ fiber: D.TRANSPORT.capacityPerLink + 100 }), (e) => e.code === 'capacity_exceeded');
assert.throws(() => send({ fiber: 0 }), (e) => e.code === 'validation_failed');
assert.throws(() => send({ fiber: 5000 }), (e) => e.code === 'capacity_exceeded');
assert.throws(() => send({ fiber: 10 * D.TRANSPORT.capacityPerLink }), (e) => e.code === 'capacity_exceeded');
const noIx = T.addOperator(h, 'no-ix', { x: 12, y: 0, infra: { internet_exchange: 0 } });
assert.throws(() => h.run('sendTransport', { userId: noIx.userId, fromTownId: noIx.townId, toTownId: b.townId, cargo: { fiber: 10 } }), (e) => e.code === 'no_transport_link');
const before = T.town(h, a.townId).fiber;

View file

@ -142,7 +142,7 @@ test('loot, cache, siege, loyalty, scan, incumbent, decommission, transport plan
const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } };
assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true);
assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link');
assert.equal(R.transportPlan(town, { fiber: 501 }, 0, 0).code, 'capacity_exceeded');
assert.equal(R.transportPlan(town, { fiber: D.TRANSPORT.capacityPerLink + 1 }, 0, 0).code, 'capacity_exceeded');
assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources');
assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed');
assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed');

View file

@ -0,0 +1,21 @@
'use strict';
/* Regression: sharing a report when no reportCleanup event is pending used to throw (ensureCleanup needs ctx.enqueue, which a plain
* command ctx lacks) and surface as a 500. Found in a browser run with hand-made reports. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const A = require('../server/alliances');
test('reportShare works when no cleanup event is pending and then schedules one', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice');
const al = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, 'Alpha', 'ALP', a.opId, h.clock.now()).lastInsertRowid);
A.addMember(h.db, al, a.opId, 'leader', h.clock.now());
const rid = Number(h.db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)', h.worldId, 'scan', h.clock.now(), h.clock.now() + 1000, '{}', '{}').lastInsertRowid);
h.db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', rid, a.userId, 'attacker');
assert.equal(h.db.get("SELECT COUNT(*) n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 0);
const r = h.run('reportShare', { userId: a.userId, reportId: rid });
assert.equal(r.changed, true);
assert.equal(h.db.get("SELECT COUNT(*) n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 1);
assert.equal(h.run('reportShare', { userId: a.userId, reportId: rid }).changed, false);
});

View file

@ -84,7 +84,7 @@ test('trade: terms - 1:2 ratio band, capacity, distinct resources, links, resour
const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } });
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 501 })).code, 'capacity_exceeded');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: D.TRANSPORT.capacityPerLink, wantAmount: D.TRANSPORT.capacityPerLink + 1 })).code, 'capacity_exceeded');
assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed');