Merge fix/176-save-size: warn when saving fails, smaller saves (#176)

This commit is contained in:
Frederic Jung 2026-10-27 21:19:18 +01:00
commit 8c3ac4e9df
No known key found for this signature in database
10 changed files with 104 additions and 6 deletions

View file

@ -17,6 +17,8 @@ All notable changes to this project are documented here. The project follows
- Maps with more than a thousand lines on screen draw about twice as fast: they leave out the link labels and the dots on lit fiber, which nobody could read in such a tangle. Zoom in and they come back; the selected link keeps its label.
- The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen.
- Big networks with thousands of fiber customers no longer stall: each game day and each action is about two to three times faster, and new alien-wave offers no longer freeze the game for a moment.
- The game now tells you when it cannot save: a network too big for the browser's storage, or a browser that blocks it, used to stop saving without a word (#176). Export a save from the warning to keep a backup.
- Big networks take about 40% less space to save: saves leave out customer details the game can work out again when loading (#176).
## [1.34.1] — 2026-10-27

View file

@ -2716,7 +2716,9 @@
"save.that_file_is_too_big_to":"<b>Ese archivo es demasiado grande para ser una partida.</b>",
"save.that_network_went_bankrupt_it_cannot":"Esa red quebró. No se puede recuperar, solo llorar.",
"save.that_save_has_a_pop_in":"Esa partida tiene un POP en una ciudad que esta versión no conoce ({city}).",
"save.this_browser_is_not_letting_the":"<b>Tu partida no se está guardando.</b> Este navegador no deja que el juego guarde nada (ventana privada o datos de sitios desactivados). Exporta una partida para no perder tu red.",
"save.this_replaces_name_export_it_first":"Esto reemplaza a {name}. Expórtala primero si quieres conservarla.",
"save.your_network_is_too_big_to":"<b>Tu partida no se está guardando.</b> Tu red se ha vuelto demasiado grande para el almacenamiento de este navegador. Exporta una partida ahora y guarda el archivo: es tu copia de seguridad.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objetivo:</b> {goal} · <b>Tiempo:</b> {d} días · empiezas en {city}",
"scenario_progress.goal_was_not_reached_in_d":"{goal} no se logró en {d} días. Sigue jugando esta red en modo libre, o inténtalo de nuevo.",
"scenario_progress.just_in_time":"Justo a tiempo.",

View file

@ -2716,7 +2716,9 @@
"save.that_file_is_too_big_to":"<b>Ce fichier est trop gros pour être une sauvegarde.</b>",
"save.that_network_went_bankrupt_it_cannot":"Ce réseau a fait faillite. Impossible de le ressusciter, on ne peut que le pleurer.",
"save.that_save_has_a_pop_in":"Cette sauvegarde a un POP dans une ville que cette version ne connaît pas ({city}).",
"save.this_browser_is_not_letting_the":"<b>Votre partie n'est pas sauvegardée.</b> Ce navigateur n'autorise pas le jeu à stocker quoi que ce soit (fenêtre privée ou données de sites désactivées). Exportez une sauvegarde pour garder votre réseau.",
"save.this_replaces_name_export_it_first":"Cela remplace {name}. Exporte-le d’abord si tu veux le garder.",
"save.your_network_is_too_big_to":"<b>Votre partie n'est pas sauvegardée.</b> Votre réseau est devenu trop gros pour le stockage de ce navigateur. Exportez une sauvegarde maintenant et gardez le fichier : c'est votre copie de secours.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objectif :</b> {goal} · <b>Durée :</b> {d} jours · départ à {city}",
"scenario_progress.goal_was_not_reached_in_d":"Objectif non atteint en {d} jours : {goal}. Continue avec ce réseau en partie libre, ou réessaie.",
"scenario_progress.just_in_time":"Juste à temps.",

View file

@ -2716,7 +2716,9 @@
"save.that_file_is_too_big_to":"<b>Quel file è troppo grande per essere un salvataggio.</b>",
"save.that_network_went_bankrupt_it_cannot":"Quella rete è finita in bancarotta. Non si può resuscitare, solo piangere.",
"save.that_save_has_a_pop_in":"Quel salvataggio ha un POP in una città che questa versione non conosce ({city}).",
"save.this_browser_is_not_letting_the":"<b>La partita non viene salvata.</b> Questo browser non permette al gioco di salvare nulla (finestra privata o dati dei siti disattivati). Esporta un salvataggio per non perdere la tua rete.",
"save.this_replaces_name_export_it_first":"Sostituisce {name}. Esportala prima, se vuoi tenerla.",
"save.your_network_is_too_big_to":"<b>La partita non viene salvata.</b> La tua rete è diventata troppo grande per lo spazio di questo browser. Esporta un salvataggio adesso e tieni il file: è il tuo backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Obiettivo:</b> {goal} · <b>Tempo:</b> {d} giorni · si parte da {city}",
"scenario_progress.goal_was_not_reached_in_d":"Obiettivo non raggiunto in {d} giorni: {goal}. Continua a giocare questa rete in modalità libera, o riprova.",
"scenario_progress.just_in_time":"Appena in tempo.",

View file

@ -2716,7 +2716,9 @@
"save.that_file_is_too_big_to":"<b>Esse arquivo é grande demais para ser um save.</b>",
"save.that_network_went_bankrupt_it_cannot":"Essa rede foi à falência. Não dá para trazer de volta, só chorar.",
"save.that_save_has_a_pop_in":"Esse save tem um POP numa cidade que esta versão não conhece ({city}).",
"save.this_browser_is_not_letting_the":"<b>Seu jogo não está sendo salvo.</b> Este navegador não deixa o jogo guardar nada (janela anônima ou dados de sites desativados). Exporte um save para não perder sua rede.",
"save.this_replaces_name_export_it_first":"Isso substitui {name}. Exporte antes se quiser guardar.",
"save.your_network_is_too_big_to":"<b>Seu jogo não está sendo salvo.</b> Sua rede ficou grande demais para o armazenamento deste navegador. Exporte um save agora e guarde o arquivo: é o seu backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Objetivo:</b> {goal} · <b>Tempo:</b> {d} dias · começa em {city}",
"scenario_progress.goal_was_not_reached_in_d":"Objetivo não alcançado em {d} dias: {goal}. Continue jogando esta rede no modo livre, ou tente de novo.",
"scenario_progress.just_in_time":"Bem na hora.",

View file

@ -40,7 +40,7 @@ function sanitize(s){
for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);}
const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity));
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;};
s.biz=s.biz.filter(okBiz).map(fixBiz);s.offers=s.offers.filter(okBiz).map(fixBiz);
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>unpackBiz(fixBiz(b),ids));}s.offers=s.offers.filter(okBiz).map(fixBiz);
// Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked.
for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k];
if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};}

