Merge upstream main and reconcile community exchanges

This commit is contained in:
Nick Bouwhuis 2026-10-24 15:15:22 +02:00
commit e0e1500b8e
24 changed files with 2265 additions and 346 deletions

View file

@ -4,22 +4,23 @@ const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const root = path.join(__dirname, '..');
test('build stamps version and date into the site', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
const html = fs.readFileSync(path.join(root, '_site', 'index.html'), 'utf8');
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
const html = fs.readFileSync(path.join(OUT, 'index.html'), 'utf8');
assert.match(html, /const APP_VERSION='9\.9\.9'/);
assert.match(html, /"softwareVersion": "9\.9\.9"/);
assert.match(fs.readFileSync(path.join(root, '_site', 'sitemap.xml'), 'utf8'), /<lastmod>2030-01-01<\/lastmod>/);
assert.match(fs.readFileSync(path.join(OUT, 'sitemap.xml'), 'utf8'), /<lastmod>2030-01-01<\/lastmod>/);
for (const f of ['favicon.svg', 'favicon.ico', 'apple-touch-icon.png', 'icon-192.png', 'icon-512.png', 'site.webmanifest', 'robots.txt', 'images/og-image.png', '404.html', 'CNAME', 'version.json']) {
assert.ok(fs.existsSync(path.join(root, '_site', f)), `${f} is shipped`);
assert.ok(fs.existsSync(path.join(OUT, f)), `${f} is shipped`);
}
});
test('version.json carries the release notes from the changelog', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
const v = JSON.parse(fs.readFileSync(path.join(root, '_site', 'version.json'), 'utf8'));
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
const v = JSON.parse(fs.readFileSync(path.join(OUT, 'version.json'), 'utf8'));
assert.equal(v.version, '1.0.0');
assert.ok(v.notes.length >= 5);
assert.ok(v.notes.every((n) => !n.startsWith('-')));
@ -34,3 +35,8 @@ test('head carries the SEO and social metadata', () => {
JSON.parse(block.replace(/<\/?script[^>]*>/g, ''));
}
});
test('a release build refuses to ship without release notes', () => {
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } }));
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected');
});

View file

@ -25,7 +25,7 @@ test('a year of scripted play stays healthy', () => {
const { ev, errors } = load();
seed(ev, 7);
ev("ACT.start({})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1});ACT.rs({city:'fra'})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'})");
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});ACT.launchBB({city:'ams'})");
for (let d = 0; d < 360; d++) {
ev('dayTick()');
@ -43,7 +43,7 @@ test('every incident and event type fires and clears cleanly', () => {
seed(ev, 3);
ev("ACT.start({});S.cash=1e8;S.lvl=4;S.day=100");
ev("for(const c of ['ams','lon','nyc','mos','mnl'])ACT.buildPop({city:c})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1});ACT.rs({city:'fra'})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'})");
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()");
ev("UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2");
ev("const df=S.links.find(l=>l.kind==='df');ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day");
@ -97,11 +97,11 @@ test('saves never resurrect a bankrupt game', () => {
test('LAGs add members, capacity and cost to transit, IX ports and PNIs', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;S.lvl=4;S.pops.fra.rgen=2;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true})");
ev("const t=S.transit[0];window.__c0=S.cash;ACT.lagT({id:t.id,d:1});ACT.lagT({id:t.id,d:1});ACT.lagIx({city:'fra',d:1});compute()");
assert.equal(ev('S.transit[0].n'), 3);
assert.equal(ev("S.ixn.fra"), 2);
assert.equal(ev("__c0-S.cash"), 1500 * 2 + 1500, 'two transit members and one IX member were charged');
assert.equal(ev("__c0-S.cash"), 1500 * 2 + ev("ixPortMo('fra',1)"), 'two transit members and one IX member were charged');
assert.equal(ev("ixCap('fra')"), 190);
assert.equal(ev("R.cost.transit>0"), true);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:2})");

View file

@ -20,17 +20,35 @@ function load(opts = {}) {
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; }; }
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
window.Path2D = class { moveTo() {} quadraticCurveTo() {} closePath() {} };
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);
},
});
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(`Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`);
}
module.exports = { load, seed };

193
tests/issues.test.js Normal file
View file