View file

@ -13,10 +13,10 @@ Object.assign(ACT,{
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
menu:()=>{if(!S||!UI.started){showTitle();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>${isPhone()?installRow():''}
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}${isPhone()?installRow():''}
<div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},'')}
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},saveFailing()?'pink':'')}
${btn(tr('game_and_settings.import_a_save_from_a_file'),'importPick',{},'')}
${btn(tr('game_and_settings.share_your_network_image_card'),'share',{},'')}
${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')}

View file

@ -4,16 +4,31 @@
again (1 minute, then 2, 4, at most 5); leaving the page, exporting or another game (a new S) still try at once. */
function save(force){if(!S||S.lost)return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};const f=UI.saveFail;
if(!force&&f&&f.s===S&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
try{localStorage.setItem('sot-save-v1',JSON.stringify(S));UI.saveFail=null;}
catch(e){UI.saveFail={s:S,at:performance.now(),wait:f&&f.s===S?Math.min(300000,f.wait*2):60000};}
try{localStorage.setItem('sot-save-v1',JSON.stringify(packSave(S)));UI.saveFail=null;}
catch(e){const again=f&&f.s===S;UI.saveFail={s:S,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)};
// Say so once per game (#176): a save that silently fails loses everything since the last one that worked.
if(!again)toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}}]);}
UI.lastSave=performance.now();}
/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no
requirements, the normal route, no warnings yet. The save leaves defaults out and sanitize() puts them back, so
the game after loading is the same; older versions read a missing field as its default too. An alien wave's
description is rebuilt from its fiber. */
const BIZ_DEF={city2:null,latMax:null,route:'normal',sites:null,slots:0,warned:false,warn60:false};
function packBiz(b){const o={};for(const k in b){const v=b[k];if(v===undefined||BIZ_DEF[k]===v||(k==='reqs'&&Array.isArray(v)&&!v.length)||(k==='pm'&&v===b.mood)||(k==='what'&&b.type==='wwave'&&b.link))continue;o[k]=v;}return o;}
function unpackBiz(b,links){for(const k in BIZ_DEF)if(!(k in b))b[k]=BIZ_DEF[k];if(!('pm' in b)&&b.mood!==undefined)b.pm=b.mood;if(!Array.isArray(b.reqs))b.reqs=[];
if(b.type==='wwave'&&b.what===undefined){const l=links.get(b.link);b.what=l?wwWhat(l,b.slots||1):'';}return b;}
const packSave=s=>({...s,biz:s.biz.map(packBiz)});
// Out of room (quota) or not allowed to store at all (private window, blocked site data): different advice.
const saveFull=e=>!!e&&(e.name==='QuotaExceededError'||e.name==='NS_ERROR_DOM_QUOTA_REACHED'||e.code===22||e.code===1014);
const saveFailing=()=>!!(UI.saveFail&&UI.saveFail.s===S);
const saveFailMsg=()=>UI.saveFail&&UI.saveFail.full?tr('save.your_network_is_too_big_to'):tr('save.this_browser_is_not_letting_the');
// Save whenever the player might be leaving: tab hidden, page closing or reloading.
addEventListener('pagehide',()=>save(true));
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save(true);else checkUpdate();});
/* Export / import: move a network to another device or keep a backup. The file is the same
object the autosave writes, wrapped with a little metadata. */
function saveFileName(){const d=new Date().toISOString().slice(0,10),n=(S&&S.name||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
function exportSave(){if(!S)return;save(true);const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S},null,1)],{type:'application/json'});
function exportSave(){if(!S)return;save(true);const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1)],{type:'application/json'});
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName();document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName())}),'good');}
function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_is_not_valid_json')};let j;try{j=JSON.parse(txt);}catch(e){return {err:tr('save.that_file_is_not_valid_json')};}