@ -0,0 +1,193 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function base(ev) {
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
}
test('#4 several transits in one city share the load instead of filling one by one', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()");
const u = JSON.parse(ev("JSON.stringify(S.transit.map(t=>R.useT[t.id]||0))"));
assert.equal(u.length, 2);
assert.ok(u[0] > 0 && u[1] > 0, `both carry traffic (${u})`);
assert.ok(Math.abs(u[0] - u[1]) / (u[0] + u[1]) < 0.35, `roughly balanced (${u})`);
// local exits still win over far ones: a transit in London is not used while Frankfurt has room
ev("ACT.buildPop({city:'lon'});UI.via=null;openLinkModal('fra','lon');ACT.buildLink({tier:3});closeModal();ACT.buyTransit({city:'lon',net:'tly',tier:1});compute()");
assert.equal(ev("R.useT[S.transit.find(t=>t.city==='lon').id]||0"), 0, 'remote transit stays idle');
// backup-only still means backup only
ev("S.transit[1].pref='low';compute()");
assert.equal(ev("R.useT[S.transit[1].id]||0"), 0);
assert.deepEqual(errors, []);
});
test('#5 export writes a file and import restores it, with checks', () => {
const { ev, dom, errors } = load();
const window = dom.window;
base(ev);
ev("S.name='Export Me';S.cash=1234567;compute()");
let blobText = null;
window.URL.createObjectURL = b => { blobText = b; return 'blob:x'; };
window.URL.revokeObjectURL = () => {};
window.HTMLAnchorElement.prototype.click = function () { window.__dl = this.download; };
ev("ACT.exportSave()");
assert.match(window.__dl, /^series-of-tubes-export-me-\d{4}-\d\d-\d\d\.json$/);
const txt = ev("JSON.stringify({app:'series-of-tubes',version:APP_VERSION,S})");
assert.ok(blobText);
ev("S.cash=1;S.name='Other'");
assert.match(ev(`parseSave('{"nope":1}').err`), /does not look/);
assert.match(ev(`parseSave('not json').err`), /not valid JSON/);
assert.match(ev(`parseSave(JSON.stringify(Object.assign(JSON.parse(${JSON.stringify(txt)}).S,{lost:true}))).err`), /bankrupt/);
ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`);
assert.equal(ev("S.name"), 'Export Me');
assert.equal(ev("S.cash"), 1234567);
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), 'Export Me', 'saved on this device');
ev("showHelp()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Export save.*Import a save/);
assert.deepEqual(errors, []);
});
test('#6 full transit, IX, caches and routers show up in the NOC and on the map', () => {
const { ev, errors } = load();
base(ev);
ev("S.pops.fra.bb.d=5000;ACT.buyTransit({city:'fra',net:'cog',tier:0});ACT.buyIx({city:'ams',tier:0,signed:true});S.caches.push({id:'cx',city:'fra',net:'akm'});compute()");
ev("R.nodeLoad.fra=R.nodeCap.fra;UI.hotMap=hotByCity()");
const ks = JSON.parse(ev("JSON.stringify(hotPorts().map(h=>h.k))"));
for (const k of ['t', 'c', 'r']) assert.ok(ks.includes(k), `${k} is reported hot (${ks})`);
assert.ok(ev("UI.hotMap.fra&&UI.hotMap.fra.t>=0.9"));
ev("ACT.leftTab({t:'noc'})"); // NOC reads R as it is now (router forced hot above)
const noc = ev("document.getElementById('leftBody')?document.getElementById('leftBody').textContent:document.body.textContent");
assert.match(noc, /running hot/);
assert.match(noc, /Akamaybe Box cache/);
assert.match(noc, /transit/);
ev("draw&&draw(performance.now())");
assert.deepEqual(errors, []);
});
test('some routers take forever to boot, PacketOinkers most of all', () => {
const { ev, errors } = load();
base(ev);
const pct = JSON.parse(ev("JSON.stringify(RG.map((G,g)=>{let n=0;for(const c of ALLC){S.pops[c]=S.pops[c]||{rgen:g,routers:1};S.pops[c].rgen=g;if(slowBoot(c))n++;}return n/ALLC.length;}))"));
assert.ok(pct[0] < pct[2] && pct[2] > 0.2 && pct[0] < 0.3, `bigger chassis are slow more often (${pct})`);
assert.match(ev("RG[2].chip"), /PacketOinker/);
// find a slow and a fast POP and crash them
ev("for(const c of ALLC)if(c!=='fra')delete S.pops[c];S.pops.fra.rgen=2;S.pops.fra.routers=1");
const slowCity = ev("ALLC.find(c=>{S.pops[c]={rgen:2,routers:1,down:0};const s=slowBoot(c);if(!s)delete S.pops[c];return s;})");
ev(`for(const c of Object.keys(S.pops))if(c!=='${slowCity}')delete S.pops[c];S.transit=[];S.ixp={};for(let i=0;i<800&&!S.inc.some(x=>x.type==='crash');i++){fireFailure();S.inc=S.inc.filter(x=>x.type==='crash');}`);
const inc = JSON.parse(ev("JSON.stringify(S.inc.find(i=>i.type==='crash'))"));
assert.ok(inc.slow, 'crash on a slow booter is flagged');
assert.ok(inc.until - ev('S.day') >= 4, 'and lasts longer');
ev(`S.cash=1e6;ACT.fixInc({id:'${inc.id}'})`);
assert.equal(ev(`S.inc.find(i=>i.id==='${inc.id}').until`), ev('S.day+1'), 'rushing it still takes a day');
ev(`selectCity('${slowCity}');ACT.tab({t:'infra'})`);
assert.match(ev("document.getElementById('panelBody').textContent"), /a slow one/);
assert.deepEqual(errors, []);
});
test('the network name opens a menu with save, load and start over', () => {
const { ev, errors } = load();
base(ev);
ev("document.querySelector('[data-act=menu]').click()");
const t = ev("document.getElementById('modalCard').textContent");
for (const w of ['Export save', 'Import a save', 'Start a new network', 'Back to the map']) assert.ok(t.includes(w), w);
ev("document.querySelector('#modalCard [data-act=resetAsk]').click()");
assert.match(ev("document.getElementById('modalCard').textContent"), /cannot be undone/);
ev("document.querySelector('#modalCard [data-act=newgame]').click()");
assert.equal(ev("!!localStorage.getItem('sot-save-v1')&&JSON.parse(localStorage.getItem('sot-save-v1')).day>0"), false);
assert.deepEqual(errors, []);
});
test('a rare global outage shows a banner, dents traffic and only happens once', () => {
const { ev, errors } = load();
base(ev);
ev("compute()");const before = ev("R.demand");
ev("elephant();compute();renderAll()");
assert.ok(ev("R.demand") < before * 0.8);
assert.equal(ev("document.getElementById('mega').hidden"), false);
for (let i = 0; i < 5; i++) ev("dayTick()");
ev("renderAll()");
assert.equal(ev("document.getElementById('mega').hidden"), true);
assert.equal(ev("S.phpDone"), true);
assert.deepEqual(errors, []);
});
test('badges unlock with a rarity, persist across games, and secret ones stay hidden', () => {
const { ev, errors } = load();
base(ev);
ev("localStorage.removeItem('sot-badges');S.ach={};compute();checkGoals();ACT.leftTab({t:'goals'})");
let txt = ev("document.body.textContent");
assert.match(txt, /Badges/);
assert.match(txt, /\?\?\?/, 'secret badges are hidden');
ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute();checkGoals()");
assert.ok(ev("S.ach.hello!==undefined"), 'first peering badge');
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-badges')).hello"), 'remembered across games');
ev("S.stats.sharks=3;checkGoals()");
assert.ok(ev("S.ach.bait!==undefined&&S.ach.shark!==undefined"));
ev("ACT.leftTab({t:'goals'})");
txt = ev("document.body.textContent");
assert.match(txt, /Legendary/);
assert.equal(ev("GOALS.some(g=>g.id==='gi')&&GOALS.some(g=>g.id==='t10')"), true);
assert.equal(ev("document.getElementById('hBank').className"), 'badge');
assert.deepEqual(errors, []);
});
test('Auto-TE spills overflow onto an alternate path when the shortest one is full', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("for(const c of ['ams','lon','par'])ACT.buildPop({city:c});const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',0);L('ams','lon',1,'uly');L('fra','par',1);L('par','lon',1,'chn');ACT.buyTransit({city:'lon',net:'lvl',tier:1});compute()");
const dem = ev("R.demand");
assert.ok(ev("R.served") < dem - 1, 'without TE the 10G link caps it');
ev("ACT.buyTE();compute()");
assert.ok(ev("R.served") > dem * 0.97, 'with TE nearly everything is served');
assert.ok(ev("R.teMoved") > 1);
assert.ok(ev("R.load[S.links.find(l=>l.a==='fra'&&l.b==='par').id]") > 1, 'the Paris path carries the overflow');
ev("ACT.leftTab({t:'noc'})");
assert.match(ev("document.body.textContent"), /Auto-TE/);
ev("ACT.teToggle();compute()");
assert.ok(ev("R.served") < dem - 1, 'switching it off goes back to shortest path only');
assert.deepEqual(errors, []);
});
test('rare badges hook into incidents and deals', () => {
const { ev, errors } = load();
base(ev);
ev("addInc({type:'cut',ref:'x',until:S.day+1,msg:'A crocodile took a bite. A ship dragged its anchor.'});checkGoals()");
assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe!==undefined"));
ev("S.stats.survived=100;checkGoals()");
assert.ok(ev("S.ach.unbreak!==undefined"));
assert.equal(ev("BADGES.length>=46&&new Set(BADGES.map(b=>b.id)).size===BADGES.length"), true);
assert.deepEqual(errors, []);
});
test('#7 NOC legend, sortable network table and transit destinations', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();ACT.dash()");
let t = ev("document.getElementById('dashCard').textContent");
assert.match(t, /Who your transit carries/);
assert.match(t, /IX peering/, 'legend explains the colours');
const top = JSON.parse(ev("JSON.stringify(transitTop(S.transit.map(t=>t.id),3))"));
assert.ok(top.length > 0 && top[0][1] > 0);
assert.equal(ev(`typeof offTransitHint('${top[0][0]}','fra')`), 'string');
ev("ACT.dashSort({k:'cost'})");
assert.equal(ev("UI.dashSort"), 'cost');
ev("ACT.dashSort({k:'cost'})");
assert.equal(ev("UI.dashDir"), 1, 'second tap flips the order');
ev("selectCity('fra');ACT.tab({t:'up'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Top destinations on this port/);
assert.deepEqual(errors, []);
});
test('#11 pausing freezes the dots on the links', () => {
const { ev, errors } = load();
base(ev);
ev("ACT.animSet({v:'on'});UI.speed=1;last=1000;frame(1016)");
const t0 = ev("animT");
ev("UI.speed=0;frame(1100);frame(1400)");
assert.equal(ev("animT"), t0, 'clock stands still while paused');
ev("UI.speed=1;frame(1416)");
assert.ok(ev("animT") > t0, 'and moves again on play');
assert.deepEqual(errors, []);
});

170
tests/modes.test.js Normal file
View file

@ -0,0 +1,170 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('sandbox: endless money, every unlock, nothing breaks, no badges', () => {
const { ev, errors } = load();
ev("ACT.modeSet({m:'sandbox'});ACT.start({})");
assert.equal(ev("S.mode"), 'sandbox');
assert.equal(ev("S.lvl"), 4);
ev("S.cash=5;for(let i=0;i<120;i++)dayTick()");
assert.ok(ev("S.cash") >= 1e8, 'money refills');
assert.equal(ev("S.stats.incidents"), 0, 'no failures');
assert.equal(ev("Object.keys(S.ach||{}).length"), 0, 'no badges in sandbox');
assert.match(ev("document.getElementById('hAsn').textContent"), /Sandbox/);
assert.deepEqual(errors, []);
});
test('scenarios: rules apply, goals complete, deadlines fail, seeds repeat', () => {
const { ev, errors } = load();
ev("ACT.scenarios()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Weekly challenge/);
ev("ACT.startScn({id:'stg'})");
assert.equal(ev("S.home"), 'stg');
ev("ACT.buyTransit({city:'stg',net:'drz',tier:1})");
assert.equal(ev("S.transit.length"), 0, 'no transit in the Spätzle-IX scenario');
ev("ACT.startScn({id:'redsea',sure:1})");
assert.equal(ev("cablesOk('mrs','sin').length"), 0, 'Red Sea routes are gone');
assert.ok(ev("cablesFor('mrs','sin').length") > 0);
ev("ACT.startScn({id:'carnaval',sure:1})");
assert.ok(ev("S.biz.some(b=>b.type==='event'&&b.start===90)"), 'Carnaval is pre-booked');
ev("S.day=99;S.scn.done=0;dayTick()");
assert.ok(ev("!!S.scn.failed"), 'deadline passes');
assert.match(ev("document.getElementById('modalCard').textContent"), /Time's up/);
// weekly: same seed gives the same first random numbers
ev("ACT.startWeekly({sure:1})");const a = ev("[Math.random(),Math.random()].join()");
ev("ACT.startWeekly({sure:1})");const b = ev("[Math.random(),Math.random()].join()");
assert.equal(a, b);
ev("S.stats.peak=1234;S.day=364;dayTick()");
assert.match(ev("document.getElementById('modalCard').textContent"), /score/i);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).weekly"));
assert.deepEqual(errors, []);
});
test('completing a scenario records it and unlocks a badge', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-scn');ACT.startScn({id:'spat'});R.reach=1;R.served=200;scnTick(10)");
assert.equal(ev("S.scn.done"), 10);
assert.ok(ev("!!JSON.parse(localStorage.getItem('sot-scn')).spat"));
ev("checkBadges()");
assert.ok(ev("S.ach.scen1!==undefined"));
assert.deepEqual(errors, []);
});
test('traceroute shows hops, the exit and the AS path', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'ams',net:'lvl',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()");
let r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.match(r.text, /traceroute to/);
assert.match(r.text, /ams/, 'goes via Amsterdam to transit');
assert.deepEqual(r.asPath.slice(0, 2), [ev('S.asn'), ev("NET.lvl.asn")]);
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'akm'}))"));
assert.match(r.why, /peering/i, 'open network over the IX route server');
r = JSON.parse(ev("JSON.stringify(traceroute('ams',{city:'fra'}))"));
assert.match(r.text, /fra/);
ev("S.links[0].cut=S.day+3;compute()");
r = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'nfx'}))"));
assert.ok(/unreachable/.test(r.text) || /peering/i.test(r.why));
ev("ACT.trace({city:'fra'})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Traceroute/);
ev("ACT.share()");
assert.deepEqual(errors, []);
});
test('conferences: register, attend, and selective peers get easier for a while', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0");
ev("S.day=confDay(CONFS.find(c=>c.c==='fra'),0)-20;ACT.leftTab({t:'deals'})");
assert.match(ev("document.body.textContent"), /DENOG-ish/);
const key = ev("upcomingConfs(30).find(c=>c.c==='fra').key");
ev(`ACT.confGo({key:'${key}'})`);
const need0 = ev("(()=>{R.demTo.nfx=0;return peerOk('nfx','ix','fra').why})()");
ev("for(let i=0;i<21;i++)dayTick()");
assert.ok(ev("S.conf&&S.conf.until>S.day"), 'conference glow is on');
const need1 = ev("(()=>{R.demTo.nfx=0;return peerOk('nfx','ix','fra').why})()");
assert.notEqual(need0, need1, 'threshold dropped');
ev("checkGoals()");
assert.ok(ev("S.ach.hallway!==undefined"));
assert.deepEqual(errors, []);
});
test('the guided tutorial walks through the first steps and can be skipped', () => {
const { ev, dom, errors } = load();
dom.window.__TUBES_TUT__ = true;
ev("localStorage.removeItem('sot-tut');ACT.start({})");
assert.equal(ev("document.getElementById('coach').hidden"), false);
assert.match(ev("document.getElementById('coach').textContent"), /Launch broadband/);
ev("ACT.launchBB({city:S.home});renderAll()");
assert.match(ev("document.getElementById('coach').textContent"), /Step 2/);
ev("ACT.tutSkip()");
assert.equal(ev("document.getElementById('coach').hidden"), true);
assert.equal(ev("localStorage.getItem('sot-tut')"), '1');
assert.deepEqual(errors, []);
});
test('animations can be switched off, on or follow the system, and the choice sticks', () => {
const { ev, errors } = load();
ev("ACT.start({});ACT.menu()");
assert.match(ev("document.getElementById('modalCard').textContent"), /Animations/);
ev("ACT.animSet({v:'off'})");
assert.equal(ev("document.documentElement.classList.contains('no-anim')"), true);
assert.equal(ev("animOn()"), false);
ev("floater(0,0,'x','#000')");
assert.equal(ev("FLOATS.length"), 0, 'no floating text when off');
assert.equal(ev("localStorage.getItem('sot-anim')"), 'off');
ev("ACT.animSet({v:'on'})");
assert.equal(ev("document.documentElement.classList.contains('anim-force')"), true);
assert.equal(ev("animOn()"), true);
ev("ACT.soundSet({v:'off'})");
assert.equal(ev("UI.muted"), true);
assert.deepEqual(errors, []);
});
test('half speed and deeper zoom', () => {
const { ev, errors } = load();
ev("ACT.start({});ACT.speed({v:0.5})");
assert.equal(ev("UI.speed"), 0.5);
assert.equal(ev("document.getElementById('sp0.5').classList.contains('on')"), true);
ev("ACT.speed({v:7})");
assert.equal(ev("UI.speed"), 0.5, 'bogus speeds are ignored');
ev("cam.z=1;for(let i=0;i<40;i++)zoomAt(100,100,1.2)");
assert.equal(ev("cam.z"), 6);
assert.deepEqual(errors, []);
});
test('the map draws at every zoom, with and without animations, without throwing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;ACT.launchBB({city:'fra'});for(const c of ['ams','lon','nyc'])ACT.buildPop({city:c});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();compute()");
for (const z of [0.35, 0.8, 1.4, 3, 6]) ev(`cam.z=${z};draw(performance.now());draw(0)`);
ev("ACT.animSet({v:'off'});frame(performance.now()+16)");
assert.ok(ev("ctx&&ctx.calls.n") > 100, 'the canvas was actually drawn on');
assert.deepEqual(errors, []);
});
test('RouteScript: parses safely, reports errors helpfully, and changes routing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();compute()");
let p = JSON.parse(ev("JSON.stringify(teParse('spill at 80%\\ncap transit cogentle at 3 gbps\\nprefer ix for goggle\\nnonsense here\\navoid transit for gogle'))"));
assert.equal(p.errors.length, 2, 'the nonsense line and the typo fail');
assert.match(p.errors[1], /Did you mean Goggle/, 'typos get a suggestion');
p = JSON.parse(ev("JSON.stringify(teParse('avoid transit for zzzzqqq').errors)"));
assert.match(p[0], /unknown network/);
assert.match(ev("teParse('drain pariss').errors[0]"), /Did you mean Paris/);
assert.equal(ev("teParse('alert(1)').n"), 0, 'nothing is ever evaluated');
const cog = "R.useT[S.transit.find(t=>t.net==='cog').id]||0";
const before = ev(cog);
ev("ACT.teEdit();document.getElementById('teSrc').value='cap transit cogentle at 3 gbps';ACT.teDeploy()");
assert.ok(ev(cog) <= 3.0001 && before > 3, `Cogentle capped (${before} -> ${ev(cog)})`);
assert.ok(ev("R.useT[S.transit.find(t=>t.net==='lvl').id]") > 0, 'overflow went to the other upstream');
// a fat-fingered deploy earns its badge
ev("ACT.teEdit();document.getElementById('teSrc').value='drain frankfurt\\ncap transit level tree at 0 gbps\\ncap transit cogentle at 0 gbps';ACT.teDeploy();checkGoals()");
assert.ok(ev("S.ach.fat!==undefined"));
// errors block a deploy
ev("ACT.teEdit();document.getElementById('teSrc').value='spill at 5%';ACT.teDeploy()");
assert.match(ev("document.getElementById('modalCard').textContent"), /commit failed/);
ev("ACT.teClear()");
assert.equal(ev("S.te.script"), '');
assert.deepEqual(errors, []);
});

View file

@ -34,7 +34,7 @@ test('a snubbing peer tears down an existing session and the Request button expl
assert.ok(k, 'found a snub starting at an IX');
const [id, c, d] = k.split('@');
ev(`S.day=${d}`);
ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1});S.peers['${id}@${c}']=true;compute()`);
ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1,signed:true});S.peers['${id}@${c}']=true;compute()`);
assert.equal(ev(`ixSessions('${c}').has('${id}')`), true);
ev('dayTick()');
assert.equal(ev(`!!S.peers['${id}@${c}']`), false, 'session torn down');
@ -56,9 +56,9 @@ test('remote peering is offered but costs more, gives less and gets refused more
const txt = () => ev("document.getElementById('panelBody').textContent");
ev("ACT.buyIx({city:'ams',tier:1});compute()");
assert.equal(ev("isRemote('ams')"), true);
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*1.5)"), 'reseller markup');
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*1.5*ixMul('ams'))"), 'reseller markup');
assert.equal(ev("ixCap('ams')"), ev("PORT[1].g*0.8"), 'oversubscribed port');
const refusers = JSON.parse(ev("JSON.stringify(ixMembers('ams').filter(noRemote))"));
const refusers = JSON.parse(ev("JSON.stringify(ixMembers('ams').filter(id=>noRemote(id)&&!snub(id,'ams')))"));
assert.ok(refusers.length > 0, 'some members refuse remote peers');
const r = JSON.parse(ev(`JSON.stringify(peerOk('${refusers[0]}','ix','ams'))`));
assert.equal(r.ok, false); assert.equal(r.remote, true);
@ -73,60 +73,107 @@ test('remote peering is offered but costs more, gives less and gets refused more
assert.deepEqual(errors, []);
});
test('Amsterdam has a second IX, FRIES-IX, with free ports up to 400G', () => {
test('DE-KICKS hides prices, haggles, harmonises upwards, auto-enrolls add-ons and fights to keep you', () => {
const { ev, errors } = load();
setup(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(cityIxes('ams'))")), ['ams', 'ams:fries']);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Price on request/);
ev("ACT.buyIx({city:'fra',tier:1})");
assert.equal(ev("S.ixp.fra===undefined"), true, 'no port without signing');
assert.match(ev("document.getElementById('modalCard').textContent"), /Confidential/);
ev("S.dk.q.m=1.5;ACT.dkAccept()");
assert.equal(ev("S.ixp.fra"), 1);
assert.equal(ev("ixPortMo('fra',1)"), ev("Math.round(PORT[1].ix*1.5*ixMul('fra'))"));
// haggling always moves something
ev("S.dk.q={city:'mad',tier:1,m:1.5,h:0}");
for (let i = 0; i < 3; i++) ev("if(S.dk.q)ACT.dkHaggle()");
assert.ok(ev("!S.dk.q||S.dk.q.m!==1.5||S.dk.stall>S.day"));
// yearly harmonisation
const m0 = ev("S.dk.m.fra");
ev("let n=0;while(n++<400){S.day++;if((S.day+hstr('fra')%90)%365===0)break;}S.day--;dkTick(S.day+1)");
assert.ok(ev("S.dk.m.fra") > m0, 'price went up');
// add-ons show up on the invoice until you opt out (twice)
ev("S.dk.add.fra=[{n:'Route Server Gold',blurb:'gold',mo:500,day:S.day}]");
assert.equal(ev("dkAddonMo('fra')"), 500);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /auto-enrolled/);
ev("ACT.dkOptOut({city:'fra',n:'Route Server Gold'})");
assert.equal(ev("S.dk.add.fra.length"), 1, 'first click only asks');
ev("ACT.dkOptOut({city:'fra',n:'Route Server Gold'})");
assert.equal(ev("S.dk.add.fra.length"), 0);
// leaving: a retention offer first
ev("ACT.cancelIx({city:'fra'});ACT.cancelIx({city:'fra'})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Before you go/);
const full = ev("ixPortMo('fra',1)");
ev("ACT.dkStay({city:'fra'})");
assert.ok(ev("ixPortMo('fra',1)") < full, 'promo price');
ev("ACT.cancelIx({city:'fra'});ACT.cancelIx({city:'fra'})");
assert.equal(ev("S.ixp.fra"), undefined, 'second time you can actually leave');
ev("ACT.buildPop({city:'ams'})");
assert.equal(ev("ixPortMo('ams',1)"), ev("Math.round(PORT[1].ix*ixMul('ams'))"), 'other IXs keep open pricing');
assert.deepEqual(errors, []);
});
test('Amsterdam has FRIES-IX, with free ports up to 400G', () => {
const { ev, errors } = load();
setup(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(ixIdsIn('ams'))")), ['ams', 'ams~2', 'ams~3']);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1;compute()");
const cash = () => ev('S.cash');
let c0 = cash();
ev("ACT.buyIx({city:'ams:fries',tier:2})");
assert.equal(ev("S.ixp['ams:fries']"), 2);
ev("ACT.buyIx({city:'ams~3',tier:2})");
assert.equal(ev("S.ixp['ams~3']"), 2);
assert.equal(cash(), c0, '400G port is free');
assert.equal(ev("S.ixp.ams"), undefined, 'HAMS-IX is separate');
c0 = cash();
ev("ACT.lagIx({city:'ams:fries',d:1})");
ev("ACT.lagIx({city:'ams~3',d:1})");
assert.equal(cash(), c0, 'LAG members are free too');
assert.equal(ev("ixPortMo('ams:fries',3)"), ev('PORT[3].ix'), '800G costs the usual price');
ev("ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams:fries'});compute()");
assert.ok(ev("ixSessions('ams:fries').has('drz')"));
assert.equal(ev("ixSessions('ams:fries').has('ggl')"), false, 'Goggle is not a member');
assert.equal(ev("R.useIx['ams:fries']!==undefined&&R.useIx.ams!==undefined"), true, 'both fabrics carry traffic');
assert.equal(ev("R.cost.ix"), ev("PORT[1].ix"), "only the HAMS-IX port is billed");
assert.equal(ev("ixPortMo('ams~3',3)"), ev("Math.round(PORT[3].ix*ixMul('ams~3'))"), '800G costs the usual price');
ev("ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams~3'});compute()");
assert.ok(ev("ixSessions('ams~3').has('drz')"));
assert.equal(ev("ixSessions('ams~3').has('ggl')"), false, 'Goggle is not a member');
assert.equal(ev("R.useIx['ams~3']!==undefined&&R.useIx.ams!==undefined"), true, 'both fabrics carry traffic');
assert.equal(ev("R.cost.ix"), ev("ixPortMo('ams',1)"), "only the HAMS-IX port is billed");
ev("selectCity('ams');ACT.tab({t:'peer'})");
const txt = ev("document.getElementById('panelBody').textContent");
assert.match(txt, /FRIES-IX/); assert.match(txt, /HAMS-IX/);
ev("S.ev.ixdown={'ams:fries':S.day+2};compute()");
assert.equal(ev("R.useIx['ams:fries']"), undefined, 'a FRIES-IX outage drops only that fabric');
assert.match(ev("ixBlock('ams~3',true)"), /LAG member <small>free/);
ev("save();restored=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));");
assert.equal(ev("restored.ixp['ams~3']"), 2, 'free port survives save migration');
assert.equal(ev("restored.ixn['ams~3']"), 2, 'free LAG survives save migration');
ev("S.ev.ixdown={'ams~3':S.day+2};compute()");
assert.equal(ev("R.useIx['ams~3']"), undefined, 'a FRIES-IX outage drops only that fabric');
assert.notEqual(ev("R.useIx.ams"), undefined);
ev("S.ev.ixdown={};compute()");
ev("ACT.cancelIx({city:'ams:fries'});ACT.cancelIx({city:'ams:fries'})");
assert.equal(ev("S.ixp['ams:fries']"), undefined);
ev("ACT.cancelIx({city:'ams~3'});ACT.cancelIx({city:'ams~3'})");
assert.equal(ev("S.ixp['ams~3']"), undefined);
assert.equal(ev("S.ixp.ams"), 1, 'leaving FRIES-IX keeps the HAMS-IX port');
assert.equal(ev("Object.keys(S.rs).filter(k=>S.rs[k]).length"), 0);
assert.deepEqual(errors, []);
});
test('second exchanges are wired up in every city that has one, and Barcelona has Catnip-IX', () => {
test('community exchanges are wired up in every city, and Barcelona has Catnip-IX', () => {
const { ev, errors } = load();
setup(ev);
const bad = ev("Object.keys(XIX).flatMap(k=>XIX[k].members.filter(id=>!NET[id]||!NET[id].pops.includes(XIX[k].city)).map(id=>k+':'+id)).join()");
const exchanges = ['ams~3', 'mad~2', 'fra~2', 'lon~2', 'nyc~3', 'jnb~2', 'syd~2', 'tok~2'];
const bad = ev("XIX.filter(x=>x.core).map(x=>x.id).flatMap(k=>XIXM[k].members.filter(id=>!NET[id]||!NET[id].pops.includes(XIXM[k].c)).map(id=>k+':'+id)).join()");
assert.equal(bad, '', 'every member has a POP in the city');
assert.ok(ev("Object.keys(XIX).every(k=>CITY[XIX[k].city].ix&&cityIxes(XIX[k].city).includes(k))"), 'each sits beside a main IX');
assert.equal(ev("ixPortMo('mad:paella',1)"), ev("Math.round(ixPortMo('mad',1)*0.6)"), 'Paella-NIX is cheaper than Siesta-IX');
assert.ok(ev("Object.keys(XIXM).every(k=>CITY[XIXM[k].c].ix&&ixIdsIn(XIXM[k].c).includes(k))"), 'each sits beside a main IX');
ev("ACT.buildPop({city:'mad'})");
assert.equal(ev("ixPortMo('mad~2',1)"), ev("Math.round(PORT[1].ix*0.6*IX_REG.EU)"), 'Paella-NIX is cheaper than Siesta-IX');
assert.equal(ev("ixName('bcn')"), 'Catnip-IX');
for (const k of JSON.parse(ev('JSON.stringify(Object.keys(XIX))'))) {
const c = k.split(':')[0];
for (const k of exchanges) {
const c = k.split('~')[0];
ev(`if(!S.pops.${c})ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=RG.length-1;ACT.buyIx({city:'${k}',tier:1});ACT.rs({city:'${k}'})`);
assert.equal(ev(`S.ixp['${k}']`), 1, `port at ${k}`);
}
ev('compute()');
for (const k of JSON.parse(ev('JSON.stringify(Object.keys(XIX))')))
for (const k of exchanges)
assert.ok(ev(`ixSessions('${k}').size`) > 0, `route server sessions at ${k}`);
for (const c of ['ams', 'mad', 'fra', 'lon', 'nyc', 'jnb', 'syd', 'tok', 'bcn']) {
ev(`selectCity('${c}');ACT.tab({t:'peer'})`);
const txt = ev("document.getElementById('panelBody').textContent");
for (const k of JSON.parse(ev(`JSON.stringify(cityIxes('${c}'))`))) assert.ok(txt.includes(ev(`ixName('${k}')`)), `${k} shown in ${c}`);
for (const k of JSON.parse(ev(`JSON.stringify(ixIdsIn('${c}'))`))) assert.ok(txt.includes(ev(`ixName('${k}')`)), `${k} shown in ${c}`);
}
assert.deepEqual(errors, []);
});

View file

@ -4,6 +4,7 @@ const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { load } = require('./harness');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const root = path.join(__dirname, '..');
function playedGame() {
@ -31,8 +32,8 @@ test('leaving the page saves the game', () => {
test('returning players see what is new after an update, once', () => {
const { saved } = playedGame();
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
const file = path.join(root, '_site', 'index.html');
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
const file = path.join(OUT, 'index.html');
const b = load({ file, storage: { 'sot-save-v1': saved, 'sot-seen-version': '1.0.0' } });
const text = b.ev("document.getElementById('modalCard').textContent");
assert.match(text, /New in Series of Tubes 1\.1\.0/);

324
tests/regions.test.js Normal file
View file

@ -0,0 +1,324 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); }
test('new cities exist, sit on land and have sellers, cables and IX members', () => {
const { ev, errors } = load();
start(ev);
const ids = ['for', 'rio', 'bue', 'scl', 'lim', 'bog', 'pan', 'del', 'maa', 'blr', 'hyd', 'tpe', 'auh', 'fuj', 'cpt'];
for (const c of ids) {
assert.ok(ev(`!!CITY['${c}']`), c);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
}
for (const c of ['for', 'rio', 'bue', 'scl', 'lim', 'bog', 'pan', 'maa', 'tpe', 'fuj', 'cpt'])
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev("ixMembers('sao').includes('clr')&&ixMembers('del').includes('jio')&&ixMembers('tpe').includes('cht')"));
assert.ok(ev("CABLE_PAIRS.some(p=>(p.a==='scl'&&p.b==='syd')||(p.a==='syd'&&p.b==='scl'))"), 'Humboldt-ish cable to Sydney');
assert.deepEqual(errors, []);
});
test('South America: no land route over the Darién Gap, the Andes cost double, IX.brrr is cheap', () => {
const { ev } = load();
start(ev);
assert.equal(ev("isSub('pan','bog')"), true, 'Panama to Bogotá is subsea');
assert.equal(ev("isSub('mia','sao')"), true);
assert.equal(ev("isSub('bue','sao')"), false);
assert.equal(ev("landMult('scl','bue')"), 2);
assert.equal(ev("landMult('bue','sao')"), 1);
assert.match(ev("landWhy('scl','bue')"), /Andes/);
assert.equal(ev("regionMult('sao')"), 1.6);
ev("ACT.buildPop({city:'sao'})");
assert.ok(ev("ixPortMo('sao',1)") < ev("PORT[1].ix*0.5"), 'nonprofit IX ports are cheap');
ev("selectCity('sao');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Run by a nonprofit/);
});
test('Brazilian POPs attract provedores', () => {
const { ev } = load();
start(ev);
ev("ACT.buildPop({city:'rio'})");
const seen = JSON.parse(ev("(()=>{const o=[];for(let i=0;i<300;i++){S.offers=[];spawnOffer();o.push(...S.offers.filter(x=>x.type==='provedor').map(x=>x.city));}return JSON.stringify(o)})()"));
assert.ok(seen.length > 0, 'provedor offers appear');
assert.ok(seen.every(c => c === 'rio'), 'only in Brazilian POPs');
});
test('UAE: duopoly fiber only, no dark fiber, free-zone license', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev("dfAllowed('dxb','auh')"), false);
assert.equal(ev("dfAllowed('dxb','bom')"), true);
assert.equal(ev("landMult('dxb','fuj')"), 3);
assert.equal(ev("popCost('auh')-popCost('fra')"), ev('UAE_LIC'));
ev("ACT.buildPop({city:'dxb'});UI.lmode='df';openLinkModal('dxb','auh')");
assert.match(ev("document.getElementById('modalCard').textContent"), /No dark fiber inside the UAE/);
ev("UI.lmode='wave';openLinkModal('dxb','auh')");
assert.match(ev("document.getElementById('modalCard').textContent"), /licensed operators/);
ev("closeModal()");
assert.deepEqual(errors, []);
});
test('regional incidents: Taiwan anchors, Andes landslides, load shedding', () => {
const { ev, errors } = load();
start(ev);
ev("for(const c of ['tpe','scl','bue','cpt'])ACT.buildPop({city:c})");
ev("UI.via=null;openLinkModal('tpe','hkg');ACT.buildLink({tier:1});closeModal()");
ev("UI.via='land';openLinkModal('scl','bue');ACT.buildLink({tier:1});closeModal()");
assert.ok(ev("S.links.some(l=>l.a==='tpe'&&l.sub)") && ev("S.links.some(l=>l.a==='scl'&&!l.sub)"), 'links built');
let anchors = 0, andes = 0, shed = 0;
for (let i = 0; i < 400; i++) {
ev("S.inc=[];for(const l of S.links)l.cut=0;for(const c in S.pops){S.pops[c].down=0;S.pops[c].gen=false}fireFailure()");
const m = ev("S.inc.map(x=>x.msg).join(' ')");
if (/anchor/.test(m) && /Taipei/.test(m)) anchors++;
if (/Andes|mountain pass|llama|4,000/.test(m)) andes++;
if (/Load shedding/.test(m)) shed++;
}
assert.ok(anchors > 0, 'anchors drag over Taiwan cables');
assert.ok(andes > 0, 'the Andes break fiber');
assert.ok(shed > 0, 'South Africa sheds load');
assert.deepEqual(errors, []);
});
test('every new city panel renders', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['for', 'pan', 'del', 'tpe', 'auh', 'fuj', 'cpt', 'bog']) {
ev(`selectCity('${c}');for(const t of ['cust','up','peer','links','infra'])ACT.tab({t})`);
}
assert.deepEqual(errors, []);
});
test('Asia-Pacific and Eastern Europe POPs exist with sellers', () => {
const { ev } = load();
start(ev);
for (const c of ['mel', 'bne', 'drw', 'osa', 'kul', 'bkk', 'sgn', 'khi', 'dac', 'cbo', 'waw', 'prg', 'vie', 'bud', 'buh', 'tll', 'ist'])
assert.ok(ev(`!!CITY['${c}']&&NETS.some(n=>n.price&&n.pops.includes('${c}'))`), c);
assert.ok(ev("CABLE_PAIRS.some(p=>p.cid==='balt')&&CABLE_PAIRS.some(p=>p.cid==='darwin')&&CABLE_PAIRS.some(p=>p.cid==='smw4')"));
});
test('metro diversity: a second site keeps half the POP up and uplinks follow their site', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()");
const cap0 = ev("nodeCap('fra')");
ev("ACT.addSite({city:'fra'})");
assert.ok(ev("S.pops.fra.site2"));
ev("ACT.siteSet({k:'t',id:S.transit[1].id,s:'b'})");
assert.equal(ev("S.transit[1].site"), 'b');
// a power cut in site A: the POP stays up at half capacity, only site-B transit works
ev("addInc({type:'site',ref:'fra',site:'a',until:S.day+3,msg:'x',cost:0});compute()");
assert.equal(ev("popUp('fra')"), true);
assert.equal(ev("nodeCap('fra')"), cap0 / 2);
assert.equal(ev("R.useT[S.transit[0].id]||0"), 0, 'site A transit is dark');
assert.ok(ev("R.useT[S.transit[1].id]") > 0, 'site B transit carries traffic');
// the incident path also uses the second site
ev("S.inc=[];S.pops.fra.gen=false;for(let i=0;i<500&&!S.inc.some(x=>x.type==='site'||x.type==='ring');i++){fireFailure();S.inc=S.inc.filter(x=>x.type==='site'||x.type==='ring');for(const c in S.pops)S.pops[c].down=0;}");
assert.ok(ev("S.inc.some(x=>x.type==='site'||x.type==='ring')"), 'site outages and ring cuts happen');
ev("selectCity('fra');ACT.tab({t:'infra'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Metro diversity/);
ev("selectCity('fra');ACT.tab({t:'up'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Site:/);
assert.deepEqual(errors, []);
});
test('the giants ask for AI WANs, multi-site training, ingests and hundreds of fiber pairs', () => {
const { ev, errors } = load();
start(ev);
ev("for(const c of ['ash','dal','chi','nyc'])ACT.buildPop({city:c})");
ev("UI.pending={a:'chi',b:'ash'};UI.lmode='df';UI.dfSrc='build';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.links.filter(l=>l.kind==='df').forEach(l=>l.ready=S.day)");
const seen = {};
for (let i = 0; i < 600; i++) { ev('S.offers=[];spawnOffer()'); for (const o of JSON.parse(ev("JSON.stringify(S.offers.filter(o=>o.mega).map(o=>({t:o.type,c:bCities(o),r:o.rate,bw:o.bw})))"))) seen[o.t] = o; }
for (const t of ['aiwan', 'mtrain', 'ingest', 'pairs']) assert.ok(seen[t], `${t} offers appear`);
assert.ok(seen.mtrain.c.length >= 3, 'training runs span several sites');
assert.ok(seen.aiwan.bw >= 3200);
// accept one and make sure it earns
ev("for(let i=0;i<400&&!S.offers.some(o=>o.type==='pairs');i++){S.offers=[];spawnOffer();}const o=S.offers.find(o=>o.type==='pairs');ACT.accept({id:o.id});compute()");
assert.ok(ev("S.biz.some(b=>b.type==='pairs')"));
assert.ok(ev("R.revMo") > 0);
ev("selectCity('dal')");
assert.match(ev("document.getElementById('panelBody').textContent+''"), /./);
ev("ACT.leftTab({t:'deals'})");
assert.deepEqual(errors, []);
});
test('#8 ports can be split across both buildings, so one dark site only halves them', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});ACT.addSite({city:'fra'});compute()");
const full = ev("ixCap('fra')");
const cash0 = ev("S.cash");
ev("ACT.siteSet({k:'ix',id:'fra',s:'ab'})");
assert.equal(ev("(S.ixn||{}).fra"), 2, 'choosing Both adds a second member');
assert.equal(ev("S.ixSite.fra"), 'ab');
assert.ok(ev("S.cash") < cash0, 'and charges for it');
const two = ev("ixCap('fra')");
ev("addInc({type:'site',ref:'fra',site:'a',until:S.day+3,msg:'x',cost:0});compute()");
assert.ok(ev("ixCap('fra')") > 0 && ev("ixCap('fra')") < two, 'site A dark: the IX port runs on its site-B half');
assert.ok(ev("R.useIx.fra||0") > 0, 'and still carries traffic');
ev("ACT.siteSet({k:'t',id:S.transit[0].id,s:'ab'});compute()");
assert.equal(ev("S.transit[0].n"), 2);
assert.ok(ev("R.useT[S.transit[0].id]||0") > 0, 'split transit survives the dark site');
ev("ACT.lagT({id:S.transit[0].id,d:-1})");
assert.equal(ev("S.transit[0].site"), 'a', 'one member left: back in one building');
ev("selectCity('fra');ACT.tab({t:'infra'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /split/);
assert.ok(full > 0);
assert.deepEqual(errors, []);
});
test('routers: wave and port sizes match what the box can actually take', () => {
const { ev } = load();
start(ev);
assert.equal(ev("LT.map(t=>t.n).join()"), '10G,100G,400G,800G,1.6T,6.4T');
assert.equal(ev("PORT[RG[3].maxP].n"), '1.6T', 'the 1.6T router has 1.6T ports');
assert.equal(ev("LT[RG[2].maxLT].n"), '800G', 'an 800G router stops at 800G waves');
assert.equal(ev("LT[RG[3].maxLT].n"), '6.4T');
// an old save with a 1.6T wave (old tier 3) keeps its 1.6T wave after migration
const old = ev("(()=>{const s=JSON.parse(JSON.stringify(S));delete s.ltv;s.links=[{id:'x',a:'fra',b:'ams',kind:'wave',tier:3,km:364,mo:1,cut:0}];s.pops.ams={day:0,routers:1};return JSON.stringify(s)})()");
assert.equal(ev(`LT[migrate(JSON.parse(${JSON.stringify(old)})).links[0].tier].n`), '1.6T');
});
test('London–Amsterdam: many cheap cables and dark fiber you can lease under the sea', () => {
const { ev, errors } = load();
start(ev);
assert.ok(ev("cablesFor('lon','ams').length") >= 4);
assert.equal(ev("dfAllowed('lon','ams')"), true);
assert.equal(ev("dfAllowed('lon','nyc')"), false, 'not on long subsea routes');
ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'ams'});UI.pending={a:'lon',b:'ams'};UI.lmode='df';UI.dfSrc='build';UI.dfSys='lite';ACT.orderDf();UI.lmode='wave'");
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='df'))"));
assert.ok(l && l.sub && l.cable && !l.own, 'a subsea IRU, never self-built');
assert.deepEqual(errors, []);
});
test('#10 your own IX fabric can be upgraded, and grows', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.buildPop({city:'mex'});ACT.foundIx({city:'mex'});compute()");
assert.equal(ev("ixCap('mex')"), 400);
ev("ACT.myIxUp({city:'mex'});compute()");
assert.equal(ev("ixCap('mex')"), 1600);
assert.equal(ev("myFab('mex').max"), 20);
ev("selectCity('mex');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Your own fabric · 1.6T/);
assert.deepEqual(errors, []);
});
test('wave prices follow regional markets and fall over time', () => {
const { ev } = load();
start(ev);
const eu = ev("waveMarket('fra','ams',false).reg"), us = ev("waveMarket('nyc','ash',false).reg"), af = ev("waveMarket('lon','lag',true).reg");
assert.ok(eu < us && us < af, `Europe ${eu} < US ${us} < Africa ${af}`);
const m0 = ev("waveMarket('fra','ams',false).m");
ev("S.day=720");
assert.ok(ev("waveMarket('fra','ams',false).m") < m0, 'two years later it is cheaper');
assert.ok(ev("cablesFor('cai','dxb').length") > 0, 'Cairo–Dubai over the Red Sea');
assert.match(ev("marketNote('fra','ams',false)"), /Europe/);
});
test('the Gulf: Saudi licences, and a spat that cuts Qatar off from its neighbours', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev("popCost('ruh')-popCost('fra')"), ev('KSA_LIC'));
ev("ACT.buildPop({city:'doh'});ACT.buildPop({city:'ruh'});UI.via='land';openLinkModal('doh','ruh');ACT.buildLink({tier:1});closeModal()");
const l = "S.links.find(l=>[l.a,l.b].includes('doh'))";
assert.equal(ev(`linkDown(${l})`), false);
ev("S.ev.gulf=S.day+60");
assert.equal(ev(`linkDown(${l})`), true, 'the border is closed');
ev("ACT.startScn({id:'redsea',sure:1})");
assert.equal(ev("cablesOk('cai','jed').length+cablesOk('jed','bom').length"), 0, 'the Red Sea crisis covers Egypt and Jeddah too');
assert.deepEqual(errors, []);
});
test('Italy, Portugal, Greece and more US cities are on the map and wired up', () => {
const { ev, errors } = load();
for (const c of ['mil', 'rom', 'pmo', 'lis', 'ath', 'atn', 'den', 'phx', 'bos', 'hou', 'slc']) {
assert.ok(ev(`!!CITY.${c}`), c);
assert.ok(ev(`NETS.filter(n=>n.price&&n.pops.includes('${c}')).length`) >= 2, `${c} has transit sellers`);
}
for (const [a, b] of [['lis', 'for'], ['lis', 'atn'], ['mil', 'pmo'], ['pmo', 'cai'], ['ath', 'ist'], ['bos', 'dub']])
assert.ok(ev(`cablesFor('${a}','${b}').length`) > 0, `${a}-${b} cable`);
assert.deepEqual(errors, []);
});
test('network ids are unique, and the long tail is small and spread over exchanges', () => {
const { ev } = load();
assert.equal(ev("new Set(NETS.map(n=>n.id)).size===NETS.length"), true);
const tail = ev("NETS.filter(n=>n.tail).length");
assert.ok(tail >= 50, `${tail} small peers`);
assert.ok(ev("NETS.filter(n=>n.tail).every(n=>n.share<=0.003&&n.pops.every(c=>CITY[c]&&!CITY[c].ixOnly))"));
assert.ok(ev("NETS.filter(n=>n.tail&&n.ix.some(x=>x.includes('~'))).length") >= 5, 'some only sit on challenger IXs');
});
test('several exchanges per city: overlapping members, cheaper challengers, separate ports', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.deepEqual(JSON.parse(ev("JSON.stringify(ixIdsIn('ams'))")), ['ams', 'ams~2', 'ams~3']);
const a = JSON.parse(ev("JSON.stringify(ixMembers('ams'))")), b = JSON.parse(ev("JSON.stringify(ixMembers('ams~2'))"));
assert.ok(a.some(x => b.includes(x)), 'shared members');
assert.ok(b.some(x => !a.includes(x)) && a.some(x => !b.includes(x)), 'and different ones');
assert.ok(ev("ixPortMo('ams~2',1)") < ev("ixPortMo('ams',1)"), 'challenger is cheaper');
ev("ACT.buyIx({city:'ams~2',tier:1});ACT.rs({city:'ams~2'});compute()");
assert.equal(ev("S.ixp['ams~2']"), 1);
assert.equal(ev("S.ixp.ams"), undefined);
assert.ok(ev("ixSessions('ams~2').size") > 3);
assert.ok(ev("R.sessions") > 3);
ev("ACT.peerAll({city:'ams~2'})");
ev("selectCity('ams');ACT.tab({t:'peer'})");
const t = ev("document.getElementById('panelBody').textContent");
assert.match(t, /3 exchanges compete/);
assert.match(t, /NL-Nyx/);
ev("save();load2=JSON.parse(localStorage.getItem('sot-save-v1'));sanitize(load2)");
assert.equal(ev("load2.ixp['ams~2']"), 1, 'saves keep challenger ports');
ev("ACT.cancelIx({city:'ams~2'});ACT.cancelIx({city:'ams~2'})");
assert.equal(ev("S.ixp['ams~2']"), undefined);
assert.equal(ev("Object.keys(S.peers).some(k=>k.endsWith('@ams~2'))"), false);
assert.deepEqual(errors, []);
});
test('Voda-Phony only peers for money now, and EU price wars cut port prices', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.equal(ev("NET.vdp.pol"), 'paid');
assert.equal(ev("peerOk('vdp','ix','ams').ok"), false);
assert.ok(ev("peerOk('vdp','pni','ams').fee") > 0);
assert.ok(ev("ixPortMo('ams',1)") < ev("PORT[1].ix"), 'EU ports are cheaper');
ev("ACT.buyIx({city:'ams',tier:1});const before=ixPortMo('ams',1);const r=Math.random;Math.random=()=>0;ixPriceWar(S.day);Math.random=r;window.__b=before");
assert.ok(ev("ixPortMo('ams',1)") < ev("__b"), 'price cut');
assert.deepEqual(errors, []);
});
test('router ports are finite: plugging in fills them, more routers or bigger models add room', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'ams'})");
assert.equal(ev("portsMax('ams')"), 8, 'one Rusty has 8 ports');
ev("for(const n of ['cog','lvl','tly','ntt','drz','tng'])ACT.buyTransit({city:'ams',net:n,tier:1});ACT.buyIx({city:'ams',tier:1});ACT.buyIx({city:'ams~2',tier:1})");
assert.equal(ev("portsUsed('ams')"), 8);
ev("ACT.buyIx({city:'ams~3',tier:1})");
assert.equal(ev("S.ixp['ams~3']"), undefined, 'no ninth port');
assert.match(ev("document.getElementById('toasts').textContent"), /No free router ports/);
ev("ACT.buyIx({city:'ams~3',tier:0})");
assert.equal(ev("S.ixp['ams~3']"), undefined, 'not even a 10G breakout');
ev("ACT.addRouter({city:'ams'})");
assert.equal(ev("portsMax('ams')"), 16);
ev("ACT.buyIx({city:'ams~3',tier:0})");
assert.equal(ev("S.ixp['ams~3']"), 0);
assert.equal(ev("portsUsed('ams')"), 8.25, '10G rides a breakout');
ev("ACT.rmRouter({city:'ams'})");
assert.equal(ev("S.pops.ams.routers"), 2, 'cannot remove a router whose ports are in use');
const arr = ev("RG.findIndex(r=>/Arrrhipster 7280/.test(r.n))");
assert.ok(arr > 0);
ev(`ACT.upRouter({city:'ams',g:${arr}})`);
assert.equal(ev("S.pops.ams.rgen"), arr, 'swapped to the Arrrhipster');
assert.equal(ev("portsMax('ams')"), 96);
assert.equal(ev("bootMin('ams')") < 30, true, 'boots fast');
ev("selectCity('ams');ACT.tab({t:'infra'});ACT.models()");
assert.match(ev("document.getElementById('panelBody').textContent"), /Knockia/);
const mk = ev("RG.findIndex(r=>/Mikrowtik/.test(r.n))");
ev("ACT.buyTransit({city:'ams',net:'cog',tier:2})");
assert.equal(ev("S.transit.find(t=>t.net==='cog'&&t.city==='ams').tier"), 2);
ev(`ACT.upRouter({city:'ams',g:${mk}})`);
assert.equal(ev("S.pops.ams.rgen"), arr, 'a smaller model that cannot fit is refused');
assert.ok(ev("RG.every(r=>r.ports>0&&r.cls>=0&&r.maxP<PORT.length)"));
assert.deepEqual(errors, []);
});