View file

@ -2717,7 +2717,9 @@
"save.that_file_is_too_big_to":"<b>That file is too big to be a save.</b>",
"save.that_network_went_bankrupt_it_cannot":"That network went bankrupt. It cannot be brought back, only mourned.",
"save.that_save_has_a_pop_in":"That save has a POP in a city this version does not know ({city}).",
"save.this_browser_is_not_letting_the":"<b>Your game is not being saved.</b> This browser is not letting the game store anything (a private window, or site data turned off). Export a save to keep your network.",
"save.this_replaces_name_export_it_first":"This replaces {name}. Export it first if you want to keep it.",
"save.your_network_is_too_big_to":"<b>Your game is not being saved.</b> Your network has grown too big for this browser's storage. Export a save now and keep the file: it is your backup.",
"scenario_progress.goal_goal_time_d_days_start":"<b>Goal:</b> {goal} · <b>Time:</b> {d} days · start in {city}",
"scenario_progress.goal_was_not_reached_in_d":"{goal} was not reached in {d} days. Keep playing this network as free play, or try again.",
"scenario_progress.just_in_time":"Just in time.",

71
tests/save-size.test.js Normal file
View file

@ -0,0 +1,71 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed).
const refuse = name => `window.__err=${JSON.stringify(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem;
P.setItem=function(k,v){if(k==='sot-save-v1'&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError'));
ev('save()');
const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent));
assert.equal(toasts().length, 1, 'one warning');
assert.match(toasts()[0].textContent, /too big for this browser/);
assert.ok(toasts()[0].querySelector('[data-act=exportSave]'), 'with an Export button');
ev('UI.saveFail.at-=1e6;save();save(true)');
assert.equal(toasts().length, 1, 'not again for every retry');
ev('ACT.menu()');
const card = ev("document.getElementById('modalCard').innerHTML");
assert.match(card, /not being saved/);
assert.doesNotMatch(card, /saves itself every few seconds/, 'the menu no longer claims it saves');
// Once a save works again, the menu goes back to normal.
ev("__err=null;save(true);ACT.menu()");
assert.equal(ev('saveFailing()'), false);
assert.match(ev("document.getElementById('modalCard').innerHTML"), /saves itself every few seconds/);
assert.deepEqual(errors, []);
});
test('#176 storage that is blocked altogether gets its own advice', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()');
assert.match(dom.window.document.body.textContent, /private window/);
assert.deepEqual(errors, []);
});
// A network with plenty of alien waves and ordinary customers, the shape of big late-game saves.
const bigBiz = "ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});" +
"S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});" +
"for(let i=0;i<300;i++){const slots=1+i%4;S.biz.push({id:'w'+i,city:'fra',city2:'ams',reqs:[],latMax:null,route:'normal',name:'Carrier '+i,type:'wwave',bw:1,rate:4000,mood:100-i%9*1.37,since:i,sites:null,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots),pm:i%2?100:99,warned:i%5===0,warn60:false});}" +
"S.biz.push({id:'l2',city:'fra',city2:'ams',reqs:['diverse'],latMax:3.2,route:'fast',name:'Fast Co',type:'hft',bw:5,rate:900,mood:80,since:0,sites:null,slots:0,pm:81,warned:false,warn60:true});" +
"S.biz.push({id:'d1',city:'fra',city2:null,reqs:[],latMax:null,route:'normal',name:'Plain Co',type:'dia',bw:5,rate:600,mood:100,since:0,sites:null,slots:0});compute()";
const sorted = "JSON.stringify(S.biz.map(b=>Object.keys(b).sort().map(k=>[k,b[k]])))";
test('#176 saves leave customer defaults out, and loading puts them back exactly', () => {
const { ev, errors } = load();
ev(bigBiz);
const full = ev('JSON.stringify(S).length'), packed = ev('JSON.stringify(packSave(S)).length');
assert.ok(packed < full * 0.75, `the save is much smaller (${packed} vs ${full})`);
const before = ev(sorted);
ev("save(true);S=migrate(loadSave());compute()");
const after = JSON.parse(ev(sorted)), want = JSON.parse(before);
// Customers that never got warnings or a previous mood come back with the defaults; everything else is identical.
const norm = list => list.map(b => Object.fromEntries(b)).map(b => ({ pm: b.mood, warned: false, warn60: false, ...b }));
assert.deepEqual(norm(after), norm(want));
assert.equal(ev("S.biz.find(b=>b.id==='l2').route"), 'fast', 'a chosen route is kept');
assert.equal(ev("S.biz.find(b=>b.id==='w7').what"), ev("wwWhat(S.links.find(l=>l.id==='df1'),4)"), 'alien waves get their description back');
assert.match(ev("localStorage.getItem('sot-save-v1')"), /"Carrier 1"/);
assert.doesNotMatch(ev("localStorage.getItem('sot-save-v1')"), /alien wave on your/, 'descriptions are not stored');
assert.deepEqual(errors, []);
});
test('#176 an older, unpacked save still loads the same', () => {
const { ev, errors } = load();
ev(bigBiz);
const before = ev(sorted);
ev("S=migrate(JSON.parse(JSON.stringify(S)));compute()");
const norm = list => list.map(b => Object.fromEntries(b)).map(b => ({ pm: b.mood, warned: false, warn60: false, ...b }));
assert.deepEqual(norm(JSON.parse(ev(sorted))), norm(JSON.parse(before)));
assert.deepEqual(errors, []);
});