From 36629195cc7d8427b2afbdeb627dd429363e7e76 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 02:02:10 +0000 Subject: [PATCH 01/18] Say why a link is down when a closed border took it (#329) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Gulf spat and Russia's sovereign internet drill take links down in linkDown(), and the map draws them broken, but the link panels only explained cuts and incidents, so a Doha–Abu Dhabi wave looked healthy in its panel with no way to fix it. The panels now show a 'Border closed' section with the days left, and the wave and dark fiber modals warn before leasing across the closed Qatar border. --- CHANGELOG.md | 2 + site/i18n/de.js | 4 ++ site/i18n/es.js | 4 ++ site/i18n/fr.js | 4 ++ site/i18n/it.js | 4 ++ site/i18n/pt.js | 4 ++ src/game/80-simulation/40-billing.js | 5 ++- src/game/93-ui/70-link-panels.js | 5 ++- src/game/95-modals/70-link-modal.js | 1 + src/game/95-modals/90-fiber-modals.js | 2 +- src/i18n/en.js | 4 ++ tests/border-closed-links.test.js | 53 +++++++++++++++++++++++++++ 12 files changed, 89 insertions(+), 3 deletions(-) create mode 100644 tests/border-closed-links.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index db3d467..744dfae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). + ## [3.3.0] — 2026-11-09 - You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. diff --git a/site/i18n/de.js b/site/i18n/de.js index 3d0e0a9..5402b72 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2780,11 +2780,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Premium-Übergänge gibt es nur in Hongkong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben günstiger · ein Bagger kappt alle", "link_modal.sold_out_for_n_days":"ausverkauft für {n} Tage", +"link_modal.the_borders_around_qatar_are_closed":"Die Grenzen rund um Katar sind geschlossen: Ein Link zwischen Doha und Saudi-Arabien oder den VAE bleibt dunkel, bis sich die Nachbarn wieder vertragen.", "link_modal.the_landing_permit_dispute_in_city":"Der Streit um die Anlandegenehmigung in {city} blockiert neue Subsea-Links für weitere {n} Tage.", "link_modal.waves_are_leased_at_a_flat":"Waves werden zu einer festen Monatsrate gemietet. Größer und länger kostet mehr, und Subsea das 1,8-Fache. Der erste Monat ist jetzt fällig.", "link_modal.waves_on_the_same_route_share":"Waves auf derselben Route teilen ihr Schicksal: Ein Bagger kappt sie alle.", "link_modal.you_already_have_n_link_here":{"one":"Du hast hier schon {n} Link ({list}). Parallele Links bringen Kapazität. Wie soll dieser geroutet werden?","other":"Du hast hier schon {n} Links ({list}). Parallele Links bringen Kapazität. Wie soll dieser geroutet werden?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"Eine größere Fabric trägt mehr Traffic und hat Platz für mehr Mitglieder. Dein Router hier muss trotzdem mithalten.", +"link_panels.a_diplomatic_spat_has_closed_the":"Ein diplomatischer Streit hat die Grenzen rund um Katar geschlossen, also ist jeder Link zwischen Doha und Saudi-Arabien oder den VAE down. Da gibt es nichts zu reparieren und keinen Eilauftrag für Diplomatie: nimm den langen Weg außen herum, übers Meer.", "link_panels.a_link_on_standby_carries_traffic":"Ein Link im Standby trägt nur Traffic, wenn die anderen Links zwischen diesen Städten voll oder down sind.", "link_panels.a_link_s_cost_is_its":"Die Kosten eines Links sind seine Länge in km plus 60, mal ein Faktor. Traffic nimmt den Pfad mit den niedrigsten Gesamtkosten.", "link_panels.a_regen_site_turns_the_light":"Ein Regen-Standort verwandelt das Licht auf halber Strecke zurück in Bits und schickt es frisch weiter, also müssen Optiken nur bis zum nächsten Standort reichen. Jeder braucht eine Regen-Karte für jeden beleuchteten Kanal. {price}/Monat pro Standort für die Hütte.", @@ -2799,6 +2801,7 @@ "link_panels.behind_the_great_firewall":"Hinter der Großen Firewall", "link_panels.biggest_fabric_money_can_buy":"Die größte Fabric, die man für Geld kaufen kann.", "link_panels.biggest_feeder_egress_in_city_set":"Größter Zubringer: {egress} in {city}. Stell ihn auf „Nur Backup“, gib den Kunden einen näheren Ausgang (Peering, einen Cache, lokalen Transit) oder erhöhe die Metrik dieses Links.", +"link_panels.border_closed":"Grenze geschlossen", "link_panels.build_a_pop_here_first":"Bau hier zuerst einen POP.", "link_panels.cancel_the_iru":"IRU kündigen", "link_panels.carry_here":"Hierher leiten", @@ -2896,6 +2899,7 @@ "link_panels.running_an_exchange_in_mainland":"Einen Exchange in Festlandchina zu betreiben braucht eine ganz andere Lizenz. Peere mit chinesischen Netzen über PNIs oder triff sie in Hongkong.", "link_panels.runs_at_g_per_channel_on":"Läuft auf dieser Route mit {g} pro Kanal (Langstreckenmodus).", "link_panels.runs_on_its_own_route_a":"Läuft auf eigener Route. Ein Schnitt hier trifft die anderen Links nicht.", +"link_panels.russia_has_unplugged_itself_from_the":"Russland hat sich für eine Übung zum souveränen Internet vom Rest des Internets abgekoppelt. Alles, was das Land verlässt, ist bis morgen dunkel.", "link_panels.sell_one_price":"Einen verkaufen {price}", "link_panels.selling_spare_capacity":"Freie Kapazität verkaufen", "link_panels.shares_a_trench_with_n_other":{"one":"Teilt sich einen Graben mit {n} anderen Link. Ein Schnitt legt alle lahm.","other":"Teilt sich einen Graben mit {n} anderen Links. Ein Schnitt legt alle lahm."}, diff --git a/site/i18n/es.js b/site/i18n/es.js index 4348512..feaa272 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2778,11 +2778,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Los cruces premium solo se venden en Hong Kong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Misma zanja más barato · una retroexcavadora corta todo", "link_modal.sold_out_for_n_days":"agotado durante {n} días", +"link_modal.the_borders_around_qatar_are_closed":"Las fronteras de Catar están cerradas: un enlace entre Doha y Arabia Saudí o los EAU seguirá a oscuras hasta que los vecinos hagan las paces.", "link_modal.the_landing_permit_dispute_in_city":"La disputa por el permiso de aterrizaje en {city} bloquea los enlaces submarinos nuevos durante {n} días más.", "link_modal.waves_are_leased_at_a_flat":"Las ondas se alquilan a tarifa mensual plana. Más grande y más largo cuesta más, y lo submarino 1,8×. El primer mes vence ahora.", "link_modal.waves_on_the_same_route_share":"Las ondas de la misma ruta comparten su suerte: una retroexcavadora las corta todas.", "link_modal.you_already_have_n_link_here":{"one":"Ya tienes {n} enlace aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?","other":"Ya tienes {n} enlaces aquí ({list}). Los enlaces paralelos suman capacidad. ¿Cómo debe enrutarse este?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"Una fabric mayor transporta más tráfico y tiene sitio para más miembros. Tu router de aquí aún tiene que aguantar el ritmo.", +"link_panels.a_diplomatic_spat_has_closed_the":"Una disputa diplomática ha cerrado las fronteras de Catar, así que todos los enlaces entre Doha y Arabia Saudí o los EAU están caídos. No hay nada que reparar ni reparación urgente para la diplomacia: da la vuelta larga, por mar.", "link_panels.a_link_on_standby_carries_traffic":"Un enlace en espera solo lleva tráfico cuando los demás enlaces entre estas ciudades están llenos o caídos.", "link_panels.a_link_s_cost_is_its":"El coste de un enlace es su longitud en km más 60, por un multiplicador. El tráfico toma la ruta con el menor coste total.", "link_panels.a_regen_site_turns_the_light":"Un sitio regenerador convierte la luz de nuevo en bits a mitad de camino y la envía renovada, así que las ópticas solo tienen que llegar al siguiente sitio. Cada uno necesita una tarjeta regeneradora por cada canal iluminado. {price}/mes por sitio por la caseta.", @@ -2797,6 +2799,7 @@ "link_panels.behind_the_great_firewall":"Tras el Gran Cortafuegos", "link_panels.biggest_fabric_money_can_buy":"La fabric más grande que el dinero puede comprar.", "link_panels.biggest_feeder_egress_in_city_set":"Mayor alimentador: {egress} en {city}. Ponlo en «Solo respaldo», dale a los clientes una salida más cercana (peering, una caché, tránsito local) o sube la métrica de este enlace.", +"link_panels.border_closed":"Frontera cerrada", "link_panels.build_a_pop_here_first":"Construye primero un POP aquí.", "link_panels.cancel_the_iru":"Cancelar la IRU", "link_panels.carry_here":"Llevar aquí", @@ -2894,6 +2897,7 @@ "link_panels.running_an_exchange_in_mainland":"Gestionar un intercambio en China continental requiere una licencia totalmente distinta. Haz peering con redes chinas por PNIs, o encuéntrate con ellas en Hong Kong.", "link_panels.runs_at_g_per_channel_on":"Funciona a {g} por canal en esta ruta (modo de larga distancia).", "link_panels.runs_on_its_own_route_a":"Va por su propia ruta. Un corte aquí deja en pie los otros enlaces.", +"link_panels.russia_has_unplugged_itself_from_the":"Rusia se ha desconectado del resto de internet para un simulacro de internet soberano. Todo lo que sale del país está a oscuras hasta mañana.", "link_panels.sell_one_price":"Vender uno {price}", "link_panels.selling_spare_capacity":"Vendiendo capacidad sobrante", "link_panels.shares_a_trench_with_n_other":{"one":"Comparte zanja con {n} enlace más. Un corte los tumba a todos.","other":"Comparte zanja con {n} enlaces más. Un corte los tumba a todos."}, diff --git a/site/i18n/fr.js b/site/i18n/fr.js index a3c7813..f971279 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2778,11 +2778,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Les passages premium ne sont vendus qu’à Hong Kong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Même tranchée moins cher · une pelleteuse coupe tout", "link_modal.sold_out_for_n_days":"épuisé pour {n} jours", +"link_modal.the_borders_around_qatar_are_closed":"Les frontières autour du Qatar sont fermées : un lien entre Doha et l'Arabie saoudite ou les Émirats restera éteint jusqu'à ce que les voisins se réconcilient.", "link_modal.the_landing_permit_dispute_in_city":"Le litige sur le permis d’atterrissement à {city} bloque les nouveaux liens sous-marins pendant encore {n} jours.", "link_modal.waves_are_leased_at_a_flat":"Les longueurs d’onde se louent à tarif mensuel fixe. Plus c’est gros et long, plus c’est cher, et le sous-marin coûte 1,8×. Le premier mois est à payer tout de suite.", "link_modal.waves_on_the_same_route_share":"Les longueurs d’onde d’un même parcours partagent son sort : une pelleteuse les coupe toutes.", "link_modal.you_already_have_n_link_here":{"one":"Tu as déjà {n} lien ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?","other":"Tu as déjà {n} liens ici ({list}). Les liens parallèles ajoutent de la capacité. Par où faire passer celui-ci ?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric plus gros transporte plus de trafic et accueille plus de membres. Ton routeur ici doit quand même suivre.", +"link_panels.a_diplomatic_spat_has_closed_the":"Une brouille diplomatique a fermé les frontières autour du Qatar : tous les liens entre Doha et l'Arabie saoudite ou les Émirats sont coupés. Rien à réparer, et pas de réparation express pour la diplomatie : passez par le long chemin, par la mer.", "link_panels.a_link_on_standby_carries_traffic":"Un lien en attente ne porte du trafic que lorsque les autres liens entre ces villes sont pleins ou coupés.", "link_panels.a_link_s_cost_is_its":"Le coût d’un lien, c’est sa longueur en km plus 60, fois un multiplicateur. Le trafic prend le chemin au coût total le plus bas.", "link_panels.a_regen_site_turns_the_light":"Un site de régénération reconvertit la lumière en bits à mi-chemin et la renvoie toute fraîche, donc les optiques n’ont qu’à atteindre le site suivant. Chacun demande une carte de régénération par canal allumé. {price}/mois par site pour l’abri.", @@ -2797,6 +2799,7 @@ "link_panels.behind_the_great_firewall":"Derrière le Grand Pare-feu", "link_panels.biggest_fabric_money_can_buy":"Le plus gros fabric que l’argent puisse acheter.", "link_panels.biggest_feeder_egress_in_city_set":"Plus gros contributeur : {egress} à {city}. Passe-le en « Secours seul », donne aux clients une sortie plus proche (peering, cache, transit local) ou augmente la métrique de ce lien.", +"link_panels.border_closed":"Frontière fermée", "link_panels.build_a_pop_here_first":"Construis d’abord un POP ici.", "link_panels.cancel_the_iru":"Résilier l’IRU", "link_panels.carry_here":"Acheminer ici", @@ -2894,6 +2897,7 @@ "link_panels.running_an_exchange_in_mainland":"Exploiter un IX en Chine continentale exige une tout autre licence. Fais du peering avec les réseaux chinois via des PNI, ou retrouve-les à Hong Kong.", "link_panels.runs_at_g_per_channel_on":"Tourne à {g} par canal sur cette route (mode longue distance).", "link_panels.runs_on_its_own_route_a":"Suit sa propre route. Une coupure ici laisse les autres liens debout.", +"link_panels.russia_has_unplugged_itself_from_the":"La Russie s'est débranchée du reste d'internet pour un exercice d'internet souverain. Tout ce qui sort du pays reste éteint jusqu'à demain.", "link_panels.sell_one_price":"En vendre une {price}", "link_panels.selling_spare_capacity":"Vendre la capacité libre", "link_panels.shares_a_trench_with_n_other":{"one":"Partage une tranchée avec {n} autre lien. Une coupure et ils tombent tous.","other":"Partage une tranchée avec {n} autres liens. Une coupure et ils tombent tous."}, diff --git a/site/i18n/it.js b/site/i18n/it.js index 0c57513..9034753 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2778,11 +2778,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Gli attraversamenti premium si vendono solo a Hong Kong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo più economico · una ruspa li taglia tutti", "link_modal.sold_out_for_n_days":"esaurito per {n} giorni", +"link_modal.the_borders_around_qatar_are_closed":"I confini intorno al Qatar sono chiusi: un link tra Doha e l'Arabia Saudita o gli Emirati resterà spento finché i vicini non fanno pace.", "link_modal.the_landing_permit_dispute_in_city":"La disputa sui permessi di approdo a {city} blocca i nuovi link sottomarini per altri {n} giorni.", "link_modal.waves_are_leased_at_a_flat":"Le wave si affittano a canone mensile fisso. Più grandi e più lunghe costano di più, e il sottomarino costa 1,8×. Il primo mese si paga subito.", "link_modal.waves_on_the_same_route_share":"Le wave sullo stesso percorso ne condividono la sorte: una ruspa le taglia tutte.", "link_modal.you_already_have_n_link_here":{"one":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?","other":"Hai già {n} link qui ({list}). I link paralleli aggiungono capacità. Che percorso deve fare questo?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"Un fabric più grande porta più traffico e ha posto per più membri. Il tuo router qui deve comunque starci dietro.", +"link_panels.a_diplomatic_spat_has_closed_the":"Una lite diplomatica ha chiuso i confini intorno al Qatar, quindi ogni link tra Doha e l'Arabia Saudita o gli Emirati è giù. Non c'è niente da riparare e la diplomazia non ha riparazioni urgenti: fai il giro lungo, via mare.", "link_panels.a_link_on_standby_carries_traffic":"Un link in standby porta traffico solo quando gli altri link tra queste città sono pieni o giù.", "link_panels.a_link_s_cost_is_its":"Il costo di un link è la sua lunghezza in km più 60, per un moltiplicatore. Il traffico prende il percorso col costo totale più basso.", "link_panels.a_regen_site_turns_the_light":"Un sito di rigenerazione riconverte la luce in bit a metà strada e la rimanda fresca, così le ottiche devono arrivare solo al sito successivo. Ognuno richiede una scheda di rigenerazione per ogni canale acceso. {price}/mese a sito per la casupola.", @@ -2797,6 +2799,7 @@ "link_panels.behind_the_great_firewall":"Dietro il Great Firewall", "link_panels.biggest_fabric_money_can_buy":"Il fabric più grosso che si possa comprare.", "link_panels.biggest_feeder_egress_in_city_set":"Fonte principale: {egress} a {city}. Impostala su “Solo backup”, dai ai clienti un’uscita più vicina (peering, una cache, transit locale) o alza la metrica di questo link.", +"link_panels.border_closed":"Confine chiuso", "link_panels.build_a_pop_here_first":"Prima costruisci un POP qui.", "link_panels.cancel_the_iru":"Disdici l’IRU", "link_panels.carry_here":"Instrada qui", @@ -2894,6 +2897,7 @@ "link_panels.running_an_exchange_in_mainland":"Gestire un exchange nella Cina continentale richiede tutt’altra licenza. Fai peering con le reti cinesi tramite PNI, oppure incontrale a Hong Kong.", "link_panels.runs_at_g_per_channel_on":"Su questa tratta va a {g} per canale (modalità long-haul).", "link_panels.runs_on_its_own_route_a":"Segue un percorso tutto suo. Un taglio qui lascia in piedi gli altri link.", +"link_panels.russia_has_unplugged_itself_from_the":"La Russia si è staccata dal resto di internet per un'esercitazione di internet sovrano. Tutto ciò che esce dal paese resta spento fino a domani.", "link_panels.sell_one_price":"Vendine uno {price}", "link_panels.selling_spare_capacity":"Vendere la capacità libera", "link_panels.shares_a_trench_with_n_other":{"one":"Condivide lo scavo con {n} altro link. Un taglio li butta giù tutti.","other":"Condivide lo scavo con altri {n} link. Un taglio li butta giù tutti."}, diff --git a/site/i18n/pt.js b/site/i18n/pt.js index f915c74..0657f8f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2778,11 +2778,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Travessias premium só são vendidas em Hong Kong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Mesma vala mais barato · uma retro corta tudo", "link_modal.sold_out_for_n_days":"esgotado por {n} dias", +"link_modal.the_borders_around_qatar_are_closed":"As fronteiras em volta do Catar estão fechadas: um link entre Doha e a Arábia Saudita ou os Emirados vai ficar apagado até os vizinhos fazerem as pazes.", "link_modal.the_landing_permit_dispute_in_city":"A disputa de licença de desembarque em {city} bloqueia novos links subsea por mais {n} dias.", "link_modal.waves_are_leased_at_a_flat":"Waves são alugadas a uma mensalidade fixa. Maior e mais longa custa mais, e subsea é 1,8×. O primeiro mês vence agora.", "link_modal.waves_on_the_same_route_share":"Waves na mesma rota compartilham o destino: uma retroescavadeira corta todas.", "link_modal.you_already_have_n_link_here":{"one":"Você já tem {n} link aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?","other":"Você já tem {n} links aqui ({list}). Links paralelos somam capacidade. Como este deve ser roteado?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"Um fabric maior carrega mais tráfego e tem espaço para mais membros. Seu router aqui ainda precisa dar conta.", +"link_panels.a_diplomatic_spat_has_closed_the":"Uma briga diplomática fechou as fronteiras em volta do Catar, então todos os links entre Doha e a Arábia Saudita ou os Emirados estão fora do ar. Não há nada para reparar nem reparo urgente para diplomacia: faça a volta longa, pelo mar.", "link_panels.a_link_on_standby_carries_traffic":"Um link de reserva só leva tráfego quando os outros links entre estas cidades estão cheios ou fora do ar.", "link_panels.a_link_s_cost_is_its":"O custo de um link é seu comprimento em km mais 60, vezes um multiplicador. O tráfego segue o caminho de menor custo total.", "link_panels.a_regen_site_turns_the_light":"Um site de regeneração transforma a luz de volta em bits no meio do caminho e a reenvia novinha, então as ópticas só precisam alcançar o próximo site. Cada um precisa de uma placa de regeneração para cada canal aceso. {price}/mês por site pelo abrigo.", @@ -2797,6 +2799,7 @@ "link_panels.behind_the_great_firewall":"Atrás do Great Firewall", "link_panels.biggest_fabric_money_can_buy":"O maior fabric que o dinheiro pode comprar.", "link_panels.biggest_feeder_egress_in_city_set":"Maior fonte: {egress} em {city}. Coloque em “Só backup”, dê aos clientes uma saída mais próxima (peering, um cache, transit local) ou aumente a métrica deste link.", +"link_panels.border_closed":"Fronteira fechada", "link_panels.build_a_pop_here_first":"Construa um POP aqui primeiro.", "link_panels.cancel_the_iru":"Cancelar o IRU", "link_panels.carry_here":"Trazer para cá", @@ -2894,6 +2897,7 @@ "link_panels.running_an_exchange_in_mainland":"Operar um exchange na China continental exige uma licença totalmente diferente. Faça peering com redes chinesas via PNI ou encontre-as em Hong Kong.", "link_panels.runs_at_g_per_channel_on":"Nesta rota roda a {g} por canal (modo long-haul).", "link_panels.runs_on_its_own_route_a":"Segue uma rota própria. Um corte aqui deixa os outros links de pé.", +"link_panels.russia_has_unplugged_itself_from_the":"A Rússia se desligou do resto da internet para um exercício de internet soberana. Tudo o que sai do país fica apagado até amanhã.", "link_panels.sell_one_price":"Vender um {price}", "link_panels.selling_spare_capacity":"Vender capacidade ociosa", "link_panels.shares_a_trench_with_n_other":{"one":"Divide a vala com {n} outro link. Um corte derruba todos.","other":"Divide a vala com outros {n} links. Um corte derruba todos."}, diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index ddf1633..39f3e15 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -2,7 +2,10 @@ // sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} -function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l));} +const gulfPair=(a,b)=>!!((CITY[a].qa&&(CITY[b].gcc||CITY[b].uae))||(CITY[b].qa&&(CITY[a].gcc||CITY[a].uae))); +// A link a closed border has taken dark ('runet', 'gulf' or ''): no repair for it, so the panels name it instead (#329). +const borderShut=l=>S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b)?'runet':S.ev.gulf>S.day&&gulfPair(l.a,l.b)?'gulf':''; +function linkDown(l){return l.cut>S.day||!!borderShut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l));} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} // Monthly price of one connection; compute() sums these, the connections overview lists them. diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 705313a..39c6541 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -22,10 +22,11 @@ function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[ h+=``;} h+=``;return h; } +function borderSection(l){const w=borderShut(l);return w?`

${tr('link_panels.border_closed')}

${w==='gulf'?tr('link_panels.a_diplomatic_spat_has_closed_the')+' '+tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day}):tr('link_panels.russia_has_unplugged_itself_from_the')}

`:'';} function vxcPanel(l){ const load=R.load[l.id]||0,cap=VXC[l.vt].g,u=load/cap,down=linkDown(l),f=FAB[l.prov]; let h=`
${tr('link_panels.virtual_circuit_name_km_km',{name:esc(f.name),km:l.km.toLocaleString()})}

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; - if(down)h+=`

${tr('common.fabric_outage')}

${tr('link_panels.name_is_down_nothing_you_can',{name:esc(f.name)})}

`; + h+=borderSection(l);if(down&&!borderShut(l))h+=`

${tr('common.fabric_outage')}

${tr('link_panels.name_is_down_nothing_you_can',{name:esc(f.name)})}

`; h+=`

${tr('common.capacity')}

${tr('link_panels.name_circuit',{name:VXC[l.vt].n})}${fmtG(load)} / ${fmtG(cap)}
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${!S.pops[l.b]?`

${tr('link_panels.remote_peering_leg_into_ix',{ix:esc(CITY[l.b].ix)})}

`:''}
${VXC.map((V,t)=>t>l.vt?btn(`${V.n} ${tr('common.price_mo',{price:fmt$(vxcMo(l.km,l.sub,t))})}`,'upVxc',{id:l.id,t},'sm'):'').join('')}
@@ -117,6 +118,7 @@ function dfPanel(l){ if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; + h+=borderSection(l); h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${mwG(l)?` · ${tr('market.g_sold_as_managed',{g:fmtCap(mwG(l))})}`:''}${fmtG(load)} / ${fmtG(cap)}
${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; @@ -149,6 +151,7 @@ function linkPanel(id){ const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; if(cut)h+=`

${tr('common.cut_2e50')}

${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}

${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; + h+=borderSection(l); h+=`

${tr('common.capacity')}

${tr('link_panels.name_wave',{name:LT[l.tier].n})}${fmtG(load)} / ${fmtG(cap)}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.cable?`
${tr('common.cable_system')}${esc(CAB[l.cable].name)}
`:''}
${tr('common.wave_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${u>=0.9?`

${tr('link_panels.congested_upgrade_it_or_add_a')}

`:''} diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index 5041ab6..4fcce96 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -15,6 +15,7 @@ function openLinkModal(a,b){ openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):bare?(road?tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY[bare].name}):tr('link_modal.no_subsea_cable_lands_in_city_own',{city:CITY[bare].name})):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${(cabOpen()?!ownCabWhy(a,b):bare)?ownCabTeaser(a,b):''}`);return;} if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`

${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}

`);return;} if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`

${landWhy(a,b)}

`; + if(S.ev.gulf>S.day&&gulfPair(a,b))route+=`

${tr('link_modal.the_borders_around_qatar_are_closed')} ${tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day})}

`; route+=`

📈 ${esc(marketNote(a,b,sub))}

`; const wr=waveRoute(a,b,mult,border); openModal(`${head} diff --git a/src/game/95-modals/90-fiber-modals.js b/src/game/95-modals/90-fiber-modals.js index bc968bd..2cba83d 100644 --- a/src/game/95-modals/90-fiber-modals.js +++ b/src/game/95-modals/90-fiber-modals.js @@ -10,7 +10,7 @@ function dfModalBody(a,b,km,pop){ const src=UI.dfSrc==='build'&&!sc?'build':'lease',sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite',amps=ampCount(km); const up=(src==='build'?digCost(km):0)+sysCost(sys)+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO; const w=Math.round(waveMo(km,false,4)); - return `

${tr('fiber_modals.a_fiber_pair_of_your_own',{km:AMP_EVERY})}

+ return `${S.ev.gulf>S.day&&gulfPair(a,b)?`

${tr('link_modal.the_borders_around_qatar_are_closed')} ${tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day})}

`:''}

${tr('fiber_modals.a_fiber_pair_of_your_own',{km:AMP_EVERY})}

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready_n',{price:fmt$(dfLeaseMo(km)),n:leadDays(IRU_DAYS)}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_level_n',{n:CAB_LV}),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(glassLvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('specialist.dig_your_own_as_a_pioneer',{price:fmt$(digCost(km)),n:dfBuildDays(km),p:Math.round((PIONEER-1)*100)}),'dfSrc',{v:'build'},src==='build'?'pink':'ghost')}${sea?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_level_n',{n:CAB_LV}),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} ${src==='build'?`

${tr('fiber_modals.your_own_trench_almost_no_rent')}

`:''}

${tr('common.line_system')}

${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} ${!techOk('sys',k,DF_SYS[k].lvl)?tr('fiber_modals.level_n',{n:DF_SYS[k].lvl}):fmt$(sysCost(k))}`,'dfSys',{v:k},sys===k?'pink':'ghost',!techOk('sys',k,DF_SYS[k].lvl))).join('')}
${Object.keys(DF_SYS).filter(k=>!techOk('sys',k,DF_SYS[k].lvl)&&demoCan(DF_SYS[k].lvl)).map(k=>`
${demoBtn('sys',k,DF_SYS[k].lvl,'','ghost sm')} ${DF_SYS[k].n}
`).join('')} diff --git a/src/i18n/en.js b/src/i18n/en.js index 89e662f..bb7bbc3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2779,11 +2779,13 @@ "link_modal.premium_crossings_are_only_sold_in":"Premium crossings are only sold in Hong Kong.", "link_modal.same_trench_cheaper_one_backhoe_cuts":"Same trench cheaper · one backhoe cuts all", "link_modal.sold_out_for_n_days":"sold out for {n} days", +"link_modal.the_borders_around_qatar_are_closed":"The borders around Qatar are closed: a link between Doha and Saudi Arabia or the UAE will stay dark until the neighbours make up.", "link_modal.the_landing_permit_dispute_in_city":"The landing permit dispute in {city} blocks new subsea links for {n} more days.", "link_modal.waves_are_leased_at_a_flat":"Waves are leased at a flat monthly rate. Bigger and longer costs more, and subsea is 1.8×. First month is due now.", "link_modal.waves_on_the_same_route_share":"Waves on the same route share its fate: one backhoe cuts them all.", "link_modal.you_already_have_n_link_here":{"one":"You already have {n} link here ({list}). Parallel links add capacity. How should this one be routed?","other":"You already have {n} links here ({list}). Parallel links add capacity. How should this one be routed?"}, "link_panels.a_bigger_fabric_carries_more_traffic":"A bigger fabric carries more traffic and has room for more members. Your router here still has to keep up.", +"link_panels.a_diplomatic_spat_has_closed_the":"A diplomatic spat has closed the borders around Qatar, so every link between Doha and Saudi Arabia or the UAE is down. Nothing to repair and no rush job for diplomacy: route the long way round, by sea.", "link_panels.a_link_on_standby_carries_traffic":"A link on standby carries traffic only when the other links between these cities are full or down.", "link_panels.a_link_s_cost_is_its":"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.", "link_panels.a_regen_site_turns_the_light":"A regen site turns the light back into bits halfway and sends it on fresh, so optics only have to reach the next site. Each needs a regen card for every lit channel. {price}/mo per site for the hut.", @@ -2798,6 +2800,7 @@ "link_panels.behind_the_great_firewall":"Behind the Great Firewall", "link_panels.biggest_fabric_money_can_buy":"Biggest fabric money can buy.", "link_panels.biggest_feeder_egress_in_city_set":"Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.", +"link_panels.border_closed":"Border closed", "link_panels.build_a_pop_here_first":"Build a POP here first.", "link_panels.cancel_the_iru":"Cancel the IRU", "link_panels.carry_here":"Carry here", @@ -2895,6 +2898,7 @@ "link_panels.running_an_exchange_in_mainland":"Running an exchange in mainland China takes a different license entirely. Peer with Chinese networks over PNIs, or meet them in Hong Kong.", "link_panels.runs_at_g_per_channel_on":"Runs at {g} per channel on this route (long-haul mode).", "link_panels.runs_on_its_own_route_a":"Runs on its own route. A cut here leaves the other links up.", +"link_panels.russia_has_unplugged_itself_from_the":"Russia has unplugged itself from the rest of the internet for a sovereign internet drill. Everything leaving the country is dark until tomorrow.", "link_panels.sell_one_price":"Sell one {price}", "link_panels.selling_spare_capacity":"Selling spare capacity", "link_panels.shares_a_trench_with_n_other":{"one":"Shares a trench with {n} other link. One cut takes them all down.","other":"Shares a trench with {n} other links. One cut takes them all down."}, diff --git a/tests/border-closed-links.test.js b/tests/border-closed-links.test.js new file mode 100644 index 0000000..f084d0a --- /dev/null +++ b/tests/border-closed-links.test.js @@ -0,0 +1,53 @@ +// #329: a link a political event takes down (the Gulf spat, Russia's sovereign internet drill) is drawn broken on +// the map, so its panel must say why and for how long, and the link modal must warn before you lease one. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;"; +const panel = ev => ev("document.getElementById('panel').textContent"); + +test('#329 a link down for the Gulf spat says so in its panel, with the days left', () => { + const { ev, errors } = load(); + ev(start + "ACT.launchBB({city:'doh'});S.pops.auh={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:3};compute()"); + ev("S.links.push({id:'w1',a:'doh',b:'auh',kind:'wave',tier:0,km:300,sub:false,mo:1,cut:0,day:0})"); + const id = 'w1'; + ev('S.ev.gulf=S.day+40;compute()'); + assert.equal(ev(`linkDown(S.links.find(l=>l.id==='${id}'))`), true, 'the spat takes it down'); + ev(`selectLink('${id}')`); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Qatar/); + assert.match(panel(ev), /Back in 40 days/); + // Leasing another one now warns that it stays dark. + ev("openLinkModal('doh','auh')"); + assert.match(ev("document.getElementById('modalCard').textContent"), /stay dark/); + assert.match(ev("dfModalBody('doh','auh',300,0)"), /stay dark/, 'dark fiber warns too'); + // On a phone the panel is a bottom sheet with the same note. + ev(`closeModal();window.innerWidth=390;selectLink('${id}')`); + assert.match(panel(ev), /Border closed/); + ev('window.innerWidth=1280'); + // After the spat, nothing about it. + ev('S.ev.gulf=0;compute();closeModal()'); + ev(`selectLink('${id}')`); + assert.doesNotMatch(panel(ev), /Border closed/); + ev("openLinkModal('doh','auh')"); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /stay dark/); + assert.deepEqual(errors, []); +}); + +test('#329 dark fiber and virtual circuits into Qatar explain the spat too, and Russia\'s drill is named', () => { + const { ev, errors } = load(); + ev(start + "ACT.launchBB({city:'doh'});S.pops.auh={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:3};compute()"); + ev("S.links.push({id:'dfx',a:'doh',b:'auh',kind:'df',own:false,sys:'lite',ch:[],km:300,sub:false,mo:1,ready:0,cut:0,day:0});S.ev.gulf=S.day+10"); + ev("selectLink('dfx')"); + assert.match(panel(ev), /Border closed/); + ev("S.links.push({id:'vx1',a:'doh',b:'auh',kind:'vxc',prov:Object.keys(FAB)[0],vt:0,km:300,sub:false,mo:1,cut:0,day:0})"); + ev("selectLink('vx1')"); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Qatar/); + ev("S.links.push({id:'ru1',a:'mos',b:'hel',kind:'wave',tier:0,km:900,sub:false,mo:1,cut:0,day:0});S.ev.gulf=0;S.ev.runet=S.day+1"); + ev("selectLink('ru1')"); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Russia/); + assert.deepEqual(errors, []); +}); From d086fcbd9208eb76ab09a1997e80a2cbca918bf6 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 06:51:34 +0000 Subject: [PATCH 02/18] Show traffic, price per Gbps and path terms on renewal haggles; link panel city names open the city Renewal haggles in Deals now show booked and served Gbps (sites for SD-WAN), the price per Gbps now and asked, and the latency limit and path terms the customer signed for, each ticked as the network stands today (#292). The two city names in the header of wave, dark fiber and virtual circuit panels are buttons that open that city (#196). --- CHANGELOG.md | 2 + site/i18n/de.js | 6 ++ site/i18n/es.js | 6 ++ site/i18n/fr.js | 6 ++ site/i18n/it.js | 6 ++ site/i18n/pt.js | 6 ++ .../80-simulation/75-customer-lifecycle.js | 12 +++- src/game/93-ui/70-link-panels.js | 8 ++- src/i18n/en.js | 6 ++ src/styles/20-drawers.css | 2 + tests/link-panel-cities.test.js | 58 +++++++++++++++ tests/renewal-details.test.js | 72 +++++++++++++++++++ 12 files changed, 186 insertions(+), 4 deletions(-) create mode 100644 tests/link-panel-cities.test.js create mode 100644 tests/renewal-details.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 744dfae..68dcebc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). +- A customer asking for a discount at renewal now shows how much traffic they book and get, the price per Gbps now and asked, and any latency limit or path terms they signed for, each ticked or crossed as your network stands today (#292). +- The two city names at the top of a wave, dark fiber or virtual circuit panel now open that city, for example to upgrade the router there before a bigger link (#196). ## [3.3.0] — 2026-11-09 diff --git a/site/i18n/de.js b/site/i18n/de.js index 5402b72..9f2feba 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2738,6 +2738,12 @@ "lifecycle.odd_wireguard":"Sie gehen komplett remote. Alle 40 Leute fahren WireGuard aus ihren Küchen, und die Büroleitung ist nur noch für die Pflanzen.", "lifecycle.odd_wrong_blue":"Die neue Büroleitung will alle Kabel in derselben Farbe, und deins ist das falsche Blau.", "lifecycle.referred_by":"Empfohlen von {name}, einem deiner zufriedensten Kunden.", +"lifecycle.ren_diverse":"zwei getrennte Pfade", +"lifecycle.ren_lat":"Latenz bis {max} ms (jetzt {now})", +"lifecycle.ren_no_subsea":"kein Seekabel", +"lifecycle.ren_per_g":"{was} → {price} pro Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} Standort × {bw} gebucht, {srv} geliefert","other":"{n} Standorte × {bw} gebucht, {srv} geliefert"}, +"lifecycle.ren_traffic":"{bw} gebucht, {srv} geliefert", "lifecycle.renewal_haggle":"Verlängerung am {date}: wird verhandelt", "lifecycle.renewals":"Verlängerungen", "lifecycle.renewals_soon":"Verlängerungen", diff --git a/site/i18n/es.js b/site/i18n/es.js index feaa272..3b2f43e 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2736,6 +2736,12 @@ "lifecycle.odd_wireguard":"Se pasan al teletrabajo total. Los 40 empleados usarán WireGuard desde sus cocinas, y la línea de la oficina es solo para las plantas.", "lifecycle.odd_wrong_blue":"La nueva responsable de oficina quiere todos los cables del mismo color, y el tuyo es del azul equivocado.", "lifecycle.referred_by":"Recomendado por {name}, uno de tus clientes más contentos.", +"lifecycle.ren_diverse":"dos rutas diversas", +"lifecycle.ren_lat":"latencia de hasta {max} ms (ahora {now})", +"lifecycle.ren_no_subsea":"sin cable submarino", +"lifecycle.ren_per_g":"{was} → {price} por Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} sede × {bw} contratados, {srv} servidos","other":"{n} sedes × {bw} contratados, {srv} servidos"}, +"lifecycle.ren_traffic":"{bw} contratados, {srv} servidos", "lifecycle.renewal_haggle":"renovación el {date}: negociando", "lifecycle.renewals":"Renovaciones", "lifecycle.renewals_soon":"Renovaciones", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f971279..fd6e367 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2736,6 +2736,12 @@ "lifecycle.odd_wireguard":"Ils passent en télétravail complet. Les 40 salariés utiliseront WireGuard depuis leur cuisine, et la ligne du bureau ne sert plus qu'aux plantes.", "lifecycle.odd_wrong_blue":"La nouvelle responsable des locaux veut tous les câbles de la même couleur, et le vôtre n'est pas le bon bleu.", "lifecycle.referred_by":"Recommandé par {name}, l'un de vos clients les plus satisfaits.", +"lifecycle.ren_diverse":"deux chemins diversifiés", +"lifecycle.ren_lat":"latence jusqu’à {max} ms (maintenant {now})", +"lifecycle.ren_no_subsea":"pas de câble sous-marin", +"lifecycle.ren_per_g":"{was} → {price} par Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} site × {bw} réservés, {srv} servis","other":"{n} sites × {bw} réservés, {srv} servis"}, +"lifecycle.ren_traffic":"{bw} réservés, {srv} servis", "lifecycle.renewal_haggle":"renouvellement le {date} : en négociation", "lifecycle.renewals":"Renouvellements", "lifecycle.renewals_soon":"Renouvellements", diff --git a/site/i18n/it.js b/site/i18n/it.js index 9034753..797cb9b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2736,6 +2736,12 @@ "lifecycle.odd_wireguard":"Passano al lavoro tutto da remoto. I 40 dipendenti useranno WireGuard dalle loro cucine, e la linea dell'ufficio serve solo alle piante.", "lifecycle.odd_wrong_blue":"Il nuovo responsabile dell'ufficio vuole tutti i cavi dello stesso colore, e il tuo è del blu sbagliato.", "lifecycle.referred_by":"Consigliato da {name}, uno dei tuoi clienti più contenti.", +"lifecycle.ren_diverse":"due percorsi diversi", +"lifecycle.ren_lat":"latenza entro {max} ms (ora {now})", +"lifecycle.ren_no_subsea":"niente cavi sottomarini", +"lifecycle.ren_per_g":"{was} → {price} per Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} sede × {bw} prenotati, {srv} serviti","other":"{n} sedi × {bw} prenotati, {srv} serviti"}, +"lifecycle.ren_traffic":"{bw} prenotati, {srv} serviti", "lifecycle.renewal_haggle":"rinnovo il {date}: si tratta", "lifecycle.renewals":"Rinnovi", "lifecycle.renewals_soon":"Rinnovi", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0657f8f..626a03a 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2736,6 +2736,12 @@ "lifecycle.odd_wireguard":"Vão trabalhar 100% remoto. Os 40 funcionários vão usar WireGuard da cozinha, e a linha do escritório fica só para as plantas.", "lifecycle.odd_wrong_blue":"A nova gerente do escritório quer todos os cabos da mesma cor, e o seu é do azul errado.", "lifecycle.referred_by":"Indicado por {name}, um dos seus clientes mais felizes.", +"lifecycle.ren_diverse":"dois caminhos diversos", +"lifecycle.ren_lat":"latência de até {max} ms (agora {now})", +"lifecycle.ren_no_subsea":"sem cabo submarino", +"lifecycle.ren_per_g":"{was} → {price} por Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} unidade × {bw} contratados, {srv} entregues","other":"{n} unidades × {bw} contratados, {srv} entregues"}, +"lifecycle.ren_traffic":"{bw} contratados, {srv} entregues", "lifecycle.renewal_haggle":"renovação em {date}: negociando", "lifecycle.renewals":"Renovações", "lifecycle.renewals_soon":"Renovações", diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index aa9bc4c..d7b60e2 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -113,11 +113,21 @@ function mktPrice(from){const m=mkt();for(let i=from;iMath.round((b.rate+b.hag.rate)/2); const clBill=(b,rate)=>BIZ_T[b.type].fiber?rate:b.bw*rate; const clHags=()=>S?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0; +/* What is at stake in a renewal (#292): how much traffic they book and get, the price per Gbps now and asked, and the + path terms they signed for (latency, diverse, no subsea), each ticked as it stands today. Two short lines for a phone. */ +function clRenInfo(b){const T=BIZ_T[b.type],tick=v=>`${v?'✓':'✗'} `,top=[],rq=[]; + if(!T.fiber){const sf=bizSf(b),srv=`${fmtG(b.bw*sf)}`; + top.push(b.sites?trn('lifecycle.ren_sites_traffic',b.sites.length,{bw:fmtG(b.bw),srv}):tr('lifecycle.ren_traffic',{bw:fmtG(b.bw),srv})); + top.push(tr('lifecycle.ren_per_g',{was:fmt$(b.rate),price:fmt$(b.hag.rate)}));} + for(const k of b.reqs||[]){const Q=REQS[k];if(!Q)continue;const ok=Q.ok(b); + if(k==='lat'){const v=R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2);rq.push(tick(ok)+tr('lifecycle.ren_lat',{max:b.latMax,now:isFinite(v)?tr('common.ms_ms_one_way',{ms:v.toFixed(1)}):tr('common.no_path')}));} + else rq.push(tick(ok)+(k==='diverse'?tr('lifecycle.ren_diverse'):k==='sharks'?tr('lifecycle.ren_no_subsea'):esc(typeof Q.l==='function'?Q.l(b):Q.l)));} + return (top.length?`
${top.join(' · ')}
`:'')+(rq.length?`
${rq.join(' · ')}
`:'');} // The renewals waiting for an answer, at the top of Deals. function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return ''; return `

${tr('lifecycle.renewals')}

${tr('lifecycle.unanswered_matches')}

`+hs.map(b=>{const now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate,was=bizMo(b); return `
${esc(b.name)}
${esc(BIZ_T[b.type].l)} · ${esc(clWhere(b))} · ${tr('ui.n_d_left',{n:b.hag.until-S.day})}
-
${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}
${slRenRow(b)} +
${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}
${clRenInfo(b)}${slRenRow(b)}
${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway',{price:fmt$(clBill(b,clMid(b)))}),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}
`;}).join('');} // The contract line on a customer row. const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):''; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 39c6541..ff99639 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -23,9 +23,11 @@ function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[ h+=`
`;return h; } function borderSection(l){const w=borderShut(l);return w?`

${tr('link_panels.border_closed')}

${w==='gulf'?tr('link_panels.a_diplomatic_spat_has_closed_the')+' '+tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day}):tr('link_panels.russia_has_unplugged_itself_from_the')}

`:'';} +// Both ends of a link in its panel header open that city (#196), say to upgrade the router there for a bigger wave. +const lkEnds=l=>[l.a,l.b].map(c=>cityOn(c)?btn(esc(CITY[c].name),'popGo',{city:c},'clink'):esc(CITY[c].name)).join(' ⇄ '); function vxcPanel(l){ const load=R.load[l.id]||0,cap=VXC[l.vt].g,u=load/cap,down=linkDown(l),f=FAB[l.prov]; - let h=`
${tr('link_panels.virtual_circuit_name_km_km',{name:esc(f.name),km:l.km.toLocaleString()})}

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; + let h=`
${tr('link_panels.virtual_circuit_name_km_km',{name:esc(f.name),km:l.km.toLocaleString()})}

${lkEnds(l)}

`; h+=borderSection(l);if(down&&!borderShut(l))h+=`

${tr('common.fabric_outage')}

${tr('link_panels.name_is_down_nothing_you_can',{name:esc(f.name)})}

`; h+=`

${tr('common.capacity')}

${tr('link_panels.name_circuit',{name:VXC[l.vt].n})}${fmtG(load)} / ${fmtG(cap)}
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${!S.pops[l.b]?`

${tr('link_panels.remote_peering_leg_into_ix',{ix:esc(CITY[l.b].ix)})}

`:''} @@ -114,7 +116,7 @@ function layPanel(l){const d=S.day,st=layStart(l),q=layQuote(l),km=Math.round(la return h;} function dfPanel(l){ const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys]; - let h=`
${tr('link_panels.dark_fiber_kind_km_km',{kind:l.own?tr('link_panels.your_own_build'):tr('common.leased_iru'),km:l.km.toLocaleString()})}

${A} ⇄ ${B}

`; + let h=`
${tr('link_panels.dark_fiber_kind_km_km',{kind:l.own?tr('link_panels.your_own_build'):tr('common.leased_iru'),km:l.km.toLocaleString()})}

${lkEnds(l)}

`; if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; @@ -149,7 +151,7 @@ function linkPanel(id){ if(l.kind==='vxc')return vxcPanel(l); if(l.kind==='df')return dfPanel(l); const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); - let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; + let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${lkEnds(l)}

`; if(cut)h+=`

${tr('common.cut_2e50')}

${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}

${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; h+=borderSection(l); h+=`

${tr('common.capacity')}

${tr('link_panels.name_wave',{name:LT[l.tier].n})}${fmtG(load)} / ${fmtG(cap)}
diff --git a/src/i18n/en.js b/src/i18n/en.js index bb7bbc3..2649cfc 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2737,6 +2737,12 @@ "lifecycle.odd_wireguard":"They are going fully remote. All 40 staff will run WireGuard from their kitchens, and the office line is just for the plants.", "lifecycle.odd_wrong_blue":"The new office manager wants every cable the same colour, and yours is the wrong blue.", "lifecycle.referred_by":"Referred by {name}, one of your happiest customers.", +"lifecycle.ren_diverse":"two diverse paths", +"lifecycle.ren_lat":"latency within {max} ms (now {now})", +"lifecycle.ren_no_subsea":"no subsea cable", +"lifecycle.ren_per_g":"{was} → {price} per Gbps", +"lifecycle.ren_sites_traffic":{"one":"{n} site × {bw} booked, {srv} served","other":"{n} sites × {bw} booked, {srv} served"}, +"lifecycle.ren_traffic":"{bw} booked, {srv} served", "lifecycle.renewal_haggle":"renewal on {date}: haggling", "lifecycle.renewals":"Renewals", "lifecycle.renewals_soon":"Renewals", diff --git a/src/styles/20-drawers.css b/src/styles/20-drawers.css index 31fc819..8dfcadd 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -49,6 +49,8 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .b.green{background:var(--ok);color:#fff} .b.sm{font-size:12px;padding:2px 8px 1px;border-radius:9px;box-shadow:0 2px 0 var(--ink)} .b.big{font-size:18px;padding:7px 18px 5px} +/* A city name in a heading that opens the city (link panels, #196): reads as the heading, underlined like a link. */ +.b.clink,.b.clink:active{font:inherit;color:inherit;background:none;border:0;box-shadow:none;transform:none;padding:2px 0;border-radius:0;white-space:normal;text-align:left;text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:4px;text-decoration-color:var(--me)} .b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px} .logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em} diff --git a/tests/link-panel-cities.test.js b/tests/link-panel-cities.test.js new file mode 100644 index 0000000..5bbfef0 --- /dev/null +++ b/tests/link-panel-cities.test.js @@ -0,0 +1,58 @@ +// #196: the two city names at the top of a link panel (wave, dark fiber, virtual circuit) open that city's panel. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;"; +const ends = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#panel .ph h2 button[data-act=\"popGo\"]')].map(b=>[b.textContent,JSON.parse(b.dataset.args).city]))")); +const click = (ev, i) => ev(`document.querySelectorAll('#panel .ph h2 button[data-act="popGo"]')[${i}].click()`); + +function setup(ev) { + ev(start + "ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});compute()"); + ev("S.links.push({id:'w1',a:'fra',b:'ams',kind:'wave',tier:0,km:360,sub:false,mo:1,cut:0,day:0})"); + ev("S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:false,sys:'lite',ch:[],km:360,sub:false,mo:1,ready:0,cut:0,day:0})"); + ev("S.links.push({id:'vx1',a:'fra',b:'ams',kind:'vxc',prov:Object.keys(FAB)[0],vt:0,km:360,sub:false,mo:1,cut:0,day:0});compute()"); +} + +for (const [id, kind] of [['w1', 'wave'], ['df1', 'dark fiber'], ['vx1', 'virtual circuit']]) { + test(`#196 a ${kind} panel links both of its cities, and a click opens the city`, () => { + const { ev, errors } = load(); + setup(ev); + ev(`selectLink('${id}')`); + assert.deepEqual(ends(ev), [['Frankfurt', 'fra'], ['Amsterdam', 'ams']]); + assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Frankfurt ⇄ Amsterdam/); + click(ev, 1); + assert.equal(ev("UI.sel.type+':'+UI.sel.id"), 'city:ams', 'the far end is selected'); + assert.equal(ev("cam.x"), ev("CITY.ams.x"), 'and the map moves to it'); + assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Amsterdam/); + ev(`selectLink('${id}')`); + click(ev, 0); + assert.equal(ev("UI.sel.id"), 'fra'); + assert.deepEqual(errors, []); + }); +} + +test('#196 on a 390 px phone the city links sit in the bottom sheet header and still open the city', () => { + const { ev, errors } = load(); + setup(ev); + ev("window.innerWidth=390;renderAll();selectLink('w1')"); + assert.equal(ev("isPhone()"), true); + assert.equal(ends(ev).length, 2); + // The link styling: reads as heading text that wraps, not a button that pushes the header wider. + assert.match(ev("document.querySelector('#panel .ph h2 button').className"), /\bclink\b/); + click(ev, 0); + assert.equal(ev("UI.sel.type+':'+UI.sel.id"), 'city:fra'); + assert.deepEqual(errors, []); +}); + +test('#196 a city the map does not show stays plain text', () => { + const { ev, errors } = load(); + setup(ev); + ev("selectLink('w1')"); + // cityOn() is false for an off-map city without a POP or IX port: no button to a panel that would not open. + ev("CITY.ams.off=true;delete S.pops.ams;renderPanel()"); + assert.deepEqual(ends(ev), [['Frankfurt', 'fra']]); + assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Frankfurt ⇄ Amsterdam/); + ev("delete CITY.ams.off"); + assert.deepEqual(errors, []); +}); diff --git a/tests/renewal-details.test.js b/tests/renewal-details.test.js new file mode 100644 index 0000000..091aee3 --- /dev/null +++ b/tests/renewal-details.test.js @@ -0,0 +1,72 @@ +// #292: a renewal haggle in Deals shows what is at stake: traffic booked and served, the price per Gbps now and asked, +// and the path terms the customer signed for, each ticked as it stands today. It fits on a phone. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;"; +// Frankfurt, Paris and Amsterdam in a triangle, so Frankfurt-Amsterdam has a direct path and one round through Paris. +function net(ev) { + ev(start + "ACT.launchBB({city:'fra'});ACT.buildPop({city:'par'});ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}"); + for (const [a, b] of [['fra', 'par'], ['par', 'ams'], ['fra', 'ams']]) ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal()`); +} +const deals = ev => { ev("UI.left='deals';renderLeft()"); return ev("document.getElementById('left').innerHTML"); }; +const row = (ev, name) => ev(`(()=>{const r=[...document.querySelectorAll('#left .row')].find(r=>r.querySelector('.nm')&&r.querySelector('.nm').textContent==='${name}');return r?r.textContent:''})()`); + +test('#292 an IP customer\'s renewal shows booked and served traffic and the price per Gbps', () => { + const { ev, errors } = load(); + net(ev); + ev("S.biz.push({id:'h1',city:'ams',city2:null,name:'Haggle Hosting',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:540,until:S.day+20}});compute()"); + deals(ev); + const t = row(ev, 'Haggle Hosting'); + assert.match(t, /5\.0 Gbps booked, [\d.]+ Gbps served/); + assert.ok(t.includes(ev("fmt$(600)") + ' → ' + ev("fmt$(540)") + ' per Gbps'), t); + assert.match(t, /Pays .* wants .* to renew/, 'the monthly bills are still there'); + assert.deepEqual(errors, []); +}); + +test('#292 a circuit\'s renewal shows its latency limit and path terms, ticked as they stand today', () => { + const { ev, errors } = load(); + net(ev); + ev("S.biz.push({id:'c1',city:'fra',city2:'ams',name:'Tulip Bank',type:'l2vpn',bw:10,rate:300,reqs:['lat','diverse','sharks'],latMax:50,route:'fast',mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:250,until:S.day+20}});compute()"); + deals(ev); + let t = row(ev, 'Tulip Bank'); + assert.match(t, /10\.0 Gbps booked, 10\.0 Gbps served/); + assert.match(t, /✓ latency within 50 ms \(now [\d.]+ ms one-way\)/); + assert.match(t, /✓ two diverse paths/, 'direct and round through Paris'); + assert.match(t, /✓ no subsea cable/); + // A tight budget the network cannot meet is crossed out, with what it gets today. + ev("S.biz.find(b=>b.id==='c1').latMax=0.5;compute()"); + deals(ev); + t = row(ev, 'Tulip Bank'); + assert.match(t, /✗ latency within 0\.5 ms/); + assert.doesNotMatch(t, /undefined|NaN/); + assert.deepEqual(errors, []); +}); + +test('#292 SD-WAN shows its sites, fiber deals show no Gbps, and served traffic below what is booked is red', () => { + const { ev, errors } = load(); + net(ev); + ev("S.biz.push({id:'s1',city:'fra',city2:null,sites:['fra','par','ams'],name:'Kebab Kingdom',type:'sdwan',bw:2,rate:400,reqs:[],mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:360,until:S.day+20}});compute()"); + deals(ev); + assert.match(row(ev, 'Kebab Kingdom'), /3 sites × 2\.0 Gbps booked/); + assert.doesNotMatch(row(ev, 'Kebab Kingdom'), /✓|✗/, 'no path terms when they asked for none'); + assert.equal(ev("clRenInfo({...S.biz.find(b=>b.id==='s1'),type:'dfpair'})"), '', 'a fiber pair is not sold by the Gbps'); + ev("R.l2['s1']=0.5"); + assert.match(ev("clRenInfo(S.biz.find(b=>b.id==='s1'))"), /color:var\(--bad\)">0\.5 Gbps/); + assert.deepEqual(errors, []); +}); + +test('#292 the renewal row fits a 390 px phone', () => { + const { ev, errors } = load(); + net(ev); + ev("S.biz.push({id:'c1',city:'fra',city2:'ams',name:'Tulip Bank',type:'l2vpn',bw:10,rate:300,reqs:['lat','diverse'],latMax:50,route:'fast',mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:250,until:S.day+20}});compute()"); + ev("window.innerWidth=390;renderAll()"); + deals(ev); + assert.match(row(ev, 'Tulip Bank'), /booked, .* served/); + // Every new line is a wrapping meta line, never one wide nowrap element. + const info = ev("clRenInfo(S.biz.find(b=>b.id==='c1'))"); + assert.match(info, /^
/); + assert.doesNotMatch(info, /nowrap|width:\s*\d{3,}px/); + assert.deepEqual(errors, []); +}); From e51510a1159a2205d0b5cc1a55ce141ed6f12544 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 06:56:02 +0000 Subject: [PATCH 03/18] Strict latency contracts: big late-game customers who pay for a latency SLA (#137) From customer level 7, low-latency wholesale routes ask for 1.6 or 3.2 Tbps between two cities with the latency limit trading links already have (REQS.lat on the circuit latency compute() measures). They pay about three times a hyperscaler DCI per Gbps on the same route, never grow past 3.2 Tbps, and every day over the limit after the provisioning grace credits a day's fee and costs extra patience. New rule F9 in gameplay-rules. --- .claude/skills/gameplay-rules/SKILL.md | 1 + CHANGELOG.md | 1 + site/i18n/de.js | 6 +- site/i18n/es.js | 6 +- site/i18n/fr.js | 6 +- site/i18n/it.js | 6 +- site/i18n/pt.js | 6 +- src/game/40-progress/10-businesses.js | 6 +- src/game/60-features/38-latency-contracts.js | 25 +++ src/game/80-simulation/50-sanitize.js | 2 +- .../80-simulation/70-customers-and-events.js | 2 +- .../80-simulation/75-customer-lifecycle.js | 3 +- src/game/88-days/10-day-tick.js | 6 +- src/i18n/en.js | 6 +- tests/gameplay-rules.test.js | 24 +++ tests/latency-contracts.test.js | 162 ++++++++++++++++++ 16 files changed, 255 insertions(+), 13 deletions(-) create mode 100644 src/game/60-features/38-latency-contracts.js create mode 100644 tests/latency-contracts.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index d6fba4b..f1a5bee 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -72,6 +72,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | | F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | | F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | +| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. | ## DDoS diff --git a/CHANGELOG.md b/CHANGELOG.md index 744dfae..124425f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). - A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). ## [3.3.0] — 2026-11-09 diff --git a/site/i18n/de.js b/site/i18n/de.js index 5402b72..b0339b6 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -407,7 +407,6 @@ "broker.win_text":"{name} (AS{asn}) hat in {days} Tagen eigene Kabel auf {n} Kontinente verlegt und verkauft anderen Carriern Kapazität für {mo} im Monat. Die Ozeane sind jetzt dein Graben.", "broker.won_on_date":"Gewonnen am {date}: Deine eigenen Kabel überspannen die Ozeane, und Carrier zahlen dir für ihre Nutzung.", "broker.your_glass_gear_is_already_yours":"Als Kabelmakler gehören dir jede Fiber, jedes Leitungssystem, jede Optik, jedes Seekabel und die Router, um sie zu beleuchten, schon jetzt, egal was das Level sagt.", -"businesses.a_free_pni_with_voda_phony":"Ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.", "businesses.agi_lab_allegedly":"AGI-Labor (angeblich)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI-Labore (angeblich), die KI-WANs mit 12,8 bis 25,6 Tbps wollen, und kostenlose PNIs mit Du-opoly und Ooh-redoo. Hardware: Mikrowtik-CCR-3.2T-Router.", "businesses.ai_gpu_data_center":"KI-GPU-Rechenzentrum", @@ -436,6 +435,8 @@ "businesses.hundreds_of_fiber_pairs":"Hunderte Faserpaare", "businesses.internet_weather_system":"Internet-Wettersystem", "businesses.it_s_not_dns_there_s":"Es ist nicht DNS. Auf keinen Fall ist es DNS. Es war DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Low-Latency-Wholesale-Routen (ab 1.6T, mit Latenz-SLA) und ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.", +"businesses.low_latency_wholesale_route":"Low-Latency-Wholesale-Route", "businesses.mars_mission_ground_station":"Bodenstation für die Marsmission", "businesses.mars_mission_ground_stations_gear":"Bodenstationen für die Marsmission. Hardware: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mars-Mission über deine Pies", @@ -2656,6 +2657,9 @@ "keys.show_this_list":"Diese Liste zeigen", "keys.space":"Leertaste", "keys.zoom_the_map_out_or":"Karte heraus- oder hineinzoomen", +"latency_contracts.credits_paid":"{price} an SLA-Gutschriften gezahlt", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} läuft mit {ms} ms, über den {max} ms aus dem Vertrag. Jeder Tag darüber kostet dich eine Tagesgebühr an SLA-Gutschriften ({price}).", +"latency_contracts.sla_terms":"Latenz-SLA {ms} ms: eine Tagesgebühr zurück für jeden Tag darüber · nie mehr als {max}", "lease_swaps.cap_fabric_circuit":"{cap}-Fabric-Verbindung", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} auf einer Dark-Fiber-IRU", "lease_swaps.cap_wave":"{cap}-Wave", diff --git a/site/i18n/es.js b/site/i18n/es.js index feaa272..c4bdb73 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) tendió sus propios cables hasta {n} continentes y vende {mo} al mes de capacidad a otros operadores, en {days} días. Los océanos son ahora tu zanja.", "broker.won_on_date":"Ganado el {date}: tus propios cables cruzan los océanos y los operadores te pagan por usarlos.", "broker.your_glass_gear_is_already_yours":"Como bróker de cables, toda la fibra, los sistemas de línea, los ópticos, los cables submarinos y los routers para iluminarlos ya son tuyos, diga lo que diga el nivel.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio de AGI (supuestamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratorios de AGI (supuestamente) que quieren WAN de IA de 12.8 a 25.6 Tbps, y PNIs gratis con Du-opoly y Ooh-redoo. Equipo: routers Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Centro de datos de GPU para IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Cientos de pares de fibra", "businesses.internet_weather_system":"Sistema meteorológico de internet", "businesses.it_s_not_dns_there_s":"No es el DNS. Imposible que sea el DNS. Era el DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rutas mayoristas de baja latencia (desde 1.6T, con SLA de latencia) y un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.", +"businesses.low_latency_wholesale_route":"Ruta mayorista de baja latencia", "businesses.mars_mission_ground_station":"Estación terrestre de misión a Marte", "businesses.mars_mission_ground_stations_gear":"Estaciones terrestres de misiones a Marte. Equipo: El Router del Fin del Universo.", "businesses.mars_mission_over_your_pies":"Misión a Marte por tus pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostrar esta lista", "keys.space":"Espacio", "keys.zoom_the_map_out_or":"Alejar o acercar el mapa", +"latency_contracts.credits_paid":"{price} pagados en créditos SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} va a {ms} ms, por encima de los {max} ms del contrato. Cada día por encima te cuesta un día de cuota en créditos SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latencia {ms} ms: un día de cuota devuelto por cada día por encima · nunca más de {max}", "lease_swaps.cap_fabric_circuit":"Circuito de fabric de {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} en una IRU de fibra oscura", "lease_swaps.cap_wave":"Onda de {cap}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f971279..0b0b12e 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) a posé ses propres câbles jusqu’à {n} continents et vend {mo} de capacité par mois à d’autres opérateurs, en {days} jours. Les océans sont ta tranchée maintenant.", "broker.won_on_date":"Gagné le {date} : tes propres câbles traversent les océans, et les opérateurs te paient pour s’en servir.", "broker.your_glass_gear_is_already_yours":"En courtier en câbles, toute la fibre, les systèmes de ligne, les optiques, les câbles sous-marins et les routeurs pour les allumer sont déjà à toi, quoi que dise le niveau.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.", "businesses.agi_lab_allegedly":"Labo d’AGI (soi-disant)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Des labos d’AGI (soi-disant) qui veulent des WAN IA de 12,8 à 25,6 Tbps, et des PNI gratuits avec Du-opoly et Ooh-redoo. Matos : routeurs Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Datacenter GPU pour l’IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Des centaines de paires de fibre", "businesses.internet_weather_system":"Météo d’Internet", "businesses.it_s_not_dns_there_s":"Ce n’est pas le DNS. Impossible que ce soit le DNS. C’était le DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Des routes de gros à faible latence (à partir de 1.6T, avec SLA de latence), et un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.", +"businesses.low_latency_wholesale_route":"Route de gros à faible latence", "businesses.mars_mission_ground_station":"Station sol de mission martienne", "businesses.mars_mission_ground_stations_gear":"Stations sol de missions martiennes. Matos : The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mission martienne via tes pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Afficher cette liste", "keys.space":"Espace", "keys.zoom_the_map_out_or":"Dézoomer ou zoomer la carte", +"latency_contracts.credits_paid":"{price} versés en crédits SLA", +"latency_contracts.over_sla":"{name} : {a} ⇄ {b} tourne à {ms} ms, au-delà des {max} ms du contrat. Chaque jour au-dessus te coûte une journée de facture en crédits SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latence {ms} ms : une journée de facture remboursée par jour au-dessus · jamais plus de {max}", "lease_swaps.cap_fabric_circuit":"circuit fabric {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} sur un IRU de fibre noire", "lease_swaps.cap_wave":"longueur d’onde {cap}", diff --git a/site/i18n/it.js b/site/i18n/it.js index 9034753..e95b6a2 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) ha posato i propri cavi fino a {n} continenti e vende {mo} al mese di capacità ad altri operatori, in {days} giorni. Gli oceani ora sono la tua trincea.", "broker.won_on_date":"Vinto il {date}: i tuoi cavi attraversano gli oceani e gli operatori ti pagano per usarli.", "broker.your_glass_gear_is_already_yours":"Da broker di cavi, ogni fibra, sistema di linea, ottica, cavo sottomarino e i router per accenderli sono già tuoi, qualunque cosa dica il livello.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio AGI (a sentir loro)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratori AGI (a sentir loro) che vogliono AI WAN da 12.8 a 25.6 Tbps, e PNI gratuiti con Du-opoly e Ooh-redoo. Gear: router Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Data center GPU per l’AI", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Centinaia di coppie in fibra", "businesses.internet_weather_system":"Sistema meteorologico di internet", "businesses.it_s_not_dns_there_s":"Non è il DNS. Non può essere il DNS. Era il DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rotte wholesale a bassa latenza (da 1.6T in su, con SLA di latenza) e un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.", +"businesses.low_latency_wholesale_route":"Rotta wholesale a bassa latenza", "businesses.mars_mission_ground_station":"Stazione di terra per una missione su Marte", "businesses.mars_mission_ground_stations_gear":"Stazioni di terra per missioni su Marte. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Missione su Marte via i tuoi pie", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostra questo elenco", "keys.space":"Spazio", "keys.zoom_the_map_out_or":"Zoom indietro o avanti sulla mappa", +"latency_contracts.credits_paid":"{price} pagati in crediti SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} viaggia a {ms} ms, oltre i {max} ms del contratto. Ogni giorno sopra ti costa un giorno di canone in crediti SLA ({price}).", +"latency_contracts.sla_terms":"SLA di latenza {ms} ms: un giorno di canone restituito per ogni giorno sopra · mai più di {max}", "lease_swaps.cap_fabric_circuit":"circuito fabric da {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} su una dark fiber IRU", "lease_swaps.cap_wave":"wave da {cap}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0657f8f..11e4a50 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) lançou os próprios cabos até {n} continentes e vende {mo} por mês de capacidade a outras operadoras, em {days} dias. Os oceanos agora são a sua vala.", "broker.won_on_date":"Vencido em {date}: seus próprios cabos cruzam os oceanos e as operadoras pagam para usá-los.", "broker.your_glass_gear_is_already_yours":"Como corretor de cabos, toda fibra, sistema de linha, óptico, cabo submarino e os roteadores para acendê-los já são seus, diga o nível o que disser.", -"businesses.a_free_pni_with_voda_phony":"Um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.", "businesses.agi_lab_allegedly":"Laboratório de AGI (supostamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratórios de AGI (supostamente) querendo AI WANs de 12.8 a 25.6 Tbps, e PNIs grátis com a Du-opoly e a Ooh-redoo. Gear: routers Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Data center de GPU para IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Centenas de pares de fibra", "businesses.internet_weather_system":"Sistema meteorológico da internet", "businesses.it_s_not_dns_there_s":"Não é DNS. Não tem como ser DNS. Era DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rotas atacadistas de baixa latência (a partir de 1.6T, com SLA de latência) e um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.", +"businesses.low_latency_wholesale_route":"Rota atacadista de baixa latência", "businesses.mars_mission_ground_station":"Estação terrestre de missão a Marte", "businesses.mars_mission_ground_stations_gear":"Estações terrestres de missões a Marte. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Missão a Marte pelos seus pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostrar esta lista", "keys.space":"Espaço", "keys.zoom_the_map_out_or":"Afastar ou aproximar o mapa", +"latency_contracts.credits_paid":"{price} pagos em créditos de SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} roda a {ms} ms, acima dos {max} ms do contrato. Cada dia acima te custa um dia de mensalidade em créditos de SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latência {ms} ms: um dia de mensalidade devolvido por cada dia acima · nunca mais que {max}", "lease_swaps.cap_fabric_circuit":"circuito de fabric de {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} numa IRU de dark fiber", "lease_swaps.cap_wave":"wave de {cap}", diff --git a/src/game/40-progress/10-businesses.js b/src/game/40-progress/10-businesses.js index a79314c..dc45c81 100644 --- a/src/game/40-progress/10-businesses.js +++ b/src/game/40-progress/10-businesses.js @@ -28,6 +28,10 @@ const BIZ_T={ pairs:{l:tr('businesses.hundreds_of_fiber_pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, esport:{l:tr('businesses.esports_world_final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, sov:{l:tr('businesses.sovereign_cloud_region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, + // Strict latency contracts (#137): a carrier or market-data network buys big capacity on one route with a latency SLA, + // the premium paid for the guaranteed milliseconds (km), credits paid for every day over it (38-latency-contracts.js), + // and never more than max: one customer cannot carry a whole level. + lowlat:{l:tr('businesses.low_latency_wholesale_route'),opts:[1600,3200],max:3200,rate:0,l2:true,lat:true,sla:true,km:2,lv:7,names:['Great Circle Clearing House','Straight Line Settlements','Millisecond Markets Exchange','Photon Arbitrage Partners','Shortest Path Securities','Tick Feed Torrent Co.','Matching Engine Mirror Ltd','Speed-of-Glass Replication','Order Book Express','Consolidated Tape Worm']}, cgame:{l:tr('businesses.cloud_gaming_platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, metav:{l:tr('common.metaverse_platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, agi:{l:tr('businesses.agi_lab_allegedly'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, @@ -49,7 +53,7 @@ const LEVELS=[ {n:tr('common.big_league'),q:tr('businesses.your_mtu_is_9000_on_every'),req:tr('businesses.peak_3_tbps_10_pops_3'),unlock:tr('businesses.ai_training_interconnects_and')}, {n:tr('common.continental_carrier'),q:tr('businesses.your_noc_has_a_chat_channel'),req:tr('businesses.peak_6_tbps_15_pops_4'),era:1.15,unlock:tr('businesses.esports_world_finals_and_the_4k')}, {n:tr('common.transcontinental'),q:tr('businesses.you_joined_the_outages_mailing_list'),req:tr('businesses.peak_9_tbps_and_20_pops'),unlock:tr('businesses.sovereign_cloud_regions_and_a_free')}, - {n:tr('common.global_backbone'),q:tr('businesses.your_asn_now_shows_up_in'),req:tr('businesses.peak_12_tbps_25_pops_5'),unlock:tr('businesses.a_free_pni_with_voda_phony')}, + {n:tr('common.global_backbone'),q:tr('businesses.your_asn_now_shows_up_in'),req:tr('businesses.peak_12_tbps_25_pops_5'),unlock:tr('businesses.low_latency_routes_and_a_free_pni')}, {n:tr('common.packet_empire'),q:tr('businesses.your_maintenance_window_is_2_a'),req:tr('businesses.peak_16_tbps_and_32_pops'),era:1.15,unlock:tr('businesses.cloud_gaming_platforms_and_the_cloud')}, {n:tr('businesses.six_continent_carrier'),q:tr('businesses.somewhere_on_every_continent_a'),req:tr('businesses.peak_21_tbps_40_pops_6'),unlock:tr('businesses.metaverse_platforms_it_finally_took')}, {n:tr('businesses.backbone_of_backbones'),q:tr('businesses.your_routing_table_needs_its_own'),req:tr('businesses.peak_26_tbps_and_50_pops'),era:1.2,unlock:tr('businesses.the_vr_era_eyeballs_want_20')}, diff --git a/src/game/60-features/38-latency-contracts.js b/src/game/60-features/38-latency-contracts.js new file mode 100644 index 0000000..d430c54 --- /dev/null +++ b/src/game/60-features/38-latency-contracts.js @@ -0,0 +1,25 @@ +/* ---------- Strict latency contracts (#137) ---------- + Late in the game, carriers and market-data networks buy 1.6 or 3.2T on one route with a latency SLA, the way real + low-latency wholesale is sold: a premium per Gbps for guaranteed milliseconds, and a service credit for every day the + circuit runs over them. They are an ordinary customer type (BIZ_T.lowlat) with the latency requirement every trading + link has (REQS.lat on R.l2lat, the one-way path latency compute() measures), offered from customer level LC_LV, and + never bigger than BIZ_T.lowlat.max: one contract cannot carry a level on its own. */ +const LC_LV=BIZ_T.lowlat.lv,LC_MOOD=3,LC_GRACE=15; +// Once a day for each customer, from the mood check: a latency customer over its SLA after the provisioning grace is +// credited that day's fee and loses patience faster than for a bandwidth problem alone. Returns that extra mood lost. +function lcBreach(b,d){const T=BIZ_T[b.type];if(!T||!T.sla)return 0; + if(d-(b.since||0)0)||REQS.lat.ok(b)){delete b.lcB;return 0;} + const cr=Math.round(bizMo(b)/monLen(d));S.cash-=cr;b.lcCr=(b.lcCr||0)+cr; + if(!b.lcB){b.lcB=1;const v=R.l2lat[b.id]; + toast(tr('latency_contracts.over_sla',{name:esc(b.name),a:CITY[b.city].name,b:CITY[b.city2].name,ms:isFinite(v)?v.toFixed(1):'∞',max:b.latMax,price:fmt$(cr)}),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);} + return LC_MOOD;} +// The contract, on its offer and customer rows (bRisk()). +function lcNote(b){const T=BIZ_T[b.type];if(!T||!T.sla)return ''; + return `
⏱️ ${tr('latency_contracts.sla_terms',{ms:b.latMax,max:fmtG(T.max)})}${b.lcCr>0?' · '+tr('latency_contracts.credits_paid',{price:fmt$(b.lcCr)}):''}
`;} +// Saves: credits paid and the breach flag are numbers and a flag; a contract is never bigger than its type allows. +function lcSanitize(s){for(const b of [...s.biz,...s.offers]){const T=BIZ_T[b.type]; + if(b.lcCr!==undefined){const v=Math.round(+b.lcCr);if(Number.isFinite(v)&&v>0)b.lcCr=v;else delete b.lcCr;} + if(b.lcB!==undefined){if(b.lcB)b.lcB=1;else delete b.lcB;} + if(T&&T.max)b.bw=Math.min(T.max,Math.max(T.opts[0],b.bw)); + if(T&&T.sla&&Array.isArray(b.reqs)&&!b.reqs.includes('lat'))b.reqs.unshift('lat'); + if(T&&T.sla&&!(b.latMax>0)&&isCity(b.city)&&b.city2&&isCity(b.city2))b.latMax=latMaxOf(b.city,b.city2);}} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index db35e34..7d0d9cd 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -113,7 +113,7 @@ function sanitize(s){ three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} - specSanitize(s); + specSanitize(s);lcSanitize(s); cmFix(s); pieSanitize(s);pieIncFix(s);volFix(s); if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js index cf037a7..f2a906c 100644 --- a/src/game/80-simulation/70-customers-and-events.js +++ b/src/game/80-simulation/70-customers-and-events.js @@ -5,7 +5,7 @@ function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boole function bHas(o){return !!BIZ_T[o.type].cap||!!BIZ_T[o.type].orbit||bCities(o).every(c=>S.pops[c]);} function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}
`:'';} +function bRisk(b){return (BIZ_T[b.type]?.gaming&&!ddosOff()?`
⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}
`:'')+lcNote(b);} function bTerms(o){const T=BIZ_T[o.type];if(T.cap)return capTerms(o); if(T.event){const live=S.day>=o.start;return tr('customers_and_events.bw_extra_for_d_days_when',{bw:fmtG(o.bw),d:o.dur,when:live?tr('customers_and_events.day_n_of_d',{n:S.day-o.start+1,d:o.dur}):tr('customers_and_events.starting_in_n_d',{n:o.start-S.day}),fee:fmt$(o.fee)});} if(T.sdwan)return tr('customers_and_events.n_sites_list_bw_per_site',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index aa9bc4c..b93f6be 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -59,7 +59,8 @@ function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); // Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. -function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;} +// A type with a most (max) never grows past it (#137). +function clGrow(b){const T=BIZ_T[b.type];if(T.fiber||(T.max&&b.bw>=T.max))return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=T.max?Math.min(T.max,up||b.bw*2):up||b.bw*2;return true;} // Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 572e7ed..f4b3f58 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -69,10 +69,10 @@ function* dayPost(d){ (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood - const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); + const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b),lcX=lcBreach(b,d); if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2); else if(S.day-(b.since||0)<15){} - else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; + else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0)+lcX);b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; // An orbit customer served in full but promised more (the shark's full sky) grumbles, and never cancels over it. if(BIZ_T[b.type].orbit&&sf>=0.95&&reachOk)b.mood=Math.max(b.mood,Math.min(b.pm,PIE_GRUMBLE)); if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(tr('day_tick.name_cancelled_too_many_outages_and',{name:esc(b.name),city:CITY[b.city].name}),'bad');sfx('err');} @@ -134,7 +134,7 @@ function spawnOffer(){ const bk=broker(),dfR=S.links.some(l=>l.kind==='df'&&l.ready<=S.day),dfO=S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day); if(dfR)types.push('wwave','wwave');if(dfO)types.push('dfpair');if(bk){if(dfR)types.push('wwave','wwave','wwave','wwave');if(dfO)types.push('dfpair','dfpair','dfpair');}if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper'); if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if((lv>=4||bk)&&dfO)types.push('pairs'); - if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); + if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=LC_LV&&mine.length>=2)types.push('lowlat','lowlat');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); // Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. const dense=mine.filter(c=>(CITY_PDB[c]||[])[2]>=2000);if(lv>=2&&dense.length)types.push('isp'); diff --git a/src/i18n/en.js b/src/i18n/en.js index bb7bbc3..10697f3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -406,7 +406,6 @@ "broker.win_text":"{name} (AS{asn}) laid its own cables onto {n} continents and sells {mo} a month of capacity to other carriers, in {days} days. The oceans are your trench now.", "broker.won_on_date":"Won on {date}: your own cables span the oceans, and carriers pay you to use them.", "broker.your_glass_gear_is_already_yours":"As a Cable broker, every fiber, line system, optic, subsea cable and the routers to light them are yours already, whatever the level says.", -"businesses.a_free_pni_with_voda_phony":"A free PNI with Voda-Phony. Gear: Absolute Unit 3.2T routers, 3.2T ports and 12.8T waves.", "businesses.agi_lab_allegedly":"AGI lab (allegedly)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI labs (allegedly) wanting AI WANs of 12.8 to 25.6 Tbps, and free PNIs with Du-opoly and Ooh-redoo. Gear: Mikrowtik CCR 3.2T routers.", "businesses.ai_gpu_data_center":"AI GPU data center", @@ -435,6 +434,8 @@ "businesses.hundreds_of_fiber_pairs":"Hundreds of fiber pairs", "businesses.internet_weather_system":"Internet weather system", "businesses.it_s_not_dns_there_s":"It's not DNS. There's no way it's DNS. It was DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Low-latency wholesale routes (1.6T and up, with a latency SLA), and a free PNI with Voda-Phony. Gear: Absolute Unit 3.2T routers, 3.2T ports and 12.8T waves.", +"businesses.low_latency_wholesale_route":"Low-latency wholesale route", "businesses.mars_mission_ground_station":"Mars mission ground station", "businesses.mars_mission_ground_stations_gear":"Mars mission ground stations. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mars mission over your pies", @@ -2655,6 +2656,9 @@ "keys.show_this_list":"Show this list", "keys.space":"Space", "keys.zoom_the_map_out_or":"Zoom the map out or in", +"latency_contracts.credits_paid":"{price} paid in SLA credits", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} runs at {ms} ms, over the {max} ms in its contract. Every day over costs you a day's fee in SLA credits ({price}).", +"latency_contracts.sla_terms":"Latency SLA {ms} ms: a day's fee back for every day over it · never more than {max}", "lease_swaps.cap_fabric_circuit":"{cap} fabric circuit", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} on a dark fiber IRU", "lease_swaps.cap_wave":"{cap} wave", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 44414ca..4352927 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -485,6 +485,30 @@ test('F8: a managed wave costs your own capacity, rides one optic, and is priced assert.deepEqual(g.errors, []); }); +test('F9: a latency contract is late, capped, achievable, paid for its latency and credited when over it (#137)', () => { + const T = J('BIZ_T.lowlat'); + assert.ok(T.lv >= 7, `F9: from customer level 7, not ${T.lv}`); + assert.ok(T.l2 && T.lat && T.sla, 'F9: a circuit with a latency limit and an SLA'); + assert.ok(Math.min(...T.opts) >= 1600 && Math.max(...T.opts) <= T.max && T.max <= 3200, 'F9: 1.6T and up, never past 3.2T'); + assert.equal(ev("(()=>{const x={type:'lowlat',bw:BIZ_T.lowlat.max};return clGrow(x)||x.bw!==BIZ_T.lowlat.max;})()"), false, 'F9: never grows past its most'); + // Per Gbps on the same route, the bare contract beats any other big circuit with every extra it can ask for. + const best = ev("Math.max(...['hyper','ai','aiwan'].map(t=>BIZ_T[t].km))*(1+REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus)"); + assert.ok(T.km > best, `F9: ${T.km} per km-unit against the best other big circuit's ${best}`); + const g = load(); + g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=BIZ_T.lowlat.lv-1;S.biz=[];S.offers=[];for(const c of ['nyc','chi','lon','fra','tok','sin'])if(!S.pops[c])ACT.buildPop({city:c});compute()"); + const spawn = (n) => g.ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers.filter(o=>o.type==='lowlat'));}S.offers=[];return JSON.stringify(out);})()`); + assert.deepEqual(JSON.parse(spawn(400)), [], 'F9: none below its level'); + g.ev('S.lvl=BIZ_T.lowlat.lv'); + const os = JSON.parse(spawn(400)); + assert.ok(os.length > 0, 'F9: offered at its level'); + for (const o of os) assert.ok(g.ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), `F9: ${o.city}–${o.city2} in ${o.latMax} ms can be built`); + g.ev("S.biz.push({id:'x',type:'lowlat',name:'X',city:'nyc',city2:'chi',bw:1600,rate:100,reqs:['lat'],latMax:0.1,mood:100,since:S.day-30});compute()"); + const cash = g.ev('S.cash'); + assert.equal(g.ev("lcBreach(S.biz.find(b=>b.id==='x'),S.day)"), g.ev('LC_MOOD'), 'F9: over its limit, it loses patience'); + assert.equal(Math.round(cash - g.ev('S.cash')), g.ev('Math.round(1600*100/monLen(S.day))'), "F9: and a day's fee comes back as a credit"); + assert.deepEqual(g.errors, []); +}); + // D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail. const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()"); const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`); diff --git a/tests/latency-contracts.test.js b/tests/latency-contracts.test.js new file mode 100644 index 0000000..df345f2 --- /dev/null +++ b/tests/latency-contracts.test.js @@ -0,0 +1,162 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Strict latency contracts (#137): big customers who pay for a latency SLA on one route, late in the game. +const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'nyc'})"; +const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};S.pops['${c}'].rgen=RG.length-1;`; +const wave = (id, a, b) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'wave',tier:6,n:1,km:kmBetween('${a}','${b}'),cut:0,mo:0,day:0,ready:0});`; +const CITIES = ['nyc', 'chi', 'ash', 'mia', 'lon', 'fra']; +const net = () => CITIES.map(pop).join('') + wave('nc', 'nyc', 'chi') + wave('na', 'nyc', 'ash') + wave('am', 'ash', 'mia') + wave('mc', 'mia', 'chi') + 'compute();'; +// Spawn n offers, each on its own, and keep them all. +const spawnMany = (ev, n) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers);}S.offers=[];return JSON.stringify(out);})()`)); +// A latency contract on New York ⇄ Chicago, signed long enough ago that its provisioning grace is over. +const sign = (bw = 1600) => `(()=>{const b={id:'lc1',city:'nyc',city2:'chi',name:'Shortest Path Securities',type:'lowlat',bw:${bw},rate:500,reqs:['lat'],latMax:latMaxOf('nyc','chi'),route:'fast',mood:100,since:S.day-30};S.biz.push(b);compute();return b.id;})()`; + +test('#137 latency contracts are offered only from their customer level, sized and priced as promised', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV-1'); + assert.ok(ev('LC_LV') >= 7, 'a late-game customer'); + const early = spawnMany(ev, 600); + assert.equal(early.filter((o) => o.type === 'lowlat').length, 0, 'never below its level'); + ev('S.lvl=LC_LV'); + const late = spawnMany(ev, 600); + const lc = late.filter((o) => o.type === 'lowlat'); + assert.ok(lc.length >= 5, `they call at their level (${lc.length})`); + for (const o of lc) { + assert.ok([1600, 3200].includes(o.bw), 'big: 1.6T or 3.2T'); + assert.equal(o.reqs[0], 'lat', 'always a latency limit'); + assert.equal(o.latMax, ev(`latMaxOf('${o.city}','${o.city2}')`), 'the limit every latency customer gets'); + assert.ok(ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), 'and one something you can build meets'); + } + // Pay: per Gbps on the same route, above any other high-volume circuit (hyperscaler DCI, AI interconnects), whatever they ask for. + const per = (o) => o.rate / ev(`150+kmBetween('${o.city}','${o.city2}')*0.08`); + const big = late.filter((o) => ['hyper', 'ai', 'aiwan'].includes(o.type)); + assert.ok(big.length >= 5, 'there are other big circuits to compare with'); + assert.ok(Math.min(...lc.map(per)) > Math.max(...big.map(per)), 'a latency contract pays more per Gbps than any other big circuit'); + // Same size, same route: a 1.6T latency contract against a 1.6T hyperscaler DCI with every extra a DCI can ask for. + const o = lc[0], km = ev(`kmBetween('${o.city}','${o.city2}')`); + const dciBest = (150 + km * 0.08) * ev('BIZ_T.hyper.km') * (1 + ev("REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus")); + assert.ok(1600 * o.rate > 1600 * dciBest, 'beats a fully loaded DCI of the same size'); + assert.deepEqual(errors, []); +}); + +test('#137 the latency limit is the circuit latency the game already measures, and breaking it costs credits and the customer', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV'); + ev(sign()); + const b = "S.biz.find(b=>b.id==='lc1')"; + assert.ok(ev(`R.l2lat['lc1']<=${b}.latMax`), 'the direct wave meets it'); + assert.ok(ev(`REQS.lat.ok(${b})`)); + assert.ok(ev(`bizSf(${b})>=0.95`), 'and carries all of it'); + // Cut the direct wave: the circuit reroutes the long way round, still carried in full but too slow. + ev("S.links.find(l=>l.id==='nc').cut=S.day+400;compute()"); + assert.ok(ev(`bizSf(${b})>=0.95`), 'all the bandwidth still arrives'); + assert.ok(ev(`R.l2lat['lc1']>${b}.latMax`), 'over its limit'); + assert.ok(!ev(`REQS.lat.ok(${b})`), 'REQS.lat says so'); + assert.ok(ev(`bizWhy(${b}).some(w=>/latency/i.test(w))`), 'and the customer row says why'); + // A day over: a day's fee back as an SLA credit, and more patience lost than a plain latency customer (HFT) loses. + const cash = ev('S.cash'), mo = ev(`bizMo(${b})`), days = ev('monLen(S.day)'); + const extra = ev(`lcBreach(${b},S.day)`); + assert.equal(extra, ev('LC_MOOD')); + assert.equal(Math.round(cash - ev('S.cash')), Math.round(mo / days), "a day's fee credited"); + assert.equal(ev(`${b}.lcCr`), Math.round(mo / days)); + assert.equal(ev("lcBreach({type:'hft',since:0,latMax:1,city:'nyc',city2:'chi',reqs:['lat'],id:'x'},S.day)"), 0, 'only latency contracts pay credits'); + // In the provisioning grace (rule F1) nothing is credited and nothing is lost. + assert.equal(ev(`(()=>{const x={...${b},id:'lc2',since:S.day-3};return lcBreach(x,S.day);})()`), 0); + // Day after day over the limit: unhappy, warned, and gone, with credits paid every day. + const m0 = ev(`${b}.mood`); + ev('dayTick()'); + const m1 = ev(`${b}.mood`); + assert.ok(m0 - m1 >= 6 - 1e-9, `loses at least 6 a day over its SLA (${m0} → ${m1})`); + let gone = false; + for (let i = 0; i < 40 && !gone; i++) { + ev("S.links.find(l=>l.id==='nc').cut=S.day+400;dayTick()"); + gone = !ev("S.biz.some(b=>b.id==='lc1')"); + } + assert.ok(gone, 'a contract over its latency for weeks cancels'); + assert.deepEqual(errors, []); +}); + +test('#137 a latency contract within its limit stays happy and pays no credits', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev(sign()); + ev("S.biz.find(b=>b.id==='lc1').mood=90"); + for (let i = 0; i < 5; i++) ev("S.links.forEach(l=>l.cut=0);dayTick()"); + const b = ev("JSON.stringify(S.biz.find(b=>b.id==='lc1')||null)"); + const o = JSON.parse(b); + assert.ok(o, 'still a customer'); + assert.equal(o.lcCr, undefined, 'no credits'); + assert.equal(o.lcB, undefined, 'not in breach'); + assert.ok(o.mood > 90, `happier every day it is served (${o.mood})`); + assert.deepEqual(errors, []); +}); + +test('#137 the volume cap holds: renewals, a sales shark and an edited save never take one past 3.2T', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev(sign(1600)); + const b = "S.biz.find(b=>b.id==='lc1')"; + assert.ok(ev('Math.max(...BIZ_T.lowlat.opts)<=BIZ_T.lowlat.max'), 'a shark bumps an offer one size up its list, never past the most'); + assert.equal(ev(`clGrow(${b})`), true, 'grows to the next size once'); + assert.equal(ev(`${b}.bw`), 3200); + assert.equal(ev(`clGrow(${b})`), false, 'and never past it'); + assert.equal(ev(`${b}.bw`), 3200); + assert.equal(ev("(()=>{const x={type:'hyper',bw:6400};clGrow(x);return x.bw;})()"), 12800, 'other customers still double past their top size'); + // An edited save asking for more is cut back to the most the type sells. + ev(`${b}.bw=51200`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev(`${b}.bw`), 3200); + assert.deepEqual(errors, []); +}); + +test('#137 old saves load, and new fields from a save are checked', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + // A save from before latency contracts: nothing of theirs in it. + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.ok(!ev("S.biz.some(b=>b.type==='lowlat')")); + // A save with a contract whose fields were edited or lost. + ev(sign()); + ev(`(()=>{const s=JSON.parse(JSON.stringify(S)),b=s.biz.find(b=>b.id==='lc1');b.lcCr='lots';b.lcB='yes';delete b.latMax;b.reqs=[];S=migrate(s);compute();})()`); + const b = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.id==='lc1'))")); + assert.equal(b.lcCr, undefined, 'junk credits dropped'); + assert.equal(b.lcB, 1, 'flag as a flag'); + assert.equal(b.latMax, ev("latMaxOf('nyc','chi')"), 'the latency limit comes back'); + assert.ok(b.reqs.includes('lat'), 'and its requirement'); + ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.biz.find(b=>b.id==='lc1').lcCr=${lit(1234.4)};S=migrate(s);})()`); + assert.equal(ev("S.biz.find(b=>b.id==='lc1').lcCr"), 1234); + assert.deepEqual(errors, []); +}); + +test('#137 offer and customer rows on a 390 px phone', () => { + const { ev, dom, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV'); + ev("S.offers.push({id:'o1',city:'nyc',city2:'chi',name:'Great Circle Clearing House',type:'lowlat',bw:3200,rate:900,reqs:['lat'],latMax:latMaxOf('nyc','chi'),exp:S.day+40})"); + dom.window.innerWidth = 390; + ev("ACT.leftTab({t:'deals'});renderAll()"); + const html = dom.window.document.body.innerHTML; + assert.match(html, /Great Circle Clearing House/); + assert.match(html, /Low-latency wholesale route/); + assert.match(html, /Latency SLA [\d.]+ ms: a day's fee back for every day over it · never more than 3\.20 Tbps/); + ev("ACT.accept({id:'o1'})"); + const c = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.name==='Great Circle Clearing House'))")); + assert.equal(c.route, 'fast', 'routed for latency'); + assert.equal(c.latMax, ev("latMaxOf('nyc','chi')")); + ev(`S.biz.find(b=>b.id===${lit(c.id)}).lcCr=5000;renderAll()`); + const cs = ev('custSection()'); + assert.match(cs, /Low-latency wholesale route/); + assert.match(cs, /\$5\.0k paid in SLA credits/); + assert.deepEqual(errors, []); +}); From 32b0b282f817d4535b0764426334101958c0d8e8 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 07:03:57 +0000 Subject: [PATCH 04/18] Bulk actions for the late game: POP standards, kit everywhere, buy on signing, network search - POP standards by kind (micro, medium, regional hub), one button per POP and one per kind in Utilities (#315) - Redundancy kit at every POP from Utilities, and in the intern's template (#317) - Offers that need a generator, second router or second site can buy it and sign (#241) - The intern's Light more fiber order can leave new fiber dark (#316) - Search and connected-only filter for a POP's transit, exchange, PNI and cache lists (#199) - The link panel moves on to the next parallel link after a decommission (#119) --- CHANGELOG.md | 6 + site/i18n/de.js | 44 ++++ site/i18n/es.js | 44 ++++ site/i18n/fr.js | 44 ++++ site/i18n/it.js | 44 ++++ site/i18n/pt.js | 44 ++++ src/agent/10-domains.js | 2 + src/agent/20-commands.js | 23 +++ src/agent/30-docs.js | 1 + src/agent/60-dispatch.js | 2 +- src/game/60-features/39-req-fix.js | 20 ++ src/game/60-features/80-new-game.js | 2 +- src/game/60-features/95-standing-orders.js | 9 +- src/game/60-features/96-pop-tiers.js | 49 +++++ src/game/70-rules/95-utilities.js | 6 + src/game/80-simulation/50-sanitize.js | 2 + src/game/90-actions/46-net-filter.js | 6 + src/game/90-actions/51-customer-fix.js | 10 + src/game/90-actions/60-links.js | 5 +- src/game/90-actions/85-pop-tiers.js | 16 ++ src/game/90-actions/88-utilities.js | 8 + src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/50-city-panel.js | 12 +- src/game/93-ui/51-net-filter.js | 14 ++ src/game/93-ui/52-pni-list.js | 5 +- src/game/93-ui/55-utilities.js | 8 + src/game/93-ui/70-link-panels.js | 5 +- src/i18n/en.js | 44 ++++ src/styles/36-net-filter.css | 5 + tests/bulk-actions.test.js | 226 +++++++++++++++++++++ tests/mcp-commands.test.js | 2 +- 31 files changed, 692 insertions(+), 18 deletions(-) create mode 100644 src/game/60-features/39-req-fix.js create mode 100644 src/game/60-features/96-pop-tiers.js create mode 100644 src/game/90-actions/46-net-filter.js create mode 100644 src/game/90-actions/51-customer-fix.js create mode 100644 src/game/90-actions/85-pop-tiers.js create mode 100644 src/game/93-ui/51-net-filter.js create mode 100644 src/styles/36-net-filter.css create mode 100644 tests/bulk-actions.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 744dfae..ff61ad9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). +- Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). +- A customer asking for a backup generator, a second router or a second site at POPs you already have now shows what is missing and what it costs, with a button that buys exactly that and signs the deal. Nothing is bought unless you press it (#241). +- The NOC intern's "Light more fiber" order can now leave new fiber dark, so a fiber handed over in the night no longer pulls in traffic before you are ready for it. Fiber you light yourself still gets more optics when it runs hot (#316). +- The Transit and Peering tabs of a POP have a search box for a network's name or AS number and a "Connected only" switch, so you can find the one network you need in a long list, on phones too (#199). +- Decommissioning one of several links between the same two cities keeps the link panel open on the next one, so you can hand back a row of waves without reopening it each time (#119). - A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). ## [3.3.0] — 2026-11-09 diff --git a/site/i18n/de.js b/site/i18n/de.js index 5402b72..52f3ae3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3161,6 +3161,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.", "modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…", "modals.your_own_subsea_cable_level_n":"Eigenes Seekabel Level {n} oder Tier 1", +"net_filter.clear":"Zurücksetzen", +"net_filter.connected_only":"Nur verbundene", +"net_filter.find_a_network":"Netzwerk oder AS-Nummer suchen", "networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.", "networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.", "networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.", @@ -3396,6 +3399,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Ab", +"ops.p_fresh":"Neue Glasfaser anknipsen", "ops.p_g":"Ab", "ops.p_how":"Wie", "ops.p_keep":"Einen in Reserve", @@ -3927,6 +3931,29 @@ "pop_std.none":"Keiner", "pop_std.not_all_of_the_standard":"Nicht genug Geld oder Level für den ganzen Standard in {city}: Er bekam, was passte.", "pop_std.standard_for_new_pops":"Standard für neue POPs", +"pop_tiers.apply_cost":"Auf Standard bringen {cost}", +"pop_tiers.bring_up_n":{"one":"{n} POP hochbringen {cost}","other":"{n} POPs hochbringen {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind}: {n} POP auf den Standard gebracht.","other":"{kind}: {n} POPs auf den Standard gebracht."}, +"pop_tiers.bulk_note":"Jeder POP, den du als eine Art markiert hast, in einem Rutsch auf ihren Standard gebracht. Ändere einen Standard (neues Modell, mehr Router) und drück nochmal.", +"pop_tiers.city_is_kind":"{city} erfüllt den Standard {kind}.", +"pop_tiers.hub":"Regionaler Hub", +"pop_tiers.mark":"Markieren", +"pop_tiers.medium":"Mittlerer POP", +"pop_tiers.meets_it":"Erfüllt", +"pop_tiers.micro":"Mikro-POP", +"pop_tiers.model_locked":"{model} gibt es ab Kundenlevel {lv}.", +"pop_tiers.n_below":{"one":"{n} unter dem Standard","other":"{n} unter dem Standard"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"pop_tiers.n_stuck":{"one":"{n} geht noch nicht","other":"{n} gehen noch nicht"}, +"pop_tiers.no_kind":"Noch keine Art", +"pop_tiers.not_all":"In {city} ging nicht der ganze Standard rein. Schau in den Infra-Tab.", +"pop_tiers.not_set":"noch nicht festgelegt", +"pop_tiers.note":"Speichere die Router eines POPs als Standard und markiere dann andere POPs als diese Art. Auf Standard bringen fügt Router hinzu und tauscht auf das größere Modell, nie einen Schritt zurück. Unter Werkzeuge bringst du alle POPs einer Art auf einmal hoch.", +"pop_tiers.save_here":"Diese Router speichern", +"pop_tiers.saved":"{kind} ist jetzt {desc}.", +"pop_tiers.swapped_today":"Die Router hier wurden heute getauscht. Versuch es morgen wieder.", +"pop_tiers.this_pop_is":"Dieser POP: {kind}", +"pop_tiers.title":"POP-Standards", "pops_transit_ix.40_off_for_6_months":"40 % Rabatt für 6 Monate", "pops_transit_ix.40_off_ix_for_6_months":"40 % Rabatt auf {ix} für 6 Monate.
Dein Account Manager ist erleichtert. Das Kleingedruckte liest du später.", "pops_transit_ix.after_consulting_with_management_the":"„Nach Rücksprache mit dem Management …“
Der Preis ist gestiegen. Das Management wurde konsultiert.", @@ -4194,6 +4221,12 @@ "release_notes.read_the_full_notes_on_github":"Alle Hinweise auf GitHub lesen", "release_notes.series_of_tubes_v_is_out":"Series of Tubes {v} ist da!", "release_notes.your_game_is_saved_automatically":"Dein Spiel wird automatisch gespeichert.", +"req_fix.bought":"Gekauft: {list} für {cost}.", +"req_fix.buy_and_sign":"Kaufen und unterschreiben {cost}", +"req_fix.buys_list":"Es fehlt: {list}. {cost} + {mo}/Monat.", +"req_fix.generator_in_city":"ein Notstromaggregat in {city}", +"req_fix.second_router_in_city":"ein zweiter Router in {city}", +"req_fix.second_site_in_city":"ein zweiter Standort in {city}", "requirements.a_spare_fiber_pair_in_your":"ein freies Faserpaar in deinem Graben {a}–{b}", "requirements.afraid_of_sharks_needs_a_path":"Angst vor Haien: braucht einen Pfad ohne Seekabel", "requirements.backup_generator_in_every_city_they":"Notstromgenerator in jeder Stadt, in der sie vertreten sind", @@ -4828,9 +4861,20 @@ "utilities.caches_requested":"{n} Cache-Boxen in {city} installiert.", "utilities.ix_peering":"IX-Peering im ganzen Netz", "utilities.join_route_servers":"Allen Route Servern beitreten ({n})", +"utilities.kit_all_applied":{"one":"Redundanz-Kit in {n} POP eingebaut.","other":"Redundanz-Kit in {n} POPs eingebaut."}, +"utilities.kit_all_apply":{"one":"Kit in {n} POP {cost}","other":"Kit in alle {n} POPs {cost}"}, +"utilities.kit_all_done":"Jeder POP hat das komplette Kit.", +"utilities.kit_all_quote":{"one":"{n} POP braucht es · {cost} + {mo}/Monat","other":"{n} POPs brauchen es · {cost} + {mo}/Monat"}, "utilities.kit_applied":"Redundanz in {city} aktualisiert.", "utilities.kit_balanced":"Hardware installiert und Caches ausgeglichen.", "utilities.kit_cost":"Einmalig: {cost} · Zusätzliche Kosten pro Monat: {mo}", +"utilities.kit_everywhere":"Redundanz-Kit überall", +"utilities.kit_everywhere_note":"Das Kit in jedem POP, dem noch ein Teil davon fehlt: Notstrom, zweites Gebäude, zweiter Router, Caches auf beide Standorte verteilt. Ein Preis für alle.", +"utilities.kit_new_pops_hire":"Stell einen NOC-Praktikanten ein, dann eröffnest du neue POPs aus einer Vorlage, das Kit schon drin.", +"utilities.kit_new_pops_off":"Neue POPs aus der Vorlage von {name} kommen ohne das Kit.", +"utilities.kit_new_pops_on":"Neue POPs aus der Vorlage von {name} bekommen das Kit gleich mit.", +"utilities.kit_new_pops_start":"Kit in die Vorlage", +"utilities.kit_new_pops_stop":"Kit aus der Vorlage nehmen", "utilities.peer_counts":"{ready} möglich · {existing} bestehend · {blocked} nicht verfügbar", "utilities.peering_note":"Fordert an jedem IX, an dem du bist, alle möglichen Peers an. Bestehende Sessions, auch über Route Server, werden übersprungen. Absagen und Traffic-Schwellen gelten weiter. Es werden keine Ports oder bezahlten PNIs gekauft.", "utilities.peers_requested":"{n} neue IX-Peering-Sessions aufgebaut.", diff --git a/site/i18n/es.js b/site/i18n/es.js index feaa272..467c907 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3159,6 +3159,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.", "modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…", "modals.your_own_subsea_cable_level_n":"Tu propio cable submarino nivel {n} o Tier 1", +"net_filter.clear":"Borrar", +"net_filter.connected_only":"Solo conectadas", +"net_filter.find_a_network":"Buscar una red o número de AS", "networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.", "networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.", @@ -3394,6 +3397,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Por encima de", +"ops.p_fresh":"Encender fibra nueva", "ops.p_g":"Desde", "ops.p_how":"Cómo", "ops.p_keep":"Dejar uno de reserva", @@ -3925,6 +3929,29 @@ "pop_std.none":"Ninguno", "pop_std.not_all_of_the_standard":"No hay dinero o nivel para todo el estándar en {city}: recibió lo que cupo.", "pop_std.standard_for_new_pops":"Estándar para nuevos POP", +"pop_tiers.apply_cost":"Ponerlo al día {cost}", +"pop_tiers.bring_up_n":{"one":"Poner al día {n} POP {cost}","other":"Poner al día {n} POPs {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind}: {n} POP puesto al día.","other":"{kind}: {n} POPs puestos al día."}, +"pop_tiers.bulk_note":"Cada POP que marcaste de un tipo, puesto al día con su estándar de una vez. Cambia un estándar (un modelo nuevo, más routers) y vuelve a pulsar.", +"pop_tiers.city_is_kind":"{city} cumple el estándar {kind}.", +"pop_tiers.hub":"Hub regional", +"pop_tiers.mark":"Marcarlo", +"pop_tiers.medium":"POP mediano", +"pop_tiers.meets_it":"Lo cumple", +"pop_tiers.micro":"Micro POP", +"pop_tiers.model_locked":"{model} se desbloquea en el nivel de clientes {lv}.", +"pop_tiers.n_below":{"one":"{n} por debajo del estándar","other":"{n} por debajo del estándar"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"pop_tiers.n_stuck":{"one":"{n} todavía no puede","other":"{n} todavía no pueden"}, +"pop_tiers.no_kind":"Sin tipo aún", +"pop_tiers.not_all":"En {city} no entró todo el estándar. Revisa la pestaña Infra.", +"pop_tiers.not_set":"sin definir", +"pop_tiers.note":"Guarda los routers de un POP como estándar y marca otros POPs de ese tipo. Ponerlo al día añade routers y cambia al modelo más grande, nunca un paso atrás. En Utilidades pones al día todos los POPs de un tipo a la vez.", +"pop_tiers.save_here":"Guardar estos routers", +"pop_tiers.saved":"{kind} ahora es {desc}.", +"pop_tiers.swapped_today":"Los routers de aquí se cambiaron hoy. Prueba mañana.", +"pop_tiers.this_pop_is":"Este POP: {kind}", +"pop_tiers.title":"Estándares de POP", "pops_transit_ix.40_off_for_6_months":"40 % de descuento durante 6 meses", "pops_transit_ix.40_off_ix_for_6_months":"40 % de descuento en {ix} durante 6 meses.
Tu gestor de cuenta está aliviado. Lee la letra pequeña más tarde.", "pops_transit_ix.after_consulting_with_management_the":"«Tras consultar con la dirección…»
El precio subió. Se consultó a la dirección.", @@ -4192,6 +4219,12 @@ "release_notes.read_the_full_notes_on_github":"Lee las notas completas en GitHub", "release_notes.series_of_tubes_v_is_out":"¡Ya salió Series of Tubes {v}!", "release_notes.your_game_is_saved_automatically":"Tu partida se guarda automáticamente.", +"req_fix.bought":"Comprado: {list} por {cost}.", +"req_fix.buy_and_sign":"Comprar y firmar {cost}", +"req_fix.buys_list":"Falta: {list}. {cost} + {mo}/mes.", +"req_fix.generator_in_city":"un generador de respaldo en {city}", +"req_fix.second_router_in_city":"un segundo router en {city}", +"req_fix.second_site_in_city":"un segundo sitio en {city}", "requirements.a_spare_fiber_pair_in_your":"un par de fibra libre en tu zanja {a}–{b}", "requirements.afraid_of_sharks_needs_a_path":"Miedo a los tiburones: necesita una ruta sin cable submarino", "requirements.backup_generator_in_every_city_they":"Generador de respaldo en cada ciudad que toquen", @@ -4826,9 +4859,20 @@ "utilities.caches_requested":"Se han instalado {n} cachés en {city}.", "utilities.ix_peering":"Peering IX en toda la red", "utilities.join_route_servers":"Unirse a todos los route servers ({n})", +"utilities.kit_all_applied":{"one":"Kit de redundancia instalado en {n} POP.","other":"Kit de redundancia instalado en {n} POPs."}, +"utilities.kit_all_apply":{"one":"Kit en {n} POP {cost}","other":"Kit en los {n} POPs {cost}"}, +"utilities.kit_all_done":"Todos los POPs tienen el kit completo.", +"utilities.kit_all_quote":{"one":"{n} POP lo necesita · {cost} + {mo}/mes","other":"{n} POPs lo necesitan · {cost} + {mo}/mes"}, "utilities.kit_applied":"Redundancia actualizada en {city}.", "utilities.kit_balanced":"Hardware instalado y cachés equilibradas.", "utilities.kit_cost":"Pago único: {cost} · Coste mensual adicional: {mo}", +"utilities.kit_everywhere":"Kit de redundancia en todas partes", +"utilities.kit_everywhere_note":"El kit en cada POP al que todavía le falta alguna parte: generador, segundo edificio, segundo router, cachés repartidas entre sitios. Un solo precio para todos.", +"utilities.kit_new_pops_hire":"Contrata a un becario del NOC para abrir POPs nuevos con una plantilla que ya incluye el kit.", +"utilities.kit_new_pops_off":"Los POPs nuevos abiertos con la plantilla de {name} llegan sin el kit.", +"utilities.kit_new_pops_on":"Los POPs nuevos abiertos con la plantilla de {name} también llevan el kit.", +"utilities.kit_new_pops_start":"Meter el kit en la plantilla", +"utilities.kit_new_pops_stop":"Sacarlo de la plantilla", "utilities.peer_counts":"{ready} elegibles · {existing} existentes · {blocked} no disponibles", "utilities.peering_note":"Solicita peers elegibles en cada IX al que te hayas unido. Se omiten las sesiones existentes, incluidos los peers del route server. Los rechazos y umbrales de tráfico siguen vigentes. No se compran puertos ni PNI de pago.", "utilities.peers_requested":"Se han establecido {n} nuevas sesiones de peering IX.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f971279..e91f313 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3159,6 +3159,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.", "modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…", "modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin niveau {n} ou Tier 1", +"net_filter.clear":"Effacer", +"net_filter.connected_only":"Connectés seulement", +"net_filter.find_a_network":"Chercher un réseau ou un numéro d'AS", "networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.", "networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.", "networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.", @@ -3394,6 +3397,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Au-delà de", +"ops.p_fresh":"Allumer la fibre neuve", "ops.p_g":"À partir de", "ops.p_how":"Comment", "ops.p_keep":"En garder un de secours", @@ -3925,6 +3929,29 @@ "pop_std.none":"Aucun", "pop_std.not_all_of_the_standard":"Pas assez d'argent ou de niveau pour tout le standard à {city} : il a reçu ce qui passait.", "pop_std.standard_for_new_pops":"Standard des nouveaux POP", +"pop_tiers.apply_cost":"Le mettre à niveau {cost}", +"pop_tiers.bring_up_n":{"one":"Mettre {n} POP à niveau {cost}","other":"Mettre {n} POP à niveau {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind} : {n} POP mis à niveau.","other":"{kind} : {n} POP mis à niveau."}, +"pop_tiers.bulk_note":"Chaque POP que tu as marqué d'un type, mis à niveau selon son standard d'un seul coup. Change un standard (nouveau modèle, plus de routeurs) et appuie à nouveau.", +"pop_tiers.city_is_kind":"{city} respecte le standard {kind}.", +"pop_tiers.hub":"Hub régional", +"pop_tiers.mark":"Le marquer", +"pop_tiers.medium":"POP moyen", +"pop_tiers.meets_it":"Conforme", +"pop_tiers.micro":"Micro-POP", +"pop_tiers.model_locked":"{model} se débloque au niveau clients {lv}.", +"pop_tiers.n_below":{"one":"{n} sous le standard","other":"{n} sous le standard"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"pop_tiers.n_stuck":{"one":"{n} ne peut pas encore","other":"{n} ne peuvent pas encore"}, +"pop_tiers.no_kind":"Pas encore de type", +"pop_tiers.not_all":"Tout le standard n'a pas pu être installé à {city}. Regarde l'onglet Infra.", +"pop_tiers.not_set":"pas encore défini", +"pop_tiers.note":"Enregistre les routeurs d'un POP comme standard, puis marque d'autres POP de ce type. La mise à niveau ajoute des routeurs et passe au plus gros modèle, jamais un pas en arrière. Les Utilitaires mettent à niveau tous les POP d'un type d'un coup.", +"pop_tiers.save_here":"Enregistrer ces routeurs", +"pop_tiers.saved":"{kind} est maintenant {desc}.", +"pop_tiers.swapped_today":"Les routeurs ici ont été changés aujourd'hui. Réessaie demain.", +"pop_tiers.this_pop_is":"Ce POP : {kind}", +"pop_tiers.title":"Standards de POP", "pops_transit_ix.40_off_for_6_months":"40 % de remise pendant 6 mois", "pops_transit_ix.40_off_ix_for_6_months":"40 % de remise sur {ix} pendant 6 mois.
Ton account manager est soulagé. Lis les petites lignes plus tard.", "pops_transit_ix.after_consulting_with_management_the":"« Après consultation de la direction… »
Le prix a augmenté. La direction a été consultée.", @@ -4192,6 +4219,12 @@ "release_notes.read_the_full_notes_on_github":"Lire les notes complètes sur GitHub", "release_notes.series_of_tubes_v_is_out":"Series of Tubes {v} est sorti !", "release_notes.your_game_is_saved_automatically":"Ta partie est sauvegardée automatiquement.", +"req_fix.bought":"Acheté : {list} pour {cost}.", +"req_fix.buy_and_sign":"Acheter et signer {cost}", +"req_fix.buys_list":"Il manque : {list}. {cost} + {mo}/mois.", +"req_fix.generator_in_city":"un groupe électrogène à {city}", +"req_fix.second_router_in_city":"un second routeur à {city}", +"req_fix.second_site_in_city":"un second site à {city}", "requirements.a_spare_fiber_pair_in_your":"une paire de fibre libre dans ta tranchée {a}–{b}", "requirements.afraid_of_sharks_needs_a_path":"A peur des requins : veut un chemin sans câble sous-marin", "requirements.backup_generator_in_every_city_they":"Groupe électrogène dans chaque ville qu’il touche", @@ -4826,9 +4859,20 @@ "utilities.caches_requested":"{n} caches installés à {city}.", "utilities.ix_peering":"Peering IX sur tout le réseau", "utilities.join_route_servers":"Rejoindre tous les route servers ({n})", +"utilities.kit_all_applied":{"one":"Kit de redondance installé dans {n} POP.","other":"Kit de redondance installé dans {n} POP."}, +"utilities.kit_all_apply":{"one":"Kit pour {n} POP {cost}","other":"Kit pour les {n} POP {cost}"}, +"utilities.kit_all_done":"Chaque POP a le kit complet.", +"utilities.kit_all_quote":{"one":"{n} POP en a besoin · {cost} + {mo}/mois","other":"{n} POP en ont besoin · {cost} + {mo}/mois"}, "utilities.kit_applied":"Redondance mise à jour à {city}.", "utilities.kit_balanced":"Matériel installé et caches équilibrés.", "utilities.kit_cost":"Coût initial : {cost} · Coût mensuel supplémentaire : {mo}", +"utilities.kit_everywhere":"Kit de redondance partout", +"utilities.kit_everywhere_note":"Le kit dans chaque POP à qui il en manque une partie : groupe électrogène, second bâtiment, second routeur, caches répartis entre les sites. Un seul prix pour tous.", +"utilities.kit_new_pops_hire":"Embauche un stagiaire NOC pour ouvrir de nouveaux POP depuis un modèle, kit déjà compris.", +"utilities.kit_new_pops_off":"Les nouveaux POP ouverts avec le modèle de {name} arrivent sans le kit.", +"utilities.kit_new_pops_on":"Les nouveaux POP ouverts avec le modèle de {name} reçoivent aussi le kit.", +"utilities.kit_new_pops_start":"Mettre le kit dans le modèle", +"utilities.kit_new_pops_stop":"Le retirer du modèle", "utilities.peer_counts":"{ready} éligibles · {existing} existants · {blocked} indisponibles", "utilities.peering_note":"Demande les peers éligibles sur chaque IX rejoint. Les sessions existantes, y compris via le route server, sont ignorées. Les refus et seuils de trafic restent applicables. Aucun port ni PNI payant ne sera acheté.", "utilities.peers_requested":"{n} nouvelles sessions de peering IX établies.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 9034753..9f86192 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3159,6 +3159,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.", "modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…", "modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino livello {n} o Tier 1", +"net_filter.clear":"Cancella", +"net_filter.connected_only":"Solo collegate", +"net_filter.find_a_network":"Cerca una rete o un numero AS", "networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.", "networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.", "networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.", @@ -3394,6 +3397,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Oltre", +"ops.p_fresh":"Accendi la fibra nuova", "ops.p_g":"Da", "ops.p_how":"Come", "ops.p_keep":"Tienine uno di scorta", @@ -3925,6 +3929,29 @@ "pop_std.none":"Nessuno", "pop_std.not_all_of_the_standard":"Non bastano soldi o livello per tutto lo standard a {city}: ha avuto quello che si poteva.", "pop_std.standard_for_new_pops":"Standard per i nuovi POP", +"pop_tiers.apply_cost":"Portalo allo standard {cost}", +"pop_tiers.bring_up_n":{"one":"Porta {n} POP allo standard {cost}","other":"Porta {n} POP allo standard {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind}: {n} POP portato allo standard.","other":"{kind}: {n} POP portati allo standard."}, +"pop_tiers.bulk_note":"Ogni POP che hai segnato di un tipo, portato al suo standard in un colpo solo. Cambia uno standard (un modello nuovo, più router) e premi di nuovo.", +"pop_tiers.city_is_kind":"{city} rispetta lo standard {kind}.", +"pop_tiers.hub":"Hub regionale", +"pop_tiers.mark":"Segnalo", +"pop_tiers.medium":"POP medio", +"pop_tiers.meets_it":"In regola", +"pop_tiers.micro":"Micro POP", +"pop_tiers.model_locked":"{model} si sblocca al livello clienti {lv}.", +"pop_tiers.n_below":{"one":"{n} sotto lo standard","other":"{n} sotto lo standard"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"pop_tiers.n_stuck":{"one":"{n} non può ancora","other":"{n} non possono ancora"}, +"pop_tiers.no_kind":"Nessun tipo ancora", +"pop_tiers.not_all":"A {city} non è entrato tutto lo standard. Controlla la scheda Infra.", +"pop_tiers.not_set":"non ancora definito", +"pop_tiers.note":"Salva i router di un POP come standard, poi segna altri POP di quel tipo. Portarlo allo standard aggiunge router e passa al modello più grande, mai un passo indietro. Da Utilità porti allo standard tutti i POP di un tipo in una volta.", +"pop_tiers.save_here":"Salva questi router", +"pop_tiers.saved":"{kind} ora è {desc}.", +"pop_tiers.swapped_today":"I router qui sono stati cambiati oggi. Riprova domani.", +"pop_tiers.this_pop_is":"Questo POP: {kind}", +"pop_tiers.title":"Standard dei POP", "pops_transit_ix.40_off_for_6_months":"40% di sconto per 6 mesi", "pops_transit_ix.40_off_ix_for_6_months":"40% di sconto su {ix} per 6 mesi.
Il tuo account manager tira un sospiro di sollievo. Le clausole in piccolo leggile dopo.", "pops_transit_ix.after_consulting_with_management_the":"“Dopo un confronto con il management…”
Il prezzo è salito. Il management è stato consultato.", @@ -4192,6 +4219,12 @@ "release_notes.read_the_full_notes_on_github":"Leggi le note complete su GitHub", "release_notes.series_of_tubes_v_is_out":"È uscito Series of Tubes {v}!", "release_notes.your_game_is_saved_automatically":"La tua partita viene salvata automaticamente.", +"req_fix.bought":"Comprato: {list} per {cost}.", +"req_fix.buy_and_sign":"Compra e firma {cost}", +"req_fix.buys_list":"Manca: {list}. {cost} + {mo}/mese.", +"req_fix.generator_in_city":"un generatore di backup a {city}", +"req_fix.second_router_in_city":"un secondo router a {city}", +"req_fix.second_site_in_city":"un secondo sito a {city}", "requirements.a_spare_fiber_pair_in_your":"una coppia di fibre libera nel tuo scavo {a}–{b}", "requirements.afraid_of_sharks_needs_a_path":"Ha paura degli squali: vuole un percorso senza cavi sottomarini", "requirements.backup_generator_in_every_city_they":"Generatore di backup in ogni città che tocca", @@ -4826,9 +4859,20 @@ "utilities.caches_requested":"Installate {n} cache a {city}.", "utilities.ix_peering":"Peering IX su tutta la rete", "utilities.join_route_servers":"Unisciti a tutti i route server ({n})", +"utilities.kit_all_applied":{"one":"Kit di ridondanza installato in {n} POP.","other":"Kit di ridondanza installato in {n} POP."}, +"utilities.kit_all_apply":{"one":"Kit per {n} POP {cost}","other":"Kit per tutti i {n} POP {cost}"}, +"utilities.kit_all_done":"Ogni POP ha il kit completo.", +"utilities.kit_all_quote":{"one":"{n} POP ne ha bisogno · {cost} + {mo}/mese","other":"{n} POP ne hanno bisogno · {cost} + {mo}/mese"}, "utilities.kit_applied":"Ridondanza aggiornata a {city}.", "utilities.kit_balanced":"Hardware installato e cache bilanciate.", "utilities.kit_cost":"Una tantum: {cost} · Costo mensile aggiuntivo: {mo}", +"utilities.kit_everywhere":"Kit di ridondanza ovunque", +"utilities.kit_everywhere_note":"Il kit in ogni POP a cui ne manca ancora un pezzo: generatore, secondo edificio, secondo router, cache divise tra i siti. Un solo prezzo per tutti.", +"utilities.kit_new_pops_hire":"Assumi uno stagista del NOC per aprire nuovi POP da un modello con il kit già dentro.", +"utilities.kit_new_pops_off":"I nuovi POP aperti dal modello di {name} arrivano senza kit.", +"utilities.kit_new_pops_on":"I nuovi POP aperti dal modello di {name} ricevono anche il kit.", +"utilities.kit_new_pops_start":"Metti il kit nel modello", +"utilities.kit_new_pops_stop":"Toglilo dal modello", "utilities.peer_counts":"{ready} idonei · {existing} esistenti · {blocked} non disponibili", "utilities.peering_note":"Richiedi i peer idonei in ogni IX a cui partecipi. Le sessioni esistenti, inclusi i peer del route server, vengono saltate. Rifiuti e soglie di traffico restano validi. Non vengono acquistate porte o PNI a pagamento.", "utilities.peers_requested":"Stabilite {n} nuove sessioni di peering IX.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0657f8f..3a21141 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3159,6 +3159,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.", "modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…", "modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino nível {n} ou Tier 1", +"net_filter.clear":"Limpar", +"net_filter.connected_only":"Só ligadas", +"net_filter.find_a_network":"Procurar uma rede ou número AS", "networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.", "networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.", @@ -3394,6 +3397,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Acima de", +"ops.p_fresh":"Acender fibra nova", "ops.p_g":"A partir de", "ops.p_how":"Como", "ops.p_keep":"Manter um de reserva", @@ -3925,6 +3929,29 @@ "pop_std.none":"Nenhum", "pop_std.not_all_of_the_standard":"Sem dinheiro ou nível para todo o padrão em {city}: recebeu o que coube.", "pop_std.standard_for_new_pops":"Padrão para novos POPs", +"pop_tiers.apply_cost":"Pôr no padrão {cost}", +"pop_tiers.bring_up_n":{"one":"Pôr {n} POP no padrão {cost}","other":"Pôr {n} POPs no padrão {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind}: {n} POP posto no padrão.","other":"{kind}: {n} POPs postos no padrão."}, +"pop_tiers.bulk_note":"Cada POP que marcaste de um tipo, posto no seu padrão de uma só vez. Muda um padrão (um modelo novo, mais routers) e carrega outra vez.", +"pop_tiers.city_is_kind":"{city} cumpre o padrão {kind}.", +"pop_tiers.hub":"Hub regional", +"pop_tiers.mark":"Marcar", +"pop_tiers.medium":"POP médio", +"pop_tiers.meets_it":"Cumpre", +"pop_tiers.micro":"Micro POP", +"pop_tiers.model_locked":"{model} desbloqueia no nível de clientes {lv}.", +"pop_tiers.n_below":{"one":"{n} abaixo do padrão","other":"{n} abaixo do padrão"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"pop_tiers.n_stuck":{"one":"{n} ainda não pode","other":"{n} ainda não podem"}, +"pop_tiers.no_kind":"Ainda sem tipo", +"pop_tiers.not_all":"Nem todo o padrão entrou em {city}. Vê o separador Infra.", +"pop_tiers.not_set":"ainda não definido", +"pop_tiers.note":"Guarda os routers de um POP como padrão e depois marca outros POPs desse tipo. Pôr no padrão adiciona routers e troca para o modelo maior, nunca um passo atrás. Em Utilitários pões todos os POPs de um tipo no padrão de uma vez.", +"pop_tiers.save_here":"Guardar estes routers", +"pop_tiers.saved":"{kind} agora é {desc}.", +"pop_tiers.swapped_today":"Os routers aqui foram trocados hoje. Tenta amanhã.", +"pop_tiers.this_pop_is":"Este POP: {kind}", +"pop_tiers.title":"Padrões de POP", "pops_transit_ix.40_off_for_6_months":"40% de desconto por 6 meses", "pops_transit_ix.40_off_ix_for_6_months":"40% de desconto no {ix} por 6 meses.
Seu account manager respirou aliviado. Leia as letras miúdas depois.", "pops_transit_ix.after_consulting_with_management_the":"“Depois de consultar a diretoria…”
O preço subiu. A diretoria foi consultada.", @@ -4192,6 +4219,12 @@ "release_notes.read_the_full_notes_on_github":"Leia as notas completas no GitHub", "release_notes.series_of_tubes_v_is_out":"Saiu o Series of Tubes {v}!", "release_notes.your_game_is_saved_automatically":"Seu jogo é salvo automaticamente.", +"req_fix.bought":"Comprado: {list} por {cost}.", +"req_fix.buy_and_sign":"Comprar e assinar {cost}", +"req_fix.buys_list":"Falta: {list}. {cost} + {mo}/mês.", +"req_fix.generator_in_city":"um gerador de backup em {city}", +"req_fix.second_router_in_city":"um segundo router em {city}", +"req_fix.second_site_in_city":"um segundo site em {city}", "requirements.a_spare_fiber_pair_in_your":"um par de fibra livre na sua vala {a}–{b}", "requirements.afraid_of_sharks_needs_a_path":"Tem medo de tubarão: quer um caminho sem cabo submarino", "requirements.backup_generator_in_every_city_they":"Gerador de backup em toda cidade que tocar", @@ -4826,9 +4859,20 @@ "utilities.caches_requested":"Instaladas {n} caches em {city}.", "utilities.ix_peering":"Peering IX em toda a rede", "utilities.join_route_servers":"Aderir a todos os route servers ({n})", +"utilities.kit_all_applied":{"one":"Kit de redundância instalado em {n} POP.","other":"Kit de redundância instalado em {n} POPs."}, +"utilities.kit_all_apply":{"one":"Kit em {n} POP {cost}","other":"Kit nos {n} POPs {cost}"}, +"utilities.kit_all_done":"Todos os POPs têm o kit completo.", +"utilities.kit_all_quote":{"one":"{n} POP precisa · {cost} + {mo}/mês","other":"{n} POPs precisam · {cost} + {mo}/mês"}, "utilities.kit_applied":"Redundância atualizada em {city}.", "utilities.kit_balanced":"Hardware instalado e caches equilibradas.", "utilities.kit_cost":"Custo único: {cost} · Custo mensal adicional: {mo}", +"utilities.kit_everywhere":"Kit de redundância em todo lado", +"utilities.kit_everywhere_note":"O kit em cada POP a que ainda falta alguma parte: gerador, segundo prédio, segundo router, caches divididos entre sites. Um só preço para todos.", +"utilities.kit_new_pops_hire":"Contrata um estagiário do NOC para abrir POPs novos a partir de um modelo, já com o kit.", +"utilities.kit_new_pops_off":"POPs novos abertos com o modelo de {name} vêm sem o kit.", +"utilities.kit_new_pops_on":"POPs novos abertos com o modelo de {name} também levam o kit.", +"utilities.kit_new_pops_start":"Pôr o kit no modelo", +"utilities.kit_new_pops_stop":"Tirá-lo do modelo", "utilities.peer_counts":"{ready} elegíveis · {existing} existentes · {blocked} indisponíveis", "utilities.peering_note":"Solicita peers elegíveis em todos os IX a que aderiste. As sessões existentes, incluindo peers do route server, são ignoradas. Recusas e limites de tráfego continuam a aplicar-se. Não são compradas portas nem PNI pagos.", "utilities.peers_requested":"Estabelecidas {n} novas sessões de peering IX.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index f1b8a8f..4a29ab0 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -38,6 +38,8 @@ const API_DOMAINS={ opsKey:{table:'OPSK',kind:'key'}, opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The three POP standards (#315). + popTier:{kind:'enum',values:()=>POP_TIERS.slice()}, // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, callAmount:{kind:'enum',values:()=>CALL_AMTS.slice()}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index de2324b..86d5437 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -239,6 +239,10 @@ const API_CMD={ /* ---------- customers ---------- */ accept:{args:[['id','entityId']], doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, + acceptFix:{args:[['id','entityId'],['cost','integer',false]],watch:['pops','biz','offers'], + quote:a=>{const q=S?reqFix(S.offers.find(x=>x.id===a.id)):null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};}, + pass:a=>({id:a.id,cost:a.cost??((reqFix(S.offers.find(x=>x.id===a.id))||{}).cost)}), + doc:'Buy what an offer asks for at POPs you already have (backup generator, a second router, a second site), then sign it. Pass the quoted setup as cost; the game checks it still matches.'}, decline:{args:[['id','entityId']], doc:'Throw an offer away.'}, salesHire:{args:[['id','salesPersona']], @@ -402,6 +406,22 @@ const API_CMD={ quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};}, pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}), doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches. Nothing to do reads as no_effect.'}, + utilityKitAll:{args:[['cost','integer',false],['city','cityId',false]],watch:['pops','caches'], + quote:a=>{const q=S?utilityKitAll():null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};}, + pass:a=>({city:a.city,cost:a.cost??((utilityKitAll()||{}).cost)}), + doc:'Install the redundancy kit at every POP still missing part of it, at one quoted price. From customer level 2. Pass the quoted setup as cost.'}, + utilityKitNew:{args:[['city','cityId',false]],watch:['ops'], + doc:'Put the redundancy kit in the intern\'s new-POP template, or take it out (the same switch as in the Ops sheet).'}, + ptSave:{args:[['city','cityId'],['k','popTier']],watch:['popTiers'], + doc:'Save a POP\'s routers (model and count) as one of three POP standards: micro, medium or hub. The POP is marked as that kind. From customer level 2.'}, + ptApply:{args:[['city','cityId'],['k','popTier'],['cost','integer',false]],watch:['pops.#city','popTiers'], + quote:a=>{const q=S?ptPlan(a.city,a.k):null;return q?{setup:q.cost,monthly:q.mo,blocked:q.why?[q.why]:[]}:{setup:0};}, + pass:a=>({city:a.city,k:a.k,cost:a.cost??((S&&ptPlan(a.city,a.k))||{cost:0}).cost}), + doc:'Mark a POP as one kind and bring its routers up to that standard: add routers, swap to the standard\'s model if it is bigger. Never a step down. Pass the quoted setup as cost.'}, + ptAll:{args:[['k','popTier'],['cost','integer',false],['city','cityId',false]],watch:['pops','popTiers'], + quote:a=>{const A=S?ptAll(a.k):null;return A?{setup:A.cost}:{setup:0};}, + pass:a=>({k:a.k,city:a.city,cost:a.cost??(ptAll(a.k)||{}).cost}), + doc:'Bring every POP marked as one kind up to that standard, at one quoted price. Pass the quoted setup as cost.'}, utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'], quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};}, pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}), @@ -530,6 +550,9 @@ const API_VIEW={ pniFilter:{args:[['f','pniFilter']],doc:'Filter the PNI list: all, via transit, worth it, already PNI.'}, pniGrp:{args:[['g','string'],['o','boolean',false]],doc:'Fold or unfold one group of the PNI list.'}, pniSort:{args:[],doc:'Flip the PNI list sort between A-Z and worth-it-first.'}, + netFind:{args:[['q','string']],doc:'Filter a POP\'s transit, exchange, PNI and cache lists by network name or AS number.'}, + netOnly:{args:[],doc:'Show only the networks you are connected to in a POP\'s lists, or all of them again.'}, + netClear:{args:[],doc:'Clear the network search and the connected-only switch.'}, puzzleMenu:{args:[],doc:'Open the puzzle list.'}, puzzleDoor:{args:[],doc:'From the title screen: open the puzzle list (keeps the typed name).'}, pzFinish:{args:[],doc:'Puzzles only: run the star count and show the results sheet.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 83e7449..8ed02c5 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -62,6 +62,7 @@ const API_STATE_DOC={ core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, + popTiers:{type:'map',doc:'POP standards by kind: def.micro|medium|hub is {g: router model, rt: routers} or null; at maps a POP city to its kind.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, diff --git a/src/agent/60-dispatch.js b/src/agent/60-dispatch.js index 94957fd..4d403fb 100644 --- a/src/agent/60-dispatch.js +++ b/src/agent/60-dispatch.js @@ -19,7 +19,7 @@ function apiValidate(spec,args){ // maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. const API_FP_LEN=['links','transit','pni','caches','biz','offers','nni','loans','loanOffers','inc','scrubs']; const API_FP_KEYS=['pops','ixp','peers','myIx','done','ach','merged','confReg']; -const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','demo','charter','monkey','seatOff','pz','ar','dk','ev']; +const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','popTiers','demo','charter','monkey','seatOff','pz','ar','dk','ev']; function apiFp(watch,args){ if(!S)return null; const f={cash:S.cash,day:S.day,lvl:S.lvl||1,won:!!S.won,lost:!!S.lost}; diff --git a/src/game/60-features/39-req-fix.js b/src/game/60-features/39-req-fix.js new file mode 100644 index 0000000..41e9966 --- /dev/null +++ b/src/game/60-features/39-req-fix.js @@ -0,0 +1,20 @@ +/* ---------- Buy what a customer asks for, on signing (#241) ---------- + Some requirements are hardware at a POP you already have: a backup generator, a second router, a second building. + An offer that asks for them gets a second button that buys exactly what is missing and signs, with the price on it. + Never silent: the player presses it, and nothing is bought unless the deal can be signed right after. */ +const REQ_FIX=['gen','routers','metro']; +// What is missing for this offer, priced as the Infra tab's own buttons price it: [{k, city, cost, mo}], with totals. +function reqFix(o){if(!o||!bHas(o)||pzOn())return null;const items=[],cs=[o.city,o.city2].filter(Boolean); + for(const k of o.reqs||[]){if(!REQ_FIX.includes(k)||!REQS[k]||REQS[k].ok(o))continue; + for(const c of k==='routers'?[o.city]:cs){const p=S.pops[c];if(!p||items.some(x=>x.k===k&&x.city===c))continue; + if(k==='gen'&&!p.gen)items.push({k,city:c,cost:GEN_COST,mo:GEN_MO}); + else if(k==='metro'&&!p.site2)items.push({k,city:c,cost:SITE2_COST,mo:SITE2_MO}); + else if(k==='routers'&&(p.routers||1)<2){const g=p.rgen||0;items.push({k,city:c,cost:routerCost(g,p.routers||1),mo:routerMo(g)});}}} + if(!items.length)return null;return {items,cost:items.reduce((a,x)=>a+x.cost,0),mo:items.reduce((a,x)=>a+x.mo,0)};} +// Whether accept() would sign this offer now: the same checks, so money is never spent on a deal that then refuses. +const reqFixCanSign=o=>bHas(o)&&!(BIZ_T[o.type].event&&S.day>=o.start); +const REQ_FIX_L={gen:N_('req_fix.generator_in_city'),routers:N_('req_fix.second_router_in_city'),metro:N_('req_fix.second_site_in_city')}; +// The button and one line saying what it buys. sm: the button size the list around it uses. +function reqFixHtml(o){const q=reqFix(o);if(!q||!reqFixCanSign(o))return ''; + return `
${tr('req_fix.buys_list',{list:q.items.map(x=>tr(REQ_FIX_L[x.k],{city:CITY[x.city].name})).join(', '),cost:fmt$(q.cost),mo:fmt$(q.mo)})}
+
${btn(tr('req_fix.buy_and_sign',{cost:fmt$(q.cost)}),'acceptFix',{id:o.id,cost:q.cost},'pink sm',S.cash`;} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index d21c562..03368f8 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, - done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,popTiers:ptNew(),won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; } diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 4071caa..21cb7cb 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -25,7 +25,10 @@ const OPS=[ {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}}, {k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}}, - {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}}, + {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}, + // New fiber pulls traffic onto itself the day it is lit (#316): the player may want to light it by hand, when the + // ports behind it are ready. Off: fiber without a channel stays dark; lit fiber still gets more optics when hot. + fresh:{d:true,v:[true,false],l:N_('ops.p_fresh'),f:v=>v?tr('common.on'):tr('common.off')}}}, // Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to // a chosen line system. A line system swap is a day without that fiber: only where the traffic gets around it. {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, @@ -208,8 +211,8 @@ const OPS_RUN={ const lag=o.lag(),wantLag=o.n()<2&&o.rt>1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig(); if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;})){KV.rv=null;KV.pu.clear();break;} KV.rv=null;KV.pu.clear();X.did('ports',o.at+' '+job.w);yield;}}, - *optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o); - for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue; + *optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',fresh=opsP('optics','fresh'),gpd=(o,l)=>optG(o,l)/optCost(o); + for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day||(!fresh&&!(l.ch||[]).length))continue; let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead(); // New fiber gets its first channel; lit fiber gets more while it runs hot. for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length:load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)<=0)break; diff --git a/src/game/60-features/96-pop-tiers.js b/src/game/60-features/96-pop-tiers.js new file mode 100644 index 0000000..f0af3a8 --- /dev/null +++ b/src/game/60-features/96-pop-tiers.js @@ -0,0 +1,49 @@ +/* ---------- POP standards: micro, medium, regional hub (#315) ---------- + Real networks build a few kinds of POP, not one: a small edge site, a medium one, a regional hub. The player saves a + POP's routers as one of three standards and marks POPs as that kind; a POP is brought up to its standard with one + button, and every POP of a kind with one more once the standard grows (a new model unlocked, more routers). Which POP + is which stays the player's choice, so growth stays selective. Never a step down: a POP with a bigger model keeps it. + The standard for brand-new POPs (#240, 96-pop-standard.js) is a separate thing. From customer level 2, like the intern. */ +const POP_TIERS=['micro','medium','hub']; +const POP_TIER_L={micro:N_('pop_tiers.micro'),medium:N_('pop_tiers.medium'),hub:N_('pop_tiers.hub')}; +const ptNew=()=>({def:{micro:null,medium:null,hub:null},at:{}}); +const ptOn=()=>!!S&&opsCanHire()&&!pzOn(); +const ptO=()=>S.popTiers||(S.popTiers=ptNew()); +// Saves are untrusted: known kinds, router models that exist, POPs that still exist. +function ptSanitize(s){const o=s.popTiers&&typeof s.popTiers==='object'&&!Array.isArray(s.popTiers)?s.popTiers:{},n=ptNew(),d=o.def&&typeof o.def==='object'?o.def:{},at=o.at&&typeof o.at==='object'&&!Array.isArray(o.at)?o.at:{}; + for(const k of POP_TIERS){const x=d[k];if(x&&typeof x==='object'&&Number.isInteger(x.g)&&RG[x.g])n.def[k]={g:x.g,rt:int(x.rt,1,RMAX,1)};} + for(const c of Object.keys(at))if(isCity(c)&&own(s.pops,c)&&POP_TIERS.includes(at[c]))n.at[c]=at[c]; + s.popTiers=n;} +// The clicks that bring a POP up to a standard, in order, priced as each click prices it: a second router first where a +// lone router carries traffic (so the swap is a rolling upgrade, not a maintenance window), the bigger model, the rest of +// the routers. null when the POP already meets it. why: what stops it today. +function ptPlan(c,k){const p=S.pops[c],d=S.popTiers&&S.popTiers.def[k];if(!p||!d)return null; + const g0=p.rgen||0,rt0=p.routers||1,up=d.g!==g0&&RG[d.g].cap>RG[g0].cap,steps=[];let rt=rt0,cost=0; + if(up&&rt===1&&d.rt>=2&&!popIdle(c)){cost+=routerCost(g0,1);steps.push('add');rt=2;} + if(up){cost+=Math.max(0,Math.round(RG[d.g].cost*rt*hwMul('rt')*techMul(RG[d.g].lvl))-tradeIn(g0,rt));steps.push('swap');} + const g=up?d.g:g0;while(rt(n-1)*ROUTER_MO+cageMo(n),why=up?(!techOk('rg',d.g,RG[d.g].lvl)?tr('pop_tiers.model_locked',{model:esc(RG[d.g].n),lv:RG[d.g].lvl}):modelFits(c,d.g)||(p.rupDay===S.day?tr('pop_tiers.swapped_today'):'')):''; + return {steps,cost,g:d.g,mo:mo(rt)+rt*RG[g].mo-mo(rt0)-rt0*RG[g0].mo,why};} +// Run the plan through the Infra tab's own actions, quietly. True when every click went through. +function ptRun(c,q){let ok=true;opsQuiet(()=>{for(const s of q.steps){const p=S.pops[c],rt=p.routers||1,g=p.rgen||0; + if(s==='add')ACT.addRouter({city:c});else ACT.upRouter({city:c,g:q.g});if((p.routers||1)===rt&&(p.rgen||0)===g){ok=false;break;}}});return ok;} +// The POPs of one kind, the busiest first, with their plans. +function ptAll(k){const at=S.popTiers?S.popTiers.at:{},cs=Object.keys(at).filter(c=>at[c]===k&&S.pops[c]).sort((a,b)=>(R.nodeLoad[b]||0)-(R.nodeLoad[a]||0)||a.localeCompare(b)); + const todo=[],stuck=[];for(const c of cs){const q=ptPlan(c,k);if(!q)continue;(q.why?stuck:todo).push({c,q});} + return {cs,todo,stuck,cost:todo.reduce((a,x)=>a+x.q.cost,0)};} +const ptName=k=>tr(POP_TIER_L[k]),ptDesc=d=>d?`${d.rt} × ${esc(RG[d.g].n)}`:tr('pop_tiers.not_set'); +// In a POP's router section: the three standards, what this POP is, and one button each. +function popTierHtml(c){if(!ptOn()||!S.pops[c])return '';const T=ptO(),p=S.pops[c],mine=T.at[c]; + return `
${tr('pop_tiers.title')}${mine?tr('pop_tiers.this_pop_is',{kind:ptName(mine)}):tr('pop_tiers.no_kind')}
+ ${POP_TIERS.map(k=>{const d=T.def[k],q=d?ptPlan(c,k):null,same=d&&d.g===(p.rgen||0)&&d.rt===(p.routers||1); + const main=!d?'':q?btn(tr('pop_tiers.apply_cost',{cost:fmt$(q.cost)}),'ptApply',{city:c,k,cost:q.cost},mine===k?'pink sm':'sm',!!q.why||S.cash✓ ${tr('pop_tiers.meets_it')}`; + return `
${ptName(k)} ${ptDesc(d)}
${q&&q.why?`
${esc(q.why)}
`:''} +
${main}${same?'':btn(tr('pop_tiers.save_here'),'ptSave',{city:c,k},'ghost sm')}
`;}).join('')} +

${tr('pop_tiers.note')}

`;} +// In Utilities: every kind with its POPs, and one button that brings them all up to their standard. +function popTierAllHtml(city){if(!ptOn())return '';const T=ptO();if(!POP_TIERS.some(k=>T.def[k]))return ''; + return `

${tr('pop_tiers.title')}

${tr('pop_tiers.bulk_note')}

+ ${POP_TIERS.filter(k=>T.def[k]).map(k=>{const A=ptAll(k);return `
${ptName(k)} ${ptDesc(T.def[k])}
+
${trn('pop_tiers.n_pops',A.cs.length)}${A.todo.length?' · '+trn('pop_tiers.n_below',A.todo.length):''}${A.stuck.length?' · '+trn('pop_tiers.n_stuck',A.stuck.length):''}
+ ${A.todo.length?`
${btn(trn('pop_tiers.bring_up_n',A.todo.length,{cost:fmt$(A.cost)}),'ptAll',{k,cost:A.cost,city},'pink sm',S.cash`:''}
`;}).join('')}
`;} diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index b007039..20cd483 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -40,6 +40,12 @@ function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} +// The kit at every POP that lacks part of it (#317): one quote, one button. From customer level 2, like the intern: early +// on, every generator is a choice about money. +const utilityKitAllOn=()=>!!S&&opsCanHire()&&!pzOn(); +function utilityKitAll(){if(!utilityKitAllOn())return null;const cities=[];let cost=0,mo=0,moves=0; + for(const c of Object.keys(S.pops)){const q=utilityKit(c);if(!q||(!q.cost&&!q.moves.length))continue;cities.push(c);cost+=q.cost;mo+=q.mo;moves+=q.moves.length;} + return {cities,cost,mo,moves};} function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; for(const id of ixMembers(ix)){ diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index db35e34..ba08e0b 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -64,6 +64,8 @@ function sanitize(s){ // The backbone's technology: a save from before it with Auto-TE bought keeps the old rules on RSVP-TE (legacy). // The standard POP build (#240): a router model and how many. {const d=s.popStd;s.popStd=d&&typeof d==='object'&&Number.isInteger(d.g)&&RG[d.g]?{g:d.g,rt:int(d.rt,1,RMAX,1)}:null;} + // POP standards by kind (#315): micro, medium, regional hub, and which POP is which. + ptSanitize(s); {const c=s.core&&typeof s.core==='object'?s.core:null,lv=c?int(c.lv,0,4,0):(s.te?2:0);s.core={lv,run:c?int(c.run,0,lv,lv):lv};if(c?c.legacy===true:!!s.te)s.core.legacy=true;if(c&&c.lab===true)s.core.lab=true;if(c&&c.since!==undefined)s.core.since=num(c.since,0);} s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null; s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); diff --git a/src/game/90-actions/46-net-filter.js b/src/game/90-actions/46-net-filter.js new file mode 100644 index 0000000..83e3ceb --- /dev/null +++ b/src/game/90-actions/46-net-filter.js @@ -0,0 +1,6 @@ +// Find a network at a POP (#199): view state only. +Object.assign(ACT,{ + netFind:({q})=>{UI.netQ=String(q??'').slice(0,40);listReset('pni');renderPanel();}, + netOnly:()=>{UI.netOnly=!UI.netOnly;listReset('pni');renderPanel();}, + netClear:()=>{UI.netQ='';UI.netOnly=false;listReset('pni');renderPanel();}, +}); diff --git a/src/game/90-actions/51-customer-fix.js b/src/game/90-actions/51-customer-fix.js new file mode 100644 index 0000000..2e58956 --- /dev/null +++ b/src/game/90-actions/51-customer-fix.js @@ -0,0 +1,10 @@ +Object.assign(ACT,{ + // Buy what the offer asks for, then sign (#241). cost: the price the button showed; a changed quote buys nothing. + acceptFix:({id,cost})=>{const o=S.offers.find(x=>x.id===id),q=reqFix(o);if(!o||!q||!reqFixCanSign(o))return; + if(q.cost!==+cost){toast(tr('utilities.quote_changed'),'bad');sfx('err');after();return;} + if(S.cash{for(const x of q.items){if(x.k==='gen')ACT.addGen({city:x.city});else if(x.k==='metro')ACT.addSite({city:x.city});else ACT.addRouter({city:x.city});}}); + toast(esc(tr('req_fix.bought',{list:q.items.map(x=>tr(REQ_FIX_L[x.k],{city:CITY[x.city].name})).join(', '),cost:fmt$(q.cost)})),'good'); + ACT.accept({id});}, +}); diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 9848304..08e03c9 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -4,7 +4,10 @@ Object.assign(ACT,{ decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');} - const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();}, + const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}const l0=S.links.find(x=>x.id===id),sib=l0?pairLinks(l0.a,l0.b).filter(x=>x!==l0&&x.kind!=='vxc'):[];S.links=S.links.filter(l=>l.id!==id);prunePairMet(); + // One of several parallel links (#119): the panel moves on to the next one between the same cities, so a row of them + // can be handed back without opening the panel again each time. + UI.sel=sib.length?{type:'link',id:sib[0].id}:null;UI.confirm=null;after();}, // The chaos monkey takes a banana and goes home early (no bonus). mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();}, fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return; diff --git a/src/game/90-actions/85-pop-tiers.js b/src/game/90-actions/85-pop-tiers.js new file mode 100644 index 0000000..494f284 --- /dev/null +++ b/src/game/90-actions/85-pop-tiers.js @@ -0,0 +1,16 @@ +// POP standards (#315): save one, bring a POP up to one, bring every POP of a kind up to it. +Object.assign(ACT,{ + ptSave:({city,k})=>{const p=S.pops[city];if(!ptOn()||!p||!POP_TIERS.includes(k))return;const T=ptO();T.def[k]={g:p.rgen||0,rt:p.routers||1};T.at[city]=k; + toast(esc(tr('pop_tiers.saved',{kind:ptName(k),desc:`${T.def[k].rt} × ${RG[T.def[k].g].n}`})),'good');sfx('click');after();}, + // cost: the price on the button; a plan that changed under it buys nothing. A POP that already meets it is only marked. + ptApply:({city,k,cost})=>{if(!ptOn()||!S.pops[city]||!POP_TIERS.includes(k)||!ptO().def[k])return;const q=ptPlan(city,k); + if((q?q.cost:0)!==+cost){toast(tr('utilities.quote_changed'),'bad');sfx('err');after();return;} + if(q&&q.why){toast(esc(q.why),'bad');sfx('err');return;}if(q&&S.cash{if(!ptOn()||!POP_TIERS.includes(k))return;const A=ptAll(k);if(!A.todo.length)return; + if(A.cost!==+cost){utilitiesModal(city,tr('utilities.quote_changed'));return;} + if(S.cash[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id); after();const msg=tr('utilities.kit_applied',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + // Every POP's kit in one go (#317), all or nothing on the quoted price, one redraw at the end. + utilityKitAll:({cost,city})=>{const q=utilityKitAll();if(!q||!q.cities.length)return; + if(q.cost!==+cost){utilitiesModal(city,tr('utilities.quote_changed'));return;} + if(S.cash{for(const c of q.cities){const k=utilityKit(c);if(!k||S.cash{if(!opsHired())return;S.ops.tpl.kit=!S.ops.tpl.kit;sfx('click');after();utilitiesModal(city);}, utilityCaches:({city,quote,modal})=>{const q=utilityCaches(city);if(!q||!q.add.length)return; if(q.key!==quote){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} if(!portGate(city,q.ports))return; diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index f05d9f8..db5c9c9 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -46,7 +46,7 @@ function renderLeft(){checkLayer(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); - h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)} + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)}${reqFixHtml(o)}
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${pieNocBtn()}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'':''}`,'routingOpen',{},'')}
`; diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 5a89d6a..9838389 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -40,10 +40,10 @@ function cityPanel(c){ for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}${pathCtl(b)}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ - h+=portNote(c)+latNote(c); + h+=netFilterHtml()+portNote(c)+latNote(c); h+=`

${tr('common.ip_transit')}

${tr('city_panel.pay_a_bigger_network_per_gbps')}

`; - const prov=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price-b.price); - if(!prov.length)h+=`

${tr('city_panel.nobody_sells_transit_here_haul_your')}

`; + const prov0=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price-b.price),prov=prov0.filter(n=>netKeep(n,S.transit.some(x=>x.city===c&&x.net===n.id))); + if(!prov0.length)h+=`

${tr('city_panel.nobody_sells_transit_here_haul_your')}

`;else if(!prov.length)h+=netNone(); for(const n of prov){const t=S.transit.find(x=>x.city===c&&x.net===n.id);const pr=transitPerG(n,c,premOnlyAt(n,c)||!!(t&&premOn(t)))*S.priceMul; h+=`
${logo(n)}
${esc(n.name)} ${TYPE_L[n.type]}
${tr('city_panel.price_per_gbps_month_billed_on',{price:pr.toFixed(2)})}
${premOnlyAt(n,c)&&!t?`
${tr('city_panel.only_the_cn_too_premium_crossing')}
`:''}`; if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day; @@ -53,12 +53,12 @@ function cityPanel(c){ h+=`
`;} h+=`
`; }else if(UI.tab==='peer'){ - h+=portNote(c); + h+=netFilterHtml()+portNote(c); h+=ixSection(c); h+=`

${tr('city_panel.private_interconnects_pni')}

${tr('city_panel.a_dedicated_cross_connect_to_one',{dc:esc(siteName(c,'a'))})}

`; h+=pniListHtml(c); h+=`

${tr('common.embedded_caches')}

${tr('city_panel.cdns_put_free_cache_servers_inside')}

`; - for(const n of NETS.filter(n=>n.cache)){const have=S.caches.filter(x=>x.city===c&&x.net===n.id),dem=R.demTo[n.id]||0,ok=dem>=n.cache.min; + for(const n of NETS.filter(n=>n.cache&&netKeep(n,S.caches.some(x=>x.city===c&&x.net===n.id)))){const have=S.caches.filter(x=>x.city===c&&x.net===n.id),dem=R.demTo[n.id]||0,ok=dem>=n.cache.min; h+=`
${logo(n)}
${esc(n.cache.name)}
${tr('common.from_net',{net:esc(n.name)})} · ${have.length?`${trn('common.n_box',have.length)} · ${tr('city_panel.serving_v',{v:fmtG(have.reduce((a,x)=>a+(R.useCache[x.id]||0),0))})}`:tr('city_panel.100g_per_box')}
${!ok?`
${tr('city_panel.needs_min_gbps_of_traffic_to',{min:n.cache.min,net:esc(n.name),now:dem.toFixed(1)})}
`:''}
${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}
${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} h+=`
`; @@ -75,7 +75,7 @@ function cityPanel(c){ ${nl>=nc*0.95?`

${tr('city_panel.maxed_out_traffic_here_is_being')}

`:''}
${N?(!techOk('rg',Ni,N.lvl)?demoBtn('rg',Ni,N.lvl,tr('city_panel.model_level_lv',{model:esc(N.n),lv:N.lvl}),'pink'):btn(tr('city_panel.upgrade_to_model_cost_mo_mo',{model:esc(N.n),cost:fmt$(swapCost(c,Ni)),mo:fmt$(N.mo*rt)}),'upRouter',{city:c,g:Ni},'pink',S.cash=RCAGE?CAGE_MO:0))}),'addRouter',{city:c},'',S.cash1?btn(tr('common.remove_one'),'rmRouter',{city:c},'ghost sm'):''}
${rt>=RCAGE&&rt${tr('city_panel.the_standard_cage_holds_n_routers',{n:RCAGE,mo:fmt$(CAGE_MO)})}

`:''}${rt>=RMAX?`

${tr('city_panel.this_pop_has_the_most_routers',{n:RMAX})}

`:''}${rt>RCAGE?`
${tr('city_panel.cage_extension')}${fmt$(cageMo(rt))}/mo
`:''} - ${popStdHtml(c)} + ${popStdHtml(c)}${popTierHtml(c)} ${UI.models?routerModels(c):''} ${N||UI.models?`

${(p.rgen||0)>0?tr('city_panel.prices_include_p_back_for_the',{p:fmt$(tradeIn(p.rgen||0,rt))})+' ':''}${p.rupDay===S.day?tr('city_panel.new_routers_went_in_today_the')+' ':''}${rt>1?tr('city_panel.rolling_upgrade_one_router_at_a'):tr('city_panel.with_one_router_the_upgrade_needs')}

`:''}

${rt>=2?tr('city_panel.a_crash_here_only_costs_one'):tr('city_panel.one_router_is_a_single_point')}

diff --git a/src/game/93-ui/51-net-filter.js b/src/game/93-ui/51-net-filter.js new file mode 100644 index 0000000..69ba979 --- /dev/null +++ b/src/game/93-ui/51-net-filter.js @@ -0,0 +1,14 @@ +/* ---------- Find a network at a POP (#199) ---------- + The Transit and Peering tabs list every network that sells or peers there: dozens in a big city. One search box and a + "connected only" switch filter all of them (transit, exchange members, PNIs, caches). View state only, never saved; + it stays while you hop between POPs, and a Clear button says it is on. */ +const netQ=()=>(UI.netQ||'').trim().toLowerCase(); +const netFiltered=()=>!!netQ()||!!UI.netOnly; +// on: connected to that network in this list (a transit port, a session, a PNI, a cache box). A number finds an AS. +function netKeep(n,on){const q=netQ();if(q&&!n.name.toLowerCase().includes(q)&&!(n.asn&&String(n.asn).startsWith(q)))return false;return !UI.netOnly||!!on;} +function netFilterHtml(){return `
+
${btn(tr('net_filter.connected_only'),'netOnly',{},UI.netOnly?'green sm':'ghost sm')}${netFiltered()?btn(tr('net_filter.clear'),'netClear',{},'ghost sm'):''}
`;} +const netNone=()=>`

${tr('pni_list.nothing_matches')}

`; +// Typing redraws the panel. The morph swaps an input whose value changed, so the new box gets the focus and the caret back. +document.addEventListener('input',e=>{if(e.target.id!=='netQ'||!S)return;const at=e.target.selectionStart;ACT.netFind({q:e.target.value}); + const n=$('netQ');if(n&&n!==e.target){n.focus();try{n.setSelectionRange(at,at);}catch(err){}}}); diff --git a/src/game/93-ui/52-pni-list.js b/src/game/93-ui/52-pni-list.js index 40f85f1..bc26076 100644 --- a/src/game/93-ui/52-pni-list.js +++ b/src/game/93-ui/52-pni-list.js @@ -15,7 +15,8 @@ function pniRow(c,n,pn,v,chk){let h=`
${logo(n)}
${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cashportShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}
${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}
${chk.fee?`
${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}
`:''}`:`
${esc(chk.why)}
`;} return h+`
`;} function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniOpen||{}; - const rows=NETS.filter(n=>n.pops.includes(c)).map(n=>{const pn=S.pni.find(x=>x.city===c&&x.net===n.id)||null;const chk=pn?null:peerOk(n.id,'pni',c),v=pn?null:pniVal(n.id,c);return {n,pn,v,chk,s:pniStat(n.id,c).k,go:!!pn||(chk.ok&&v.g>=1)};}); + // The search (#199) first: a network it hides needs no value worked out. + const rows=NETS.filter(n=>n.pops.includes(c)).map(n=>[n,S.pni.find(x=>x.city===c&&x.net===n.id)||null]).filter(([n,pn])=>netKeep(n,pn)).map(([n,pn])=>{const chk=pn?null:peerOk(n.id,'pni',c),v=pn?null:pniVal(n.id,c);return {n,pn,v,chk,s:pniStat(n.id,c).k,go:!!pn||(chk.ok&&v.g>=1)};}); const keep=r=>f==='all'||(f==='t'&&(r.s==='t'||r.s==='none'))||(f==='worth'&&r.v&&r.v.worth)||(f==='pni'&&(r.s==='here'||r.s==='else')); const val=r=>r.v?r.v.val:-Infinity; rows.sort((a,b)=>az?a.n.name.localeCompare(b.n.name):(b.v&&b.v.worth)-(a.v&&a.v.worth)||val(b)-val(a)||a.n.name.localeCompare(b.n.name)); @@ -23,7 +24,7 @@ function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniO const shown=rows.filter(keep);if(!shown.length)return h+`

${tr('pni_list.nothing_matches')}

`; let left=listN('pni'),tot=0; for(const g of PNI_GRP){const gr=shown.filter(r=>pniGrpOf(r.n)===g);if(!gr.length)continue; - const w=gr.filter(r=>r.v&&r.v.worth).length,act=w||gr.some(r=>r.go),isOpen=f!=='all'||(open[g]??act); + const w=gr.filter(r=>r.v&&r.v.worth).length,act=w||gr.some(r=>r.go),isOpen=f!=='all'||netFiltered()||(open[g]??act); h+=`
${btn(`${isOpen?'▾':'▸'} ${esc(pniGrpL(g))} ${trn('pni_list.n_networks_w_worth_it',gr.length,{w})}`,'pniGrp',{g,o:isOpen?0:1},'ghost sm')}
`; if(!isOpen)continue;tot+=gr.length; for(const r of gr){if(left--<=0)break;h+=pniRow(c,r.n,r.pn,r.v,r.chk);}} diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index f32be67..9b56fda 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -26,5 +26,13 @@ function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.po ${ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

${btn(tr('common.peering_policy'),'leftTab',{t:'nets'},'ghost sm')}`:''} ${rows.map(r=>`
${esc(ixName(r.ix))} · ${tr('utilities.peer_counts',{ready:r.requests.length,existing:r.existing,blocked:r.blocked.length})} ${r.blocked.map(b=>`

${esc(NET[b.id].name)}: ${esc(b.why)}

`).join('')}
`).join('')}
+ ${utilityKitAllHtml(city)}${popTierAllHtml(city)} ${cities.length?`
${btn(tr('utilities.view_pop'),'utilityPick',{},'sm')}
${utilityKitHtml(city,true)}`:''}`); } +// The kit everywhere (#317), and where new POPs get it: the intern's template, which the intern clicks through. +function utilityKitAllHtml(city){const q=utilityKitAll();if(!q)return '';const tpl=opsHired()&&S.ops.tpl.kit; + return `

${tr('utilities.kit_everywhere')}

${tr('utilities.kit_everywhere_note')}

+ ${q.cities.length?`

${trn('utilities.kit_all_quote',q.cities.length,{cost:fmt$(q.cost),mo:fmt$(q.mo)})}${q.moves?' · '+tr('utilities.cache_moves',{n:q.moves}):''}

+
${btn(trn('utilities.kit_all_apply',q.cities.length,{cost:fmt$(q.cost)}),'utilityKitAll',{cost:q.cost,city},'pink',S.cash`:`

${tr('utilities.kit_all_done')}

`} +

${opsHired()?(tpl?tr('utilities.kit_new_pops_on',{name:opsName()}):tr('utilities.kit_new_pops_off',{name:opsName()})):tr('utilities.kit_new_pops_hire')}

+ ${opsHired()?`
${btn(tpl?tr('utilities.kit_new_pops_stop'):tr('utilities.kit_new_pops_start'),'utilityKitNew',{city},tpl?'ghost sm':'sm')}
`:''}
`;} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 39c6541..1af0d5f 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -16,7 +16,8 @@ function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[ else h+=`
${PORT.map((P2,i)=>i>S.ixp[c]&&portShown(i)?btn(tr('common.upgrade_port_price',{port:P2.n,price:portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)):'').join('')}${S.pops[city]&&((S.ixn||{})[c]||1)1?btn(tr('common.member'),'lagIx',{city:c,d:-1},'ghost sm'):''}${S.ixp[c]>0?btn(tr('link_panels.downgrade_port_price',{port:PORT[S.ixp[c]-1].n,price:portMo(ixPortMo(c,S.ixp[c]-1)*((S.ixn||{})[c]||1))}),'downIx',{city:c},'ghost sm'):''}${btn(S.rs[c]?tr('link_panels.leave_route_server'):tr('link_panels.join_route_server'),'rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${S.rs[c]&&ppol()!=='open'?`${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}`:''}${btn(UI.confirm==='ix'+c?tr('common.really_leave'):tr('common.leave_ix'),'cancelIx',{city:c},'ghost sm')}
`; h+=`
`; {const elig=mine?[]:ixMembers(c).filter(id=>!set.has(id)&&peerOk(id,'ix',c).ok);if(elig.length>1)h+=`
${btn(tr('link_panels.request_all_n_willing_peers',{n:elig.length}),'peerAll',{city:c},'pink sm')}
`;} - for(const id of ixMembers(c).sort((a,b)=>NSH[b]-NSH[a])){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c); + {const ms=ixMembers(c),shown=ms.filter(id=>netKeep(NET[id],set.has(id)));if(ms.length&&!shown.length)h+=netNone();} + for(const id of ixMembers(c).filter(id=>netKeep(NET[id],set.has(id))).sort((a,b)=>NSH[b]-NSH[a])){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c); h+=`
${logo(n)}
${esc(n.name)}
${TYPE_L[n.type]} ${n.pol} · ${(NSH[id]*100).toFixed(NSH[id]<0.01?1:0)}%${n.tail?' '+tr('common.tiny')+'':''}
${!on&&!chk.ok?`
${esc(chk.why)}
`:''}
${on?(viaRs||mine?`${mine?tr('common.member_fef5'):tr('common.via_rs')}`:btn(tr('common.peered_ce2f'),'unpeer',{city:c,net:id},'green sm',false,tr('link_panels.click_to_tear_down'))):btn(tr('common.request'),'peer',{city:c,net:id},'sm',!chk.ok)}
`;} h+=`
`;} @@ -142,7 +143,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${bRisk(o)}${reqList(o)}${reqFixHtml(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/src/i18n/en.js b/src/i18n/en.js index bb7bbc3..aaaf94c 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3160,6 +3160,9 @@ "modal_and_names.the_real_thing_follow_a_packet":"The real thing: follow a packet from Wi-Fi to undersea fiber.", "modals.lay_your_own_subsea_cable":"Lay your own subsea cable…", "modals.your_own_subsea_cable_level_n":"Your own subsea cable level {n} or Tier 1", +"net_filter.clear":"Clear", +"net_filter.connected_only":"Connected only", +"net_filter.find_a_network":"Find a network or AS number", "networks.a_mobile_network_named_after_the":"A mobile network named after the sound of a toast. Cheers to every 5G tower.", "networks.a_spanish_carrier_starring_in_every":"A Spanish carrier starring in every Latin American market, at least until it sells the next one.", "networks.a_tiny_telco_in_a_country":"A tiny telco in a country where the world’s cables come ashore. Prices to match.", @@ -3395,6 +3398,7 @@ "ops.ops":"Ops", "ops.ops_name":"Ops · {name}", "ops.p_at":"Above", +"ops.p_fresh":"Light new fiber", "ops.p_g":"From", "ops.p_how":"How", "ops.p_keep":"Keep one spare", @@ -3926,6 +3930,29 @@ "pop_std.none":"None", "pop_std.not_all_of_the_standard":"Not enough cash or level for the whole standard in {city}: it got what fit.", "pop_std.standard_for_new_pops":"Standard for new POPs", +"pop_tiers.apply_cost":"Bring it up {cost}", +"pop_tiers.bring_up_n":{"one":"Bring {n} POP up {cost}","other":"Bring {n} POPs up {cost}"}, +"pop_tiers.bulk_done":{"one":"{kind}: {n} POP brought up to the standard.","other":"{kind}: {n} POPs brought up to the standard."}, +"pop_tiers.bulk_note":"Every POP you marked as a kind, brought up to its standard in one go. Change a standard (a new model, more routers) and press again.", +"pop_tiers.city_is_kind":"{city} meets the {kind} standard.", +"pop_tiers.hub":"Regional hub", +"pop_tiers.mark":"Mark it", +"pop_tiers.medium":"Medium POP", +"pop_tiers.meets_it":"Meets it", +"pop_tiers.micro":"Micro POP", +"pop_tiers.model_locked":"{model} unlocks at customer level {lv}.", +"pop_tiers.n_below":{"one":"{n} below the standard","other":"{n} below the standard"}, +"pop_tiers.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"pop_tiers.n_stuck":{"one":"{n} can't take it yet","other":"{n} can't take it yet"}, +"pop_tiers.no_kind":"No kind yet", +"pop_tiers.not_all":"Not all of the standard went in at {city}. Check the Infra tab.", +"pop_tiers.not_set":"not set yet", +"pop_tiers.note":"Save a POP's routers as a standard, then mark other POPs as that kind. Bringing a POP up adds routers and swaps to the bigger model, never a step down. Utilities brings every POP of a kind up at once.", +"pop_tiers.save_here":"Save these routers", +"pop_tiers.saved":"{kind} is now {desc}.", +"pop_tiers.swapped_today":"The routers here were swapped today. Try again tomorrow.", +"pop_tiers.this_pop_is":"This POP: {kind}", +"pop_tiers.title":"POP standards", "pops_transit_ix.40_off_for_6_months":"40% off for 6 months", "pops_transit_ix.40_off_ix_for_6_months":"40% off {ix} for 6 months.
Your account manager is relieved. Read the small print later.", "pops_transit_ix.after_consulting_with_management_the":"\"After consulting with management…\"
The price went up. Management was consulted.", @@ -4193,6 +4220,12 @@ "release_notes.read_the_full_notes_on_github":"Read the full notes on GitHub", "release_notes.series_of_tubes_v_is_out":"Series of Tubes {v} is out!", "release_notes.your_game_is_saved_automatically":"Your game is saved automatically.", +"req_fix.bought":"Bought {list} for {cost}.", +"req_fix.buy_and_sign":"Buy it and sign {cost}", +"req_fix.buys_list":"Missing: {list}. {cost} + {mo}/mo.", +"req_fix.generator_in_city":"a backup generator in {city}", +"req_fix.second_router_in_city":"a second router in {city}", +"req_fix.second_site_in_city":"a second site in {city}", "requirements.a_spare_fiber_pair_in_your":"a spare fiber pair in your {a}–{b} trench", "requirements.afraid_of_sharks_needs_a_path":"Afraid of sharks: needs a path with no subsea cable", "requirements.backup_generator_in_every_city_they":"Backup generator in every city they touch", @@ -4827,9 +4860,20 @@ "utilities.caches_requested":"Installed {n} cache boxes in {city}.", "utilities.ix_peering":"Network-wide IX peering", "utilities.join_route_servers":"Join all route servers ({n})", +"utilities.kit_all_applied":{"one":"Redundancy kit installed at {n} POP.","other":"Redundancy kit installed at {n} POPs."}, +"utilities.kit_all_apply":{"one":"Kit {n} POP {cost}","other":"Kit all {n} POPs {cost}"}, +"utilities.kit_all_done":"Every POP has the full kit.", +"utilities.kit_all_quote":{"one":"{n} POP needs it · {cost} + {mo}/mo","other":"{n} POPs need it · {cost} + {mo}/mo"}, "utilities.kit_applied":"Redundancy updated in {city}.", "utilities.kit_balanced":"Hardware installed and caches balanced.", "utilities.kit_cost":"One-off: {cost} · Additional monthly cost: {mo}", +"utilities.kit_everywhere":"Redundancy kit everywhere", +"utilities.kit_everywhere_note":"The kit at every POP still missing part of it: generator, second building, second router, caches balanced between sites. One price for all of them.", +"utilities.kit_new_pops_hire":"Hire a NOC intern to open new POPs from a template with the kit already in.", +"utilities.kit_new_pops_off":"New POPs opened from {name}'s template come without the kit.", +"utilities.kit_new_pops_on":"New POPs opened from {name}'s template get the kit too.", +"utilities.kit_new_pops_start":"Put the kit in the template", +"utilities.kit_new_pops_stop":"Leave it out of the template", "utilities.peer_counts":"{ready} eligible · {existing} existing · {blocked} unavailable", "utilities.peering_note":"Request eligible peers at every IX you have joined. Existing sessions, including route-server peers, are skipped. Refusals and traffic thresholds still apply. No ports or paid PNIs are purchased.", "utilities.peers_requested":"Established {n} new IX peering sessions.", diff --git a/src/styles/36-net-filter.css b/src/styles/36-net-filter.css new file mode 100644 index 0000000..2bae154 --- /dev/null +++ b/src/styles/36-net-filter.css @@ -0,0 +1,5 @@ +/* Find a network at a POP (#199) and the POP standards rows (#315). */ +.netf{display:flex;flex-direction:column;gap:6px;margin:0 0 10px} +.netf input.t{font-size:16px;padding:6px 10px;min-height:44px} +.netf .btns{margin:0} +.ptier .row .btns{margin-top:4px} diff --git a/tests/bulk-actions.test.js b/tests/bulk-actions.test.js new file mode 100644 index 0000000..ad5c58c --- /dev/null +++ b/tests/bulk-actions.test.js @@ -0,0 +1,226 @@ +// Late-game busywork: one policy or one button instead of many clicks, never a decision taken away. +// #316 the intern can leave new fiber dark, #119 the link panel stays open on a sibling, #317 the kit at every POP, +// #241 buy what a customer needs on signing, #315 POP standards by kind, #199 find a network at a POP. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +function setup(t, extra = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.nextFail=S.nextEvent=1e9;UI.speed=0;compute();" + extra); + return h; +} +const doc = h => h.dom.window.document; +const text = (h, sel) => [...doc(h).querySelectorAll(sel)].map(e => e.textContent).join('\n'); +const reload = ev => ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()"); + +/* ---------- #316: new fiber stays dark when the player says so ---------- */ +const FIBER = "S.lvl=4;S.rules=makeRules('freeze');ACT.launchBB({city:'fra'});S.pops.fra.rgen=2;ACT.buildPop({city:'ams'});S.pops.ams.rgen=2;compute();" + + "ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();" + + "S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();S.ops.on.optics=true;"; +const ch = ev => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').ch)")); + +test('#316 by default the intern still lights new fiber, also in a save from before the switch', t => { + const { ev, errors } = setup(t, FIBER); + assert.equal(ev("opsP('optics','fresh')"), true); + ev("S.ops.p.optics={}"); + reload(ev); + assert.equal(ev("opsP('optics','fresh')"), true, 'an old save has no setting: the old behaviour'); + ev('opsDay(S.day)'); + assert.ok(ch(ev).length > 0); + assert.deepEqual(errors, []); +}); + +test('#316 told not to, the intern leaves new fiber dark but still grows hot lit fiber', t => { + const { ev, errors } = setup(t, FIBER); + ev("ACT.opsOpen();ACT.opsParam({k:'optics',p:'fresh',v:1})"); + assert.equal(ev("opsP('optics','fresh')"), false); + ev('opsDay(S.day)'); + assert.deepEqual(ch(ev), [], 'dark fiber stays dark'); + ev("S.links.find(l=>l.id==='f').ch=['zr8'];compute();R.load.f=dfCap(S.links.find(l=>l.id==='f'))*0.95;opsDay(S.day)"); + assert.ok(ch(ev).length > 1, 'a lit, hot fiber still gets more optics'); + reload(ev); + assert.equal(ev("opsP('optics','fresh')"), false, 'the switch survives a reload'); + ev("S.ops.p.optics.fresh='maybe';S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("opsP('optics','fresh')"), true, 'a bad value is repaired to the default'); + assert.deepEqual(errors, []); +}); + +test('#316 the switch is in the Ops sheet', t => { + const h = setup(t, FIBER); + h.ev('ACT.opsOpen()'); + assert.match(h.ev("document.getElementById('modalCard').textContent"), /Light new fiber/); + assert.deepEqual(h.errors, []); +}); + +/* ---------- #119: decommissioning one of several waves keeps the panel open ---------- */ +test('#119 the link panel moves on to the next parallel link, and closes after the last', t => { + const h = setup(t, "ACT.buildPop({city:'ams'});" + + "for(const id of ['w1','w2','w3'])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier:0,km:450,sub:false,cut:0,mo:1000});compute();UI.sel={type:'link',id:'w1'};renderAll()"); + const { ev, errors } = h; + ev("ACT.rmLink({id:'w1'});ACT.rmLink({id:'w1'})"); + assert.equal(ev("S.links.some(l=>l.id==='w1')"), false); + assert.equal(ev('JSON.stringify(UI.sel)'), JSON.stringify({ type: 'link', id: 'w2' })); + assert.equal(ev("document.getElementById('panel').hidden"), false, 'the panel is still open'); + ev("ACT.rmLink({id:'w2'});ACT.rmLink({id:'w2'})"); + assert.equal(ev('UI.sel.id'), 'w3'); + ev("ACT.rmLink({id:'w3'});ACT.rmLink({id:'w3'})"); + assert.equal(ev('UI.sel'), null, 'the last link closes it'); + assert.deepEqual(errors, []); +}); + +/* ---------- #317: the redundancy kit at every POP ---------- */ +const POPS = "for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute();"; +test('#317 one button kits every POP, at the sum of the per-POP quotes', t => { + const { ev, errors } = setup(t, POPS + 'S.lvl=2;'); + const q = JSON.parse(ev('JSON.stringify(utilityKitAll())')); + assert.equal(q.cities.length, 4); + assert.equal(q.cost, ev("Object.keys(S.pops).reduce((a,c)=>a+utilityKit(c).cost,0)")); + ev("ACT.utilities({})"); + assert.match(ev("document.getElementById('modalCard').textContent"), /Kit all 4 POPs/); + const cash = ev('S.cash'); + ev(`ACT.utilityKitAll({cost:${q.cost + 1}})`); + assert.equal(ev('S.cash'), cash, 'a stale quote buys nothing'); + assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); + ev(`ACT.utilityKitAll({cost:${q.cost}})`); + assert.equal(ev('S.cash'), cash - q.cost); + assert.equal(ev("Object.values(S.pops).every(p=>p.gen&&p.site2&&p.routers>=2)"), true); + assert.match(ev("document.getElementById('modalCard').textContent"), /Every POP has the full kit/); + assert.deepEqual(errors, []); +}); + +test('#317 needs level 2, never spends what is not there, and can put the kit in the intern\'s template', t => { + const { ev, errors } = setup(t, POPS); + ev('S.lvl=1;ACT.utilities({})'); + assert.equal(ev('utilityKitAll()'), null); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /Redundancy kit everywhere/); + ev('S.lvl=2;window.q=utilityKitAll().cost;S.cash=q-1;ACT.utilityKitAll({cost:q})'); + assert.equal(ev('S.cash'), ev('q-1')); + assert.equal(ev("Object.values(S.pops).some(p=>p.gen)"), false); + ev("S.cash=1e8;ACT.opsHire({id:'annie'});closeModal();S.ops.tpl.kit=false;ACT.utilities({})"); + assert.match(ev("document.getElementById('modalCard').textContent"), /come without the kit/); + ev('ACT.utilityKitNew({})'); + assert.equal(ev('S.ops.tpl.kit'), true); + assert.match(ev("document.getElementById('modalCard').textContent"), /get the kit too/); + assert.deepEqual(errors, []); +}); + +/* ---------- #241: buy what the customer asks for, on signing ---------- */ +const OFFER = (reqs, extra = {}) => `ACT.buildPop({city:'ams'});S.offers.push(${lit({ id: 'o1', city: 'fra', city2: 'ams', name: 'Needy Corp', type: 'l2vpn', bw: 1, rate: 900, reqs, exp: 30, ...extra })});compute();`; +test('#241 the offer shows what is missing with its price, and one button buys it and signs', t => { + const h = setup(t, OFFER(['gen', 'routers'])); + const { ev, errors } = h; + const q = JSON.parse(ev("JSON.stringify(reqFix(S.offers[0]))")); + assert.deepEqual(q.items.map(x => x.k + '@' + x.city), ['gen@fra', 'gen@ams', 'routers@fra']); + assert.equal(q.cost, ev("2*GEN_COST+routerCost(0,1)")); + ev("UI.left='deals';UI.leftOpen=true;window.innerWidth=390;renderAll()"); + const card = text(h, '#left'); + assert.match(card, /Missing: a backup generator in Frankfurt, a backup generator in Amsterdam, a second router in Frankfurt/); + assert.match(card, /Buy it and sign/); + assert.ok(doc(h).querySelector('[data-act="acceptFix"]'), 'the button is there on a phone'); + const cash = ev('S.cash'); + ev(`ACT.acceptFix({id:'o1',cost:${q.cost}})`); + assert.equal(ev('S.cash'), cash - q.cost); + assert.equal(ev("S.pops.fra.gen&&S.pops.ams.gen&&S.pops.fra.routers===2"), true); + assert.equal(ev("S.biz.some(b=>b.id==='o1')&&!S.offers.length"), true, 'signed'); + assert.equal(ev("reqOk(S.biz.find(b=>b.id==='o1'))"), true, 'and every requirement is met'); + assert.deepEqual(errors, []); +}); + +test('#241 never silent: a stale price, too little cash or a deal that cannot be signed buys nothing', t => { + const { ev, errors } = setup(t, OFFER(['metro'])); + const cost = ev("reqFix(S.offers[0]).cost"); + assert.equal(cost, ev('2*SITE2_COST')); + ev(`ACT.acceptFix({id:'o1',cost:${cost - 1}})`); + assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false); + ev(`S.cash=${cost - 1};ACT.acceptFix({id:'o1',cost:${cost}})`); + assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false); + ev(`S.cash=1e8;S.offers[0].city2='lon';ACT.acceptFix({id:'o1',cost:${cost}})`); + assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false, 'no POP in London: nothing is bought'); + assert.equal(ev("reqFixHtml(S.offers[0])"), ''); + ev("S.offers[0].city2='ams';S.offers[0].reqs=['nocog']"); + assert.equal(ev("reqFix(S.offers[0])"), null, 'only hardware at a POP is offered'); + assert.deepEqual(errors, []); +}); + +/* ---------- #315: POP standards by kind ---------- */ +test('#315 save a standard, bring a POP up to it, then every POP of that kind at once', t => { + const h = setup(t, POPS + "S.lvl=4;S.pops.fra.routers=2;S.pops.fra.rgen=1;compute();"); + const { ev, errors } = h; + ev("UI.sel={type:'city',id:'fra'};UI.tab='links';window.innerWidth=390;renderAll()"); + assert.match(text(h, '#panel'), /POP standards/); + assert.match(text(h, '#panel'), /Regional hub/); + ev("ACT.ptSave({city:'fra',k:'medium'})"); + assert.equal(ev("JSON.stringify(S.popTiers.def.medium)"), JSON.stringify({ g: 1, rt: 2 })); + assert.equal(ev('S.popTiers.at.fra'), 'medium'); + const q = JSON.parse(ev("JSON.stringify(ptPlan('ams','medium'))")); + assert.deepEqual(q.steps, ['swap', 'add'], 'an empty POP swaps first, then adds'); + const cash = ev('S.cash'); + ev(`ACT.ptApply({city:'ams',k:'medium',cost:${q.cost}})`); + assert.equal(ev('S.cash'), cash - q.cost, 'charged exactly the quote'); + assert.equal(ev("S.pops.ams.routers===2&&S.pops.ams.rgen===1&&S.popTiers.at.ams==='medium'"), true); + // The standard grows: one button brings both medium POPs up. + ev("S.pops.fra.routers=3;S.pops.fra.rgen=2;S.pops.fra.rupDay=-1;ACT.ptSave({city:'fra',k:'medium'});S.pops.fra.routers=2;S.pops.fra.rgen=1;S.pops.ams.rupDay=-1;compute()"); + const A = JSON.parse(ev("JSON.stringify({n:ptAll('medium').todo.length,cost:ptAll('medium').cost})")); + assert.equal(A.n, 2); + ev('ACT.utilities({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Bring 2 POPs up/); + ev(`ACT.ptAll({k:'medium',cost:${A.cost}})`); + assert.equal(ev("['fra','ams'].every(c=>S.pops[c].routers===3&&S.pops[c].rgen===2)"), true); + assert.equal(ev("ptAll('medium').todo.length"), 0); + assert.deepEqual(errors, []); +}); + +test('#315 a busy lone router gets its partner before the swap, and never a step down', t => { + const { ev, errors } = setup(t, POPS + "S.lvl=4;ACT.launchBB({city:'ams'});S.popTiers.def.hub={g:2,rt:2};S.popTiers.def.micro={g:0,rt:1};compute();"); + assert.deepEqual(JSON.parse(ev("JSON.stringify(ptPlan('ams','hub').steps)")), ['add', 'swap']); + ev("ACT.ptApply({city:'ams',k:'hub',cost:ptPlan('ams','hub').cost})"); + assert.equal(ev("S.pops.ams.routers===2&&S.pops.ams.rgen===2"), true); + assert.equal(ev("S.inc.some(i=>i.type==='maint'&&i.ref==='ams')"), false, 'a rolling upgrade, no maintenance window'); + assert.equal(ev("ptPlan('ams','micro')"), null, 'a smaller standard asks for nothing'); + ev("ACT.ptApply({city:'ams',k:'micro',cost:0})"); + assert.equal(ev("S.pops.ams.rgen===2&&S.pops.ams.routers===2&&S.popTiers.at.ams==='micro'"), true, 'only marked'); + assert.deepEqual(errors, []); +}); + +test('#315 level 1 has no standards, and saves old and broken load', t => { + const h = setup(t, POPS); + const { ev, errors } = h; + ev("UI.sel={type:'city',id:'fra'};UI.tab='links';renderAll()"); + assert.doesNotMatch(text(h, '#panel'), /POP standards/); + ev("ACT.ptSave({city:'fra',k:'micro'})"); + assert.equal(ev('S.popTiers.def.micro'), null); + ev('delete S.popTiers;S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('JSON.stringify(S.popTiers)'), JSON.stringify({ def: { micro: null, medium: null, hub: null }, at: {} })); + ev("S.popTiers={def:{micro:{g:999,rt:2},hub:{g:1,rt:99},bogus:{g:1,rt:1}},at:{fra:'hub',ams:'nope',xyz:'micro',ber:'hub'}};S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('JSON.stringify(S.popTiers)'), JSON.stringify({ def: { micro: null, medium: null, hub: { g: 1, rt: ev('RMAX') } }, at: { fra: 'hub' } })); + assert.deepEqual(errors, []); +}); + +/* ---------- #199: find a network at a POP ---------- */ +test('#199 search and connected-only filter the transit, exchange and PNI lists, on a phone', t => { + const h = setup(t, "S.lvl=4;ACT.buyTransit({city:'fra',net:'cog',tier:0});compute();window.innerWidth=390;UI.sel={type:'city',id:'fra'};UI.tab='up';renderAll()"); + const { ev, errors } = h; + const rows = () => [...doc(h).querySelectorAll('#panel .row .nm')].map(e => e.textContent.trim()); + const all = rows().length; + assert.ok(doc(h).getElementById('netQ'), 'the search box is there'); + ev("ACT.netOnly()"); + assert.equal(rows().length, 1); + assert.match(rows()[0], /Cogentle/); + ev("ACT.netClear()"); + assert.equal(rows().length, all); + // Typing into the box filters as you go, and the box keeps focus and text. + ev("const i=document.getElementById('netQ');i.focus();i.value='goggle';i.dispatchEvent(new window.Event('input',{bubbles:true}))"); + assert.equal(ev("document.activeElement.id"), 'netQ'); + assert.equal(ev("UI.netQ"), 'goggle'); + ev("UI.tab='peer';renderAll()"); + const peer = rows(); + assert.ok(peer.length > 0 && peer.every(r => /Goggle/.test(r)), peer.join(' | ')); + ev("ACT.netFind({q:'zzzz'})"); + assert.match(text(h, '#panel'), /No network here matches this filter/); + ev("ACT.netFind({q:String(NET.ggl.asn)})"); + assert.match(text(h, '#panel'), /Goggle/, 'an AS number finds the network'); + assert.deepEqual(errors, []); +}); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 9101521..76db0bc 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -226,7 +226,7 @@ test('a dry run prices every command that has a price, and changes nothing', () setChCount: { id: df, o: 'zr4', n: 2 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, - utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, + utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, acceptFix: { id: 'none' }, ptApply: { city: 'fra', k: 'medium' }, ptAll: { k: 'medium' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); From d8223bad0401f5bfe43ba5536eb2146667ef9391 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 07:14:36 +0000 Subject: [PATCH 05/18] Tests: route fuzz compares the customer catalog, day steps waits longer for its trial A new customer type changes which offers a seeded late-game draws, so the fuzz games cannot play move for move like main (as with a world change), and the sales-trial race in day-steps comes on day 46 instead of before day 20. --- tests/day-steps.test.js | 3 ++- tests/route-fuzz.test.js | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js index 027b065..866cc51 100644 --- a/tests/day-steps.test.js +++ b/tests/day-steps.test.js @@ -189,7 +189,8 @@ test('a customer dropped while a sales trial routes: the trial runs again on the p.ev(TICK_ERR); p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};"); let found = false; - for (let d = 0; d < 20 && !found; d++) { + // Which day such a trial comes depends on the offers the seeded game draws (day 46 since latency contracts joined them). + for (let d = 0; d < 60 && !found; d++) { p.ev('rwDay()'); for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) { if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; } diff --git a/tests/route-fuzz.test.js b/tests/route-fuzz.test.js index 8207da4..c0787f2 100644 --- a/tests/route-fuzz.test.js +++ b/tests/route-fuzz.test.js @@ -17,10 +17,10 @@ function pages() { let base = head; try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {} let P = { base: openPage(base, 'base'), head: openPage(head, 'head') }; - // A change to the world itself (cities, networks, cables) or to what links cost cannot route like main: there is no - // same game to compare. Then the base is this checkout too, and the cache on/off check still runs; equivalence with - // main resumes once it lands. - const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)])])"); + // A change to the world itself (cities, networks, cables, the kinds of customers that call) or to what links cost + // cannot route like main: there is no same game to compare. Then the base is this checkout too, and the cache on/off + // check still runs; equivalence with main resumes once it lands. + const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)]),Object.keys(BIZ_T).map(t=>[t,BIZ_T[t].lv||1,BIZ_T[t].opts])])"); if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; } return P; } From 69cdb3e372f525ab6c9bbea867a7bb12033175c5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 07:25:21 +0000 Subject: [PATCH 06/18] Grow sideways in the late game: localised eyeball traffic, spread AI campuses, PNIs by router, spill tiers Traffic to networks that sell to homes now starts where their users live (#48), giant AI circuits come from campuses in 34 metros and less often from crowded ones (#61), a PNI bundles eight members per router up to 32 (#323), and RouteScript spill tiers move overflow onto detours within a latency budget (#136). --- .claude/skills/gameplay-rules/SKILL.md | 2 + CHANGELOG.md | 4 + docs/ARCHITECTURE.md | 6 +- site/i18n/de.js | 5 + site/i18n/es.js | 5 + site/i18n/fr.js | 5 + site/i18n/it.js | 5 + site/i18n/pt.js | 5 + src/agent/20-commands.js | 2 +- src/agent/40-read.js | 2 +- src/game/30-networks/45-home-markets.js | 26 ++++ src/game/60-features/95-standing-orders.js | 2 +- src/game/70-rules/20-exchanges.js | 5 + src/game/70-rules/95-utilities.js | 2 +- src/game/80-simulation/20-routescript.js | 10 +- src/game/80-simulation/29-route-core.js | 35 ++++- src/game/80-simulation/30-compute.js | 12 +- src/game/80-simulation/50-sanitize.js | 6 +- .../80-simulation/70-customers-and-events.js | 56 +++++++- src/game/90-actions/20-pops-transit-ix.js | 2 +- src/game/90-actions/85-routing-and-routers.js | 2 +- src/game/93-ui/52-pni-list.js | 2 +- src/game/94-dashboard/40-connections.js | 2 +- src/i18n/en.js | 5 + tests/endgame-scale.test.js | 134 ++++++++++++++++++ tests/gameplay-rules.test.js | 22 +++ tests/pnis-and-sold-out.test.js | 2 +- tests/route-fuzz.test.js | 8 +- tests/speed.test.js | 2 +- 29 files changed, 340 insertions(+), 36 deletions(-) create mode 100644 src/game/30-networks/45-home-markets.js create mode 100644 tests/endgame-scale.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index d6fba4b..8147b3f 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -39,6 +39,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | | N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. | | N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. | +| N8 | A POP's traffic to the networks that sell to homes (`cc`) goes mostly to those whose users live near it: at home above the world share, on other continents below (`locSh()`, `45-home-markets.js`). Only that split moves: a city's total and every network without home markets keep their shares. | People mostly talk to people near them, and peering with an eyeball where its users are must beat hauling its traffic to two cities (#48). | ## Modes and rules @@ -72,6 +73,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | | F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | | F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | +| F9 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). | ## DDoS diff --git a/CHANGELOG.md b/CHANGELOG.md index 744dfae..2f8424d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323). +- Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). +- Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). +- RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). - A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). ## [3.3.0] — 2026-11-09 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index dc99967..3563dd0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -159,7 +159,8 @@ The day: carry (`t.carry`): see step 4. 3. Builds flows: for every POP, its demand (eyeballs and customers) split across destination networks by their traffic share (`NSH`, with regional variants for - China, Russia and Korea). Incidents can add junk flows or scale demand. + China, Russia and Korea), localised per city: the networks that sell to homes split their part by where their users + live (`locSh()`, `30-networks/45-home-markets.js`, #48). Incidents can add junk flows or scale demand. 4. Routes flows rank by rank: the nearest usable exit first, ECMP across equal exits (a PNI goes before an IX port at the same distance: `PNI_TIE`, #298), consuming link, router (`nodeCap`) and exit capacity. A carrier's own transit port also @@ -168,7 +169,8 @@ The day: POP when the port is set to carry. Such a port is still an ordinary transit exit for the other POPs. Backup, RouteScript and Auto-TE rules keep their say, and so does a Prefer-marked port at its own POP (the other POPs keep the rule). With Auto-TE, overflow spills - onto alternate paths; RouteScript rules (`teRules()`) can prefer, avoid, cap, drain + onto alternate paths (spill tiers, `spill at 80% within 10 ms`, first try the fastest detour under the line within + that budget: `tiers()` in `29-route-core.js`); RouteScript rules (`teRules()`) can prefer, avoid, cap, drain or blackhole. 5. Layer-2 customers (L2VPN, SD-WAN, waves) are carved out of link capacity first. 6. Totals costs (`R.cost`) and revenue (`R.rev`) per month. diff --git a/site/i18n/de.js b/site/i18n/de.js index 5402b72..c4e986e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3890,6 +3890,7 @@ "pni_list.f_pni":"Schon PNI", "pni_list.f_transit":"Über Transit", "pni_list.f_worth":"Lohnt sich", +"pni_list.lag_full_add_a_router":"LAG voll mit {n} Mitgliedern: Jeder Router hier fasst {more}, bis {max}. Stell einen Router dazu, um ihn zu vergrößern.", "pni_list.list_more":"{list} +{n}", "pni_list.little_to_gain_here":"Hier gibt's wenig zu holen: {g}", "pni_list.n_here":"{g} hier", @@ -3950,6 +3951,7 @@ "pops_transit_ix.router_installed_in_city_upside_down":"Router in {city} installiert.
Kopfüber, wie es hier unten üblich ist. Den Paketen scheint es egal zu sein.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Bei DE-KICKS unterschrieben.
Willkommen in der Familie. Bitte erzähl niemandem, was du zahlst.", "pops_transit_ix.stay_take_the_discount":"Bleiben, Rabatt nehmen", +"pops_transit_ix.this_pni_already_bundles_n_ports":"Dieser PNI bündelt schon {n} Ports, mehr fassen deine Router hier nicht. Jeder Router nimmt {more} Mitglieder eines PNI auf, bis {max}: Stell einen Router dazu für mehr.", "pops_transit_ix.wait_before_you_go":"Warte! Bevor du gehst …", "pops_transit_ix.we_value_our_partnership_too_much":"Uns ist unsere Partnerschaft zu wichtig, als dass eine Kleinigkeit wie der Preis im Weg stehen sollte.", "pops_transit_ix.you_need_a_license_first_foreign":"Du brauchst zuerst eine Lizenz.
Ausländische Netze brauchen ein Joint Venture, um in Festlandchina zu bauen.", @@ -4322,6 +4324,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Jedes Gigabit, das dein Netz verlässt, wählt einen Ausgang: einen PNI, einen IX-Port oder einen Transit-Port. Ohne Eingriff nimmt es das nächste Peering mit freiem Platz (in derselben Stadt den PNI vor dem IX-Port) und Transit erst, wenn kein Peering es nehmen kann. RouteScript ändert diese Wahl, so wie Local-Pref, AS-Path-Prepending und Wartungs-Drains auf echten Routern.", "routescript.filled_in_from_your_network_as":"Ausgefüllt mit deinem Netz, wie es gerade ist. Lade eins, lies es, prüfe es, dann deploye es.", "routescript.for_a_ddos_rtbh_the_target":"Bei einem DDoS: Blackhole das Ziel upstream und stell Geschäftskunden an erste Stelle. Das Ziel ist so lange offline, also entferne es, wenn der Angriff vorbei ist.", +"routescript.from_this_load_on_spill_onto":"Eine Spill-Stufe: Sobald der kürzeste Pfad so voll ist, nimmt der Überlauf den besten Umweg, wenn er höchstens so viele Millisekunden dazulegt und selbst unter derselben Linie bleibt. Staple sie (80 % within 10 ms, 90 % within 20 ms), damit heißere Links früher und weiter ausweichen.", "routescript.great_question_here_is_a_production":"Tolle Frage! Hier ist ein produktionsreifes Skript, maßgeschneidert für deinen Live-Traffic. Ich habe es gründlich geprüft.", "routescript.help_and_ready_made_scripts":"Hilfe und fertige Skripte", "routescript.here_you_go_i_was_trained":"Bitte schön! Ich wurde mit jeder Router-Config trainiert, die je in einem Forum gepostet wurde, auch denen mit dem Titel „warum geht das nicht“.", @@ -4333,6 +4336,7 @@ "routescript.line_n_i_don_t_understand":"Zeile {n}: Ich verstehe „{text}“ nicht. Versuch: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"Zeile {n}: prepend 1- bis 3-mal", "routescript.line_n_spill_must_be_between":"Zeile {n}: spill muss zwischen 20 % und 100 % liegen", +"routescript.line_n_within_1_to_100_ms":"Zeile {n}: within muss zwischen 1 und 100 ms liegen", "routescript.live_state_rules":"Live: {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Wartungsfenster: Ändere die Namen, deploye, erledige die Arbeit und entferne es dann wieder.", "routescript.missing_what":"{what} fehlt", @@ -4369,6 +4373,7 @@ "routing.routing_and_ddos":"Routing & DDoS", "routing.trace_note":"Folge einem Paket Hop für Hop und sieh, warum es genau dort rausgeht.", "routing.trace_run":"Tracen", +"routing_and_routers.a_pni_here_bundles_n_ports":"Verkleinere zuerst einen PNI.
Dein PNI mit {net} bündelt {n} Ports, und mit einem Router weniger passen nur {m}.", "routing_and_routers.maintenance_window_in_city":"Wartungsfenster in {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"{model} wird ab Kundenlevel {lv} freigeschaltet.", "routing_and_routers.new_router_in_city_swapped_before":"Neuer Router in {city}
Getauscht, bevor irgendwas eingesteckt war: null Ausfallzeit, null wütende Kunden.", diff --git a/site/i18n/es.js b/site/i18n/es.js index feaa272..95661cb 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3888,6 +3888,7 @@ "pni_list.f_pni":"Ya con PNI", "pni_list.f_transit":"Por tránsito", "pni_list.f_worth":"Merece la pena", +"pni_list.lag_full_add_a_router":"LAG lleno con {n} miembros: cada router aquí admite {more}, hasta {max}. Añade un router para ampliarlo.", "pni_list.list_more":"{list} +{n}", "pni_list.little_to_gain_here":"Poco que ganar aquí: {g}", "pni_list.n_here":"{g} aquí", @@ -3948,6 +3949,7 @@ "pops_transit_ix.router_installed_in_city_upside_down":"Router instalado en {city}.
Boca abajo, como es costumbre por aquí. A los paquetes no parece importarles.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Firmado con DE-KICKS.
Bienvenido a la familia. Por favor, no le digas a nadie lo que pagas.", "pops_transit_ix.stay_take_the_discount":"Quedarme y aceptar el descuento", +"pops_transit_ix.this_pni_already_bundles_n_ports":"Este PNI ya agrupa {n} puertos, todo lo que caben en tus routers aquí. Cada router admite {more} miembros de un PNI, hasta {max}: añade un router para más.", "pops_transit_ix.wait_before_you_go":"¡Espera! Antes de irte…", "pops_transit_ix.we_value_our_partnership_too_much":"Valoramos demasiado nuestra relación como para dejar que algo tan pequeño como el precio se interponga.", "pops_transit_ix.you_need_a_license_first_foreign":"Primero necesitas una licencia.
Las redes extranjeras necesitan una empresa conjunta para construir en China continental.", @@ -4320,6 +4322,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Cada gigabit que sale de tu red elige una salida: un PNI, un puerto IX o un puerto de tránsito. Si no haces nada, toma el peering más cercano con sitio (en la misma ciudad, el PNI antes que el puerto IX), y el tránsito solo cuando ningún peering puede llevarlo. RouteScript cambia esas elecciones, como hacen local-pref, el prepend de AS-path y los drenajes de mantenimiento en routers reales.", "routescript.filled_in_from_your_network_as":"Rellenado con tu red tal como está ahora mismo. Carga uno, léelo, compruébalo y luego despliega.", "routescript.for_a_ddos_rtbh_the_target":"Para un DDoS: haz blackhole al objetivo aguas arriba y prioriza a los clientes empresariales. El objetivo queda a oscuras mientras dure, así que quítalo cuando acabe el ataque.", +"routescript.from_this_load_on_spill_onto":"Un escalón de spill: cuando el camino más corto está así de lleno, el exceso toma el mejor desvío si no añade más de esos milisegundos y se queda bajo la misma línea. Apílalos (80% within 10 ms, 90% within 20 ms) para desviar antes y más lejos cuanto más calientes estén los enlaces.", "routescript.great_question_here_is_a_production":"¡Gran pregunta! Aquí tienes un script listo para producción, a medida de tu tráfico en vivo. Lo he revisado a fondo.", "routescript.help_and_ready_made_scripts":"Ayuda y scripts ya hechos", "routescript.here_you_go_i_was_trained":"¡Aquí tienes! Me entrenaron con todas las configuraciones de router que se hayan publicado en un foro, incluidas las tituladas «por qué esto no funciona».", @@ -4331,6 +4334,7 @@ "routescript.line_n_i_don_t_understand":"línea {n}: no entiendo «{text}». Prueba: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"línea {n}: prepend de 1 a 3 veces", "routescript.line_n_spill_must_be_between":"línea {n}: spill debe estar entre 20 % y 100 %", +"routescript.line_n_within_1_to_100_ms":"línea {n}: within debe estar entre 1 y 100 ms", "routescript.live_state_rules":"En vivo: {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Ventana de mantenimiento: cambia los nombres, despliega, haz el trabajo y quítalo.", "routescript.missing_what":"falta {what}", @@ -4367,6 +4371,7 @@ "routing.routing_and_ddos":"Routing y DDoS", "routing.trace_note":"Sigue un paquete salto a salto y mira por qué sale por donde sale.", "routing.trace_run":"Trazar", +"routing_and_routers.a_pni_here_bundles_n_ports":"Reduce primero un PNI.
Tu PNI con {net} agrupa {n} puertos, y con un router menos solo caben {m}.", "routing_and_routers.maintenance_window_in_city":"Ventana de mantenimiento en {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"{model} se desbloquea en el nivel de cliente {lv}.", "routing_and_routers.new_router_in_city_swapped_before":"Router nuevo en {city}
Cambiado antes de conectar nada: cero inactividad, cero clientes enfadados.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f971279..a8c0711 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3888,6 +3888,7 @@ "pni_list.f_pni":"Déjà en PNI", "pni_list.f_transit":"Via le transit", "pni_list.f_worth":"Rentable", +"pni_list.lag_full_add_a_router":"LAG plein à {n} membres : chaque routeur ici en tient {more}, jusqu’à {max}. Ajoute un routeur pour l’agrandir.", "pni_list.list_more":"{list} +{n}", "pni_list.little_to_gain_here":"Peu à gagner ici : {g}", "pni_list.n_here":"{g} ici", @@ -3948,6 +3949,7 @@ "pops_transit_ix.router_installed_in_city_upside_down":"Routeur installé à {city}.
À l’envers, comme le veut la coutume ici. Les paquets n’ont pas l’air de s’en soucier.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Signé avec DE-KICKS.
Bienvenue dans la famille. Merci de ne dire à personne combien tu paies.", "pops_transit_ix.stay_take_the_discount":"Rester et prendre la remise", +"pops_transit_ix.this_pni_already_bundles_n_ports":"Ce PNI regroupe déjà {n} ports, tout ce que tes routeurs ici peuvent tenir. Chaque routeur prend {more} membres d’un PNI, jusqu’à {max} : ajoute un routeur pour aller plus loin.", "pops_transit_ix.wait_before_you_go":"Attends ! Avant de partir…", "pops_transit_ix.we_value_our_partnership_too_much":"Nous tenons trop à notre partenariat pour laisser un détail comme le prix se mettre en travers.", "pops_transit_ix.you_need_a_license_first_foreign":"Il te faut d’abord une licence.
Les réseaux étrangers ont besoin d’une joint-venture pour construire en Chine continentale.", @@ -4320,6 +4322,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Chaque gigabit qui quitte votre réseau choisit une sortie : une PNI, un port IX ou un port de transit. Livré à lui-même, il prend le peering le plus proche qui a de la place (dans une même ville, la PNI avant le port IX), et le transit seulement quand aucun peering ne peut le prendre. RouteScript change ces choix, comme le font local-pref, l’AS-path prepending et les drains de maintenance sur de vrais routeurs.", "routescript.filled_in_from_your_network_as":"Remplis à partir de votre réseau tel qu’il est en ce moment. Chargez-en un, lisez-le, vérifiez-le, puis déployez.", "routescript.for_a_ddos_rtbh_the_target":"Pour un DDoS : blackhole la cible en amont et sers d’abord les clients professionnels. La cible est coupée tant que ça dure, alors retire-le quand l’attaque est finie.", +"routescript.from_this_load_on_spill_onto":"Un palier de spill : dès que le plus court chemin est aussi plein, le trop-plein prend le meilleur détour s’il n’ajoute pas plus de ces millisecondes et reste lui-même sous la même ligne. Empile-les (80% within 10 ms, 90% within 20 ms) pour déborder plus tôt et plus loin quand les liens chauffent.", "routescript.great_question_here_is_a_production":"Excellente question ! Voici un script prêt pour la production, taillé pour votre trafic. Je l’ai vérifié minutieusement.", "routescript.help_and_ready_made_scripts":"Aide et scripts tout prêts", "routescript.here_you_go_i_was_trained":"Et voilà ! J’ai été entraîné sur toutes les configs de routeur jamais postées sur un forum, y compris celles intitulées « pourquoi ça marche pas ».", @@ -4331,6 +4334,7 @@ "routescript.line_n_i_don_t_understand":"ligne {n} : je ne comprends pas « {text} ». Essaie : spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"ligne {n} : prepend de 1 à 3 fois", "routescript.line_n_spill_must_be_between":"ligne {n} : spill doit être entre 20 % et 100 %", +"routescript.line_n_within_1_to_100_ms":"ligne {n} : within doit être entre 1 et 100 ms", "routescript.live_state_rules":"État : {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Fenêtre de maintenance : changez les noms, déployez, faites le travail, puis retirez-le.", "routescript.missing_what":"élément manquant : {what}", @@ -4367,6 +4371,7 @@ "routing.routing_and_ddos":"Routage et DDoS", "routing.trace_note":"Suis un paquet saut par saut et vois pourquoi il sort là où il sort.", "routing.trace_run":"Tracer", +"routing_and_routers.a_pni_here_bundles_n_ports":"Réduis d’abord un PNI.
Ton PNI avec {net} regroupe {n} ports, et avec un routeur de moins il n’en tient que {m}.", "routing_and_routers.maintenance_window_in_city":"Fenêtre de maintenance à {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"Le {model} se débloque au niveau client {lv}.", "routing_and_routers.new_router_in_city_swapped_before":"Nouveau routeur à {city}
Remplacé avant que quoi que ce soit ne soit branché : zéro interruption, zéro client fâché.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 9034753..ae47317 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3888,6 +3888,7 @@ "pni_list.f_pni":"Già in PNI", "pni_list.f_transit":"Tramite transit", "pni_list.f_worth":"Conviene", +"pni_list.lag_full_add_a_router":"LAG pieno a {n} membri: ogni router qui ne regge {more}, fino a {max}. Aggiungi un router per allargarlo.", "pni_list.list_more":"{list} +{n}", "pni_list.little_to_gain_here":"Poco da guadagnare qui: {g}", "pni_list.n_here":"{g} qui", @@ -3948,6 +3949,7 @@ "pops_transit_ix.router_installed_in_city_upside_down":"Router installato a {city}.
A testa in giù, come si usa da queste parti. Ai pacchetti non sembra importare.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Firmato con DE-KICKS.
Benvenuto in famiglia. Per favore, non dire a nessuno quanto paghi.", "pops_transit_ix.stay_take_the_discount":"Resta, prendi lo sconto", +"pops_transit_ix.this_pni_already_bundles_n_ports":"Questo PNI raggruppa già {n} porte, tutte quelle che i tuoi router qui possono reggere. Ogni router regge {more} membri di un PNI, fino a {max}: aggiungi un router per averne di più.", "pops_transit_ix.wait_before_you_go":"Aspetta! Prima che tu vada…", "pops_transit_ix.we_value_our_partnership_too_much":"Teniamo troppo alla nostra partnership per lasciare che una sciocchezza come il prezzo si metta in mezzo.", "pops_transit_ix.you_need_a_license_first_foreign":"Prima ti serve una licenza.
Per costruire nella Cina continentale le reti straniere hanno bisogno di una joint venture.", @@ -4320,6 +4322,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Ogni gigabit che esce dalla tua rete sceglie un’uscita: una PNI, una porta IX o una porta di transito. Se lo lasci fare, prende il peering più vicino con spazio libero (nella stessa città, la PNI prima della porta IX), e il transito solo quando nessun peering può prenderlo. RouteScript cambia queste scelte, come fanno local-pref, AS-path prepending e drain di manutenzione sui router veri.", "routescript.filled_in_from_your_network_as":"Compilati dalla tua rete così com’è adesso. Caricane uno, leggilo, controllalo, poi fai il deploy.", "routescript.for_a_ddos_rtbh_the_target":"Per un DDoS: metti il bersaglio in blackhole a monte e servi prima i clienti business. Il bersaglio resta al buio finché dura, quindi toglila quando l’attacco è finito.", +"routescript.from_this_load_on_spill_onto":"Un gradino di spill: quando il percorso più corto è pieno a questo punto, il traffico in eccesso prende la deviazione migliore se aggiunge al massimo questi millisecondi e resta sotto la stessa soglia. Impilali (80% within 10 ms, 90% within 20 ms) per deviare prima e più lontano man mano che i link si scaldano.", "routescript.great_question_here_is_a_production":"Ottima domanda! Ecco uno script pronto per la produzione, su misura per il tuo traffico. L’ho controllato a fondo.", "routescript.help_and_ready_made_scripts":"Aiuto e script pronti", "routescript.here_you_go_i_was_trained":"Ecco qua! Sono stato addestrato su ogni configurazione di router mai pubblicata in un forum, comprese quelle intitolate “perché non funziona”.", @@ -4331,6 +4334,7 @@ "routescript.line_n_i_don_t_understand":"riga {n}: non capisco “{text}”. Prova: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"riga {n}: prepend da 1 a 3 volte", "routescript.line_n_spill_must_be_between":"riga {n}: spill deve essere tra 20% e 100%", +"routescript.line_n_within_1_to_100_ms":"riga {n}: within deve essere tra 1 e 100 ms", "routescript.live_state_rules":"Stato: {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Finestra di manutenzione: cambia i nomi, fai il deploy, fai il lavoro, poi toglilo.", "routescript.missing_what":"{what} mancante", @@ -4367,6 +4371,7 @@ "routing.routing_and_ddos":"Routing e DDoS", "routing.trace_note":"Segui un pacchetto hop dopo hop e scopri perché esce proprio lì.", "routing.trace_run":"Traccia", +"routing_and_routers.a_pni_here_bundles_n_ports":"Prima riduci un PNI.
Il tuo PNI con {net} raggruppa {n} porte, e con un router in meno ne reggi solo {m}.", "routing_and_routers.maintenance_window_in_city":"Finestra di manutenzione a {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"{model} si sblocca al livello clienti {lv}.", "routing_and_routers.new_router_in_city_swapped_before":"Nuovo router a {city}
Sostituito prima che ci fosse collegato qualcosa: zero downtime, zero clienti arrabbiati.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0657f8f..59ba267 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3888,6 +3888,7 @@ "pni_list.f_pni":"Já com PNI", "pni_list.f_transit":"Por trânsito", "pni_list.f_worth":"Compensa", +"pni_list.lag_full_add_a_router":"LAG cheio com {n} membros: cada router aqui aguenta {more}, até {max}. Adiciona um router para o aumentar.", "pni_list.list_more":"{list} +{n}", "pni_list.little_to_gain_here":"Pouco a ganhar aqui: {g}", "pni_list.n_here":"{g} aqui", @@ -3948,6 +3949,7 @@ "pops_transit_ix.router_installed_in_city_upside_down":"Roteador instalado em {city}.
De cabeça para baixo, como é costume por aqui. Os pacotes não parecem se importar.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Contrato assinado com a DE-KICKS.
Bem-vindo à família. Por favor, não conte a ninguém quanto você paga.", "pops_transit_ix.stay_take_the_discount":"Ficar com o desconto", +"pops_transit_ix.this_pni_already_bundles_n_ports":"Este PNI já agrupa {n} portas, tudo o que os teus routers aqui aguentam. Cada router aguenta {more} membros de um PNI, até {max}: adiciona um router para mais.", "pops_transit_ix.wait_before_you_go":"Espere! Antes de ir…", "pops_transit_ix.we_value_our_partnership_too_much":"Valorizamos demais nossa parceria para deixar uma bobagem como o preço atrapalhar.", "pops_transit_ix.you_need_a_license_first_foreign":"Primeiro você precisa de uma licença.
Redes estrangeiras precisam de uma joint venture para construir na China continental.", @@ -4320,6 +4322,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Todo gigabit que sai da sua rede escolhe uma saída: uma PNI, uma porta de IX ou uma porta de trânsito. Por conta própria, ele pega o peering mais próximo que tem espaço (na mesma cidade, a PNI antes da porta de IX), e trânsito só quando nenhum peering consegue levar. O RouteScript muda essas escolhas, como local-pref, AS-path prepending e drains de manutenção fazem em roteadores de verdade.", "routescript.filled_in_from_your_network_as":"Preenchidos a partir da sua rede como ela está agora. Carregue um, leia, verifique e depois faça o deploy.", "routescript.for_a_ddos_rtbh_the_target":"Para um DDoS: coloque o alvo em blackhole no upstream e priorize os clientes empresariais. O alvo fica fora do ar enquanto durar, então remova quando o ataque acabar.", +"routescript.from_this_load_on_spill_onto":"Um degrau de spill: quando o caminho mais curto está assim cheio, o excesso segue o melhor desvio se não acrescentar mais do que esses milissegundos e ficar abaixo da mesma linha. Empilha-os (80% within 10 ms, 90% within 20 ms) para desviar mais cedo e mais longe à medida que os links aquecem.", "routescript.great_question_here_is_a_production":"Ótima pergunta! Aqui está um script pronto para produção, sob medida para o seu tráfego. Eu verifiquei tudo com cuidado.", "routescript.help_and_ready_made_scripts":"Ajuda e scripts prontos", "routescript.here_you_go_i_was_trained":"Aqui está! Fui treinado em todas as configurações de roteador já postadas num fórum, inclusive as com o título “por que isso não funciona”.", @@ -4331,6 +4334,7 @@ "routescript.line_n_i_don_t_understand":"linha {n}: não entendi “{text}”. Tente: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"linha {n}: prepend de 1 a 3 vezes", "routescript.line_n_spill_must_be_between":"linha {n}: spill deve estar entre 20% e 100%", +"routescript.line_n_within_1_to_100_ms":"linha {n}: within tem de estar entre 1 e 100 ms", "routescript.live_state_rules":"Ao vivo: {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Janela de manutenção: troque os nomes, faça o deploy, faça o trabalho e depois remova.", "routescript.missing_what":"falta {what}", @@ -4367,6 +4371,7 @@ "routing.routing_and_ddos":"Roteamento e DDoS", "routing.trace_note":"Siga um pacote salto a salto e veja por que ele sai por onde sai.", "routing.trace_run":"Traçar", +"routing_and_routers.a_pni_here_bundles_n_ports":"Reduz primeiro um PNI.
O teu PNI com {net} agrupa {n} portas, e com um router a menos só cabem {m}.", "routing_and_routers.maintenance_window_in_city":"Janela de manutenção em {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"{model} desbloqueia no nível de cliente {lv}.", "routing_and_routers.new_router_in_city_swapped_before":"Roteador novo em {city}
Trocado antes de qualquer coisa estar conectada: zero downtime, zero clientes bravos.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index de2324b..8e25978 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -101,7 +101,7 @@ const API_CMD={ cancelPni:{args:[['id','entityId']],confirm:'arg',pass:a=>({id:a.id,ok:1}), doc:'Cancel a PNI or its pending augment.'}, lagP:{args:[['id','entityId'],['d','step']],watch:['pni.#id'], - doc:'Add or remove a LAG member on a PNI. Adding is an augment with a lead time.'}, + doc:'Add or remove a LAG member on a PNI, up to 8 per router at the POP (pniLagMax, at most PNI_LAG_MAX). Adding is an augment with a lead time.'}, sacrif:{args:[['id','entityId']],watch:['pni.#id'], doc:'Mark a PNI sacrificial, so attack traffic is steered into it.'}, peerPol:{args:[['p','peerPolicy']],watch:['ppol'], diff --git a/src/agent/40-read.js b/src/agent/40-read.js index e767e2d..0b596d8 100644 --- a/src/agent/40-read.js +++ b/src/agent/40-read.js @@ -26,7 +26,7 @@ function apiJson(v){ carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders each recipe's script, because the source is a function and some read the live network. The recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,PNI_LAG_MAX,PNI_LAG_RT,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; const API_MADE={ BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), diff --git a/src/game/30-networks/45-home-markets.js b/src/game/30-networks/45-home-markets.js new file mode 100644 index 0000000..15be11a --- /dev/null +++ b/src/game/30-networks/45-home-markets.js @@ -0,0 +1,26 @@ +/* Where each network's users live (#48). A network that sells to homes lists its home markets (cc, see W2), and that is + where its eyeballs are. People mostly talk to people near them, so a POP's traffic to the networks that sell to homes + goes mostly to the ones at home: a New York POP sends a lot to Comecast and little to Doitsche Telekomm, Frankfurt + the other way round. Together those networks keep the share the city's table gives them; only how it splits between + them follows geography. Content and carriers without home markets are everywhere and keep their shares. + Routing is unchanged: traffic leaves at the nearest exit (hot potato), so an eyeball peered with in the cities its + users are in takes that traffic off your backbone where it starts, and one peered with in two cities has it hauled + there from everywhere else. */ +const LOC_HOME=1,LOC_REG=0.3,LOC_FAR=0.08; +const LOC_NIX=new Map(NETS.map((n,j)=>[n.id,j])); +// Per network index: its home countries and the regions they are in, or null (no home market: everywhere). +let LOC_NET=null; +function locNets(){if(LOC_NET)return LOC_NET;const ccReg=new Map(); + for(const c of CITIES){let s=ccReg.get(c.cc);if(!s)ccReg.set(c.cc,s=new Set());s.add(c.reg);} + LOC_NET=NETS.map(n=>{if(!n.cc)return null;const cc=new Set(Array.isArray(n.cc)?n.cc:[n.cc]),reg=new Set();for(const k of cc)for(const r of ccReg.get(k)||[])reg.add(r);return {cc,reg};}); + return LOC_NET;} +// How near a city is to a network's users: at home, on the same continent, or far away. +const locW=(h,C)=>h.cc.has(C.cc)?LOC_HOME:h.reg.has(C.reg)?LOC_REG:LOC_FAR; +/* A city's shares in table T (by network index), localised. The tables and the map never change after load, so each + city's array is made once per table and kept. */ +const LOC_SH=new Map(); +function locSh(T,c){let m=LOC_SH.get(T);if(!m)LOC_SH.set(T,m=new Map());let a=m.get(c);if(a)return a; + const L=locNets(),C=CITY[c],NN=NETS.length;a=new Float64Array(NN);let g=0,gw=0; + for(let j=0;j0){const f=g/gw;for(let j=0;jlagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue; L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(), - lag:()=>n()ACT.lagP({id:p.id,d:1})}:null, + lag:()=>n()ACT.lagP({id:p.id,d:1})}:null, ups:()=>{const out=[];for(let t=p.g1?0:p.tier+1;tACT.pni({city:c,net:p.net,tier:t})});}return out;}});} // Nominal capacity, not ixCap(): a LACP fault or one building down halves a LAG for a day or two, not worth a bigger port. for(const x in S.ixp){const c=ixCity(x),use=(R.useIx[x]||0)*opsAhead(),n=()=>(S.ixn||{})[x]||1,cap=()=>lagCap(PORT[S.ixp[x]].g,n())*(isRemote(x)?REMOTE_CAP:1),pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue; diff --git a/src/game/70-rules/20-exchanges.js b/src/game/70-rules/20-exchanges.js index b451433..44d0c2f 100644 --- a/src/game/70-rules/20-exchanges.js +++ b/src/game/70-rules/20-exchanges.js @@ -23,6 +23,11 @@ function ixMembers(c){if(XIXM[c])return XIXM[c].members.slice();if(S.myIx[c])ret const IX_MEM={}; // LAG: several identical ports bundled into one logical link. Flow hashing is never perfectly even, so a bundle carries ~95% of the sum. const LAG_MAX=8; +/* A PNI bundle grows with the routers it lands on (#323): eight members per router at the POP, so a PNI fatter than eight + ports costs another router (its price and its port slots), up to 32 members, the most the big LAG implementations + bundle. Only PNIs: transit, exchange and fabric ports stay at LAG_MAX. */ +const PNI_LAG_RT=8,PNI_LAG_MAX=32; +function pniLagMax(c){const p=S.pops[c];return Math.min(PNI_LAG_MAX,PNI_LAG_RT*((p&&p.routers)||1));} function lagCap(g,n){n=n||1;return g*n*(n>1?0.95:1);} function lagName(tier,n){return (n||1)>1?`${n}×${PORT[tier].n} LAG`:tr('common.port_port',{port:PORT[tier].n});} function ixCap(c){return ixLagF(c)*(S.myIx[c]?myFab(c).g*(myIxLive(c)?1:0):liveCap(PORT[S.ixp[c]].g,ixCity(c),(S.ixSite||{})[c],(S.ixn||{})[c])*(isRemote(c)?REMOTE_CAP:1));} diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index b007039..fa11190 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -14,7 +14,7 @@ function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new // list of networks, and Goggle is throttled to half in Russia. The world shares (NSH) would size boxes for networks the // city cannot even reach, and too few for the ones it uses most. const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH; -const cityNetSh=(c,id)=>(cityShTab(c)[id]||0)*(id==='ggl'&&ruCity(c)?0.5:1); +const cityNetSh=(c,id)=>{const j=LOC_NIX.get(id);return (j===undefined?0:locSh(cityShTab(c),c)[j])*(id==='ggl'&&ruCity(c)?0.5:1);}; // A city's total share only depends on its table and on the Russian throttle, and the tables never change after load: // summed once per kind of city, not once per network asked about (that was cities × networks² every shift). const CSH_SUM=new Map(); diff --git a/src/game/80-simulation/20-routescript.js b/src/game/80-simulation/20-routescript.js index 7e63919..bd69f95 100644 --- a/src/game/80-simulation/20-routescript.js +++ b/src/game/80-simulation/20-routescript.js @@ -9,6 +9,9 @@ cap transit cogentle at 20 gbps avoid transit for goggle # Move traffic before links are completely full spill at 85% +# Hot links spill early onto detours that cost little latency +# spill at 80% within 10 ms +# spill at 90% within 20 ms # Local-pref: use the cheap upstream first, the pricey one last # prefer transit cogentle # avoid transit level tree @@ -27,9 +30,11 @@ function teFind(word,list,label){const w=slug(word);if(!w)return {err:tr('routes const pre=list.filter(x=>w.length>=3&&slug(x.name).startsWith(w));if(pre.length===1)return {v:pre[0].id}; const best=list.map(x=>({x,d:Math.min(lev(w,slug(x.name)),lev(w,x.id))})).sort((a,b)=>a.d-b.d)[0]; return {err:tr('routescript.unknown_what_word',{what:label,word})+(best&&best.d<=3?tr('routescript.did_you_mean_name',{name:best.x.name}):'')};} -function teParse(src){const out={spill:null,cap:{},net:{},up:{},prep:{},protect:false,drain:new Set(),avoid:new Set(),blackhole:false,errors:[],n:0}; +function teParse(src){const out={spill:null,tiers:[],cap:{},net:{},up:{},prep:{},protect:false,drain:new Set(),avoid:new Set(),blackhole:false,errors:[],n:0}; const lines=String(src||'').split('\n').slice(0,60); lines.forEach((raw,i)=>{const line=raw.replace(/#.*/,'').trim().toLowerCase();if(!line)return;const L=i+1;let m; + // A spill tier (#136): from this load on, detours that add at most this many milliseconds. + if(m=line.match(/^spill\s+at\s+(\d{1,3})\s*%\s+within\s+(\d{1,3})\s*ms$/)){const v=+m[1],ms=+m[2];if(v<20||v>100)out.errors.push(tr('routescript.line_n_spill_must_be_between',{n:L}));else if(ms<1||ms>100)out.errors.push(tr('routescript.line_n_within_1_to_100_ms',{n:L}));else{out.tiers.push({at:v/100,ms});out.tiers.sort((a,b)=>a.at-b.at||a.ms-b.ms);out.n++;}return;} if(m=line.match(/^spill\s+at\s+(\d{1,3})\s*%$/)){const v=+m[1];if(v<20||v>100)out.errors.push(tr('routescript.line_n_spill_must_be_between',{n:L}));else{out.spill=v/100;out.n++;}return;} if(m=line.match(/^(prefer|avoid)\s+(pni|ix|transit)\s+for\s+(.+)$/)){const r=teFind(m[3],NETS,tr('common.network'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}const o=out.net[r.v]=out.net[r.v]||{};o[m[1]]=TE_KINDS[m[2]];out.n++;return;} if(m=line.match(/^cap\s+transit\s+(.+?)\s+at\s+(\d+(?:\.\d+)?)\s*(gbps|tbps|g|t)$/)){const r=teFind(m[1],NETS.filter(n=>n.price),tr('common.transit_provider'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.cap[r.v]=+m[2]*(m[3][0]==='t'?1000:1);out.n++;return;} @@ -103,6 +108,7 @@ function teHelpModal(){const rule=(code,what)=>`
${code}
${tr('routescript.deploy_makes_it_live_for_the')}

${tr('common.rules')}

${rule('spill at 85%',tr('routescript.move_traffic_to_the_next_exit'))} + ${rule('spill at 80% within 10 ms',tr('routescript.from_this_load_on_spill_onto'))} ${rule('prefer pni for goggle',tr('routescript.send_one_network_s_traffic_over'))} ${rule('avoid transit for netchill',tr('routescript.use_that_kind_of_exit_for'))} ${rule('cap transit cogentle at 20 gbps',tr('routescript.a_ceiling_on_one_provider_so'))} @@ -122,7 +128,7 @@ function teModal(msg){const src=UI.teDraft!==undefined?UI.teDraft:(S.te.script||

${tr('routescript.write_rules_check_them_against_live')}

${msg||''}
${btn(tr('routescript.check_dry_run'),'teCheck',{},'')}${btn(tr('common.deploy'),'teDeploy',{},'pink')}${S.te.script?btn(tr('common.remove_script'),'teClear',{},'ghost sm'):''}${btn(tr('common.optimize'),'teOpt',{},'ghost sm')}${btn(tr('routescript.reset_to_example'),'teExample',{},'ghost sm')}
${btn('✨ '+tr('routescript.slop_it_with_ai'),'teSlop',{},'aibtn')}${btn(tr('routescript.help_and_ready_made_scripts'),'teHelp',{},'ghost sm')}
-

${tr('common.rules_7b18')} spill at 80% · prefer pni|ix|transit for NETWORK · avoid pni|ix|transit for NETWORK · cap transit PROVIDER at 20 gbps · prefer|avoid transit PROVIDER · prepend transit PROVIDER 1-3 · protect customers · drain CITY · avoid link CITY-CITY · blackhole ddos

+

${tr('common.rules_7b18')} spill at 80% · spill at 80% within 10 ms · prefer pni|ix|transit for NETWORK · avoid pni|ix|transit for NETWORK · cap transit PROVIDER at 20 gbps · prefer|avoid transit PROVIDER · prepend transit PROVIDER 1-3 · protect customers · drain CITY · avoid link CITY-CITY · blackhole ddos

${S.te.script?`

${tr('routescript.live_state_rules',{state:S.te.on?tr('common.deployed'):tr('routescript.controller_is_off'),rules:teRules()?tr('routescript.n_rules_active',{n:teRules().n}):tr('common.not_active')})}

`:''}`);} function teTrial(src){const keep=S.te.script,on=S.te.on,before={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0}; S.te.script=src;S.te.on=true;compute();const after={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0,bh:R.teBlack||0}; diff --git a/src/game/80-simulation/29-route-core.js b/src/game/80-simulation/29-route-core.js index 1e14cdc..895085f 100644 --- a/src/game/80-simulation/29-route-core.js +++ b/src/game/80-simulation/29-route-core.js @@ -9,7 +9,7 @@ function routeCore(){ // The day's state, set by nodes() and run(). (TR, base and eff, the ranks, are for the reference loop of the tests.) let NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD, E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, - TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff, + TE,SPILL,TT,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff, NX=0,USED=null,CAPX=null,CIX=null,HPX=null,DTX=null,VISX=null,TEF=null,EP=0; // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. // F: its index; fci, fnj: its city and network index. BRX: BRJ with each list as a list object of one shape (lx()). @@ -98,9 +98,35 @@ function routeCore(){ // with free capacity, as long as they are no more than twice as long. const send=(x,want)=>{ let room=Math.min(want,FREM[F],CAPX[x]-USED[x]);if(room<=1e-6)return;const ci=CIX[x]; - const P=PP[ci]||(PP[ci]=walkP(Pv,fci,ci));if(!P.dead)room-=push(x,P,room,TE&&SPILL<1?1-SPILL:0); + const P=PP[ci]||(PP[ci]=walkP(Pv,fci,ci));if(TT&&ci!==fci){room=tiers(x,P,room,ci);if(room<=1e-6)return;} + if(!P.dead)room-=push(x,P,room,TE&&SPILL<1?1-SPILL:0); if(TE&&room>1e-6&&FREM[F]>1e-6&&USED[x]1e-6;k++){const P=altPath(fci,ci,Dv[ci]);if(!P)break;const m=push(x,P,Math.min(room,CAPX[x]-USED[x]));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} }; + /* Spill tiers (#136, `spill at 80% within 10 ms`): the shortest path fills up to a tier's line, then what does not fit + takes the fastest detour whose links are all still under that line, if it adds no more than the tier's milliseconds; + the next tier lets links run hotter and detours longer. After the last tier the usual rules above take over. A detour + is searched by latency over the links under the line (tierSearch), and kept per pair and tier while it still is: + links only fill up while routing, so a pair with no detour under a line never gets one. */ + const pathMs=P=>{let ms=P.ms;if(ms<0){ms=0;const p=P.path;for(let k=0;k{const n=TEO.length-1,core=CORE;if(!TSD||TSD.length!==n){TSD=new Float64Array(n);TSP=new Array(n);TSS=new Int32Array(n);TSG=0;} + const g=++TSG,D=TSD,P=TSP,ST=TSS;let m=0;D[src]=0;ST[src]=g;TH[0]=0;THU[0]=src;m=1; + while(m){let best=0;for(let i=1;iD[u])continue;if(u===dst)break; + for(let k=TEO[u],K=TEO[u+1];ke.cap*keep+1e-3)||(HAS[v]&&NRES[v]<=1e-3)||(core&&OUT[v]&&v!==dst))continue; + const nd=d+e.lat;if(nd>lim||!(nd<(ST[v]===g?D[v]:Infinity)))continue;D[v]=nd;ST[v]=g;P[v]=e;TH[m]=nd;THU[m]=v;m++;}} + return ST[dst]===g?walkP(P,src,dst):null;}; + const tierPath=(t,keep,src,dst,lim)=>{const key=(src*NC+dst)*TT.length+t,c=TC.get(key);if(c===false)return null; + if(c){let ok=true;const p=c.path,ni=c.ni;for(let k=0;kp[k].cap*keep+1e-3)){ok=false;break;} + if(ok)for(let k=0;k1e-3)){ok=false;break;}} + if(ok)return pathMs(c)<=lim?c:null;} + const Q=tierSearch(src,dst,keep,Infinity);TC.set(key,Q||false);return Q&&pathMs(Q)<=lim?Q:null;}; + const tiers=(x,P,room,ci)=>{for(let t=0;t1e-6;t++){const T=TT[t],keep=1-T.at; + room-=push(x,P,room,keep); + if(room<=1e-6||FREM[F]<=1e-6||!(USED[x]1e-6){room-=m;R2.teMoved+=m;}} + return room;}; // Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over // them by free capacity (like several transits in one city), then top up in order if one fills. // The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order). @@ -204,10 +230,11 @@ function routeCore(){ return {nodeTake,carry, nodes(o){({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD}=o);}, run(o,PASSES,RANKS,RSET){({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, - TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff}=o); + TE,SPILL,TT,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff}=o); NX=E.length;USED=new Float64Array(NX);CAPX=new Float64Array(NX);CIX=new Int32Array(NX);HPX=new Uint8Array(NX);DTX=new Float64Array(NX);VISX=new Int32Array(NX); for(let x=0;xn==='ggl'&&ru?0.5:1;let sa=shArr.get(SH),sm=shSum.get(SH);if(!sa){shArr.set(SH,sa=NETS.map(n=>SH[n.id]||0));shSum.set(SH,sm=[]);} - const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; + // This city's own split: its traffic to networks that sell to homes goes mostly to the ones whose users are near (#48). + const ls=locSh(SH,c); + const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?ls[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; - for(let j=0;jday?ev.pmtud:null,kr=CITY[c].kr; - for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; + for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; // With `protect customers`, the business part first, then the rest (no arrays: this runs per city and network). const bf=d0>0?biz/d0:0,sp=!!(TRX&&TRX.protect&&bf>0),cn2=cacheNets.has(n.id); for(let q=0;q<(sp?2:1);q++){const x=sp?(q?a*(1-bf):a*bf):a,bz=sp&&!q;if(x<=0)continue;if(cn2){flow(ci,j,x*0.85,true,bz);flow(ci,j,x*0.15,false,bz);} @@ -186,7 +188,7 @@ function compute(){RW.gen++; if(!R2.egDesc[ek])R2.egDesc[ek]={lab:clean?labOf(N_('compute.scrubbed_traffic_from_city'),'city',CITY[A].name):labOf(N_('compute.attack_entering_in_city'),'city',CITY[from].name),city:B,k:'l2'}; for(const i of ni)if(HAS[i])nodeTake(i,amt);for(const l of path){l.res-=amt;l.ld+=amt;if(!clean){l.jk=(l.jk||0)+amt;JK=1;}carry(l,ek,clean?NN+2:NN,Bi,amt);}return amt;}; const DD=ddosLoad({E,okBy,R2,autoBh:!!(TRX&&TRX.blackhole),haul,ms:msOf}); - const TE=!!(S.te&&S.te.on)&&coreTE(),TR=TE?teRules():null,REACH=coreTeReach();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1; + const TE=!!(S.te&&S.te.on)&&coreTE(),TR=TE?teRules():null,REACH=coreTeReach();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1,TT=TR&&TR.tiers.length?TR.tiers:null; /* A network in a peer's customer cone, reached through that peer (#85): after every network you peer with directly (its AS path is one hop longer) and before transit. */ const base=(e,n)=>e.pref==='low'?4:e.rank>0&&e.rank<3&&coneOf(e,n)?CONE_RANK:e.rank; @@ -216,7 +218,7 @@ function compute(){RW.gen++; R.egT and R.netEg list them in; both are written back after routing. NEG: each network's R.netEg record. */ const EGT=new Float64Array(4),EGO=[],NEA=new Float64Array(NN*4),NEO=[],NEG=[]; ROUTE.run({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, - TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff},PASSES,RANKS,RSET); + TE,SPILL,TT,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff},PASSES,RANKS,RSET); for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i]; for(const k of EGO)R2.egT[EXK[k]]=EGT[k];for(const j of NEO){const ne=NEG[j];for(let k=0;k<4;k++)ne[EXK[k]]=NEA[j*4+k];} (()=>{ diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index db35e34..249bd7d 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -20,7 +20,7 @@ function sanitize(s){ for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); - const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); + const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),plag=v=>int(v,1,PNI_LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.kind==='df'?cmClean(l.list):null;if(L)l.list=L;else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its @@ -32,9 +32,9 @@ function sanitize(s){ if(!ks.has(k)||typeof v!=='string'||!own(MET,v)||v==='normal')delete pm[k];}} const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t.carry===true||delete t.carry,t.premium=premOnlyAt(NET[t.net],t.city)||!!t.premium&&premCity(NET[t.net],t.city),t)); - s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); + s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=plag(x.n),x.sacrif=!!x.sacrif,x)); // PNIs on order (#…): delivery day, a pending augment, and 1G for the one network that sells it - for(const x of s.pni){if(x.ready!==undefined)x.ready=num(x.ready,0);if(x.g1)x.g1=x.tier===0&&x.net==='dtk'?true:undefined;else delete x.g1;if(x.up){const u=x.up;x.up=u&&typeof u==='object'?{tier:tier(u.tier),n:lag(u.n),ready:num(u.ready,0),g1:!!u.g1&&x.net==='dtk'&&tier(u.tier)===0,...(u.site==='ab'?{site:'ab'}:{})}:undefined;if(!x.up)delete x.up;}} + for(const x of s.pni){if(x.ready!==undefined)x.ready=num(x.ready,0);if(x.g1)x.g1=x.tier===0&&x.net==='dtk'?true:undefined;else delete x.g1;if(x.up){const u=x.up;x.up=u&&typeof u==='object'?{tier:tier(u.tier),n:plag(u.n),ready:num(u.ready,0),g1:!!u.g1&&x.net==='dtk'&&tier(u.tier)===0,...(u.site==='ab'?{site:'ab'}:{})}:undefined;if(!x.up)delete x.up;}} // Supply chain: a shortage and a price lock, both optional. {const H=s.hw&&typeof s.hw==='object'&&!Array.isArray(s.hw)?s.hw:{},o={};const sh=H.shock,lk=H.lock; if(sh&&typeof sh==='object'&&own(HW_SHOCK,sh.k))o.shock={k:sh.k,until:num(sh.until,0),mul:clamp(num(sh.mul,1),1,2)}; diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js index cf037a7..7fd74ca 100644 --- a/src/game/80-simulation/70-customers-and-events.js +++ b/src/game/80-simulation/70-customers-and-events.js @@ -16,16 +16,60 @@ function eventTick(b,d){if(!BIZ_T[b.type].event)return false;if(d=0.95)S.stats.evFull=(S.stats.evFull||0)+1;const pay=avg>=0.95?b.fee:avg>=0.7?Math.round(b.fee*avg):-Math.round(b.fee*0.2);S.cash+=pay;S.biz=S.biz.filter(x=>x!==b); toast(pay>=0?tr('customers_and_events.name_is_over_pay_you_delivered',{name:esc(b.name),pay:fmt$(pay),pct:pct(avg)})+(avg>=0.95?' '+tr('common.flawless'):''):tr('customers_and_events.name_was_a_disaster_only_pct',{name:esc(b.name),pct:pct(avg),pay:fmt$(-pay)}),pay>=0?'good':'bad');sfx(pay>=0?'coin':'err');return true;} -/* Where the giants actually build: gigawatt AI campuses and cloud regions, mapped to the nearest city on the map. */ -const MEGA=[{c:'ash',n:'Data Center Alley'},{c:'ash',n:'Prome-the-mess Ohio'},{c:'dal',n:'Star-Gait Abilene'},{c:'dal',n:'Hyperbole Louisiana'},{c:'dal',n:'Colossus of Blues Memphis'},{c:'chi',n:'Fairweather Wisconsin'},{c:'chi',n:'Project Rainy-er Indiana'},{c:'chi',n:'Cornfield Cluster Iowa'},{c:'nyc',n:'Neocloud New Jersey'},{c:'sto',n:'Star-Gait Fjord-way'},{c:'mad',n:'Aragón Mega-shed'},{c:'dub',n:'Bring-Your-Own-Power Dublin'},{c:'auh',n:'Star-Gait UAE'},{c:'ruh',n:'Desert Kingdom AI Campus'},{c:'doh',n:'Lusail Data Oasis'},{c:'kul',n:'Johor Overflow'},{c:'hyd',n:'Vizag AI Hub'},{c:'icn',n:'Ulsan AI Campus'},{c:'tok',n:'Hokkaido Snow DC'},{c:'syd',n:'Star-Gait Down Under'},{c:'syd',n:'AirDrunk Western Sydney'},{c:'mel',n:'AirDrunk Melbourne West'},{c:'mex',n:'Querétaro Cluster'},{c:'for',n:'Short-Video Ceará Campus'},{c:'scl',n:'Quilicura Region'}]; +/* Where the giants actually build: gigawatt AI campuses and cloud regions, mapped to the nearest city on the map (#61: + not just five metros; real campuses sit all over, from Oregon to Wyoming to Querétaro). w: a hub that draws more. */ +const MEGA=[ + {c:'ash',n:'Data Center Alley',w:2}, + {c:'atn',n:'Peach-flops Georgia'}, + {c:'auh',n:'Star-Gait UAE'}, + {c:'aus',n:'Taylor-Made Texas Campus'}, + {c:'chi',n:'Fairweather Wisconsin'}, + {c:'chi',n:'Project Rainy-er Indiana'}, + {c:'cmh',n:'Prome-the-mess Ohio'}, + {c:'csn',n:'Biggest Little Cluster Reno'}, + {c:'cys',n:'Wind Chill Wyoming Campus'}, + {c:'dal',n:'Star-Gait Abilene'}, + {c:'doh',n:'Lusail Data Oasis'}, + {c:'dsm',n:'Cornfield Cluster Iowa'}, + {c:'dub',n:'Bring-Your-Own-Power Dublin'}, + {c:'for',n:'Short-Video Ceará Campus'}, + {c:'hyd',n:'Vizag AI Hub'}, + {c:'icn',n:'Ulsan AI Campus'}, + {c:'jan',n:'Hyperbole Louisiana'}, + {c:'kcy',n:'Burnt Ends Bit Barn'}, + {c:'kul',n:'Johor Overflow'}, + {c:'lit',n:'Colossus of Blues Memphis'}, + {c:'mad',n:'Aragón Mega-shed'}, + {c:'mel',n:'AirDrunk Melbourne West'}, + {c:'mty',n:'Norteño Nodes Nuevo León'}, + {c:'nyc',n:'Neocloud New Jersey'}, + {c:'phx',n:'Mesa-ive Compute Arizona'}, + {c:'qro',n:'Querétaro Cluster'}, + {c:'ric',n:'Henrico Hyperscale Hustle'}, + {c:'ruh',n:'Desert Kingdom AI Campus'}, + {c:'scl',n:'Quilicura Region'}, + {c:'sea',n:'Quincy-dence Washington'}, + {c:'sle',n:'Dilly-Dalles Oregon'}, + {c:'sto',n:'Star-Gait Fjord-way'}, + {c:'syd',n:'AirDrunk Western Sydney'}, + {c:'syd',n:'Star-Gait Down Under'}, + {c:'tok',n:'Hokkaido Snow DC'}, + {c:'yqb',n:'Hydro-Chill Québec'}, +]; +/* A campus is picked by its weight, less where giant circuits already crowd the city (#61): a metro that carries as much + as the average busy one draws half as often, three times as much a quarter. Hubs stay a bit busier, never the only ones. */ +function megaLoad(){const m=new Map(),add=(c,v)=>{if(c)m.set(c,(m.get(c)||0)+v);}; + for(const o of S.biz.concat(S.offers||[])){const T=BIZ_T[o.type];if(!T||!T.mega||!T.l2)continue;for(const c of bCities(o))add(c,o.bw||0);}return m;} +function megaPick(list,ld){let tot=0,k=0;for(const v of ld.values()){tot+=v;k++;}const avg=k?tot/k:0,w=list.map(m=>(m.w||1)/(1+(avg>0?(ld.get(m.c)||0)/avg:0))); + let r=Math.random()*w.reduce((a,b)=>a+b,0);for(let i=0;imine.includes(m.c));if(!megaMine.length)return; - if(t==='ingest'){const m=pick(megaMine),bw=pick(T.opts),dur=3+Math.floor(Math.random()*4),start=S.day+10+Math.floor(Math.random()*12); + const megaMine=MEGA.filter(m=>mine.includes(m.c));if(!megaMine.length)return;const ld=megaLoad(); + if(t==='ingest'){const m=megaPick(megaMine,ld),bw=pick(T.opts),dur=3+Math.floor(Math.random()*4),start=S.day+10+Math.floor(Math.random()*12); S.offers.push({id:uid(),city:m.c,city2:null,name:tr('customers_and_events.name_at_site',{name:nm(),site:m.n}),type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*55),exp:start-2,mega:true});return;} - if(t==='aiwan'||t==='agi'){const a=pick(megaMine),others=MEGA.filter(m=>m.c!==a.c&&(Math.random()<0.7?mine.includes(m.c):true));if(!others.length)return;const b=pick(others);if(!reqCan('diverse',{city:a.c,city2:b.c}))return;const km=kmBetween(a.c,b.c),bw=pick(T.opts); + if(t==='aiwan'||t==='agi'){const a=megaPick(megaMine,ld),others=MEGA.filter(m=>m.c!==a.c&&(Math.random()<0.7?mine.includes(m.c):true));if(!others.length)return;const b=megaPick(others,ld);if(!reqCan('diverse',{city:a.c,city2:b.c}))return;const km=kmBetween(a.c,b.c),bw=pick(T.opts); const reqs=['diverse'];if(Math.random()<0.4)reqs.push('metro'); S.offers.push({id:uid(),city:a.c,city2:b.c,name:`${nm()}: ${a.n} ⇄ ${b.n}`,type:t,bw,rate:Math.round((150+km*0.08)*T.km),reqs,exp:S.day+45,mega:true});return;} - if(t==='mtrain'){const hub=pick(megaMine),reg=CITY[hub.c].reg,pool=[...new Set(MEGA.filter(m=>m.c!==hub.c&&CITY[m.c].reg===reg).map(m=>m.c))];if(pool.length<2)return; + if(t==='mtrain'){const hub=megaPick(megaMine,ld),reg=CITY[hub.c].reg,pool=[...new Set(MEGA.filter(m=>m.c!==hub.c&&CITY[m.c].reg===reg).map(m=>m.c))];if(pool.length<2)return; const sites=[hub.c];while(sites.lengthx+kmBetween(hub.c,c),0)/(sites.length-1),bw=pick(T.opts); S.offers.push({id:uid(),city:hub.c,city2:null,sites,name:tr('customers_and_events.name_hub_site',{name:nm(),site:hub.n}),type:t,bw,rate:Math.round((150+avg*0.08)*0.6),reqs:[],exp:S.day+45,mega:true});return;} diff --git a/src/game/90-actions/20-pops-transit-ix.js b/src/game/90-actions/20-pops-transit-ix.js index 5a74050..0f5733a 100644 --- a/src/game/90-actions/20-pops-transit-ix.js +++ b/src/game/90-actions/20-pops-transit-ix.js @@ -4,7 +4,7 @@ Object.assign(ACT,{ ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();}, buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0,...(premOnlyAt(NET[net],city)?{premium:true}:{})});toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();}, lagT:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier)||!portGate(t.city,PORT_SLOT(t.tier)))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;if(n<2&&t.site==='ab')t.site='a';toast(+d>0?tr('pops_transit_ix.lag_member_added_net_in_city',{net:esc(NET[t.net].name),city:CITY[t.city].name,lag:lagName(t.tier,n)}):tr('pops_transit_ix.lag_member_removed'),'good');after();}, - lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return; + lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>PNI_LAG_MAX)return;if(d>0&&n>pniLagMax(p.city)){toast(tr('pops_transit_ix.this_pni_already_bundles_n_ports',{n:n-1,more:PNI_LAG_RT,max:PNI_LAG_MAX}),'bad');sfx('err');return;}if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return; // A LAG member is an augment: the big networks take months for that too. if(d>0){const lead=pniLead(p.net);p.up={tier:p.tier,n,ready:S.day+lead,g1:!!p.g1};if(!lead)pniUpDone(p);toast(lead?tr('pops_transit_ix.augment_ordered_with_net_eta',{net:esc(NET[p.net].name),eta:pniWhen(lead)}):tr('pops_transit_ix.augment_with_net_is_up',{net:esc(NET[p.net].name),port:p.n+'×'+pniPN(p)}),'good');after();return;}p.n=n;if(n<2&&p.site==='ab')p.site='a';sfx('build');after();}, lagIx:({city,d})=>{d=+d;if(d!==1&&d!==-1)return;if(!isIx(city)||S.ixp[city]===undefined||S.myIx[city]||!S.pops[ixCity(city)])return;S.ixn=S.ixn||{};const n=(S.ixn[city]||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&(!portGate(ixCity(city),PORT_SLOT(S.ixp[city]))||!spend(ixPortMo(city,S.ixp[city]))))return;S.ixn[city]=n;if(n<2&&S.ixSite&&S.ixSite[city]==='ab')S.ixSite[city]='a';sfx('build');after();}, diff --git a/src/game/90-actions/85-routing-and-routers.js b/src/game/90-actions/85-routing-and-routers.js index 45502f4..34de210 100644 --- a/src/game/90-actions/85-routing-and-routers.js +++ b/src/game/90-actions/85-routing-and-routers.js @@ -16,7 +16,7 @@ Object.assign(ACT,{ popStdClear:()=>{S.popStd=null;sfx('click');after();}, addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();}, models:()=>{UI.models=!UI.models;renderPanel();}, - rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();}, + rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;{const m=Math.min(PNI_LAG_MAX,PNI_LAG_RT*(p.routers-1)),big=S.pni.find(x=>x.city===city&&Math.max(x.n||1,(x.up&&x.up.n)||1)>m);if(big){toast(tr('routing_and_routers.a_pni_here_bundles_n_ports',{net:esc(NET[big.net].name),n:Math.max(big.n||1,(big.up&&big.up.n)||1),m}),'bad');sfx('err');return;}}if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();}, upRouter:({city,g})=>{const p=S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(!techOk('rg',g,RG[g].lvl)){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;} const rt=p.routers||1,old=p.rgen||0;if(p.rupDay===S.day){toast(tr('routing_and_routers.the_new_routers_in_city_are',{city:CITY[city].name}),'bad');sfx('err');return;}const back=tradeIn(old,rt);if(!spend(swapCost(city,g)))return;p.rgen=g;p.rupDay=S.day;if(back>0)toast(tr('routing_and_routers.sold_the_old_model_on_ebuy',{model:esc(RG[old].n),price:fmt$(back)}),'good'); if(rt===1&&popIdle(city))toast(tr('routing_and_routers.new_router_in_city_swapped_before',{city:CITY[city].name}),'good'); diff --git a/src/game/93-ui/52-pni-list.js b/src/game/93-ui/52-pni-list.js index 40f85f1..7b38d83 100644 --- a/src/game/93-ui/52-pni-list.js +++ b/src/game/93-ui/52-pni-list.js @@ -11,7 +11,7 @@ function pniValLine(n,c,v){ return `
${tr('pni_list.n_here',{g:fmtG(v.want)})}: ${via} → ${tr('pni_list.with_port',{port:PORT[v.tier].n,val})}
`;} function pniRow(c,n,pn,v,chk){let h=`
${logo(n)}
${esc(n.name)} ${n.pol}${v&&v.worth?` ⭐ ${tr('pni_list.worth_it')}`:''}
${pniChip(n.id,c)}
${v?pniValLine(n,c,v):''}`; if(pn&&!pniOn(pn))h+=pniWait(pn,c); - else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`
${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI${fmtG(u)}
${pn.up?`
${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}
`:''}
${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.up&&pn.up.site==='ab'?'ab':pn.site)}
${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${!pn.up&&!pn.g1&&pn.tier>pniMin(n.id)&&!msfNope(n.id,c)?btn(tr('link_panels.downgrade_port_price',{port:PORT[pn.tier-1].n,price:portMo(PORT[pn.tier-1].pni*(pn.n||1))}),'downP',{id:pn.id},'ghost sm'):''}${(pn.n||1)1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}
`;} + else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`
${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI${fmtG(u)}
${pn.up?`
${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}
`:''}
${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.up&&pn.up.site==='ab'?'ab':pn.site)}${(pn.n||1)>=pniLagMax(c)&&(pn.n||1)${tr('pni_list.lag_full_add_a_router',{n:pn.n||1,more:PNI_LAG_RT,max:PNI_LAG_MAX})}
`:''}
${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${!pn.up&&!pn.g1&&pn.tier>pniMin(n.id)&&!msfNope(n.id,c)?btn(tr('link_panels.downgrade_port_price',{port:PORT[pn.tier-1].n,price:portMo(PORT[pn.tier-1].pni*(pn.n||1))}),'downP',{id:pn.id},'ghost sm'):''}${(pn.n||1)1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}
`;} else{h+=chk.ok?`
${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cashportShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}
${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}
${chk.fee?`
${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}
`:''}`:`
${esc(chk.why)}
`;} return h+`
`;} function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniOpen||{}; diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index 83145b3..badc184 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -21,7 +21,7 @@ function connUp(r){if(r.mine)return '';const nx=t=>PORT[t+1]&&portShown(t+1)?t+1 if(nx.id===r.id);if(!p)return '';if(!pniOn(p)||p.up||msfNope(p.net,p.city))return `${!pniOn(p)||p.up?tr('common.on_order'):''}`;const n=p.n||1,i=p.g1?0:nx(p.tier),c=i>=0?(1500+PORT[i].setup/2)*n:0; if(i>=0){const a={port:PORT[i].n,cost:fmt$(c),mo:fmt$(PORT[i].pni*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'pni',{city:p.city,net:p.net,tier:i},'sm',!portOk(p.city,i)||S.cash=0)h+=btn(tr('common.upgrade_port_price',{port:PORT[i].n,price:portMo(ixPortMo(c,i)*n)}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)); if(S.pops[city]&&!S.myIx[c]&&nRouter installed in {city}.
Upside down, as is customary down here. The packets don’t seem to mind.", "pops_transit_ix.signed_with_de_kicks_welcome_to":"Signed with DE-KICKS.
Welcome to the family. Please don't tell anyone what you pay.", "pops_transit_ix.stay_take_the_discount":"Stay, take the discount", +"pops_transit_ix.this_pni_already_bundles_n_ports":"This PNI already bundles {n} ports, all your routers here can hold. Each router takes {more} members of a PNI, up to {max}: add a router for more.", "pops_transit_ix.wait_before_you_go":"Wait! Before you go…", "pops_transit_ix.we_value_our_partnership_too_much":"We value our partnership too much to let a little thing like price get in the way.", "pops_transit_ix.you_need_a_license_first_foreign":"You need a license first.
Foreign networks need a joint venture to build in mainland China.", @@ -4321,6 +4323,7 @@ "routescript.every_gigabit_leaving_your_network_picks":"Every gigabit leaving your network picks an exit: a PNI, an IX port or a transit port. Left alone, it takes the nearest peering with room (a PNI before an IX port in the same city), and transit only when no peering can take it. RouteScript changes those choices, the way local-pref, AS-path prepending and maintenance drains do on real routers.", "routescript.filled_in_from_your_network_as":"Filled in from your network as it is right now. Load one, read it, check it, then deploy.", "routescript.for_a_ddos_rtbh_the_target":"For a DDoS: blackhole the target upstream and keep business customers first. The target is dark while it lasts, so remove it when the attack is over.", +"routescript.from_this_load_on_spill_onto":"A spill tier: once the shortest path is this full, the overflow takes the best detour if it adds no more than these milliseconds and stays under the same line. Stack them (80% within 10 ms, 90% within 20 ms) to spill earlier and further as links get hotter.", "routescript.great_question_here_is_a_production":"Great question! Here is a production-ready script, tailored to your live traffic. I checked it thoroughly.", "routescript.help_and_ready_made_scripts":"Help and ready-made scripts", "routescript.here_you_go_i_was_trained":"Here you go! I was trained on every router config ever posted to a forum, including the ones titled “why is this broken”.", @@ -4332,6 +4335,7 @@ "routescript.line_n_i_don_t_understand":"line {n}: I don't understand “{text}”. Try: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos", "routescript.line_n_prepend_1_to_3":"line {n}: prepend 1 to 3 times", "routescript.line_n_spill_must_be_between":"line {n}: spill must be between 20% and 100%", +"routescript.line_n_within_1_to_100_ms":"line {n}: within must be between 1 and 100 ms", "routescript.live_state_rules":"Live: {state} · {rules}", "routescript.maintenance_window_change_the_names":"# Maintenance Window: change the names, deploy, do the work, then remove it.", "routescript.missing_what":"missing {what}", @@ -4368,6 +4372,7 @@ "routing.routing_and_ddos":"Routing & DDoS", "routing.trace_note":"Follow one packet hop by hop and see why it leaves where it does.", "routing.trace_run":"Trace", +"routing_and_routers.a_pni_here_bundles_n_ports":"Shrink a PNI first.
Your PNI with {net} bundles {n} ports, and one router fewer holds only {m}.", "routing_and_routers.maintenance_window_in_city":"Maintenance window in {city}", "routing_and_routers.model_unlocks_at_customer_level_lv":"{model} unlocks at customer level {lv}.", "routing_and_routers.new_router_in_city_swapped_before":"New router in {city}
Swapped before anything was plugged in: zero downtime, zero angry customers.", diff --git a/tests/endgame-scale.test.js b/tests/endgame-scale.test.js new file mode 100644 index 0000000..0d92788 --- /dev/null +++ b/tests/endgame-scale.test.js @@ -0,0 +1,134 @@ +// The late game grows sideways, plus one expensive way up: eyeball traffic starts where the eyeballs are (#48), giant AI +// circuits spread over many metros (#61), a PNI grows by eight members per router (#323), and Auto-TE spills early onto +// detours within a latency budget (#136). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const US = ['nyc', 'ash', 'chi', 'atn', 'den', 'sea', 'sjc', 'mia']; + +// POPs in the given cities with the same home demand, a thin backbone between neighbours and transit at every POP. +function usNetwork(ev, cities, wave) { + ev(`ACT.start({});S.cash=1e10;S.lvl=6;S.day=500;S.biz=[];S.offers=[];S.links=[];S.pops={};S.pni=[];S.caches=[];S.transit=[];S.ixp={};S.peers={};S.rs={}; + S.nextFail=1e9;S.nextEvent=1e9;const cs=${lit(cities)}; + for(const c of cs){S.pops[c]={routers:2,rgen:3,gen:true,bb:{d:400},down:0};S.transit.push({id:'t'+c,net:'cog',city:c,tier:3,n:4,down:0});} + for(let i=0;i+1 { + const { ev, errors } = load(); + usNetwork(ev, ['nyc'], 3); + const us = ev('R.demTo.cmc/R.demand'); + usNetwork(ev, ['fra'], 3); + const de = ev('R.demTo.cmc/R.demand'), deDtk = ev('R.demTo.dtk/R.demand'); + usNetwork(ev, ['nyc'], 3); + const usDtk = ev('R.demTo.dtk/R.demand'); + assert.ok(us > ev('NSH.cmc') * 3, `a New York POP sends Comecast far more than its world share (${us})`); + assert.ok(us > de * 8, `and much more than a Frankfurt POP does (${us} vs ${de})`); + assert.ok(deDtk > usDtk * 8, `Doitsche Telekomm the other way round (${deDtk} vs ${usDtk})`); + // Only the split between home networks moves: content keeps its share, and a city's total demand stays the same. + assert.ok(Math.abs(ev("[...locSh(NSH,'nyc')].reduce((a,b)=>a+b,0)") - 1) < 1e-9, 'the shares still add up to one'); + assert.equal(ev("locSh(NSH,'nyc')[LOC_NIX.get('ggl')]"), ev('NSH.ggl'), 'content is everywhere'); + assert.ok(Math.abs(ev("cityNetSh('nyc','cmc')") - ev("locSh(NSH,'nyc')[LOC_NIX.get('cmc')]")) < 1e-12, 'box sizing reads the same split'); + assert.deepEqual(errors, []); +}); + +test('#48: peering with an eyeball in more of the cities its users live in carries more of its traffic', () => { + const { ev, errors } = load(); + // A 10G backbone: hauling Comecast's traffic to two PNIs fills it, and the rest leaves over transit. + usNetwork(ev, US, 0); + const share = pnis => { + ev(`S.pni=${lit(pnis)}.map(c=>({id:'cmc@'+c,city:c,net:'cmc',tier:3,n:4}));compute()`); + return ev('(R.netEg.cmc.p||0)/R.demTo.cmc'); + }; + const two = share(['nyc', 'ash']), all = share(US); + assert.ok(all > 0.95, `a PNI in every city takes nearly all of it (${all})`); + assert.ok(two < 0.6, `two PNIs only take what the backbone can haul to them (${two})`); + assert.ok(all - two > 0.35, `more PNI locations carry more (${two} → ${all})`); + assert.deepEqual(errors, []); +}); + +test('#61: giant AI circuits spread over many metros, busy ones a bit busier', () => { + const { ev, errors } = load(); + ev(`ACT.start({});S.cash=1e12;S.lvl=11;S.biz=[];S.offers=[];for(const m of MEGA)if(!S.pops[m.c])S.pops[m.c]={routers:1,rgen:3,gen:true,bb:null,down:0}; + for(const c of ['ash','nyc','chi','dal','mex','lax','hou','bos','was'])if(!S.pops[c])S.pops[c]={routers:1,rgen:3,gen:true,bb:null,down:0};`); + ev('__reseed(61)'); + // Three hundred offers, each signed as it comes, the way a long game fills up. + const out = JSON.parse(ev(`(()=>{const cnt={};let n=0;for(let i=0;i<300;i++){const before=S.offers.length;spawnSpecial(['aiwan','mtrain','agi'][i%3]); + if(S.offers.length===before)continue;const o=S.offers.pop();S.biz.push(o);n++;for(const c of bCities(o))cnt[c]=(cnt[c]||0)+1;}return JSON.stringify({cnt,n});})()`)); + const tot = Object.values(out.cnt).reduce((a, b) => a + b, 0); + const five = ['mex', 'chi', 'dal', 'ash', 'nyc'].reduce((a, c) => a + (out.cnt[c] || 0), 0); + assert.ok(out.n > 200, `offers came (${out.n})`); + assert.ok(Object.keys(out.cnt).length >= 25, `ends in many metros (${Object.keys(out.cnt).length})`); + assert.ok(five / tot < 0.35, `the old five metros no longer get most of it (${(five / tot).toFixed(2)})`); + const avg = tot / Object.keys(out.cnt).length; + assert.ok(out.cnt.ash > avg, `Ashburn stays a bit busier than the average metro (${out.cnt.ash} vs ${avg.toFixed(1)})`); + assert.ok(out.cnt.ash < tot * 0.15, `but never the only place (${out.cnt.ash} of ${tot})`); + assert.deepEqual(errors, []); +}); + +test('#323: a PNI grows by eight members per router at the POP, up to 32', () => { + const { ev, dom, errors } = load(); + ev("ACT.start({});S.cash=1e12;S.lvl=13;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});S.pops.fra.rgen=RG_TOP;S.pops.fra.routers=1;S.rules={...(S.rules||{}),pnis:'instant'};"); + ev("S.pni.push({id:'p1',city:'fra',net:'nfx',tier:3,n:8});compute()"); + const n = () => ev("S.pni.find(p=>p.id==='p1').n"); + assert.equal(ev("pniLagMax('fra')"), 8, 'one router: eight members, as before'); + ev("ACT.lagP({id:'p1',d:1})"); + assert.equal(n(), 8, 'a ninth member needs a second router'); + assert.match(dom.window.document.getElementById('toasts').textContent, /already bundles 8 ports/); + ev("ACT.addRouter({city:'fra'})"); + assert.equal(ev("pniLagMax('fra')"), 16); + ev("ACT.lagP({id:'p1',d:1})"); + assert.equal(n(), 9, 'the second router takes eight more'); + assert.ok(Math.abs(ev("R.nodeCap.fra") - ev("nodeCap('fra')")) < 1e-9); + // Taking that router away again would leave the bundle with nowhere to land. + ev("ACT.rmRouter({city:'fra'})"); + assert.equal(ev('S.pops.fra.routers'), 2, 'the router stays while the PNI needs it'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Shrink a PNI first/); + ev("S.pops.fra.routers=6;"); + assert.equal(ev("pniLagMax('fra')"), 32, 'never more than 32 members, however many routers'); + for (let i = 0; i < 30; i++) ev("ACT.lagP({id:'p1',d:1})"); + assert.equal(n(), 32); + // The panel offers a member while there is room and says why when there is none. + ev("S.pops.fra.routers=4;UI.sel={type:'city',id:'fra'};S.pni.find(p=>p.id==='p1').n=31;"); + ev('window.innerWidth=390;renderAll()'); + assert.deepEqual(errors, []); +}); + +test('#323: saves keep their LAGs, big ones included, and garbage is clamped', () => { + const { ev, errors } = load(); + ev("ACT.start({});ACT.launchBB({city:'fra'});S.pops.fra.routers=3;"); + ev("S.pni.push({id:'old',city:'fra',net:'nfx',tier:2,n:8},{id:'big',city:'fra',net:'ggl',tier:2,n:24,up:{tier:3,n:24,ready:S.day+30}},{id:'bad',city:'fra',net:'akm',tier:1,n:999})"); + ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); + assert.equal(ev("__o.pni.find(p=>p.id==='old').n"), 8, 'an old save with an 8-port LAG loads as it was'); + assert.equal(ev("__o.pni.find(p=>p.id==='big').n"), 24); + assert.equal(ev("__o.pni.find(p=>p.id==='big').up.n"), 24); + assert.equal(ev("__o.pni.find(p=>p.id==='bad').n"), 32, 'never past the biggest bundle'); + assert.equal(ev("migrate(JSON.parse(JSON.stringify(S)))&&1"), 1); + assert.deepEqual(errors, []); +}); + +test('#136: spill tiers keep a hot link at its line while a detour within the latency budget has room', () => { + const { ev, errors } = load(); + // New York reaches its upstream in Los Angeles over a direct 10G wave, or about 10 ms longer through Miami on 800G. + ev(`ACT.start({});S.cash=1e12;S.lvl=13;for(const g of GOALS)S.done[g.id]=0;for(const c of ['nyc','lax','mia'])if(!S.pops[c])ACT.buildPop({city:c}); + for(const c of ['nyc','lax','mia']){S.pops[c].rgen=RG_TOP;S.pops[c].routers=RMAX;}if(!S.pops.nyc.bb)ACT.launchBB({city:'nyc'});S.pops.nyc.bb.d=400; + const L=(a,b,t)=>{UI.via=null;UI.lmode='wave';UI.route='main';openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();}; + L('nyc','lax',0);L('nyc','mia',3);L('mia','lax',3);S.links.forEach(l=>l.ready=0); + S.transit=[];const t=NETS.find(n=>n.price&&n.pops.includes('lax')&&n.type==='t1');ACT.buyTransit({city:'lax',net:t.id,tier:3}); + S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`); + const direct = "R.load[S.links.find(l=>l.a==='nyc'&&l.b==='lax').id]"; + const run = s => { ev(`S.te.script=${lit(s)};compute()`); return { load: ev(direct), served: ev('R.served'), moved: ev('R.teMoved') }; }; + const none = run(''), short = run('spill at 80% within 5 ms'), long = run('spill at 80% within 15 ms'), two = run('spill at 80% within 15 ms\nspill at 90% within 30 ms'); + assert.ok(none.load > 9.99, 'without tiers the direct link fills up'); + assert.ok(short.load > 9.99, 'a detour 10 ms longer is outside a 5 ms budget: the link fills up as before'); + assert.ok(Math.abs(long.load - 8) < 1e-6, `within 15 ms the link stays at 80% (${long.load})`); + assert.ok(Math.abs(two.load - 8) < 1e-6, 'the 90% tier only opens once the 80% detours are full'); + assert.ok(Math.abs(long.served - none.served) < 1e-6, 'and nothing is lost: the detour carries it'); + assert.ok(long.moved > none.moved, 'Auto-TE moved it'); + assert.equal(ev("teParse('spill at 80% within 500 ms').errors.length"), 1, 'a budget past 100 ms is refused'); + assert.equal(ev("JSON.stringify(teParse('spill at 90% within 20 ms\\nspill at 80% within 10 ms').tiers)"), '[{"at":0.8,"ms":10},{"at":0.9,"ms":20}]'); + assert.deepEqual(errors, []); +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 44414ca..9de0a5c 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -222,6 +222,16 @@ test('N7: presence is real: PoPs are cities, exchange ports only where the netwo fail('N7', bad, 'an exchange port needs an exchange in that city and a PoP there'); }); +test('N8: a POP\'s traffic to the networks that sell to homes goes mostly to those whose users live near it (#48)', () => { + // Every city keeps its total and content keeps its share: only the split between home networks follows geography. + const bad = J(`CITIES.filter(c=>{const a=locSh(NSH,c.id);let t=0;for(let j=0;j1e-12)return true;}return Math.abs(t-1)>1e-9;}).map(c=>c.id)`); + fail('N8', bad, 'locSh() must keep a city\'s total and every share of a network without home markets'); + // At home a network's share is above its world share, far away below it. + const far = J(`NETS.filter(n=>n.cc&&NSH[n.id]>0).flatMap(n=>{const cc=[].concat(n.cc),home=CITIES.find(c=>cc.includes(c.cc)),away=CITIES.find(c=>!locNets()[LOC_NIX.get(n.id)].reg.has(c.reg)); + const j=LOC_NIX.get(n.id),out=[];if(home&&!(locSh(NSH,home.id)[j]>NSH[n.id]))out.push(n.id+'@home');if(away&&!(locSh(NSH,away.id)[j] LOC_REG > LOC_FAR, and home markets (cc) are where the users are'); +}); + // ---------- Modes and rules ---------- test('M1: On-call is the classic game: the default rules, and what old saves load as', () => { @@ -488,6 +498,18 @@ test('F8: a managed wave costs your own capacity, rides one optic, and is priced // D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail. const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()"); const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`); +test('F9: growth goes sideways, plus one paid way up (#61, #323)', () => { + // A PNI bundles eight members per router at its POP, up to 32; every other LAG stays at eight. + assert.equal(ev('LAG_MAX'), 8, 'F9: transit, exchange and fabric LAGs hold eight members'); + const lim = J("[1,2,3,4,5,16].map(r=>{const o=S.pops.fra;S.pops.fra={routers:r};const m=pniLagMax('fra');if(o)S.pops.fra=o;else delete S.pops.fra;return m;})"); + assert.deepEqual(lim, [8, 16, 24, 32, 32, 32], 'F9: a PNI grows by eight members per router, up to 32'); + // Giant AI circuits land at campuses spread over many metros, no city more than two. + const per = J("MEGA.reduce((m,x)=>(m[x.c]=(m[x.c]||0)+1,m),{})"); + assert.ok(Object.keys(per).length >= 30, `F9: campuses in at least 30 metros (${Object.keys(per).length})`); + fail('F9', Object.entries(per).filter(([, n]) => n > 2).map(([c]) => c), 'no metro holds more than two campuses'); + fail('F9', J("MEGA.filter(m=>!CITY[m.c]).map(m=>m.c)"), 'campuses sit in real cities'); +}); + test('D1: attack sizes come from the world, never from your network', () => { const g = load(); ddFra(g.ev); diff --git a/tests/pnis-and-sold-out.test.js b/tests/pnis-and-sold-out.test.js index 88f5a1c..09ff39a 100644 --- a/tests/pnis-and-sold-out.test.js +++ b/tests/pnis-and-sold-out.test.js @@ -96,7 +96,7 @@ test('saves: PNIs on order survive, and garbage is repaired', () => { setup(ev); ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})"); ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); - assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX')); + assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('PNI_LAG_MAX')); assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true); assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G'); assert.deepEqual(errors, []); diff --git a/tests/route-fuzz.test.js b/tests/route-fuzz.test.js index 8207da4..7b331d5 100644 --- a/tests/route-fuzz.test.js +++ b/tests/route-fuzz.test.js @@ -17,10 +17,10 @@ function pages() { let base = head; try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {} let P = { base: openPage(base, 'base'), head: openPage(head, 'head') }; - // A change to the world itself (cities, networks, cables) or to what links cost cannot route like main: there is no - // same game to compare. Then the base is this checkout too, and the cache on/off check still runs; equivalence with - // main resumes once it lands. - const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)])])"); + // A change to the world itself (cities, networks, cables, AI campuses), to what links cost or to where each city's + // traffic goes (locSh(), #48) cannot route like main: there is no same game to compare. Then the base is this checkout + // too, and the cache on/off check still runs; equivalence with main resumes once it lands. + const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)]),MEGA.map(m=>m.c),['nyc','fra','sin'].map(c=>typeof locSh==='function'?Array.from(locSh(NSH,c)):null)])"); if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; } return P; } diff --git a/tests/speed.test.js b/tests/speed.test.js index f768206..6b69351 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -367,7 +367,7 @@ test('Auto-TE routes around a full link exactly like the plain path', () => { S.transit=[];const t=NETS.find(n=>n.price&&n.pops.includes('ams')&&n.type==='t1');ACT.buyTransit({city:'ams',net:t.id,tier:3}); S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`); const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT})'); - for (const script of ['', 'spill at 70%']) { + for (const script of ['', 'spill at 70%', 'spill at 80% within 5 ms\nspill at 90% within 20 ms']) { ev(`S.te.script=${lit(script)}`); ev('compute()'); const fast = sig(); ev('__plain()'); const ref = sig(); From 870227100d024a5c502f696a3cd1e6dc16e77f39 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 07:56:26 +0000 Subject: [PATCH 07/18] Route fuzz: leave the link panel's header city links out of the buttons both pages offer They only change the view, and main's page has plain text there, so offering them would make the two pages diverge on a screen that routes the same. --- scripts/lib/fuzz-page.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 5b05a14..769b69c 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -56,7 +56,9 @@ const screen = (w) => { if (w.where === 'modal') return btns($('modal')); if (w.where === 'city') { UI.sel = { type: 'city', id: w.city }; UI.tab = w.tab; renderAll(); return btns($('panel')); } - if (w.where === 'link') { if (!S.links.some((l) => l.id === w.id)) return []; UI.sel = { type: 'link', id: w.id }; renderAll(); return btns($('panel')); } + // The city names in a link panel's header open the city (#196); older pages have plain text there. They only change + // the view, so neither page offers them, and both stay in lockstep. + if (w.where === 'link') { if (!S.links.some((l) => l.id === w.id)) return []; UI.sel = { type: 'link', id: w.id }; renderAll(); const P = $('panel'); for (const h of P.querySelectorAll('.ph h2 [data-act]')) h.removeAttribute('data-act'); return btns(P); } if (w.where === 'dash') { $('dash').hidden = false; UI.dtab = w.tab; renderDash(); const b = btns($('dash')); return b; } if (w.where === 'left') { UI.left = w.tab; UI.leftOpen = true; renderLeft(); let b = btns($('leftBody')); From a98e34711b623e1651ba50b3b4ac90f320c46b71 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 08:37:31 +0000 Subject: [PATCH 08/18] Keep puzzles and scenarios on plain shares; per-city share sums; tests follow the new traffic split Puzzles, Architect runs and scenarios keep the table's split (their references and pars were made with it). Week 2026-W44's reference now wins on day 185 (offers draw from the wider campus list). The cache planner sums each city's own split. --- site/scenarios/weekly/2026-W44.json | 2 +- src/game/30-networks/45-home-markets.js | 4 ++++ src/game/70-rules/95-utilities.js | 13 +++++++------ src/game/80-simulation/30-compute.js | 2 +- tests/day-steps.test.js | 4 +++- tests/direct-egress.test.js | 3 ++- 6 files changed, 18 insertions(+), 10 deletions(-) diff --git a/site/scenarios/weekly/2026-W44.json b/site/scenarios/weekly/2026-W44.json index f43ff92..ce0ba22 100644 --- a/site/scenarios/weekly/2026-W44.json +++ b/site/scenarios/weekly/2026-W44.json @@ -1 +1 @@ -{"v":1,"key":"2026-W44","rev":3,"theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":4,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":28,"big":5}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":198,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":2}} +{"v":1,"key":"2026-W44","rev":3,"theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":4,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":28,"big":5}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":185,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":2}} diff --git a/src/game/30-networks/45-home-markets.js b/src/game/30-networks/45-home-markets.js index 15be11a..2ba0f77 100644 --- a/src/game/30-networks/45-home-markets.js +++ b/src/game/30-networks/45-home-markets.js @@ -24,3 +24,7 @@ function locSh(T,c){let m=LOC_SH.get(T);if(!m)LOC_SH.set(T,m=new Map());let a=m. for(let j=0;j0){const f=g/gw;for(let j=0;j!(S&&(S.mode==='puzzle'||S.pz||S.ar||S.scn)); +function cityShares(T,c){if(locOn())return locSh(T,c);let a=LOC_PLAIN.get(T);if(!a)LOC_PLAIN.set(T,a=Float64Array.from(NETS,n=>T[n.id]||0));return a;} diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index fa11190..165d8cd 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -14,12 +14,13 @@ function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new // list of networks, and Goggle is throttled to half in Russia. The world shares (NSH) would size boxes for networks the // city cannot even reach, and too few for the ones it uses most. const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH; -const cityNetSh=(c,id)=>{const j=LOC_NIX.get(id);return (j===undefined?0:locSh(cityShTab(c),c)[j])*(id==='ggl'&&ruCity(c)?0.5:1);}; -// A city's total share only depends on its table and on the Russian throttle, and the tables never change after load: -// summed once per kind of city, not once per network asked about (that was cities × networks² every shift). -const CSH_SUM=new Map(); -function cityShSum(c){const T=cityShTab(c),k=ruCity(c)?1:0;let m=CSH_SUM.get(T);if(!m)CSH_SUM.set(T,m=[null,null]); - if(m[k]===null){let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];} +const cityNetSh=(c,id)=>{const j=LOC_NIX.get(id);return (j===undefined?0:cityShares(cityShTab(c),c)[j])*(id==='ggl'&&ruCity(c)?0.5:1);}; +// A city's total share only depends on its split (its table, localised for the city, #48) and on the Russian throttle, +// and those never change after load: summed once per split, not once per network asked about (that was cities × +// networks² every shift). +const CSH_SUM=new WeakMap(); +function cityShSum(c){const a=cityShares(cityShTab(c),c),k=ruCity(c)?1:0;let m=CSH_SUM.get(a);if(!m)CSH_SUM.set(a,m=[null,null]); + if(m[k]===null){const T=cityShTab(c);let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];} function cacheDem(c,id){const t=cityShSum(c);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;} // One box per site first, if the city sends the network anything at all; then more boxes while that demand outgrows them // (100G each, #248). diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index c0b34bb..b2429ef 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -103,7 +103,7 @@ function compute(){RW.gen++; // traffic you failed to deliver, and it does not cross your links only to be thrown away. const ru=ruCity(c),thr=n=>n==='ggl'&&ru?0.5:1;let sa=shArr.get(SH),sm=shSum.get(SH);if(!sa){shArr.set(SH,sa=NETS.map(n=>SH[n.id]||0));shSum.set(SH,sm=[]);} // This city's own split: its traffic to networks that sell to homes goes mostly to the ones whose users are near (#48). - const ls=locSh(SH,c); + const ls=cityShares(SH,c); const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?ls[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; for(let j=0;j{__ot++;return ot(...a);};"); let found = false; - for (let d = 0; d < 20 && !found; d++) { + // Played until such a trial comes: on the big save that is day 51 (where each city's traffic goes decides which + // offers pass, #48). + for (let d = 0; d < 60 && !found; d++) { p.ev('rwDay()'); for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) { if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; } diff --git a/tests/direct-egress.test.js b/tests/direct-egress.test.js index cb448c5..1dc4dc3 100644 --- a/tests/direct-egress.test.js +++ b/tests/direct-egress.test.js @@ -27,7 +27,8 @@ function twoPops() { } test('at its own POP a carrier\'s port takes the traffic bound for that carrier, not an even split', () => { - const { ev, lvl, tly, errors } = newYork(); + // Both ports with room: New York's traffic to the US eyeballs in Level Tree's cone alone would fill its port (#48). + const { ev, lvl, tly, errors } = newYork(1, 150); assert.ok(via(ev, lvl, 'lvl') > 1, 'Level Tree traffic goes out of the Level Tree port'); assert.equal(via(ev, tly, 'lvl'), 0, 'and none of it out of Tell-Ya'); assert.ok(via(ev, tly, 'tly') > 1 && via(ev, lvl, 'tly') === 0, 'the same for Tell-Ya'); From 79426f7a001f2377697e031db48e8fb50ee677c3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 11:50:36 +0100 Subject: [PATCH 09/18] Move a network to another device with QR codes or a link (#263) No server and no account: the network travels gzipped in the fragment of a link, which browsers never send anywhere. One link carries all of it, to copy or share; QR codes carry it in parts that a phone's own camera app opens one after another, and the receiving page collects them in any order, then imports the network like a save file. To keep the codes few they leave out the charts' history and the news log (a year-old network: 4 codes instead of 10); the link carries everything. The QR encoder is a small built-in one, checked against the reference implementation for every mask. --- CHANGELOG.md | 1 + site/i18n/de.js | 24 +++ site/i18n/es.js | 24 +++ site/i18n/fr.js | 24 +++ site/i18n/it.js | 24 +++ site/i18n/pt.js | 24 +++ src/agent/20-commands.js | 4 +- src/game/60-features/61-qr-code.js | 59 +++++++ src/game/60-features/62-device-transfer.js | 49 ++++++ src/game/90-actions/89-game-and-settings.js | 2 +- src/game/90-actions/92-transfer.js | 14 ++ src/game/91-save.js | 6 +- src/game/95-modals/40-title.js | 2 +- src/game/95-modals/45-slots.js | 2 +- src/game/95-modals/46-transfer.js | 17 ++ src/game/95-modals/60-help.js | 2 +- src/game/96-map/95-clicks.js | 2 +- src/game/99-loop.js | 2 +- src/i18n/en.js | 24 +++ src/styles/40-modal.css | 5 + tests/device-transfer.test.js | 164 ++++++++++++++++++++ 21 files changed, 465 insertions(+), 10 deletions(-) create mode 100644 src/game/60-features/61-qr-code.js create mode 100644 src/game/60-features/62-device-transfer.js create mode 100644 src/game/90-actions/92-transfer.js create mode 100644 src/game/95-modals/46-transfer.js create mode 100644 tests/device-transfer.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c8aefcd..d55b120 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). - Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). - RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). +- You can now move a network to another device with QR codes or a link, without an account or a file: open the menu, pick Send to another device, and scan the codes with the other device's camera, or send yourself the link. Nothing is uploaded anywhere, as the codes and the link carry the network itself, and to keep the codes few they leave out your charts and news, which start fresh on the other device; on the other device, open the link or paste it under From another device on the title screen (#263). - From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). - From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). - Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). diff --git a/site/i18n/de.js b/site/i18n/de.js index 9f0a6f8..b3d0893 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4849,6 +4849,30 @@ "traceroute.this_one_is_set_to_mode":"; dieser steht auf {mode}", "traceroute.transit_is_the_last_resort":"Transit ist der letzte Ausweg", "traceroute.your_traffic_follows_the_metrics_this":"Dein Internetverkehr folgt den Metriken. Dies ist der Weg, den eine Kundenleitung auf „{mode}“ nehmen würde.", +"transfer.code_i_of_n":"Code {i} von {n}", +"transfer.copy_the_link":"Link kopieren", +"transfer.could_not_copy_the_link_here":"Der Link ließ sich hier nicht kopieren. Exportiere stattdessen deinen Spielstand.", +"transfer.from_another_device":"Von einem anderen Gerät", +"transfer.have_of_n_codes_are_here":"{have} von {n} Codes sind da", +"transfer.its_charts_and_news_start_fresh":"Seine Diagramme und Meldungen fangen hier neu an.", +"transfer.link_copied_open_it_on_your":"Link kopiert. Öffne ihn auf deinem anderen Gerät.", +"transfer.moving_a_network_here":"Netzwerk hierher holen", +"transfer.next_code":"Nächster Code", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nichts wird irgendwo hochgeladen: Codes und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.", +"transfer.on_the_other_device_open_the":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle Auf ein anderes Gerät senden. Scanne den Code mit der Kamera dieses Geräts oder füge den Link hier ein.", +"transfer.on_your_other_device_open_the":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link.", +"transfer.on_your_other_device_open_the_many":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link, dann komm für den nächsten zurück. Die Reihenfolge ist egal.", +"transfer.paste_a_transfer_link":"Transfer-Link einfügen", +"transfer.qr_code_i_of_n":"QR-Code {i} von {n}", +"transfer.scan_the_next_code_on_your":"Scanne den nächsten Code auf deinem anderen Gerät und öffne den Link. Dein Netzwerk lädt, sobald der letzte da ist.", +"transfer.send_the_link":"Link senden", +"transfer.send_to_another_device":"Auf ein anderes Gerät senden", +"transfer.start_over":"Neu anfangen", +"transfer.that_is_not_a_transfer_link":"Das ist kein Transfer-Link.", +"transfer.that_link_is_incomplete_or_damaged":"Der Link ist unvollständig oder beschädigt. Kopier ihn noch mal, komplett.", +"transfer.the_codes_leave_out_your_charts":"Damit es wenige Codes bleiben, fehlen darin deine Diagramme und Meldungen; der Link enthält alles.", +"transfer.this_browser_cannot_pack_networks_into":"Dieser Browser kann Netzwerke nicht in Links packen. Exportiere stattdessen deinen Spielstand.", +"transfer.this_network_is_too_big_for":"Dieses Netzwerk ist zu groß für Codes. Schick stattdessen den Link oder exportiere deinen Spielstand.", "tutorial.businesses_pop_up_as_bubbles_on":"Unternehmen tauchen als $-Blasen auf der Karte auf. Öffne Deals und gewinne deinen ersten Kunden.", "tutorial.grow_drag_from_your_pink_router":"Wachse: Zieh von deiner Stadt zu einer Stadt in der Nähe, um Glasfaser zu verlegen und einen zweiten POP zu eröffnen.", "tutorial.start_the_clock_with_1_and":"Starte die Uhr mit 1× und sieh zu, wie Traffic und Geld fließen. Du kannst jederzeit pausieren.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 8c6aded..2c4c333 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; esta está en {mode}", "traceroute.transit_is_the_last_resort":"el tránsito es el último recurso", "traceroute.your_traffic_follows_the_metrics_this":"Tu tráfico de internet sigue las métricas. Este es el camino que tomaría un circuito de cliente en «{mode}».", +"transfer.code_i_of_n":"Código {i} de {n}", +"transfer.copy_the_link":"Copiar el enlace", +"transfer.could_not_copy_the_link_here":"No se pudo copiar el enlace aquí. Exporta un archivo de partida.", +"transfer.from_another_device":"Desde otro dispositivo", +"transfer.have_of_n_codes_are_here":"Han llegado {have} de {n} códigos", +"transfer.its_charts_and_news_start_fresh":"Sus gráficos y noticias empiezan de cero aquí.", +"transfer.link_copied_open_it_on_your":"Enlace copiado. Ábrelo en tu otro dispositivo.", +"transfer.moving_a_network_here":"Traer una red aquí", +"transfer.next_code":"Siguiente código", +"transfer.nothing_is_uploaded_anywhere_the_codes":"No se sube nada a ningún sitio: los códigos y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.", +"transfer.on_the_other_device_open_the":"En el dispositivo con tu red, abre el menú y elige Enviar a otro dispositivo. Escanea su código con la cámara de este dispositivo o pega aquí su enlace.", +"transfer.on_your_other_device_open_the":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace.", +"transfer.on_your_other_device_open_the_many":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace; luego vuelve aquí por el siguiente. Pueden llegar en cualquier orden.", +"transfer.paste_a_transfer_link":"Pega un enlace de traspaso", +"transfer.qr_code_i_of_n":"Código QR {i} de {n}", +"transfer.scan_the_next_code_on_your":"Escanea el siguiente código en tu otro dispositivo y abre su enlace. Tu red se carga en cuanto llegue el último.", +"transfer.send_the_link":"Enviar el enlace", +"transfer.send_to_another_device":"Enviar a otro dispositivo", +"transfer.start_over":"Empezar de nuevo", +"transfer.that_is_not_a_transfer_link":"Eso no es un enlace de traspaso.", +"transfer.that_link_is_incomplete_or_damaged":"Ese enlace está incompleto o dañado. Cópialo otra vez, entero.", +"transfer.the_codes_leave_out_your_charts":"Para que sean pocos códigos, dejan fuera tus gráficos y noticias; el enlace lo lleva todo.", +"transfer.this_browser_cannot_pack_networks_into":"Este navegador no puede meter redes en enlaces. Usa un archivo de partida.", +"transfer.this_network_is_too_big_for":"Esta red es demasiado grande para códigos. Envía el enlace o exporta un archivo de partida.", "tutorial.businesses_pop_up_as_bubbles_on":"Las empresas aparecen como burbujas de $ en el mapa. Abre Tratos y firma a tu primer cliente.", "tutorial.grow_drag_from_your_pink_router":"Crece: arrastra desde tu router rosa hasta una ciudad cercana para tender fibra y abrir un segundo POP.", "tutorial.start_the_clock_with_1_and":"Pon el reloj en marcha con 1× y mira cómo fluyen el tráfico y el dinero. Puedes pausar cuando quieras.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index e7a6640..8b3467c 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":" ; celle-ci est réglée sur {mode}", "traceroute.transit_is_the_last_resort":"le transit est le dernier recours", "traceroute.your_traffic_follows_the_metrics_this":"Ton trafic internet suit les métriques. Voici le chemin que prendrait un circuit client en « {mode} ».", +"transfer.code_i_of_n":"Code {i} sur {n}", +"transfer.copy_the_link":"Copier le lien", +"transfer.could_not_copy_the_link_here":"Impossible de copier le lien ici. Exporte plutôt un fichier de sauvegarde.", +"transfer.from_another_device":"Depuis un autre appareil", +"transfer.have_of_n_codes_are_here":"{have} codes sur {n} sont arrivés", +"transfer.its_charts_and_news_start_fresh":"Ses graphiques et son fil d'infos repartent de zéro ici.", +"transfer.link_copied_open_it_on_your":"Lien copié. Ouvre-le sur ton autre appareil.", +"transfer.moving_a_network_here":"Amener un réseau ici", +"transfer.next_code":"Code suivant", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Rien n'est envoyé nulle part : les codes et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.", +"transfer.on_the_other_device_open_the":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis Envoyer vers un autre appareil. Scanne son code avec l'appareil photo de cet appareil, ou colle son lien ici.", +"transfer.on_your_other_device_open_the":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien.", +"transfer.on_your_other_device_open_the_many":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien, puis reviens ici pour le suivant. L'ordre n'a pas d'importance.", +"transfer.paste_a_transfer_link":"Colle un lien de transfert", +"transfer.qr_code_i_of_n":"QR code {i} sur {n}", +"transfer.scan_the_next_code_on_your":"Scanne le code suivant sur ton autre appareil et ouvre son lien. Ton réseau se charge dès que le dernier arrive.", +"transfer.send_the_link":"Envoyer le lien", +"transfer.send_to_another_device":"Envoyer vers un autre appareil", +"transfer.start_over":"Recommencer", +"transfer.that_is_not_a_transfer_link":"Ce n'est pas un lien de transfert.", +"transfer.that_link_is_incomplete_or_damaged":"Ce lien est incomplet ou abîmé. Copie-le à nouveau, en entier.", +"transfer.the_codes_leave_out_your_charts":"Pour garder peu de codes, ils laissent de côté tes graphiques et ton fil d'infos ; le lien contient tout.", +"transfer.this_browser_cannot_pack_networks_into":"Ce navigateur ne sait pas mettre un réseau dans un lien. Utilise plutôt un fichier de sauvegarde.", +"transfer.this_network_is_too_big_for":"Ce réseau est trop gros pour des codes. Envoie plutôt le lien, ou exporte un fichier de sauvegarde.", "tutorial.businesses_pop_up_as_bubbles_on":"Les entreprises apparaissent sous forme de bulles $ sur la carte. Ouvre Offres et signe ton premier client.", "tutorial.grow_drag_from_your_pink_router":"Grandis : fais glisser depuis ton routeur rose vers une ville proche pour poser de la fibre et ouvrir un deuxième POP.", "tutorial.start_the_clock_with_1_and":"Lance le temps en 1× et regarde le trafic et l’argent couler. Tu peux mettre en pause à tout moment.", diff --git a/site/i18n/it.js b/site/i18n/it.js index afdf926..954d9c3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; questa è impostata su {mode}", "traceroute.transit_is_the_last_resort":"il transit è l’ultima spiaggia", "traceroute.your_traffic_follows_the_metrics_this":"Il tuo traffico internet segue le metriche. Questo è il percorso che prenderebbe un circuito cliente su «{mode}».", +"transfer.code_i_of_n":"Codice {i} di {n}", +"transfer.copy_the_link":"Copia il link", +"transfer.could_not_copy_the_link_here":"Non riesco a copiare il link qui. Esporta un file di salvataggio.", +"transfer.from_another_device":"Da un altro dispositivo", +"transfer.have_of_n_codes_are_here":"Sono arrivati {have} codici su {n}", +"transfer.its_charts_and_news_start_fresh":"I suoi grafici e le notizie ripartono da zero qui.", +"transfer.link_copied_open_it_on_your":"Link copiato. Aprilo sull'altro dispositivo.", +"transfer.moving_a_network_here":"Porta qui una rete", +"transfer.next_code":"Codice successivo", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Non viene caricato nulla da nessuna parte: i codici e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.", +"transfer.on_the_other_device_open_the":"Sul dispositivo con la tua rete, apri il menu e scegli Invia a un altro dispositivo. Scansiona il codice con la fotocamera di questo dispositivo, oppure incolla qui il link.", +"transfer.on_your_other_device_open_the":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link.", +"transfer.on_your_other_device_open_the_many":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link, poi torna qui per il prossimo. L'ordine non conta.", +"transfer.paste_a_transfer_link":"Incolla un link di trasferimento", +"transfer.qr_code_i_of_n":"Codice QR {i} di {n}", +"transfer.scan_the_next_code_on_your":"Scansiona il prossimo codice sull'altro dispositivo e apri il link. La tua rete si carica appena arriva l'ultimo.", +"transfer.send_the_link":"Invia il link", +"transfer.send_to_another_device":"Invia a un altro dispositivo", +"transfer.start_over":"Ricomincia", +"transfer.that_is_not_a_transfer_link":"Questo non è un link di trasferimento.", +"transfer.that_link_is_incomplete_or_damaged":"Il link è incompleto o danneggiato. Copialo di nuovo, tutto intero.", +"transfer.the_codes_leave_out_your_charts":"Per restare pochi, i codici lasciano fuori i grafici e le notizie; il link contiene tutto.", +"transfer.this_browser_cannot_pack_networks_into":"Questo browser non riesce a mettere una rete in un link. Usa un file di salvataggio.", +"transfer.this_network_is_too_big_for":"Questa rete è troppo grande per i codici. Invia il link, oppure esporta un file di salvataggio.", "tutorial.businesses_pop_up_as_bubbles_on":"Le aziende spuntano come bolle $ sulla mappa. Apri Offerte e firma il tuo primo cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresci: trascina dal tuo router rosa su una città vicina per posare fibra e aprire un secondo POP.", "tutorial.start_the_clock_with_1_and":"Fai partire il tempo con 1× e guarda scorrere traffico e soldi. Puoi mettere in pausa quando vuoi.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9278519..e05fcd3 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; esta está configurada como {mode}", "traceroute.transit_is_the_last_resort":"transit é o último recurso", "traceroute.your_traffic_follows_the_metrics_this":"O teu tráfego de internet segue as métricas. Este é o caminho que um circuito de cliente em «{mode}» tomaria.", +"transfer.code_i_of_n":"Código {i} de {n}", +"transfer.copy_the_link":"Copiar o link", +"transfer.could_not_copy_the_link_here":"Não deu para copiar o link aqui. Exporte um arquivo de save.", +"transfer.from_another_device":"De outro dispositivo", +"transfer.have_of_n_codes_are_here":"Chegaram {have} de {n} códigos", +"transfer.its_charts_and_news_start_fresh":"Os gráficos e notícias dela recomeçam do zero aqui.", +"transfer.link_copied_open_it_on_your":"Link copiado. Abra-o no outro dispositivo.", +"transfer.moving_a_network_here":"Trazer uma rede para cá", +"transfer.next_code":"Próximo código", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nada é enviado para lugar nenhum: os códigos e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.", +"transfer.on_the_other_device_open_the":"No dispositivo com a sua rede, abra o menu e escolha Enviar para outro dispositivo. Escaneie o código com a câmera deste dispositivo ou cole o link aqui.", +"transfer.on_your_other_device_open_the":"No outro dispositivo, aponte a câmera para este código e abra o link.", +"transfer.on_your_other_device_open_the_many":"No outro dispositivo, aponte a câmera para este código e abra o link, depois volte aqui para o próximo. A ordem não importa.", +"transfer.paste_a_transfer_link":"Cole um link de transferência", +"transfer.qr_code_i_of_n":"Código QR {i} de {n}", +"transfer.scan_the_next_code_on_your":"Escaneie o próximo código no outro dispositivo e abra o link. Sua rede carrega assim que o último chegar.", +"transfer.send_the_link":"Enviar o link", +"transfer.send_to_another_device":"Enviar para outro dispositivo", +"transfer.start_over":"Recomeçar", +"transfer.that_is_not_a_transfer_link":"Isso não é um link de transferência.", +"transfer.that_link_is_incomplete_or_damaged":"Esse link está incompleto ou danificado. Copie de novo, inteiro.", +"transfer.the_codes_leave_out_your_charts":"Para serem poucos códigos, eles deixam de fora seus gráficos e notícias; o link leva tudo.", +"transfer.this_browser_cannot_pack_networks_into":"Este navegador não consegue colocar redes em links. Use um arquivo de save.", +"transfer.this_network_is_too_big_for":"Esta rede é grande demais para códigos. Envie o link ou exporte um arquivo de save.", "tutorial.businesses_pop_up_as_bubbles_on":"Empresas aparecem como bolhas de $ no mapa. Abra Negócios e feche seu primeiro cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresça: arraste do seu router rosa até uma cidade próxima para lançar fibra e abrir um segundo POP.", "tutorial.start_the_clock_with_1_and":"Comece o relógio em 1× e veja o tráfego e o dinheiro fluírem. Dá pra pausar a qualquer momento.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 84d404a..0928dea 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -637,8 +637,8 @@ const API_WHY={ const API_DENY={ speed:'time',phonePlay:'time',phoneSpeed:'time', start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', - exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPage:'files',xferPaste:'files',xferRecv:'files',xferReset:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', - install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser', }; diff --git a/src/game/60-features/61-qr-code.js b/src/game/60-features/61-qr-code.js new file mode 100644 index 0000000..d8ad571 --- /dev/null +++ b/src/game/60-features/61-qr-code.js @@ -0,0 +1,59 @@ +/* ---------- QR codes (#263) ---------- + A small QR encoder: byte mode, error correction L or M, versions 1 to 40, the standard mask penalty. The game has no + dependencies and no server, so moving a network to a phone is codes the phone's own camera app can open. + Follows ISO/IEC 18004 (and Project Nayuki's reference implementation, MIT). */ +const QR_ECC={L:[1,[7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25]], + M:[0,[10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49]]}; +const qrRaw=v=>{let r=(16*v+128)*v+64;if(v>=2){const n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36;}return r;}; +const qrDataCw=(v,e)=>Math.floor(qrRaw(v)/8)-QR_ECC[e][1][v-1]*QR_ECC[e][2][v-1]; +// The most bytes one code of this version holds (byte mode). +const qrCap=(v,e='L')=>qrDataCw(v,e)-(v<10?2:3); +function qrMul(x,y){let z=0;for(let i=7;i>=0;i--){z=(z<<1)^((z>>>7)*0x11D);z^=((y>>>i)&1)*x;}return z;} +function qrRs(data,n){const d=new Array(n).fill(0);d[n-1]=1;let root=1; + for(let i=0;i{if(v===1)return [];const n=Math.floor(v/7)+2,step=v===32?26:Math.ceil((v*4+4)/(n*2-2))*2,r=[6]; + for(let p=v*4+10;r.length(x+y)%2===0,(x,y)=>y%2===0,(x,y)=>x%3===0,(x,y)=>(x+y)%3===0,(x,y)=>(Math.floor(x/3)+Math.floor(y/2))%2===0, + (x,y)=>x*y%2+x*y%3===0,(x,y)=>(x*y%2+x*y%3)%2===0,(x,y)=>((x+y)%2+x*y%3)%2===0]; +/* bytes (Uint8Array or array) → {size, m: rows of booleans (true = dark)}, or null when it does not fit in version 40. + o.ecc 'L' (default) or 'M'; o.mask 0-7 to force one (tests); o.min/o.max bound the version. */ +function qrEncode(bytes,o={}){const e=o.ecc||'L',len=bytes.length;let v=o.min||1; + while(v<=(o.max||40)&&len>qrCap(v,e))v++;if(v>(o.max||40))return null; + const cap=qrDataCw(v,e),bits=[],put=(x,n)=>{for(let i=n-1;i>=0;i--)bits.push((x>>>i)&1);}; + put(4,4);put(len,v<10?8:16);for(const b of bytes)put(b,8); + put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);for(let p=0xEC;bits.length=ns)cw.push(blocks[j][i]); + const n=v*4+17,m=[],fn=[];for(let y=0;y{m[y][x]=d;fn[y][x]=true;}; + for(let i=0;i=0&&x=0&&y{const d=QR_ECC[e][0]<<3|mk;let r=d;for(let i=0;i<10;i++)r=(r<<1)^((r>>>9)*0x537);const b=(d<<10|r)^0x5412,bit=i=>((b>>>i)&1)===1; + for(let i=0;i<=5;i++)set(8,i,bit(i));set(8,7,bit(6));set(8,8,bit(7));set(7,8,bit(8));for(let i=9;i<15;i++)set(14-i,8,bit(i)); + for(let i=0;i<8;i++)set(n-1-i,8,bit(i));for(let i=8;i<15;i++)set(8,n-15+i,bit(i));set(8,n-8,true);}; + fmt(0); + if(v>=7){let r=v;for(let i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);const b=v<<12|r;for(let i=0;i<18;i++){const d=((b>>>i)&1)===1,a=n-11+i%3,c=Math.floor(i/3);set(a,c,d);set(c,a,d);}} + for(let i=0,r=n-1;r>=1;r-=2){if(r===6)r=5;for(let vt=0;vt>>3]>>>(7-(i&7)))&1)===1;i++;}}} + const flip=mk=>{const f=QR_MASK[mk];for(let y=0;yrow?m[a][b]:m[b][a]; + for(const row of [true,false])for(let a=0;a=5)p+=run-2;run=1;}} + for(let b=0;b+7<=n;b++){let hit=true;for(let k=0;k<7;k++)if(at(a,b+k,row)!==(k!==1&&k!==5)){hit=false;break;}if(!hit)continue; + let l=true,r=true;for(let k=1;k<=4;k++){if(b-k>=0&&at(a,b-k,row))l=false;if(b+6+k`;} diff --git a/src/game/60-features/62-device-transfer.js b/src/game/60-features/62-device-transfer.js new file mode 100644 index 0000000..3f4173e --- /dev/null +++ b/src/game/60-features/62-device-transfer.js @@ -0,0 +1,49 @@ +/* ---------- moving a network to another device (#263) ---------- + No server, no account: the network itself travels, gzipped, in the fragment of a link (#sot1....), + which browsers never send to any server. One link carries all of it, to copy or share; QR codes carry it in parts a + phone's own camera app opens one after another. The receiving page collects the parts in its storage, in any order, + and imports the network like a save file once they are all there. */ +const XFER_K='sot-xfer',XFER_RE=/sot1\.([a-z0-9]{3,8})\.(\d{1,3})\.(\d{1,3})\.([A-Za-z0-9_-]+)/,XFER_CHUNK=900,XFER_MAX=200,XFER_DAY=864e5; +// Taken out of the address bar before anything else can read it (the stats counter only loads after this script): +// a network in a link belongs to the player, and a reload must not import it again. +const XFER_HASH=(()=>{try{const h=location.hash||'';if(!h.startsWith('#sot1.'))return '';history.replaceState(null,'',location.pathname+location.search);return h.slice(1);}catch(e){return '';}})(); +const b64u=u=>b64(u).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); +const unb64u=t=>unb64(t.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice((t.length+3)%4)); +const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location.pathname:'https://seriesoftub.es/'; +// A network's save text: the one playing now (saved first), or any other straight from storage. +function xferText(id){if(id===UI.slot&&S&&!pzOn()){save(true);return Promise.resolve(JSON.stringify(packSave(S)));} + const raw=slotRaw(id);if(raw==null)return Promise.reject(new Error('no save'));return raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw);} +/* The link carries everything. The codes leave out the charts' history and the news log: more than half of a played + network, and only ever shown, never played with (the traffic odometer keeps its own count). A year-old network + takes 3 codes instead of 9; its charts start again on the other device, and the import says so. */ +const xferGz=async(t,lean)=>b64u(await gzPipe(new TextEncoder().encode(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},${lean?'"lean":1,':''}"S":${t}}`),new CompressionStream('gzip'))); +async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),o=JSON.parse(t); + const d=await xferGz(t),c=await xferGz(JSON.stringify({...o,hist:[],log:[]}),true); + const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'),n=Math.ceil(c.length/XFER_CHUNK),base=xferBase()+'#sot1.'; + // Codes and link are two transfers: a code never completes a set with a piece of the link. + const parts=n>XFER_MAX?[]:Array.from({length:n},(_,i)=>`${base}${k}.${i}.${n}.${c.slice(i*XFER_CHUNK,(i+1)*XFER_CHUNK)}`); + return {name:e?e.name:o.name,link:`${base}${k}.0.1.${d}`,parts};} +// Parts that arrived so far (one transfer at a time; a day old, they are forgotten). +function xferStore(){let s=null;try{s=JSON.parse(localStorage.getItem(XFER_K)||'null');}catch(e){} + if(!s||typeof s!=='object'||typeof s.id!=='string'||!(s.n>1&&s.n<=999)||!s.p||typeof s.p!=='object'||!(Date.now()-s.at=0&&+k=1&&is.p[k]).join(''));return true;} + try{localStorage.setItem(XFER_K,JSON.stringify(s));}catch(e){} + openModal(xferWaitHtml(s));sfx('click');return true;} +function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} + let u=null;try{u=unb64u(d);}catch(e){} + const bad=()=>{toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');};if(!u){bad();return;} + gzPipe(u,new DecompressionStream('gzip')).then(b=>{const r=parseSave(new TextDecoder().decode(b)); + if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}importAsk(r);track('xfer_in');},bad);} +// Another window got a part (or finished): the one showing the progress follows. +addEventListener('storage',e=>{if(e.key!==XFER_K||!$('xferWait'))return;const s=xferStore();if(s)openModal(xferWaitHtml(s));else ACT.helpClose();}); +addEventListener('hashchange',()=>{const h=location.hash||'';if(!h.startsWith('#sot1.'))return;try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}xferTake(h.slice(1));}); +// After boot: a page opened from a transfer link takes its part. +function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index a1671dc..9b14de0 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -30,7 +30,7 @@ Object.assign(ACT,{ ${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
- +
`);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, diff --git a/src/game/90-actions/92-transfer.js b/src/game/90-actions/92-transfer.js new file mode 100644 index 0000000..6d71136 --- /dev/null +++ b/src/game/90-actions/92-transfer.js @@ -0,0 +1,14 @@ +// Moving a network to another device (#263): codes and a link out, a pasted link in. +Object.assign(ACT,{ + xfer:({id}={})=>{const sid=slotOkId(id)?id:UI.slot;if(!sid||!slotIdx().some(e=>e.id===sid))return; + if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} + xferPack(sid).then(x=>{UI.xfer={...x,id:sid,i:0};openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}, + xferPage:({i})=>{const x=UI.xfer;if(!x||!(i>=0&&i{const x=UI.xfer;if(!x)return;const t=x.link,no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad'); + if(navigator.share&&isPhone()){navigator.share({title:'Series of Tubes',url:t}).catch(()=>{});return;} + try{navigator.clipboard.writeText(t).then(()=>toast(tr('transfer.link_copied_open_it_on_your'),'good'),no);}catch(e){no();}}, + xferFile:()=>{const x=UI.xfer;if(x)exportSlot(x.id);}, + xferRecv:()=>openModal(xferRecvHtml()), + xferPaste:()=>{const el=$('xferIn');if(el)xferTake(el.value.trim());}, + xferReset:()=>{xferClear();ACT.helpClose();}, +}); diff --git a/src/game/91-save.js b/src/game/91-save.js index f407d76..d5c71ab 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -81,11 +81,13 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_ if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')}; if(s.lost)return {err:tr('save.that_network_went_bankrupt_it_cannot')}; for(const c of Object.keys(s.pops))if(!isCity(c))return {err:tr('save.that_save_has_a_pop_in',{city:esc(String(c).slice(0,12))})}; - return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};} + return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network')),lean:!!(j.lean&&j.S)};} function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;} const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;} - UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);}; + importAsk(r);}; rd.readAsText(file);} +// A save from a file or a transfer link (#263), checked by parseSave(): what it is, and whether to load it. +function importAsk(r){UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}${r.lean?' '+tr('transfer.its_charts_and_news_start_fresh'):''}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);} // This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable. function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null; try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 54b3867..37a51ee 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -24,7 +24,7 @@ function showTitle(){
${doorsHtml()} ${homePick()}

${homeWhat()}

-
${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); +
${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); $('asnIn').addEventListener('input',e=>{UI.asnTxt=e.target.value.replace(/\D/g,'').slice(0,10);if(e.target.value!==UI.asnTxt)e.target.value=UI.asnTxt;e.target.classList.toggle('bad',!!UI.asnTxt&&!asnOk(+UI.asnTxt));}); } diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js index 047c54d..c8dff9b 100644 --- a/src/game/95-modals/45-slots.js +++ b/src/game/95-modals/45-slots.js @@ -19,7 +19,7 @@ function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h= function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network')); return `
${slotIcon(e)} ${slotLine(e)}

${nm}

${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}

- `;} + `;} const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB'; function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network')); openModal(`
🪟 ${tr('slots.two_windows_one_network')}

${tr('slots.name_is_open_in_another_window',{name:nm})}

diff --git a/src/game/95-modals/46-transfer.js b/src/game/95-modals/46-transfer.js new file mode 100644 index 0000000..5b7c78d --- /dev/null +++ b/src/game/95-modals/46-transfer.js @@ -0,0 +1,17 @@ +/* Moving a network to another device (#263): the codes to scan and the link, and on the other side, where to paste it. */ +function xferHtml(){const x=UI.xfer,n=x.parts.length,i=Math.min(x.i,n-1),nm=esc(x.name||tr('common.unnamed_network')); + const q=n?qrEncode(new TextEncoder().encode(x.parts[i])):null; + return `
📲 ${tr('transfer.send_to_another_device')}

${nm}

+ ${q?`

${n>1?tr('transfer.on_your_other_device_open_the_many'):tr('transfer.on_your_other_device_open_the')}

${qrSvg(q,tr('transfer.qr_code_i_of_n',{i:i+1,n}))} + ${n>1?`
${btn('‹','xferPage',{i:i-1},'ghost',i===0)}${tr('transfer.code_i_of_n',{i:i+1,n})}${btn(tr('transfer.next_code'),'xferPage',{i:i+1},'pink',i===n-1)}
`:''}` + :`

${tr('transfer.this_network_is_too_big_for')}

`} +
${btn(navigator.share&&isPhone()?tr('transfer.send_the_link'):tr('transfer.copy_the_link'),'xferLink',{},n?'':'pink')}${btn(tr('common.export_save'),'xferFile',{},'ghost')}
+

${n?tr('transfer.the_codes_leave_out_your_charts')+' ':''}${tr('transfer.nothing_is_uploaded_anywhere_the_codes')}

`;} +function xferRecvHtml(){return `
📲 ${tr('transfer.from_another_device')}

${tr('transfer.moving_a_network_here')}

+

${tr('transfer.on_the_other_device_open_the')}

+ +
${btn(tr('common.open'),'xferPaste',{},'pink big')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}
`;} +function xferWaitHtml(s){const have=Object.keys(s.p).length; + return `
📲 ${tr('transfer.moving_a_network_here')}

${tr('transfer.have_of_n_codes_are_here',{have,n:s.n})}

+
+

${tr('transfer.scan_the_next_code_on_your')}

${btn(tr('common.close'),'helpClose',{},'pink big')}${btn(tr('transfer.start_over'),'xferReset',{},'ghost')}
`;} diff --git a/src/game/95-modals/60-help.js b/src/game/95-modals/60-help.js index e3fd9c2..169e48c 100644 --- a/src/game/95-modals/60-help.js +++ b/src/game/95-modals/60-help.js @@ -18,7 +18,7 @@ function showHelp(){
${tr('common.waves')}
${tr('help.your_fiber_links_are_leased_waves')}
${tr('common.95th_percentile')}
${tr('help.transit_bills_sample_your_usage')}
${tr('common.routers')}
${tr('help.each_pop_s_router_model_caps')}
${tr('common.dark_fiber')}
${tr('help.lease_an_iru_or_build_your')}
${tr('common.subsea_cables')}
${tr('help.subsea_waves_can_only_follow_cable')}
${tr('common.latency')}
${tr('help.every_link_has_latency_high')}
${tr('common.noc_dashboard')}
${tr('help.the_chart_button_at_the_top')}
${tr('common.asia')}
${tr('help.a_weird_underserved_market_transit')}
${tr('common.russia')}
${tr('help.moscow_needs_a_mandatory_government')}
${tr('help.events_chains_and_wholesale')}
${tr('help.event_networks_a_final_a_festival')}
${tr('common.bank')}
${tr('help.tap_your_cash_to_open_the')}
${tr('common.lags')}
${tr('help.out_of_port_speed_bundle_up')}
${tr('common.traffic_engineering')}
${tr('help.tap_a_link_to_see_which')}
${tr('common.china')}
${tr('help.mainland_china_needs_a_license_and')}
${tr('common.weird_requirements')}
${tr('help.some_customers_come_with_conditions')}
${tr('common.customer_levels')}
${tr('help.as_your_peak_traffic_and_footprint')}
${tr('help.l2vpn_ddos_protection')}
${tr('help.businesses_may_want_a_private')}
${tr('common.ddos_attack')}
${tr('help.ddos_a_flood_comes_from')}
${tr('common.scrubbing_centers')}
${tr('help.scrubbing_a_center_pulls_floods')}
${tr('common.nni_fabrics')}
${tr('help.megapork_pocketfabric_and')}
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_and_the')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
RouteScript
${tr('help.rules_for_your_auto_te_controller')}
-

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}
`); +

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}
`); } function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`
${btn(tr('help.share_my_network'),'share',{},'pink')}

${tr('help.you_built_a_cartoon_internet_now')}

${plugHtml(true)}`);},0);openModal(`

${tr('help.you_re_a_tier_1')}

${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}

${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');} function showLose(){openModal(`

${tr('common.bankrupt')}

${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}

${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index c10b794..9919023 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','xfer','xferPage','xferLink','xferFile','xferRecv','xferPaste','xferReset'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 03f7aaa..bbb8114 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -68,7 +68,7 @@ function boot(data){ // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}} - renderHUD();renderLeft(); + renderHUD();renderLeft();xferBoot(); window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } diff --git a/src/i18n/en.js b/src/i18n/en.js index 8ace98f..d0a2a0e 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4848,6 +4848,30 @@ "traceroute.this_one_is_set_to_mode":"; this one is set to {mode}", "traceroute.transit_is_the_last_resort":"transit is the last resort", "traceroute.your_traffic_follows_the_metrics_this":"Your internet traffic follows the metrics. This is the path a customer circuit on “{mode}” would take.", +"transfer.code_i_of_n":"Code {i} of {n}", +"transfer.copy_the_link":"Copy the link", +"transfer.could_not_copy_the_link_here":"Could not copy the link here. Export a save file instead.", +"transfer.from_another_device":"From another device", +"transfer.have_of_n_codes_are_here":"{have} of {n} codes are here", +"transfer.its_charts_and_news_start_fresh":"Its charts and news start fresh here.", +"transfer.link_copied_open_it_on_your":"Link copied. Open it on your other device.", +"transfer.moving_a_network_here":"Move a network here", +"transfer.next_code":"Next code", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nothing is uploaded anywhere: the codes and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.", +"transfer.on_the_other_device_open_the":"On the device with your network, open the menu and pick Send to another device. Scan its code with this device's camera, or paste its link here.", +"transfer.on_your_other_device_open_the":"On your other device, point the camera at this code and open the link.", +"transfer.on_your_other_device_open_the_many":"On your other device, point the camera at this code and open the link, then come back here for the next one. They can arrive in any order.", +"transfer.paste_a_transfer_link":"Paste a transfer link", +"transfer.qr_code_i_of_n":"QR code {i} of {n}", +"transfer.scan_the_next_code_on_your":"Scan the next code on your other device and open its link. Your network loads as soon as the last one arrives.", +"transfer.send_the_link":"Send the link", +"transfer.send_to_another_device":"Send to another device", +"transfer.start_over":"Start over", +"transfer.that_is_not_a_transfer_link":"That is not a transfer link.", +"transfer.that_link_is_incomplete_or_damaged":"That link is incomplete or damaged. Copy it again, all of it.", +"transfer.the_codes_leave_out_your_charts":"To keep the codes few, they leave out your charts and news; the link carries everything.", +"transfer.this_browser_cannot_pack_networks_into":"This browser cannot pack networks into links. Use a save file instead.", +"transfer.this_network_is_too_big_for":"This network is too big for codes. Send the link instead, or export a save file.", "tutorial.businesses_pop_up_as_bubbles_on":"Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.", "tutorial.grow_drag_from_your_pink_router":"Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.", "tutorial.start_the_clock_with_1_and":"Start the clock with 1× and watch traffic and money flow. You can pause any time.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4c1884e..d431cd1 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -229,3 +229,8 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .cmroute{align-items:flex-start} .tag.cmhot{background:#FFE1D6;color:#B43A12} .tag.cmcool{background:#DDF1FB;color:#1E6A8C} +/* Moving a network to another device (#263). A code stays dark on white in dark mode too: cameras need the contrast. */ +svg.qr{display:block;width:100%;max-width:300px;height:auto;margin:10px auto 6px;border:3px solid var(--ink);border-radius:12px;background:#fff;box-sizing:border-box} +.xfer-nav{display:flex;align-items:center;justify-content:space-between;gap:8px;max-width:300px;margin:0 auto}.xfer-nav b{font:800 14px var(--display)} +textarea.xfer-in{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 10px;font:13px/1.35 ui-monospace,monospace;background:var(--soft);color:var(--ink);resize:vertical;word-break:break-all} +.xfer-dots{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.xfer-dots i{width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);background:var(--soft)}.xfer-dots i.on{background:var(--ok)} diff --git a/tests/device-transfer.test.js b/tests/device-transfer.test.js new file mode 100644 index 0000000..e6d49fa --- /dev/null +++ b/tests/device-transfer.test.js @@ -0,0 +1,164 @@ +// Moving a network to another device with QR codes or a link (#263): no server, the network travels in the link. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { load } = require('./harness'); +const { until } = require('./net'); + +const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); +const hash = (rows) => crypto.createHash('sha256').update(rows).digest('hex').slice(0, 16); + +// Module matrices from Project Nayuki's reference encoder (qrcodegen), byte mode, one per mask. +const REF = [ + ['https://seriesoftub.es/#sot1.ab12c.0.3.HELLO-world_42', 'L', 3, ['30728883c56ec1b1', '18174c37d6786fa7', 'a981f41d89cceb7e', 'e28c29324d50ad09', 'd05a240976233180', 'd7ad281bfed61f9e', '083a4137b252f78f', 'a82468785d358d89']], + ['x'.repeat(200), 'M', 10, ['750d745db4aee09b', '9ff2474eb4806262', 'c8294f9a437b1546', '1bf4d13e40b47c5f', 'fdce0323024df963', '87c3d49925e75834', 'b719f9e8d1b0dd89', '342f8ed986243039']], + ['Series of Tubes '.repeat(40), 'L', 17, ['6d81d73a8426ecea', 'c36740777a080ce2', '79556df75d596a27', 'c4999ca1f4c7cdff', '23185df5abef3f74', '5b2fc9fa8d26aac0', '88b5814b383833f3', '298a1c7f2a08b6ae']], + ['AS64512 '.repeat(120), 'L', 22, ['f8229058824f8960', '0c473ae025a4c779', '58c3ab340313be0a', 'd4fa9891688a1ccc', 'eaac167548e8e5f3', '3f14beb40d1dc4cf', 'a29dee8e6e34fd04', 'b0c682d9933fe28a']], + ['peering '.repeat(360), 'L', 40, ['6efd1b3513f437d0', 'c18c188947dc52bc', 'cd93f7d4626a657f', 'a596a01654473a8d', '33fa5bbfe6b4915a', 'c547ade997387b9e', 'ed333919d660b05a', '44f32c8d979821a8']], +]; + +test('the QR encoder draws exactly the reference codes, for every mask, from version 3 to 40', () => { + const { ev, errors } = load(); + for (const [s, ecc, v, masks] of REF) { + masks.forEach((h, mask) => { + const q = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}',mask:${mask}});return JSON.stringify({v:q.v,size:q.size,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join('')});})()`)); + assert.equal(q.v, v, `${s.slice(0, 12)}… version`); + assert.equal(q.size, v * 4 + 17); + assert.equal(hash(q.m), h, `${s.slice(0, 12)}… ${ecc} mask ${mask}`); + }); + // Left to choose, it picks one of the eight valid masks. + const auto = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}'});return JSON.stringify({v:q.v,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join(''),mask:q.mask});})()`)); + assert.equal(auto.v, v); + assert.equal(hash(auto.m), masks[auto.mask]); + } + assert.equal(ev("qrEncode(new Uint8Array(2954))"), null, 'more than version 40 holds'); + assert.match(ev("qrSvg(qrEncode(new TextEncoder().encode('hi')),'x')"), /^ { + const a = await sender(); + const link = a.ev('UI.xfer.link'), want = a.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"); + assert.ok(link.startsWith('https://tests.invalid/#sot1.'), link.slice(0, 40)); + assert.ok(a.ev('UI.xfer.parts.length') > 1, 'a played network takes several codes'); + assert.ok(a.ev('UI.xfer.parts.every(p=>p.length<=qrCap(22))'), 'every code is small enough to scan from a phone screen'); + + const b = load({ gzip: true, url: link }); + assert.equal(b.ev('location.hash'), '', 'the network is taken out of the address bar at once'); + await settle(b.ev, '!!UI.importing', 'it asks before loading'); + assert.match(b.ev("$('modalCard').textContent"), /Tube Mover/); + assert.doesNotMatch(b.ev("$('modalCard').textContent"), /start fresh/, 'the link carries everything'); + const hist = a.ev('JSON.stringify(S.hist)'), log = a.ev('S.log.length'); + b.ev('ACT.importGo()'); + assert.equal(b.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"), want); + assert.equal(b.ev('JSON.stringify(S.hist)'), hist, 'the charts came along'); + assert.equal(b.ev('S.log.length'), log + 1, 'the news came along (plus the welcome)'); + assert.equal(b.ev('slotIdx().length'), 1, 'it joins the networks on that device'); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); + +test('the codes arrive one by one, in any order; the network loads when the last one is in', async () => { + const a = await sender(); + const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), n = parts.length; + // Paging through the codes on the sending device. + a.ev('ACT.xferPage({i:1})'); + assert.match(a.ev("$('modalCard').textContent"), new RegExp(`Code 2 of ${n}`)); + + const b = load({ gzip: true }); + const order = parts.map((p, i) => i).reverse(); + for (const [k, i] of order.entries()) { + b.ev(`xferTake(${JSON.stringify(parts[i])})`); + if (k < n - 1) { + assert.match(b.ev("$('modalCard').textContent"), new RegExp(`${k + 1} of ${n} codes are here`)); + assert.equal(b.ev('document.querySelectorAll(".xfer-dots i.on").length'), k + 1); + // The same code twice changes nothing. + b.ev(`xferTake(${JSON.stringify(parts[i])})`); + assert.equal(b.ev('Object.keys(xferStore().p).length'), k + 1); + } + } + await settle(b.ev, '!!UI.importing', 'the last code opens the network'); + assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null, 'the parts are cleaned up'); + assert.match(b.ev("$('modalCard').textContent"), /charts and news start fresh/, 'it says what the codes left out'); + const vol = a.ev('S.vol'); + b.ev('ACT.importGo()'); + assert.equal(b.ev('S.name'), 'Tube Mover'); + assert.equal(b.ev('S.cash'), a.ev('S.cash')); + assert.equal(b.ev('S.day'), a.ev('S.day')); + assert.equal(b.ev('S.vol'), vol, 'the traffic odometer keeps its count'); + assert.equal(b.ev('S.hist.length'), 0, 'only charts and news were left out'); + assert.equal(b.ev('S.log.length'), 1, 'the news starts with the welcome'); + b.ev('for(let i=0;i<3;i++)dayTick()'); + assert.equal(b.ev('S.hist.length'), 3, 'the charts start again'); + assert.deepEqual(b.errors, []); +}); + +test('a code from another transfer starts over, and bad or cut links say so and load nothing', async () => { + const a = await sender(); + const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), link = a.ev('UI.xfer.link'); + const b = load({ gzip: true }); + b.ev(`xferTake(${JSON.stringify(parts[0])})`); + b.ev(`xferTake(${JSON.stringify(parts[1].replace(/#sot1\.[a-z0-9]+\./, '#sot1.zzzzz.'))})`); + assert.equal(b.ev("xferStore().id"), 'zzzzz'); + assert.equal(b.ev('Object.keys(xferStore().p).length'), 1); + b.ev('ACT.xferReset()'); + assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null); + + b.ev("xferTake('https://example.com/nothing-here')"); + assert.match(b.ev("$('toasts')?$('toasts').textContent:document.body.textContent"), /not a transfer link/); + b.ev(`xferTake(${JSON.stringify(link.slice(0, -40))})`); + await settle(b.ev, "/incomplete or damaged/.test(document.body.textContent)", 'a cut link is reported'); + assert.equal(b.ev('!!UI.importing'), false); + assert.equal(b.ev('S'), null, 'nothing was loaded'); + + // Pasted into the box on the title screen, the whole link works too. + b.ev('ACT.xferRecv()'); + b.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`); + await settle(b.ev, '!!UI.importing'); + assert.deepEqual(b.errors, []); +}); + +test('any network on the title screen can be sent, and the codes fit a 360 px phone', async () => { + const a = await sender(); + a.ev("ACT.toTitle()"); + const id = a.ev('slotIdx()[0].id'); + a.ev(`ACT.slotMenu({id:'${id}'})`); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xfer"]')`), 'the network menu offers it'); + a.ev('window.innerWidth=360;UI.xfer=null'); + a.ev(`document.querySelector('#modalCard [data-act="xfer"]').click()`); + await settle(a.ev, '!!UI.xfer&&!!document.querySelector("#modalCard svg.qr")', 'sent from storage, without loading it'); + assert.equal(a.ev('UI.xfer.name'), 'Tube Mover'); + assert.ok(a.ev("!!document.querySelector('#modalCard .xfer-nav')")); + const css = a.ev("[...document.styleSheets].flatMap(s=>[...s.cssRules]).map(r=>r.cssText).join('\\n')"); + assert.match(css, /svg\.qr\s*\{[^}]*max-width:\s*300px/, 'the code never gets wider than a small phone'); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferLink"]')`)); + assert.deepEqual(a.errors, []); +}); + +test('a year-old network takes a handful of codes, because the codes leave out charts and news', async () => { + const a = load({ gzip: true }); + a.ev("ACT.start({});for(let i=0;i<365;i++)dayTick();save(true);ACT.xfer({})"); + await settle(a.ev, '!!UI.xfer'); + const n = a.ev('UI.xfer.parts.length'), full = Math.ceil(a.ev("UI.xfer.link.split('.').pop().length") / 900); + assert.ok(n <= 4, `${n} codes`); + assert.ok(full >= 2 * n, `the whole network would take ${full}`); + assert.match(a.ev("$('modalCard').textContent"), /leave out your charts and news/); + assert.deepEqual(a.errors, []); +}); + +test('without compression in the browser it says so instead of failing', () => { + const { ev, errors } = load(); + ev("ACT.start({});save(true);ACT.xfer({})"); + assert.equal(ev('UI.xfer'), undefined); + assert.match(ev('document.body.textContent'), /cannot pack networks into links/); + assert.deepEqual(errors, []); +}); From 1ccdda171bd927cb9128561d2a4906bd3c46f828 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 13:19:00 +0100 Subject: [PATCH 10/18] Send a network to another device through the share sheet instead of QR codes (#263) QR codes do not scale: a played network takes several, a big one dozens. The save file now goes through the device's own share sheet (AirDrop, Quick Share, a chat with yourself, email), whatever its size, and opens on the other device with Import a save. Chromium refuses to share .json files, so there the same file goes as .txt, which Import a save now takes too. The whole-network link stays for copy and paste. The file is prepared before the tap, because a share sheet only opens straight from a user's gesture. --- CHANGELOG.md | 2 +- site/i18n/de.js | 26 +-- site/i18n/es.js | 26 +-- site/i18n/fr.js | 26 +-- site/i18n/it.js | 26 +-- site/i18n/pt.js | 26 +-- src/agent/20-commands.js | 4 +- src/game/60-features/61-qr-code.js | 59 ------ src/game/60-features/62-device-transfer.js | 50 ++--- src/game/90-actions/89-game-and-settings.js | 2 +- src/game/90-actions/92-transfer.js | 15 +- src/game/91-save.js | 4 +- src/game/95-modals/46-transfer.js | 25 +-- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 26 +-- src/styles/40-modal.css | 5 +- tests/device-transfer.test.js | 209 +++++++++----------- 17 files changed, 187 insertions(+), 346 deletions(-) delete mode 100644 src/game/60-features/61-qr-code.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d55b120..37c3991 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ All notable changes to this project are documented here. The project follows - Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). - Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). - RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). -- You can now move a network to another device with QR codes or a link, without an account or a file: open the menu, pick Send to another device, and scan the codes with the other device's camera, or send yourself the link. Nothing is uploaded anywhere, as the codes and the link carry the network itself, and to keep the codes few they leave out your charts and news, which start fresh on the other device; on the other device, open the link or paste it under From another device on the title screen (#263). +- You can now send a network to another device straight from the game: open the menu, pick Send to another device, and send the save file with AirDrop, Quick Share, a chat with yourself or email, then open it there with Import a save. You can also copy a link that carries the whole network and paste it on the other device under From another device. Nothing is uploaded anywhere (#263). - From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). - From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). - Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). diff --git a/site/i18n/de.js b/site/i18n/de.js index b3d0893..7c74d70 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4849,30 +4849,22 @@ "traceroute.this_one_is_set_to_mode":"; dieser steht auf {mode}", "traceroute.transit_is_the_last_resort":"Transit ist der letzte Ausweg", "traceroute.your_traffic_follows_the_metrics_this":"Dein Internetverkehr folgt den Metriken. Dies ist der Weg, den eine Kundenleitung auf „{mode}“ nehmen würde.", -"transfer.code_i_of_n":"Code {i} von {n}", "transfer.copy_the_link":"Link kopieren", "transfer.could_not_copy_the_link_here":"Der Link ließ sich hier nicht kopieren. Exportiere stattdessen deinen Spielstand.", +"transfer.download_the_save_file_and_send":"Lade die Spielstand-Datei herunter und schick sie an dein anderes Gerät, zum Beispiel per E-Mail oder in einem Chat mit dir selbst. Öffne sie dort mit Spielstand importieren.", "transfer.from_another_device":"Von einem anderen Gerät", -"transfer.have_of_n_codes_are_here":"{have} von {n} Codes sind da", -"transfer.its_charts_and_news_start_fresh":"Seine Diagramme und Meldungen fangen hier neu an.", -"transfer.link_copied_open_it_on_your":"Link kopiert. Öffne ihn auf deinem anderen Gerät.", +"transfer.link_copied_paste_it_on_your":"Link kopiert. Füge ihn auf deinem anderen Gerät unter Von einem anderen Gerät ein.", "transfer.moving_a_network_here":"Netzwerk hierher holen", -"transfer.next_code":"Nächster Code", -"transfer.nothing_is_uploaded_anywhere_the_codes":"Nichts wird irgendwo hochgeladen: Codes und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.", -"transfer.on_the_other_device_open_the":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle Auf ein anderes Gerät senden. Scanne den Code mit der Kamera dieses Geräts oder füge den Link hier ein.", -"transfer.on_your_other_device_open_the":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link.", -"transfer.on_your_other_device_open_the_many":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link, dann komm für den nächsten zurück. Die Reihenfolge ist egal.", -"transfer.paste_a_transfer_link":"Transfer-Link einfügen", -"transfer.qr_code_i_of_n":"QR-Code {i} von {n}", -"transfer.scan_the_next_code_on_your":"Scanne den nächsten Code auf deinem anderen Gerät und öffne den Link. Dein Netzwerk lädt, sobald der letzte da ist.", -"transfer.send_the_link":"Link senden", +"transfer.nothing_is_uploaded_anywhere_the_file":"Nichts wird irgendwo hochgeladen: Datei und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.", +"transfer.on_the_device_with_your_network":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle Auf ein anderes Gerät senden. Öffne die Datei dann hier mit Spielstand importieren.", +"transfer.or_copy_the_link_and_paste":"Oder kopiere den Link und füge ihn auf dem anderen Gerät unter Von einem anderen Gerät ein, praktisch mit einer geteilten Zwischenablage.", +"transfer.or_paste_a_transfer_link":"Oder füge einen Transfer-Link ein", +"transfer.send_the_save_file":"Spielstand senden", +"transfer.send_the_save_file_to_your":"Schick die Spielstand-Datei an dein anderes Gerät: AirDrop, Quick Share, ein Chat mit dir selbst oder E-Mail. Öffne sie dort mit Spielstand importieren.", "transfer.send_to_another_device":"Auf ein anderes Gerät senden", -"transfer.start_over":"Neu anfangen", "transfer.that_is_not_a_transfer_link":"Das ist kein Transfer-Link.", "transfer.that_link_is_incomplete_or_damaged":"Der Link ist unvollständig oder beschädigt. Kopier ihn noch mal, komplett.", -"transfer.the_codes_leave_out_your_charts":"Damit es wenige Codes bleiben, fehlen darin deine Diagramme und Meldungen; der Link enthält alles.", -"transfer.this_browser_cannot_pack_networks_into":"Dieser Browser kann Netzwerke nicht in Links packen. Exportiere stattdessen deinen Spielstand.", -"transfer.this_network_is_too_big_for":"Dieses Netzwerk ist zu groß für Codes. Schick stattdessen den Link oder exportiere deinen Spielstand.", +"transfer.this_browser_cannot_open_transfer_links":"Dieser Browser kann keine Transfer-Links öffnen. Nimm stattdessen eine Spielstand-Datei.", "tutorial.businesses_pop_up_as_bubbles_on":"Unternehmen tauchen als $-Blasen auf der Karte auf. Öffne Deals und gewinne deinen ersten Kunden.", "tutorial.grow_drag_from_your_pink_router":"Wachse: Zieh von deiner Stadt zu einer Stadt in der Nähe, um Glasfaser zu verlegen und einen zweiten POP zu eröffnen.", "tutorial.start_the_clock_with_1_and":"Starte die Uhr mit 1× und sieh zu, wie Traffic und Geld fließen. Du kannst jederzeit pausieren.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2c4c333..fb83a1a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4847,30 +4847,22 @@ "traceroute.this_one_is_set_to_mode":"; esta está en {mode}", "traceroute.transit_is_the_last_resort":"el tránsito es el último recurso", "traceroute.your_traffic_follows_the_metrics_this":"Tu tráfico de internet sigue las métricas. Este es el camino que tomaría un circuito de cliente en «{mode}».", -"transfer.code_i_of_n":"Código {i} de {n}", "transfer.copy_the_link":"Copiar el enlace", "transfer.could_not_copy_the_link_here":"No se pudo copiar el enlace aquí. Exporta un archivo de partida.", +"transfer.download_the_save_file_and_send":"Descarga el archivo de partida y envíalo a tu otro dispositivo, por ejemplo por correo o en un chat contigo mismo. Ábrelo allí con Importar una partida.", "transfer.from_another_device":"Desde otro dispositivo", -"transfer.have_of_n_codes_are_here":"Han llegado {have} de {n} códigos", -"transfer.its_charts_and_news_start_fresh":"Sus gráficos y noticias empiezan de cero aquí.", -"transfer.link_copied_open_it_on_your":"Enlace copiado. Ábrelo en tu otro dispositivo.", +"transfer.link_copied_paste_it_on_your":"Enlace copiado. Pégalo en tu otro dispositivo en Desde otro dispositivo.", "transfer.moving_a_network_here":"Traer una red aquí", -"transfer.next_code":"Siguiente código", -"transfer.nothing_is_uploaded_anywhere_the_codes":"No se sube nada a ningún sitio: los códigos y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.", -"transfer.on_the_other_device_open_the":"En el dispositivo con tu red, abre el menú y elige Enviar a otro dispositivo. Escanea su código con la cámara de este dispositivo o pega aquí su enlace.", -"transfer.on_your_other_device_open_the":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace.", -"transfer.on_your_other_device_open_the_many":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace; luego vuelve aquí por el siguiente. Pueden llegar en cualquier orden.", -"transfer.paste_a_transfer_link":"Pega un enlace de traspaso", -"transfer.qr_code_i_of_n":"Código QR {i} de {n}", -"transfer.scan_the_next_code_on_your":"Escanea el siguiente código en tu otro dispositivo y abre su enlace. Tu red se carga en cuanto llegue el último.", -"transfer.send_the_link":"Enviar el enlace", +"transfer.nothing_is_uploaded_anywhere_the_file":"No se sube nada a ningún sitio: el archivo y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.", +"transfer.on_the_device_with_your_network":"En el dispositivo con tu red, abre el menú y elige Enviar a otro dispositivo. Luego abre aquí el archivo que envía con Importar una partida.", +"transfer.or_copy_the_link_and_paste":"O copia el enlace y pégalo en el otro dispositivo en Desde otro dispositivo, práctico si tus dispositivos comparten portapapeles.", +"transfer.or_paste_a_transfer_link":"O pega un enlace de traspaso", +"transfer.send_the_save_file":"Enviar la partida", +"transfer.send_the_save_file_to_your":"Envía el archivo de partida a tu otro dispositivo: AirDrop, Quick Share, un chat contigo mismo o correo. Ábrelo allí con Importar una partida.", "transfer.send_to_another_device":"Enviar a otro dispositivo", -"transfer.start_over":"Empezar de nuevo", "transfer.that_is_not_a_transfer_link":"Eso no es un enlace de traspaso.", "transfer.that_link_is_incomplete_or_damaged":"Ese enlace está incompleto o dañado. Cópialo otra vez, entero.", -"transfer.the_codes_leave_out_your_charts":"Para que sean pocos códigos, dejan fuera tus gráficos y noticias; el enlace lo lleva todo.", -"transfer.this_browser_cannot_pack_networks_into":"Este navegador no puede meter redes en enlaces. Usa un archivo de partida.", -"transfer.this_network_is_too_big_for":"Esta red es demasiado grande para códigos. Envía el enlace o exporta un archivo de partida.", +"transfer.this_browser_cannot_open_transfer_links":"Este navegador no puede abrir enlaces de traspaso. Usa un archivo de partida.", "tutorial.businesses_pop_up_as_bubbles_on":"Las empresas aparecen como burbujas de $ en el mapa. Abre Tratos y firma a tu primer cliente.", "tutorial.grow_drag_from_your_pink_router":"Crece: arrastra desde tu router rosa hasta una ciudad cercana para tender fibra y abrir un segundo POP.", "tutorial.start_the_clock_with_1_and":"Pon el reloj en marcha con 1× y mira cómo fluyen el tráfico y el dinero. Puedes pausar cuando quieras.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 8b3467c..a82d4bc 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4847,30 +4847,22 @@ "traceroute.this_one_is_set_to_mode":" ; celle-ci est réglée sur {mode}", "traceroute.transit_is_the_last_resort":"le transit est le dernier recours", "traceroute.your_traffic_follows_the_metrics_this":"Ton trafic internet suit les métriques. Voici le chemin que prendrait un circuit client en « {mode} ».", -"transfer.code_i_of_n":"Code {i} sur {n}", "transfer.copy_the_link":"Copier le lien", "transfer.could_not_copy_the_link_here":"Impossible de copier le lien ici. Exporte plutôt un fichier de sauvegarde.", +"transfer.download_the_save_file_and_send":"Télécharge le fichier de sauvegarde et envoie-le à ton autre appareil, par exemple par e-mail ou dans une discussion avec toi-même. Ouvre-le là-bas avec Importer une sauvegarde.", "transfer.from_another_device":"Depuis un autre appareil", -"transfer.have_of_n_codes_are_here":"{have} codes sur {n} sont arrivés", -"transfer.its_charts_and_news_start_fresh":"Ses graphiques et son fil d'infos repartent de zéro ici.", -"transfer.link_copied_open_it_on_your":"Lien copié. Ouvre-le sur ton autre appareil.", +"transfer.link_copied_paste_it_on_your":"Lien copié. Colle-le sur ton autre appareil sous Depuis un autre appareil.", "transfer.moving_a_network_here":"Amener un réseau ici", -"transfer.next_code":"Code suivant", -"transfer.nothing_is_uploaded_anywhere_the_codes":"Rien n'est envoyé nulle part : les codes et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.", -"transfer.on_the_other_device_open_the":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis Envoyer vers un autre appareil. Scanne son code avec l'appareil photo de cet appareil, ou colle son lien ici.", -"transfer.on_your_other_device_open_the":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien.", -"transfer.on_your_other_device_open_the_many":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien, puis reviens ici pour le suivant. L'ordre n'a pas d'importance.", -"transfer.paste_a_transfer_link":"Colle un lien de transfert", -"transfer.qr_code_i_of_n":"QR code {i} sur {n}", -"transfer.scan_the_next_code_on_your":"Scanne le code suivant sur ton autre appareil et ouvre son lien. Ton réseau se charge dès que le dernier arrive.", -"transfer.send_the_link":"Envoyer le lien", +"transfer.nothing_is_uploaded_anywhere_the_file":"Rien n'est envoyé nulle part : le fichier et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.", +"transfer.on_the_device_with_your_network":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis Envoyer vers un autre appareil. Ouvre ensuite ici le fichier envoyé avec Importer une sauvegarde.", +"transfer.or_copy_the_link_and_paste":"Ou copie le lien et colle-le sur l'autre appareil sous Depuis un autre appareil, pratique si tes appareils partagent le presse-papiers.", +"transfer.or_paste_a_transfer_link":"Ou colle un lien de transfert", +"transfer.send_the_save_file":"Envoyer la sauvegarde", +"transfer.send_the_save_file_to_your":"Envoie le fichier de sauvegarde à ton autre appareil : AirDrop, Quick Share, une discussion avec toi-même ou un e-mail. Ouvre-le là-bas avec Importer une sauvegarde.", "transfer.send_to_another_device":"Envoyer vers un autre appareil", -"transfer.start_over":"Recommencer", "transfer.that_is_not_a_transfer_link":"Ce n'est pas un lien de transfert.", "transfer.that_link_is_incomplete_or_damaged":"Ce lien est incomplet ou abîmé. Copie-le à nouveau, en entier.", -"transfer.the_codes_leave_out_your_charts":"Pour garder peu de codes, ils laissent de côté tes graphiques et ton fil d'infos ; le lien contient tout.", -"transfer.this_browser_cannot_pack_networks_into":"Ce navigateur ne sait pas mettre un réseau dans un lien. Utilise plutôt un fichier de sauvegarde.", -"transfer.this_network_is_too_big_for":"Ce réseau est trop gros pour des codes. Envoie plutôt le lien, ou exporte un fichier de sauvegarde.", +"transfer.this_browser_cannot_open_transfer_links":"Ce navigateur ne sait pas ouvrir les liens de transfert. Utilise plutôt un fichier de sauvegarde.", "tutorial.businesses_pop_up_as_bubbles_on":"Les entreprises apparaissent sous forme de bulles $ sur la carte. Ouvre Offres et signe ton premier client.", "tutorial.grow_drag_from_your_pink_router":"Grandis : fais glisser depuis ton routeur rose vers une ville proche pour poser de la fibre et ouvrir un deuxième POP.", "tutorial.start_the_clock_with_1_and":"Lance le temps en 1× et regarde le trafic et l’argent couler. Tu peux mettre en pause à tout moment.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 954d9c3..4175c0b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4847,30 +4847,22 @@ "traceroute.this_one_is_set_to_mode":"; questa è impostata su {mode}", "traceroute.transit_is_the_last_resort":"il transit è l’ultima spiaggia", "traceroute.your_traffic_follows_the_metrics_this":"Il tuo traffico internet segue le metriche. Questo è il percorso che prenderebbe un circuito cliente su «{mode}».", -"transfer.code_i_of_n":"Codice {i} di {n}", "transfer.copy_the_link":"Copia il link", "transfer.could_not_copy_the_link_here":"Non riesco a copiare il link qui. Esporta un file di salvataggio.", +"transfer.download_the_save_file_and_send":"Scarica il file di salvataggio e invialo all'altro dispositivo, per esempio via email o in una chat con te stesso. Aprilo lì con Importa un salvataggio.", "transfer.from_another_device":"Da un altro dispositivo", -"transfer.have_of_n_codes_are_here":"Sono arrivati {have} codici su {n}", -"transfer.its_charts_and_news_start_fresh":"I suoi grafici e le notizie ripartono da zero qui.", -"transfer.link_copied_open_it_on_your":"Link copiato. Aprilo sull'altro dispositivo.", +"transfer.link_copied_paste_it_on_your":"Link copiato. Incollalo sull'altro dispositivo in Da un altro dispositivo.", "transfer.moving_a_network_here":"Porta qui una rete", -"transfer.next_code":"Codice successivo", -"transfer.nothing_is_uploaded_anywhere_the_codes":"Non viene caricato nulla da nessuna parte: i codici e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.", -"transfer.on_the_other_device_open_the":"Sul dispositivo con la tua rete, apri il menu e scegli Invia a un altro dispositivo. Scansiona il codice con la fotocamera di questo dispositivo, oppure incolla qui il link.", -"transfer.on_your_other_device_open_the":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link.", -"transfer.on_your_other_device_open_the_many":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link, poi torna qui per il prossimo. L'ordine non conta.", -"transfer.paste_a_transfer_link":"Incolla un link di trasferimento", -"transfer.qr_code_i_of_n":"Codice QR {i} di {n}", -"transfer.scan_the_next_code_on_your":"Scansiona il prossimo codice sull'altro dispositivo e apri il link. La tua rete si carica appena arriva l'ultimo.", -"transfer.send_the_link":"Invia il link", +"transfer.nothing_is_uploaded_anywhere_the_file":"Non viene caricato nulla da nessuna parte: il file e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.", +"transfer.on_the_device_with_your_network":"Sul dispositivo con la tua rete, apri il menu e scegli Invia a un altro dispositivo. Poi apri qui il file che invia con Importa un salvataggio.", +"transfer.or_copy_the_link_and_paste":"Oppure copia il link e incollalo sull'altro dispositivo in Da un altro dispositivo, comodo se i tuoi dispositivi condividono gli appunti.", +"transfer.or_paste_a_transfer_link":"Oppure incolla un link di trasferimento", +"transfer.send_the_save_file":"Invia il salvataggio", +"transfer.send_the_save_file_to_your":"Invia il file di salvataggio all'altro dispositivo: AirDrop, Quick Share, una chat con te stesso o email. Aprilo lì con Importa un salvataggio.", "transfer.send_to_another_device":"Invia a un altro dispositivo", -"transfer.start_over":"Ricomincia", "transfer.that_is_not_a_transfer_link":"Questo non è un link di trasferimento.", "transfer.that_link_is_incomplete_or_damaged":"Il link è incompleto o danneggiato. Copialo di nuovo, tutto intero.", -"transfer.the_codes_leave_out_your_charts":"Per restare pochi, i codici lasciano fuori i grafici e le notizie; il link contiene tutto.", -"transfer.this_browser_cannot_pack_networks_into":"Questo browser non riesce a mettere una rete in un link. Usa un file di salvataggio.", -"transfer.this_network_is_too_big_for":"Questa rete è troppo grande per i codici. Invia il link, oppure esporta un file di salvataggio.", +"transfer.this_browser_cannot_open_transfer_links":"Questo browser non riesce ad aprire i link di trasferimento. Usa un file di salvataggio.", "tutorial.businesses_pop_up_as_bubbles_on":"Le aziende spuntano come bolle $ sulla mappa. Apri Offerte e firma il tuo primo cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresci: trascina dal tuo router rosa su una città vicina per posare fibra e aprire un secondo POP.", "tutorial.start_the_clock_with_1_and":"Fai partire il tempo con 1× e guarda scorrere traffico e soldi. Puoi mettere in pausa quando vuoi.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index e05fcd3..6f55b36 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4847,30 +4847,22 @@ "traceroute.this_one_is_set_to_mode":"; esta está configurada como {mode}", "traceroute.transit_is_the_last_resort":"transit é o último recurso", "traceroute.your_traffic_follows_the_metrics_this":"O teu tráfego de internet segue as métricas. Este é o caminho que um circuito de cliente em «{mode}» tomaria.", -"transfer.code_i_of_n":"Código {i} de {n}", "transfer.copy_the_link":"Copiar o link", "transfer.could_not_copy_the_link_here":"Não deu para copiar o link aqui. Exporte um arquivo de save.", +"transfer.download_the_save_file_and_send":"Baixe o arquivo de save e envie para o outro dispositivo, por exemplo por e-mail ou num chat com você mesmo. Abra lá com Importar um save.", "transfer.from_another_device":"De outro dispositivo", -"transfer.have_of_n_codes_are_here":"Chegaram {have} de {n} códigos", -"transfer.its_charts_and_news_start_fresh":"Os gráficos e notícias dela recomeçam do zero aqui.", -"transfer.link_copied_open_it_on_your":"Link copiado. Abra-o no outro dispositivo.", +"transfer.link_copied_paste_it_on_your":"Link copiado. Cole-o no outro dispositivo em De outro dispositivo.", "transfer.moving_a_network_here":"Trazer uma rede para cá", -"transfer.next_code":"Próximo código", -"transfer.nothing_is_uploaded_anywhere_the_codes":"Nada é enviado para lugar nenhum: os códigos e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.", -"transfer.on_the_other_device_open_the":"No dispositivo com a sua rede, abra o menu e escolha Enviar para outro dispositivo. Escaneie o código com a câmera deste dispositivo ou cole o link aqui.", -"transfer.on_your_other_device_open_the":"No outro dispositivo, aponte a câmera para este código e abra o link.", -"transfer.on_your_other_device_open_the_many":"No outro dispositivo, aponte a câmera para este código e abra o link, depois volte aqui para o próximo. A ordem não importa.", -"transfer.paste_a_transfer_link":"Cole um link de transferência", -"transfer.qr_code_i_of_n":"Código QR {i} de {n}", -"transfer.scan_the_next_code_on_your":"Escaneie o próximo código no outro dispositivo e abra o link. Sua rede carrega assim que o último chegar.", -"transfer.send_the_link":"Enviar o link", +"transfer.nothing_is_uploaded_anywhere_the_file":"Nada é enviado para lugar nenhum: o arquivo e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.", +"transfer.on_the_device_with_your_network":"No dispositivo com a sua rede, abra o menu e escolha Enviar para outro dispositivo. Depois abra aqui o arquivo enviado com Importar um save.", +"transfer.or_copy_the_link_and_paste":"Ou copie o link e cole no outro dispositivo em De outro dispositivo, prático se seus dispositivos compartilham a área de transferência.", +"transfer.or_paste_a_transfer_link":"Ou cole um link de transferência", +"transfer.send_the_save_file":"Enviar o save", +"transfer.send_the_save_file_to_your":"Envie o arquivo de save para o outro dispositivo: AirDrop, Quick Share, um chat com você mesmo ou e-mail. Abra lá com Importar um save.", "transfer.send_to_another_device":"Enviar para outro dispositivo", -"transfer.start_over":"Recomeçar", "transfer.that_is_not_a_transfer_link":"Isso não é um link de transferência.", "transfer.that_link_is_incomplete_or_damaged":"Esse link está incompleto ou danificado. Copie de novo, inteiro.", -"transfer.the_codes_leave_out_your_charts":"Para serem poucos códigos, eles deixam de fora seus gráficos e notícias; o link leva tudo.", -"transfer.this_browser_cannot_pack_networks_into":"Este navegador não consegue colocar redes em links. Use um arquivo de save.", -"transfer.this_network_is_too_big_for":"Esta rede é grande demais para códigos. Envie o link ou exporte um arquivo de save.", +"transfer.this_browser_cannot_open_transfer_links":"Este navegador não consegue abrir links de transferência. Use um arquivo de save.", "tutorial.businesses_pop_up_as_bubbles_on":"Empresas aparecem como bolhas de $ no mapa. Abra Negócios e feche seu primeiro cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresça: arraste do seu router rosa até uma cidade próxima para lançar fibra e abrir um segundo POP.", "tutorial.start_the_clock_with_1_and":"Comece o relógio em 1× e veja o tráfego e o dinheiro fluírem. Dá pra pausar a qualquer momento.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 0928dea..0e7fdc6 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -637,8 +637,8 @@ const API_WHY={ const API_DENY={ speed:'time',phonePlay:'time',phoneSpeed:'time', start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', - exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPage:'files',xferPaste:'files',xferRecv:'files',xferReset:'files', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPaste:'files',xferRecv:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', - install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser',xferShare:'browser', }; diff --git a/src/game/60-features/61-qr-code.js b/src/game/60-features/61-qr-code.js deleted file mode 100644 index d8ad571..0000000 --- a/src/game/60-features/61-qr-code.js +++ /dev/null @@ -1,59 +0,0 @@ -/* ---------- QR codes (#263) ---------- - A small QR encoder: byte mode, error correction L or M, versions 1 to 40, the standard mask penalty. The game has no - dependencies and no server, so moving a network to a phone is codes the phone's own camera app can open. - Follows ISO/IEC 18004 (and Project Nayuki's reference implementation, MIT). */ -const QR_ECC={L:[1,[7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25]], - M:[0,[10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49]]}; -const qrRaw=v=>{let r=(16*v+128)*v+64;if(v>=2){const n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36;}return r;}; -const qrDataCw=(v,e)=>Math.floor(qrRaw(v)/8)-QR_ECC[e][1][v-1]*QR_ECC[e][2][v-1]; -// The most bytes one code of this version holds (byte mode). -const qrCap=(v,e='L')=>qrDataCw(v,e)-(v<10?2:3); -function qrMul(x,y){let z=0;for(let i=7;i>=0;i--){z=(z<<1)^((z>>>7)*0x11D);z^=((y>>>i)&1)*x;}return z;} -function qrRs(data,n){const d=new Array(n).fill(0);d[n-1]=1;let root=1; - for(let i=0;i{if(v===1)return [];const n=Math.floor(v/7)+2,step=v===32?26:Math.ceil((v*4+4)/(n*2-2))*2,r=[6]; - for(let p=v*4+10;r.length(x+y)%2===0,(x,y)=>y%2===0,(x,y)=>x%3===0,(x,y)=>(x+y)%3===0,(x,y)=>(Math.floor(x/3)+Math.floor(y/2))%2===0, - (x,y)=>x*y%2+x*y%3===0,(x,y)=>(x*y%2+x*y%3)%2===0,(x,y)=>((x+y)%2+x*y%3)%2===0]; -/* bytes (Uint8Array or array) → {size, m: rows of booleans (true = dark)}, or null when it does not fit in version 40. - o.ecc 'L' (default) or 'M'; o.mask 0-7 to force one (tests); o.min/o.max bound the version. */ -function qrEncode(bytes,o={}){const e=o.ecc||'L',len=bytes.length;let v=o.min||1; - while(v<=(o.max||40)&&len>qrCap(v,e))v++;if(v>(o.max||40))return null; - const cap=qrDataCw(v,e),bits=[],put=(x,n)=>{for(let i=n-1;i>=0;i--)bits.push((x>>>i)&1);}; - put(4,4);put(len,v<10?8:16);for(const b of bytes)put(b,8); - put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);for(let p=0xEC;bits.length=ns)cw.push(blocks[j][i]); - const n=v*4+17,m=[],fn=[];for(let y=0;y{m[y][x]=d;fn[y][x]=true;}; - for(let i=0;i=0&&x=0&&y{const d=QR_ECC[e][0]<<3|mk;let r=d;for(let i=0;i<10;i++)r=(r<<1)^((r>>>9)*0x537);const b=(d<<10|r)^0x5412,bit=i=>((b>>>i)&1)===1; - for(let i=0;i<=5;i++)set(8,i,bit(i));set(8,7,bit(6));set(8,8,bit(7));set(7,8,bit(8));for(let i=9;i<15;i++)set(14-i,8,bit(i)); - for(let i=0;i<8;i++)set(n-1-i,8,bit(i));for(let i=8;i<15;i++)set(8,n-15+i,bit(i));set(8,n-8,true);}; - fmt(0); - if(v>=7){let r=v;for(let i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);const b=v<<12|r;for(let i=0;i<18;i++){const d=((b>>>i)&1)===1,a=n-11+i%3,c=Math.floor(i/3);set(a,c,d);set(c,a,d);}} - for(let i=0,r=n-1;r>=1;r-=2){if(r===6)r=5;for(let vt=0;vt>>3]>>>(7-(i&7)))&1)===1;i++;}}} - const flip=mk=>{const f=QR_MASK[mk];for(let y=0;yrow?m[a][b]:m[b][a]; - for(const row of [true,false])for(let a=0;a=5)p+=run-2;run=1;}} - for(let b=0;b+7<=n;b++){let hit=true;for(let k=0;k<7;k++)if(at(a,b+k,row)!==(k!==1&&k!==5)){hit=false;break;}if(!hit)continue; - let l=true,r=true;for(let k=1;k<=4;k++){if(b-k>=0&&at(a,b-k,row))l=false;if(b+6+k`;} diff --git a/src/game/60-features/62-device-transfer.js b/src/game/60-features/62-device-transfer.js index 3f4173e..a2131e2 100644 --- a/src/game/60-features/62-device-transfer.js +++ b/src/game/60-features/62-device-transfer.js @@ -1,9 +1,9 @@ /* ---------- moving a network to another device (#263) ---------- - No server, no account: the network itself travels, gzipped, in the fragment of a link (#sot1....), - which browsers never send to any server. One link carries all of it, to copy or share; QR codes carry it in parts a - phone's own camera app opens one after another. The receiving page collects the parts in its storage, in any order, - and imports the network like a save file once they are all there. */ -const XFER_K='sot-xfer',XFER_RE=/sot1\.([a-z0-9]{3,8})\.(\d{1,3})\.(\d{1,3})\.([A-Za-z0-9_-]+)/,XFER_CHUNK=900,XFER_MAX=200,XFER_DAY=864e5; + No server, no account. The save file goes through the device's own share sheet (AirDrop, Quick Share, a chat with + yourself, email), whatever its size, and opens on the other device with "Import a save". For copy and paste + (a synced clipboard, a note to self) the network also fits in a link: gzipped, in the fragment (#sot1..0.1.), + which browsers never send to any server. Opening the link, or pasting it, imports the network like a save file. */ +const XFER_RE=/sot1\.([a-z0-9]{3,8})\.0\.1\.([A-Za-z0-9_-]+)/; // Taken out of the address bar before anything else can read it (the stats counter only loads after this script): // a network in a link belongs to the player, and a reload must not import it again. const XFER_HASH=(()=>{try{const h=location.hash||'';if(!h.startsWith('#sot1.'))return '';history.replaceState(null,'',location.pathname+location.search);return h.slice(1);}catch(e){return '';}})(); @@ -13,37 +13,25 @@ const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location. // A network's save text: the one playing now (saved first), or any other straight from storage. function xferText(id){if(id===UI.slot&&S&&!pzOn()){save(true);return Promise.resolve(JSON.stringify(packSave(S)));} const raw=slotRaw(id);if(raw==null)return Promise.reject(new Error('no save'));return raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw);} -/* The link carries everything. The codes leave out the charts' history and the news log: more than half of a played - network, and only ever shown, never played with (the traffic odometer keeps its own count). A year-old network - takes 3 codes instead of 9; its charts start again on the other device, and the import says so. */ -const xferGz=async(t,lean)=>b64u(await gzPipe(new TextEncoder().encode(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},${lean?'"lean":1,':''}"S":${t}}`),new CompressionStream('gzip'))); -async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),o=JSON.parse(t); - const d=await xferGz(t),c=await xferGz(JSON.stringify({...o,hist:[],log:[]}),true); - const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'),n=Math.ceil(c.length/XFER_CHUNK),base=xferBase()+'#sot1.'; - // Codes and link are two transfers: a code never completes a set with a piece of the link. - const parts=n>XFER_MAX?[]:Array.from({length:n},(_,i)=>`${base}${k}.${i}.${n}.${c.slice(i*XFER_CHUNK,(i+1)*XFER_CHUNK)}`); - return {name:e?e.name:o.name,link:`${base}${k}.0.1.${d}`,parts};} -// Parts that arrived so far (one transfer at a time; a day old, they are forgotten). -function xferStore(){let s=null;try{s=JSON.parse(localStorage.getItem(XFER_K)||'null');}catch(e){} - if(!s||typeof s!=='object'||typeof s.id!=='string'||!(s.n>1&&s.n<=999)||!s.p||typeof s.p!=='object'||!(Date.now()-s.at=0&&+kx.id===id),t=await xferText(id),name=e&&e.name||S&&S.name; + const w=`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`; + let file=null;try{const fn=saveFileName(name),ok=f=>!!navigator.canShare&&navigator.canShare({files:[f]}); + file=new File([w],fn,{type:'application/json'});if(!ok(file)){file=new File([w],fn.replace(/\.json$/,'.txt'),{type:'text/plain'});if(!ok(file))file=null;}}catch(err){file=null;} + let link=null;if(gzOk()){const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'); + link=`${xferBase()}#sot1.${k}.0.1.${b64u(await gzPipe(new TextEncoder().encode(w),new CompressionStream('gzip')))}`;} + return {id,name,file,link};} +// A link (or just its fragment, or text with one in it). function xferTake(h){const m=XFER_RE.exec(String(h||'')); if(!m){toast(tr('transfer.that_is_not_a_transfer_link'),'bad');sfx('err');return false;} - const id=m[1],i=+m[2],n=+m[3],d=m[4];if(!(n>=1&&is.p[k]).join(''));return true;} - try{localStorage.setItem(XFER_K,JSON.stringify(s));}catch(e){} - openModal(xferWaitHtml(s));sfx('click');return true;} -function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} + xferOpen(m[2]);return true;} +function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_open_transfer_links'),'bad');return;} let u=null;try{u=unb64u(d);}catch(e){} const bad=()=>{toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');};if(!u){bad();return;} gzPipe(u,new DecompressionStream('gzip')).then(b=>{const r=parseSave(new TextDecoder().decode(b)); if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}importAsk(r);track('xfer_in');},bad);} -// Another window got a part (or finished): the one showing the progress follows. -addEventListener('storage',e=>{if(e.key!==XFER_K||!$('xferWait'))return;const s=xferStore();if(s)openModal(xferWaitHtml(s));else ACT.helpClose();}); addEventListener('hashchange',()=>{const h=location.hash||'';if(!h.startsWith('#sot1.'))return;try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}xferTake(h.slice(1));}); -// After boot: a page opened from a transfer link takes its part. +// After boot: a page opened from a transfer link imports it. function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 9b14de0..3aef729 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -20,7 +20,7 @@ Object.assign(ACT,{ newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();}, keepPlaying:()=>{closeModal();}, exportSave:()=>exportSave(), - 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();}, + importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,.txt,application/json,text/plain';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;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; // An import is a new network next to the others: the one playing here is saved and kept. try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;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;setSpeed(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;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, diff --git a/src/game/90-actions/92-transfer.js b/src/game/90-actions/92-transfer.js index 6d71136..cbfb5a2 100644 --- a/src/game/90-actions/92-transfer.js +++ b/src/game/90-actions/92-transfer.js @@ -1,14 +1,13 @@ -// Moving a network to another device (#263): codes and a link out, a pasted link in. +// Moving a network to another device (#263): the save file through the share sheet, or a link to paste. Object.assign(ACT,{ xfer:({id}={})=>{const sid=slotOkId(id)?id:UI.slot;if(!sid||!slotIdx().some(e=>e.id===sid))return; - if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} - xferPack(sid).then(x=>{UI.xfer={...x,id:sid,i:0};openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}, - xferPage:({i})=>{const x=UI.xfer;if(!x||!(i>=0&&i{const x=UI.xfer;if(!x)return;const t=x.link,no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad'); - if(navigator.share&&isPhone()){navigator.share({title:'Series of Tubes',url:t}).catch(()=>{});return;} - try{navigator.clipboard.writeText(t).then(()=>toast(tr('transfer.link_copied_open_it_on_your'),'good'),no);}catch(e){no();}}, + xferPack(sid).then(x=>{UI.xfer=x;openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}, + // Straight from the tap: a share sheet only opens on a user's gesture. + xferShare:()=>{const x=UI.xfer;if(!x||!x.file)return; + try{navigator.share({files:[x.file],title:'Series of Tubes'}).then(()=>track('xfer_share'),e=>{if(e&&e.name!=='AbortError')exportSlot(x.id);});}catch(e){exportSlot(x.id);}}, + xferLink:()=>{const x=UI.xfer;if(!x||!x.link)return;const no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad'); + try{navigator.clipboard.writeText(x.link).then(()=>toast(tr('transfer.link_copied_paste_it_on_your'),'good'),no);}catch(e){no();}}, xferFile:()=>{const x=UI.xfer;if(x)exportSlot(x.id);}, xferRecv:()=>openModal(xferRecvHtml()), xferPaste:()=>{const el=$('xferIn');if(el)xferTake(el.value.trim());}, - xferReset:()=>{xferClear();ACT.helpClose();}, }); diff --git a/src/game/91-save.js b/src/game/91-save.js index d5c71ab..9c8ef2f 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -81,13 +81,13 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_ if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')}; if(s.lost)return {err:tr('save.that_network_went_bankrupt_it_cannot')}; for(const c of Object.keys(s.pops))if(!isCity(c))return {err:tr('save.that_save_has_a_pop_in',{city:esc(String(c).slice(0,12))})}; - return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network')),lean:!!(j.lean&&j.S)};} + return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};} function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;} const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;} importAsk(r);}; rd.readAsText(file);} // A save from a file or a transfer link (#263), checked by parseSave(): what it is, and whether to load it. -function importAsk(r){UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}${r.lean?' '+tr('transfer.its_charts_and_news_start_fresh'):''}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);} +function importAsk(r){UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);} // This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable. function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null; try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){} diff --git a/src/game/95-modals/46-transfer.js b/src/game/95-modals/46-transfer.js index 5b7c78d..7f41123 100644 --- a/src/game/95-modals/46-transfer.js +++ b/src/game/95-modals/46-transfer.js @@ -1,17 +1,12 @@ -/* Moving a network to another device (#263): the codes to scan and the link, and on the other side, where to paste it. */ -function xferHtml(){const x=UI.xfer,n=x.parts.length,i=Math.min(x.i,n-1),nm=esc(x.name||tr('common.unnamed_network')); - const q=n?qrEncode(new TextEncoder().encode(x.parts[i])):null; +/* Moving a network to another device (#263): the save file through the share sheet, or the link; on the other side, + where to open it. */ +function xferHtml(){const x=UI.xfer,nm=esc(x.name||tr('common.unnamed_network')); return `
📲 ${tr('transfer.send_to_another_device')}

${nm}

- ${q?`

${n>1?tr('transfer.on_your_other_device_open_the_many'):tr('transfer.on_your_other_device_open_the')}

${qrSvg(q,tr('transfer.qr_code_i_of_n',{i:i+1,n}))} - ${n>1?`
${btn('‹','xferPage',{i:i-1},'ghost',i===0)}${tr('transfer.code_i_of_n',{i:i+1,n})}${btn(tr('transfer.next_code'),'xferPage',{i:i+1},'pink',i===n-1)}
`:''}` - :`

${tr('transfer.this_network_is_too_big_for')}

`} -
${btn(navigator.share&&isPhone()?tr('transfer.send_the_link'):tr('transfer.copy_the_link'),'xferLink',{},n?'':'pink')}${btn(tr('common.export_save'),'xferFile',{},'ghost')}
-

${n?tr('transfer.the_codes_leave_out_your_charts')+' ':''}${tr('transfer.nothing_is_uploaded_anywhere_the_codes')}

`;} +

${x.file?tr('transfer.send_the_save_file_to_your'):tr('transfer.download_the_save_file_and_send')}

+
${x.file?btn(tr('transfer.send_the_save_file'),'xferShare',{},'pink big'):btn(tr('common.export_save'),'xferFile',{},'pink big')}${x.link?btn(tr('transfer.copy_the_link'),'xferLink',{},''):''}
+ ${x.link?`

${tr('transfer.or_copy_the_link_and_paste')}

`:''}

${tr('transfer.nothing_is_uploaded_anywhere_the_file')}

`;} function xferRecvHtml(){return `
📲 ${tr('transfer.from_another_device')}

${tr('transfer.moving_a_network_here')}

-

${tr('transfer.on_the_other_device_open_the')}

- -
${btn(tr('common.open'),'xferPaste',{},'pink big')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}
`;} -function xferWaitHtml(s){const have=Object.keys(s.p).length; - return `
📲 ${tr('transfer.moving_a_network_here')}

${tr('transfer.have_of_n_codes_are_here',{have,n:s.n})}

-
-

${tr('transfer.scan_the_next_code_on_your')}

${btn(tr('common.close'),'helpClose',{},'pink big')}${btn(tr('transfer.start_over'),'xferReset',{},'ghost')}
`;} +

${tr('transfer.on_the_device_with_your_network')}

+
${btn(tr('common.import_a_save'),'importPick',{},'pink big')}
+ +
${btn(tr('common.open'),'xferPaste',{},'')}
`;} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 9919023..59e3067 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','xfer','xferPage','xferLink','xferFile','xferRecv','xferPaste','xferReset'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','xfer','xferShare','xferLink','xferFile','xferRecv','xferPaste'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/i18n/en.js b/src/i18n/en.js index d0a2a0e..4c089e8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4848,30 +4848,22 @@ "traceroute.this_one_is_set_to_mode":"; this one is set to {mode}", "traceroute.transit_is_the_last_resort":"transit is the last resort", "traceroute.your_traffic_follows_the_metrics_this":"Your internet traffic follows the metrics. This is the path a customer circuit on “{mode}” would take.", -"transfer.code_i_of_n":"Code {i} of {n}", "transfer.copy_the_link":"Copy the link", "transfer.could_not_copy_the_link_here":"Could not copy the link here. Export a save file instead.", +"transfer.download_the_save_file_and_send":"Download the save file and send it to your other device, for example by email or a chat with yourself. Open it there with Import a save.", "transfer.from_another_device":"From another device", -"transfer.have_of_n_codes_are_here":"{have} of {n} codes are here", -"transfer.its_charts_and_news_start_fresh":"Its charts and news start fresh here.", -"transfer.link_copied_open_it_on_your":"Link copied. Open it on your other device.", +"transfer.link_copied_paste_it_on_your":"Link copied. Paste it on your other device under From another device.", "transfer.moving_a_network_here":"Move a network here", -"transfer.next_code":"Next code", -"transfer.nothing_is_uploaded_anywhere_the_codes":"Nothing is uploaded anywhere: the codes and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.", -"transfer.on_the_other_device_open_the":"On the device with your network, open the menu and pick Send to another device. Scan its code with this device's camera, or paste its link here.", -"transfer.on_your_other_device_open_the":"On your other device, point the camera at this code and open the link.", -"transfer.on_your_other_device_open_the_many":"On your other device, point the camera at this code and open the link, then come back here for the next one. They can arrive in any order.", -"transfer.paste_a_transfer_link":"Paste a transfer link", -"transfer.qr_code_i_of_n":"QR code {i} of {n}", -"transfer.scan_the_next_code_on_your":"Scan the next code on your other device and open its link. Your network loads as soon as the last one arrives.", -"transfer.send_the_link":"Send the link", +"transfer.nothing_is_uploaded_anywhere_the_file":"Nothing is uploaded anywhere: the file and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.", +"transfer.on_the_device_with_your_network":"On the device with your network, open the menu and pick Send to another device. Then open the file it sends with Import a save.", +"transfer.or_copy_the_link_and_paste":"Or copy the link and paste it on the other device under From another device, handy with a clipboard your devices share.", +"transfer.or_paste_a_transfer_link":"Or paste a transfer link", +"transfer.send_the_save_file":"Send the save file", +"transfer.send_the_save_file_to_your":"Send the save file to your other device: AirDrop, Quick Share, a chat with yourself or email. Open it there with Import a save.", "transfer.send_to_another_device":"Send to another device", -"transfer.start_over":"Start over", "transfer.that_is_not_a_transfer_link":"That is not a transfer link.", "transfer.that_link_is_incomplete_or_damaged":"That link is incomplete or damaged. Copy it again, all of it.", -"transfer.the_codes_leave_out_your_charts":"To keep the codes few, they leave out your charts and news; the link carries everything.", -"transfer.this_browser_cannot_pack_networks_into":"This browser cannot pack networks into links. Use a save file instead.", -"transfer.this_network_is_too_big_for":"This network is too big for codes. Send the link instead, or export a save file.", +"transfer.this_browser_cannot_open_transfer_links":"This browser cannot open transfer links. Use a save file instead.", "tutorial.businesses_pop_up_as_bubbles_on":"Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.", "tutorial.grow_drag_from_your_pink_router":"Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.", "tutorial.start_the_clock_with_1_and":"Start the clock with 1× and watch traffic and money flow. You can pause any time.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index d431cd1..d5b23cc 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -229,8 +229,5 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .cmroute{align-items:flex-start} .tag.cmhot{background:#FFE1D6;color:#B43A12} .tag.cmcool{background:#DDF1FB;color:#1E6A8C} -/* Moving a network to another device (#263). A code stays dark on white in dark mode too: cameras need the contrast. */ -svg.qr{display:block;width:100%;max-width:300px;height:auto;margin:10px auto 6px;border:3px solid var(--ink);border-radius:12px;background:#fff;box-sizing:border-box} -.xfer-nav{display:flex;align-items:center;justify-content:space-between;gap:8px;max-width:300px;margin:0 auto}.xfer-nav b{font:800 14px var(--display)} +/* Moving a network to another device (#263): a pasted link is long, so it wraps anywhere. */ textarea.xfer-in{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 10px;font:13px/1.35 ui-monospace,monospace;background:var(--soft);color:var(--ink);resize:vertical;word-break:break-all} -.xfer-dots{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.xfer-dots i{width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);background:var(--soft)}.xfer-dots i.on{background:var(--ok)} diff --git a/tests/device-transfer.test.js b/tests/device-transfer.test.js index e6d49fa..ee85db1 100644 --- a/tests/device-transfer.test.js +++ b/tests/device-transfer.test.js @@ -1,164 +1,133 @@ -// Moving a network to another device with QR codes or a link (#263): no server, the network travels in the link. +// Moving a network to another device (#263): the save file through the share sheet, or a link to paste. No server. const test = require('node:test'); const assert = require('node:assert/strict'); -const crypto = require('node:crypto'); const { load } = require('./harness'); const { until } = require('./net'); const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); -const hash = (rows) => crypto.createHash('sha256').update(rows).digest('hex').slice(0, 16); +const SNAP = "JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name,hist:S.hist.length})"; +/* A share sheet like Chromium's: no .json files, .txt yes. Calls are recorded; share() is called at once (a sheet only + opens straight from the tap). window.__shareResult: 'ok', 'abort' or 'fail'. */ +const CHROMIUM_SHARE = `navigator.canShare=d=>!!d&&Array.isArray(d.files)&&d.files.every(f=>/\\.txt$/.test(f.name)); + window.__shared=[];window.__shareResult='ok'; + navigator.share=d=>{__shared.push(d);return __shareResult==='ok'?Promise.resolve():Promise.reject(new DOMException('x',__shareResult==='abort'?'AbortError':'NotAllowedError'));};`; -// Module matrices from Project Nayuki's reference encoder (qrcodegen), byte mode, one per mask. -const REF = [ - ['https://seriesoftub.es/#sot1.ab12c.0.3.HELLO-world_42', 'L', 3, ['30728883c56ec1b1', '18174c37d6786fa7', 'a981f41d89cceb7e', 'e28c29324d50ad09', 'd05a240976233180', 'd7ad281bfed61f9e', '083a4137b252f78f', 'a82468785d358d89']], - ['x'.repeat(200), 'M', 10, ['750d745db4aee09b', '9ff2474eb4806262', 'c8294f9a437b1546', '1bf4d13e40b47c5f', 'fdce0323024df963', '87c3d49925e75834', 'b719f9e8d1b0dd89', '342f8ed986243039']], - ['Series of Tubes '.repeat(40), 'L', 17, ['6d81d73a8426ecea', 'c36740777a080ce2', '79556df75d596a27', 'c4999ca1f4c7cdff', '23185df5abef3f74', '5b2fc9fa8d26aac0', '88b5814b383833f3', '298a1c7f2a08b6ae']], - ['AS64512 '.repeat(120), 'L', 22, ['f8229058824f8960', '0c473ae025a4c779', '58c3ab340313be0a', 'd4fa9891688a1ccc', 'eaac167548e8e5f3', '3f14beb40d1dc4cf', 'a29dee8e6e34fd04', 'b0c682d9933fe28a']], - ['peering '.repeat(360), 'L', 40, ['6efd1b3513f437d0', 'c18c188947dc52bc', 'cd93f7d4626a657f', 'a596a01654473a8d', '33fa5bbfe6b4915a', 'c547ade997387b9e', 'ed333919d660b05a', '44f32c8d979821a8']], -]; - -test('the QR encoder draws exactly the reference codes, for every mask, from version 3 to 40', () => { - const { ev, errors } = load(); - for (const [s, ecc, v, masks] of REF) { - masks.forEach((h, mask) => { - const q = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}',mask:${mask}});return JSON.stringify({v:q.v,size:q.size,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join('')});})()`)); - assert.equal(q.v, v, `${s.slice(0, 12)}… version`); - assert.equal(q.size, v * 4 + 17); - assert.equal(hash(q.m), h, `${s.slice(0, 12)}… ${ecc} mask ${mask}`); - }); - // Left to choose, it picks one of the eight valid masks. - const auto = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}'});return JSON.stringify({v:q.v,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join(''),mask:q.mask});})()`)); - assert.equal(auto.v, v); - assert.equal(hash(auto.m), masks[auto.mask]); - } - assert.equal(ev("qrEncode(new Uint8Array(2954))"), null, 'more than version 40 holds'); - assert.match(ev("qrSvg(qrEncode(new TextEncoder().encode('hi')),'x')"), /^ { + const a = await sender({ share: true }); + assert.match(a.ev("$('modalCard').textContent"), /Send the save file/); + assert.equal(a.ev('UI.xfer.file.name'), 'series-of-tubes-tube-mover-' + a.ev('new Date().toISOString().slice(0,10)') + '.txt'); + a.ev(`document.querySelector('#modalCard [data-act="xferShare"]').click()`); + assert.equal(a.ev('__shared.length'), 1, 'the sheet opens in the same tap, not after waiting for anything'); + assert.equal(a.ev('__shared[0].files[0]===UI.xfer.file'), true); + + // The file arrives on the other device and opens with Import a save. + const txt = await a.dom.window.eval('__shared[0].files[0].text()'), want = a.ev(SNAP); + const b = load({ gzip: true }); + b.dom.window.__txt = txt; + b.ev("importFile(new File([__txt],'series-of-tubes-tube-mover.txt',{type:'text/plain'}))"); + await settle(b.ev, '!!UI.importing', 'it asks before loading'); + b.ev('ACT.importGo()'); + assert.equal(b.ev(SNAP), want, 'the same network, charts and all'); + // The picker takes the .txt that Chromium shares as well as .json. + b.ev("HTMLInputElement.prototype.click=function(){window.__accept=this.accept;};ACT.importPick()"); + assert.match(b.ev('__accept'), /\.txt/); + assert.match(b.ev('__accept'), /\.json/); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); + +test('a browser that shares .json gets the .json; one that cannot share files gets a download button', async () => { + const a = load({ gzip: true }); + a.ev("navigator.canShare=()=>true;navigator.share=()=>Promise.resolve();ACT.start({});save(true);ACT.xfer({})"); + await settle(a.ev, '!!UI.xfer'); + assert.match(a.ev('UI.xfer.file.name'), /\.json$/); + assert.equal(a.ev('UI.xfer.file.type'), 'application/json'); + + const c = await sender(); + assert.equal(c.ev('UI.xfer.file'), null); + assert.ok(c.ev(`!!document.querySelector('#modalCard [data-act="xferFile"]')`), 'Export save instead'); + assert.ok(!c.ev(`document.querySelector('#modalCard [data-act="xferShare"]')`)); + assert.match(c.ev("$('modalCard').textContent"), /Download the save file/); + assert.deepEqual(a.errors, []); + assert.deepEqual(c.errors, []); +}); + +test('a share that fails falls back to the download; closing the sheet does nothing', async () => { + const a = await sender({ share: true }); + a.ev("window.__dl=0;exportSlot=()=>{__dl++;}"); + a.ev("__shareResult='abort';ACT.xferShare()"); + await new Promise((r) => setTimeout(r, 50)); + assert.equal(a.ev('__dl'), 0, 'the player closed the sheet: nothing else happens'); + a.ev("__shareResult='fail';ACT.xferShare()"); + await settle(a.ev, '__dl===1', 'a refused share downloads the file instead'); + assert.deepEqual(a.errors, []); +}); + test('one link carries the whole network: opened on another device it loads the same game, and leaves the address bar', async () => { const a = await sender(); - const link = a.ev('UI.xfer.link'), want = a.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"); + const link = a.ev('UI.xfer.link'), want = a.ev(SNAP); assert.ok(link.startsWith('https://tests.invalid/#sot1.'), link.slice(0, 40)); - assert.ok(a.ev('UI.xfer.parts.length') > 1, 'a played network takes several codes'); - assert.ok(a.ev('UI.xfer.parts.every(p=>p.length<=qrCap(22))'), 'every code is small enough to scan from a phone screen'); - const b = load({ gzip: true, url: link }); assert.equal(b.ev('location.hash'), '', 'the network is taken out of the address bar at once'); await settle(b.ev, '!!UI.importing', 'it asks before loading'); assert.match(b.ev("$('modalCard').textContent"), /Tube Mover/); - assert.doesNotMatch(b.ev("$('modalCard').textContent"), /start fresh/, 'the link carries everything'); - const hist = a.ev('JSON.stringify(S.hist)'), log = a.ev('S.log.length'); b.ev('ACT.importGo()'); - assert.equal(b.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"), want); - assert.equal(b.ev('JSON.stringify(S.hist)'), hist, 'the charts came along'); - assert.equal(b.ev('S.log.length'), log + 1, 'the news came along (plus the welcome)'); + assert.equal(b.ev(SNAP), want); assert.equal(b.ev('slotIdx().length'), 1, 'it joins the networks on that device'); - assert.deepEqual(a.errors, []); - assert.deepEqual(b.errors, []); + + // Pasted on the title screen, with whatever whitespace a clipboard adds. + const c = load({ gzip: true }); + c.ev('ACT.xferRecv()'); + assert.ok(c.ev(`!!document.querySelector('#modalCard [data-act="importPick"]')`), 'Import a save is right there for the file'); + c.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`); + await settle(c.ev, '!!UI.importing'); + for (const x of [a, b, c]) assert.deepEqual(x.errors, []); }); -test('the codes arrive one by one, in any order; the network loads when the last one is in', async () => { +test('bad or cut links say so and load nothing', async () => { const a = await sender(); - const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), n = parts.length; - // Paging through the codes on the sending device. - a.ev('ACT.xferPage({i:1})'); - assert.match(a.ev("$('modalCard').textContent"), new RegExp(`Code 2 of ${n}`)); - + const link = a.ev('UI.xfer.link'); const b = load({ gzip: true }); - const order = parts.map((p, i) => i).reverse(); - for (const [k, i] of order.entries()) { - b.ev(`xferTake(${JSON.stringify(parts[i])})`); - if (k < n - 1) { - assert.match(b.ev("$('modalCard').textContent"), new RegExp(`${k + 1} of ${n} codes are here`)); - assert.equal(b.ev('document.querySelectorAll(".xfer-dots i.on").length'), k + 1); - // The same code twice changes nothing. - b.ev(`xferTake(${JSON.stringify(parts[i])})`); - assert.equal(b.ev('Object.keys(xferStore().p).length'), k + 1); - } - } - await settle(b.ev, '!!UI.importing', 'the last code opens the network'); - assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null, 'the parts are cleaned up'); - assert.match(b.ev("$('modalCard').textContent"), /charts and news start fresh/, 'it says what the codes left out'); - const vol = a.ev('S.vol'); - b.ev('ACT.importGo()'); - assert.equal(b.ev('S.name'), 'Tube Mover'); - assert.equal(b.ev('S.cash'), a.ev('S.cash')); - assert.equal(b.ev('S.day'), a.ev('S.day')); - assert.equal(b.ev('S.vol'), vol, 'the traffic odometer keeps its count'); - assert.equal(b.ev('S.hist.length'), 0, 'only charts and news were left out'); - assert.equal(b.ev('S.log.length'), 1, 'the news starts with the welcome'); - b.ev('for(let i=0;i<3;i++)dayTick()'); - assert.equal(b.ev('S.hist.length'), 3, 'the charts start again'); - assert.deepEqual(b.errors, []); -}); - -test('a code from another transfer starts over, and bad or cut links say so and load nothing', async () => { - const a = await sender(); - const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), link = a.ev('UI.xfer.link'); - const b = load({ gzip: true }); - b.ev(`xferTake(${JSON.stringify(parts[0])})`); - b.ev(`xferTake(${JSON.stringify(parts[1].replace(/#sot1\.[a-z0-9]+\./, '#sot1.zzzzz.'))})`); - assert.equal(b.ev("xferStore().id"), 'zzzzz'); - assert.equal(b.ev('Object.keys(xferStore().p).length'), 1); - b.ev('ACT.xferReset()'); - assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null); - b.ev("xferTake('https://example.com/nothing-here')"); - assert.match(b.ev("$('toasts')?$('toasts').textContent:document.body.textContent"), /not a transfer link/); + assert.match(b.ev('document.body.textContent'), /not a transfer link/); b.ev(`xferTake(${JSON.stringify(link.slice(0, -40))})`); - await settle(b.ev, "/incomplete or damaged/.test(document.body.textContent)", 'a cut link is reported'); + await settle(b.ev, '/incomplete or damaged/.test(document.body.textContent)', 'a cut link is reported'); assert.equal(b.ev('!!UI.importing'), false); assert.equal(b.ev('S'), null, 'nothing was loaded'); - - // Pasted into the box on the title screen, the whole link works too. - b.ev('ACT.xferRecv()'); - b.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`); - await settle(b.ev, '!!UI.importing'); assert.deepEqual(b.errors, []); }); -test('any network on the title screen can be sent, and the codes fit a 360 px phone', async () => { - const a = await sender(); - a.ev("ACT.toTitle()"); +test('any network on the title screen can be sent without loading it, and the screen fits a 360 px phone', async () => { + const a = await sender({ share: true }); + a.ev('ACT.toTitle()'); const id = a.ev('slotIdx()[0].id'); a.ev(`ACT.slotMenu({id:'${id}'})`); - assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xfer"]')`), 'the network menu offers it'); a.ev('window.innerWidth=360;UI.xfer=null'); a.ev(`document.querySelector('#modalCard [data-act="xfer"]').click()`); - await settle(a.ev, '!!UI.xfer&&!!document.querySelector("#modalCard svg.qr")', 'sent from storage, without loading it'); + await settle(a.ev, '!!UI.xfer', 'sent from storage'); + assert.equal(a.ev('S'), null, 'not loaded'); assert.equal(a.ev('UI.xfer.name'), 'Tube Mover'); - assert.ok(a.ev("!!document.querySelector('#modalCard .xfer-nav')")); - const css = a.ev("[...document.styleSheets].flatMap(s=>[...s.cssRules]).map(r=>r.cssText).join('\\n')"); - assert.match(css, /svg\.qr\s*\{[^}]*max-width:\s*300px/, 'the code never gets wider than a small phone'); + assert.match(await a.dom.window.eval('UI.xfer.file.text()'), /"name":"Tube Mover"/); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferShare"]')`)); assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferLink"]')`)); assert.deepEqual(a.errors, []); }); -test('a year-old network takes a handful of codes, because the codes leave out charts and news', async () => { - const a = load({ gzip: true }); - a.ev("ACT.start({});for(let i=0;i<365;i++)dayTick();save(true);ACT.xfer({})"); +test('without compression the file still goes, only the link is missing', async () => { + const a = load(); + a.ev(CHROMIUM_SHARE + "ACT.start({});save(true);ACT.xfer({})"); await settle(a.ev, '!!UI.xfer'); - const n = a.ev('UI.xfer.parts.length'), full = Math.ceil(a.ev("UI.xfer.link.split('.').pop().length") / 900); - assert.ok(n <= 4, `${n} codes`); - assert.ok(full >= 2 * n, `the whole network would take ${full}`); - assert.match(a.ev("$('modalCard').textContent"), /leave out your charts and news/); + assert.equal(a.ev('UI.xfer.link'), null); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferShare"]')`)); + assert.ok(!a.ev(`document.querySelector('#modalCard [data-act="xferLink"]')`)); assert.deepEqual(a.errors, []); }); - -test('without compression in the browser it says so instead of failing', () => { - const { ev, errors } = load(); - ev("ACT.start({});save(true);ACT.xfer({})"); - assert.equal(ev('UI.xfer'), undefined); - assert.match(ev('document.body.textContent'), /cannot pack networks into links/); - assert.deepEqual(errors, []); -}); From c137d3552d940932ff8498fa2556a1e2dd01481c Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 14:50:26 +0100 Subject: [PATCH 11/18] Send networks to another device, latency routes, POP standards and more (3.4.0) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37c3991..7b31070 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [3.4.0] — 2026-11-10 + - A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323). - Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). - Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). diff --git a/package-lock.json b/package-lock.json index ecce01c..376d165 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "3.3.0", + "version": "3.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "3.3.0", + "version": "3.4.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index 105a19a..b87e2ae 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "3.3.0", + "version": "3.4.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From e27e9e306660f8f465b3da84973294c5eac67a58 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 11 Nov 2026 12:06:23 +0100 Subject: [PATCH 12/18] Keep hand-listed alien waves on the market (#340) With the capacity market selling alien waves (or pairs), its daily pass set every fiber's listing to what the thresholds allowed: 128 waves listed by hand came back as 96 (after the 25% kept back), or were taken off entirely when the route's demand was below the minimum or the price below the floor. A listing now remembers how much was listed by hand (l.list.hw / hp). The broker lists its own share on top, capped at what the fiber has free; sales use up the broker's share first; switching a product or route off keeps the hand-listed part. cmClean() checks the new fields, so old saves load as before. Fixes #340 --- CHANGELOG.md | 2 + src/game/60-features/37-fiber-market.js | 14 ++++-- src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/53-market.js | 9 ++-- tests/fiber-broker.test.js | 2 +- tests/issues.test.js | 2 +- tests/manual-listing.test.js | 66 +++++++++++++++++++++++++ 7 files changed, 87 insertions(+), 10 deletions(-) create mode 100644 tests/manual-listing.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b31070..43a6467 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). + ## [3.4.0] — 2026-11-10 - A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323). diff --git a/src/game/60-features/37-fiber-market.js b/src/game/60-features/37-fiber-market.js index 6236f09..3bad457 100644 --- a/src/game/60-features/37-fiber-market.js +++ b/src/game/60-features/37-fiber-market.js @@ -21,10 +21,15 @@ const CM_HMAX=2.5; const cmNew=()=>({hold:25,p:JSON.parse(JSON.stringify(CM_DEF)),off:{},sh:[],news:[],seen:[]}); const cmCut=()=>broker()?0.97:0.9; /* A fiber's listing, l.list: {w: spectrum slots, p: pairs} as it always was, plus m1/m4/m8/m16 (managed 100G to 1.6T - waves) when any are listed. cmClean() checks one (a save, or after a day of sales) and returns null when nothing is left. */ + waves) when any are listed, and hw/hp: how many of w/p you listed by hand, which the broker's thresholds never take + back (#340). cmClean() checks one (a save, or after a day of sales) and returns null when nothing is left. */ const cmLs=l=>l.list||(l.list={w:0,p:0}); +const CM_HAND={w:'hw',p:'hp'}; function cmClean(L){if(!L||typeof L!=='object'||Array.isArray(L))return null;const x={w:int(L.w,0,256,0),p:int(L.p,0,2,0)};let any=x.w||x.p; + for(const k in CM_HAND){const v=Math.min(x[k],int(L[CM_HAND[k]],0,256,0));if(v)x[CM_HAND[k]]=v;} for(const p of CM_W){const v=int(L[CM_L[p]],0,256,0);if(v){x[CM_L[p]]=v;any=1;}}return any?x:null;} +// What you listed by hand of a product on a fiber (only alien waves and pairs can be). +const cmHand=(l,lk)=>(CM_HAND[lk]&&l.list&&l.list[CM_HAND[lk]])||0; // A stable number in [0,1) for a route and a question, different in every game. const cmU=(k,q)=>hstr(k+'|'+q+'|'+((S&&S.asn)||0))%100000/100000; /* How hot a route is (1 = its usual self). Its own slow cycle (two waves of 4 to 10 and 1.5 to 3 months) is what a @@ -130,7 +135,8 @@ function cmShocks(d){const C=S.cm;C.sh=C.sh.filter(x=>x.until>d); while demand is at least your minimum and the price at least your floor) or takes it off, then each listing may find a buyer: the more room the route has left and the hotter it is, the sooner; the fastest fiber sells first. */ function cmList1(r,p,s,d){const c=S.cm.p[p],lk=CM_L[p];if(!c.on||S.cm.off[r.k])return;const ok=cmDem(r,p,d)>=c.min&&cmIdx(r,p,s,0,d)*100>=c.floor; - for(const l of r.ls){const n=ok?cmSpare(l,p):0;if(n>0)cmLs(l)[lk]=n;else if(l.list)l.list[lk]=0;}} + // What you listed by hand stays listed on top of what the thresholds allow, up to what the fiber has free. + for(const l of r.ls){const h=cmHand(l,lk),n=Math.min(ok?cmSpare(l,p)+h:h,h?(p==='spec'?freeCh(l):1):Infinity);if(n>0)cmLs(l)[lk]=n;else if(l.list)l.list[lk]=0;}} // The listings as the thresholds want them right now (after you change a setting), without selling anything. function cmRelist(){const rs=cmRoutes(),sold=cmSold(rs);for(const r of rs.values())for(const p of CM_P)cmList1(r,p,sold.get(r.k)[p],S.day);cmTidy();} const cmTidy=()=>{for(const l of S.links)if(l.list){const L=cmClean(l.list);if(L)l.list=L;else delete l.list;}}; @@ -146,7 +152,9 @@ function cmDay(d=S.day){const C=S.cm;cmShocks(d);const rs=cmRoutes(),sold=cmSold while(n>0&&cmIdx(r,p,s[p],n-1,d)*100l.list[lk])l.list[CM_HAND[lk]]=l.list[lk];}} cmGrow(d);cmTidy();} /* What the next 30 and 90 days look like on a route, for a Cable broker: the route's own cycle and the news already out, but not the noise or news still to come. */ diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index aa5e4c8..eb5810e 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -1,7 +1,7 @@ Object.assign(ACT,{ // List spare capacity with a capacity broker (#203): w waves and p spare pairs, sold as the route's market wants. listFiber:({id,w,p})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.ready>S.day)return;w=Math.max(0,Math.min(freeCh(l)-((l.list&&l.list.w)||0),w|0));p=l.own?Math.max(0,Math.min((pairFree(l)?1:0)-((l.list&&l.list.p)||0),p|0)):0; - if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p; + if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p;if(w)L.hw=(L.hw||0)+w;if(p)L.hp=(L.hp||0)+p; toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} diff --git a/src/game/90-actions/53-market.js b/src/game/90-actions/53-market.js index c9e593b..a362177 100644 --- a/src/game/90-actions/53-market.js +++ b/src/game/90-actions/53-market.js @@ -2,13 +2,14 @@ Object.assign(ACT,{ marketOpen:()=>{if(!S||pzOn())return;UI.dtab='market';$('dash').hidden=false;renderDash();}, mktHold:({v})=>{if(!CM_HOLD.includes(v))return;S.cm.hold=v;cmRelist();sfx('click');after();}, - // Switching a product off takes what the broker listed of it off the market; what it already sold stays sold. + // Switching a product off takes what the broker listed of it off the market (what you listed by hand stays); what it + // already sold stays sold. mktCfg:({p,k,v})=>{const c=CM_P.includes(p)&&S.cm.p[p];if(!c)return; - if(k==='on'){c.on=!!v;if(!c.on)for(const l of S.links)if(l.list&&l.list[CM_L[p]])l.list[CM_L[p]]=0;} + if(k==='on'){c.on=!!v;if(!c.on)for(const l of S.links)if(l.list&&l.list[CM_L[p]])l.list[CM_L[p]]=cmHand(l,CM_L[p]);} else if(k==='min'&&CM_MIN[p].includes(v))c.min=v;else if(k==='floor'&&CM_FLOOR.includes(v))c.floor=v;else return; cmRelist();sfx('click');after();}, - // A route the broker leaves alone keeps nothing listed by the thresholds. + // A route the broker leaves alone keeps nothing listed by the thresholds, only what you listed by hand. mktRoute:({k})=>{const r=typeof k==='string'&&cmRoutes().get(k);if(!r)return;if(S.cm.off[k]){delete S.cm.off[k];}else{S.cm.off[k]=1; - for(const l of r.ls)if(l.list)for(const p of CM_P)if(S.cm.p[p].on)l.list[CM_L[p]]=0;} + for(const l of r.ls)if(l.list)for(const p of CM_P)if(S.cm.p[p].on)l.list[CM_L[p]]=cmHand(l,CM_L[p]);} cmRelist();sfx('click');after();}, }); diff --git a/tests/fiber-broker.test.js b/tests/fiber-broker.test.js index 7248473..1344982 100644 --- a/tests/fiber-broker.test.js +++ b/tests/fiber-broker.test.js @@ -43,7 +43,7 @@ test('a listing is kept in the save, checked, and can be taken off the market', fiber(ev, 'big', 'fra', 'ams', 450); ev("ACT.listFiber({id:'big',w:4})"); ev("const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))"); - assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='big').list)")), { w: 4, p: 0 }); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='big').list)")), { w: 4, p: 0, hw: 4 }); ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.links.find(l=>l.id==='big').list={w:'lots',p:-3};S=migrate(o)"); assert.equal(ev("S.links.find(l=>l.id==='big').list===undefined"), true, 'junk is dropped'); ev("ACT.listFiber({id:'big',w:2});ACT.unlistFiber({id:'big'})"); diff --git a/tests/issues.test.js b/tests/issues.test.js index d09c13b..9eac260 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -1279,7 +1279,7 @@ test('#51 a dark fiber shows what is rented out, and spare capacity can be liste assert.equal(ev("S.links[0].list?S.links[0].list.w:0"), 4 - b.slots, 'the listing shrinks by what sold'); // when every channel is lit or sold, only the spare pair in your own trench can be listed; then nothing is left ev("const l=S.links[0];delete l.list;l.ch=Array(chMax(l)-soldSlots(l)).fill('tp16');after();ACT.listFiber({id:'df1',w:4,p:1})"); - assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links[0].list)")), { w: 0, p: 1 }); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links[0].list)")), { w: 0, p: 1, hp: 1 }); ev("S.biz.push({id:'p1',type:'dfpair',link:'df1',city:'fra',city2:'ams',name:'X',bw:1,rate:1,reqs:[]},{id:'p2',type:'dfpair',link:'df1',city:'fra',city2:'ams',name:'Y',bw:1,rate:1,reqs:[]});delete S.links[0].list;S.offers=[];renderPanel()"); assert.match(txt(), /Nothing spare to sell on this fiber right now/); ev("ACT.listFiber({id:'df1',w:1,p:1})"); assert.equal(ev("S.links[0].list===undefined"), true); diff --git a/tests/manual-listing.test.js b/tests/manual-listing.test.js new file mode 100644 index 0000000..66b48f6 --- /dev/null +++ b/tests/manual-listing.test.js @@ -0,0 +1,66 @@ +// #340: alien waves you list by hand stay listed, whatever the capacity market's thresholds say. The broker's daily pass +// used to overwrite the listing with what the thresholds allowed, so 128 listed waves came back as 96, or as nothing. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const setup = () => { + const r = load(); + r.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[];for(const c of ['lon','nyc'])if(!S.pops[c])ACT.buildPop({city:c})"); + r.ev("S.links.push({id:'f',a:'lon',b:'nyc',kind:'df',own:true,sys:'cl',ch:[],km:5570,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});after()"); + return r; +}; +// Objects from the page come from another realm: compare them as JSON. +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +const L = ev => J(ev, "S.links.find(l=>l.id==='f').list||null"); +// A day of the market with no buyer (so nothing sells and only the listing logic runs). +const quietDay = ev => ev("(()=>{const r=Math.random;Math.random=()=>0.99;try{cmDay(S.day)}finally{Math.random=r}})()"); + +test('#340 a hand-made listing survives the broker when demand is below your minimum or the price below your floor', () => { + const { ev, errors } = setup(); + ev("S.cm.p.spec.on=true;S.cm.p.spec.min=8;S.cm.p.spec.floor=120"); + ev("ACT.listFiber({id:'f',w:128})"); + assert.equal(L(ev).w, 128); + quietDay(ev); + assert.equal(L(ev).w, 128, 'still listed the next day'); + // Changing a setting relists right away; it must not take the hand-made listing away either. + ev("ACT.mktCfg({p:'spec',k:'floor',v:100})"); + assert.equal(L(ev).w, 128); + ev("ACT.mktCfg({p:'spec',k:'on',v:0})"); + assert.equal(L(ev).w, 128, 'switching the product off keeps what you listed by hand'); + ev("ACT.mktCfg({p:'spec',k:'on',v:1});ACT.mktRoute({k:'lon|nyc'})"); + assert.equal(L(ev).w, 128, 'leaving the route alone keeps it too'); + ev("ACT.unlistFiber({id:'f'})"); + assert.equal(L(ev), null, 'unlisting still clears it'); + assert.deepEqual(errors, []); +}); + +test('#340 the broker adds its share on top of yours, and sales take from its share first', () => { + const { ev, errors } = setup(); + ev("S.cm.p.spec.on=true;S.cm.p.spec.min=1;S.cm.p.spec.floor=60;S.cm.hold=25"); + quietDay(ev); + const auto = L(ev).w; + assert.equal(auto, 96, 'the broker lists what is spare after the 25% kept back'); + ev("ACT.listFiber({id:'f',w:4})"); + quietDay(ev); + assert.equal(L(ev).w, 100, 'your 4 come out of what is kept back'); + // A buyer takes a wave: the broker's share shrinks, yours stays. + ev("(()=>{const r=Math.random;Math.random=()=>0;try{cmDay(S.day)}finally{Math.random=r}})()"); + assert.equal(ev("S.biz.filter(b=>b.type==='wwave').reduce((a,b)=>a+b.slots,0)"), 1); + assert.equal(L(ev).hw, 4); + quietDay(ev); + assert.equal(L(ev).w, 99, '95 spare after the reserve, plus your 4'); + assert.equal(L(ev).hw, 4); + assert.deepEqual(errors, []); +}); + +test('#340 the hand-made part of a listing round-trips through a save, and old saves load as before', () => { + const { ev, errors } = setup(); + ev("ACT.listFiber({id:'f',w:12})"); + const back = J(ev, "((()=>{const s=parseSave(JSON.stringify(S)).s;migrate(s);return s.links.find(l=>l.id==='f').list})())"); + assert.deepEqual(back, { w: 12, p: 0, hw: 12 }); + assert.deepEqual(J(ev, "(cmClean({w:5,p:0,hw:40}))"), { w: 5, p: 0, hw: 5 }, 'never more by hand than listed'); + assert.deepEqual(J(ev, "(cmClean({w:5,p:0}))"), { w: 5, p: 0 }, 'an old listing has nothing by hand'); + assert.equal(ev("cmClean({w:0,p:0,hw:3})"), null); + assert.deepEqual(errors, []); +}); From e2b3615a19cf8f344000bb1604e0e0e21558a288 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germain=20Carr=C3=A9?= <666182+carsso@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:35:50 +0100 Subject: [PATCH 13/18] Keep the Connections list working with 400G fabric ports (#342) --- CHANGELOG.md | 1 + src/game/94-dashboard/40-connections.js | 2 +- tests/nni.test.js | 12 ++++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43a6467..d42c2b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). +- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. ## [3.4.0] — 2026-11-10 diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index badc184..61caf58 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -26,7 +26,7 @@ function connUp(r){if(r.mine)return '';const nx=t=>PORT[t+1]&&portShown(t+1)?t+1 if(i>=0)h+=btn(tr('common.upgrade_port_price',{port:PORT[i].n,price:portMo(ixPortMo(c,i)*n)}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)); if(S.pops[city]&&!S.myIx[c]&&n=0){const c=NNI[i].mo*n;h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',{port:NNI[i].n,cost:fmt$(c),mo:fmt$(c)}):tr('common.upgrade_port_price_mo',{port:NNI[i].n,price:fmt$(c)}),'buyNni',{city,prov,tier:i},'sm',S.cash { + const { ev, errors } = open(); + ev(`S.pops.fra.rgen=${fast(5)};ACT.buyNni({city:"fra",prov:FB,tier:2});compute()`); + assert.ok(ev('portShown(3)'), 'an 800G port is on sale, so nothing stops the list from offering one'); + for (const [k, cf] of [['use', '{}'], ['k', "{k:'nni'}"]]) { + const h = ev(`UI.connSort='${k}';UI.connDir=-1;UI.cf=${cf};connSection()`); + assert.match(h, /data-act="lagNni"/, `sorted by ${k}`); + assert.doesNotMatch(h, /data-act="buyNni"/, `sorted by ${k}: no 800G fabric port`); + } + assert.deepEqual(errors, []); +}); From c52e7c774786692d5b6f3bbfce1006a0b46cf1ec Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 11 Nov 2026 15:44:08 +0100 Subject: [PATCH 14/18] Downgrade and chase connections from the NOC dashboard (#336) The Connections tab now has the POP panel's shrink buttons next to the upgrades: a downgrade to the next smaller port for transit, PNIs and IX ports, one LAG member less (also for NNIs), and Chase it for a PNI that is on order or waiting for a bigger port. Same actions and conditions as the panel; the NOC pop-out window runs them in the game. Fixes #336 --- CHANGELOG.md | 1 + src/game/94-dashboard/40-connections.js | 16 ++++- src/game/94-dashboard/90-noc-window.js | 2 +- tests/dashboard-connections.test.js | 78 +++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 tests/dashboard-connections.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d42c2b4..c1a76ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). - The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. +- The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). ## [3.4.0] — 2026-11-10 diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index 61caf58..66ba6ae 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -30,6 +30,18 @@ function connUp(r){if(r.mine)return '';const nx=t=>PORT[t+1]&&portShown(t+1)?t+1 if(i>=0){const c=NNI[i].mo*n;h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',{port:NNI[i].n,cost:fmt$(c),mo:fmt$(c)}):tr('common.upgrade_port_price_mo',{port:NNI[i].n,price:fmt$(c)}),'buyNni',{city,prov,tier:i},'sm',S.cashbtn(tr('link_panels.downgrade_port_price',{port,price}),act,args,'ghost sm'),less=(act,args)=>btn(tr('common.member'),act,{...args,d:-1},'ghost sm');let h=''; + if(r.k==='t'){const t=S.transit.find(x=>x.id===r.id);if(!t)return '';const n=t.n||1; + if(t.tier>0)h+=dn(PORT[t.tier-1].n,portMo(PORT[t.tier-1].tmo*n),'downT',{id:t.id});if(n>1)h+=less('lagT',{id:t.id});} + else if(r.k==='p'){const p=S.pni.find(x=>x.id===r.id);if(!p)return '';const n=p.n||1,chase=btn(tr('common.chase_it'),'pniChase',{id:p.id},'ghost sm'); + if(!pniOn(p))return chase; + if(p.up)h+=chase;else if(!p.g1&&p.tier>pniMin(p.net)&&!msfNope(p.net,p.city))h+=dn(PORT[p.tier-1].n,portMo(PORT[p.tier-1].pni*n),'downP',{id:p.id}); + if(n>1)h+=less('lagP',{id:p.id});} + else if(r.k==='ix'){const c=r.id,n=(S.ixn||{})[c]||1; + if(n>1)h+=less('lagIx',{city:c});if(S.ixp[c]>0)h+=dn(PORT[S.ixp[c]-1].n,portMo(ixPortMo(c,S.ixp[c]-1)*n),'downIx',{city:c});} + else if(r.k==='nni'){const [city,prov]=r.id.split('|'),pt=nniPort(city,prov);if(pt&&(pt.n||1)>1)h+=less('lagNni',{city,prov});} + return h;} function connX(r){if(r.mine)return '';const on=UI.confirm==='cc:'+r.k+':'+r.id; return btn(on?(r.k==='ix'?tr('common.really_leave'):r.k==='t'?tr('common.really_cancel'):tr('common.really_remove')):r.k==='ix'?tr('common.leave_ix'):r.k==='t'?tr('common.cancel'):r.k==='c'&&r.n>1?tr('common.box_6ee3'):r.k==='nni'?tr('common.remove_port'):tr('common.remove'),'connCancel',{k:r.k,id:r.id},on?'red sm':'ghost sm');} function connMatch(r,F){return (!F.k||r.k===F.k)&&(!F.city||r.city===F.city)&&(!F.net||r.net===F.net||(r.nets&&r.nets.includes(F.net)));} @@ -47,11 +59,11 @@ function connSection(){const all=conns(),F=UI.cf||{}; const tc=rows.reduce((a,r)=>a+r.cap,0),tu=rows.reduce((a,r)=>a+r.use,0),tm=rows.reduce((a,r)=>a+r.mo,0); if(isPhone()){const st=(r)=>r.down?` ${tr('common.down')}`:r.low?` ${tr('common.backup')}`:''; h+=`
${[['k',tr('common.type')],['city',tr('common.where')],['use',tr('common.in_use')],['mo',tr('common.per_month')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'connSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; - h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `
${N?logo(N):``}
${esc(r.name)} ${tr(CONN_K[r.k])}${st(r)}
${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('common.price_mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}
${tr('common.in_use')}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${r.mine?'':`
${connUp(r)}${connX(r)}
`}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}
`;}).join(''); + h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `
${N?logo(N):``}
${esc(r.name)} ${tr(CONN_K[r.k])}${st(r)}
${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('common.price_mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}
${tr('common.in_use')}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${r.mine?'':`
${connUp(r)}${connDown(r)}${connX(r)}
`}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}
`;}).join(''); return h+listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))+`
${trn('connections.n_connection',rows.length)}${fmtG(tu)} / ${fmtCap(Math.round(tc))} · ${tr('common.price_mo',{price:fmt$(tm)})}
`;} const th=(k,l,c)=>`${k?``:l}`; h+=`
${th('k',tr('common.type'))}${th('city',tr('common.where'))}${th('name',tr('common.with'))}${th('',tr('common.port'))}${th('use',tr('common.in_use'),'r')}${th('mo',tr('common.per_month'),'r')}`; - h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return ``;}).join(''); + h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return ``;}).join(''); h+=`
${tr(CONN_K[r.k])}${esc(CITY[r.city].name)}${N?logo(N):''}${esc(r.name)}${r.note?`
${esc(r.note)}`:''}
${esc(r.port)}${r.down?` ${tr('common.down')}`:r.low?` ${tr('common.backup')}`:''}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${fmt$(r.mo)}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connX(r)}
${tr(CONN_K[r.k])}${esc(CITY[r.city].name)}${N?logo(N):''}${esc(r.name)}${r.note?`
${esc(r.note)}`:''}
${esc(r.port)}${r.down?` ${tr('common.down')}`:r.low?` ${tr('common.backup')}`:''}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${fmt$(r.mo)}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connDown(r)}${connX(r)}
${trn('connections.n_connection',rows.length)}${fmtG(tu)} / ${fmtCap(Math.round(tc))}${fmt$(tm)}
${listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))}
`; return h;} // Where you connect to one network, as buttons that jump to the POP (Networks tab). diff --git a/src/game/94-dashboard/90-noc-window.js b/src/game/94-dashboard/90-noc-window.js index 49ff64b..fa956e0 100644 --- a/src/game/94-dashboard/90-noc-window.js +++ b/src/game/94-dashboard/90-noc-window.js @@ -6,7 +6,7 @@ const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000; // What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list. const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore','popsReg','popsSort']; -const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','mktCfg','mktHold','mktRoute','netFocus','opsOpen','pni','pniAllOpen','popGo']; +const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','downIx','downP','downT','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','mktCfg','mktHold','mktRoute','netFocus','opsOpen','pni','pniAllOpen','pniChase','popGo']; const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false}; {const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}} if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){} diff --git a/tests/dashboard-connections.test.js b/tests/dashboard-connections.test.js new file mode 100644 index 0000000..250cc07 --- /dev/null +++ b/tests/dashboard-connections.test.js @@ -0,0 +1,78 @@ +// #336: the NOC dashboard's connection list can shrink connections too (a smaller port, one LAG member fewer) and +// chase a PNI that is on order, with the same buttons and rules as the POP panel. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// A transit LAG, a live PNI LAG, a PNI on order and an IX LAG, all in Frankfurt, set up directly so nothing is left to luck. +const setup = () => { + const r = load(); + r.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.offers=[];S.nextFail=S.nextEvent=1e6;if(!S.pops.fra)ACT.buildPop({city:'fra'})"); + r.ev(`(()=>{const free=NETS.filter(n=>n.type!=='t1'&&n.type!=='cdn'&&n.pops.includes('fra')&&!msfNope(n.id,'fra')).map(n=>n.id); + S.transit=[{id:'t1',city:'fra',net:'cog',tier:2,n:2}]; + S.pni=[{id:'p1',city:'fra',net:free[0],tier:2,n:2,ready:0,site:'a',sacrif:false},{id:'p2',city:'fra',net:free[1],tier:1,n:1,ready:S.day+60,site:'a',sacrif:false}]; + const x=ixIdsIn('fra')[0];S.ixp={[x]:2};S.ixn={[x]:2};window.__ix=x;compute();})()`); + return r; +}; +const open = (ev, phone) => ev(`window.innerWidth=${phone ? 390 : 1280};UI.dtab='conn';ACT.connOpen()`); +// Every button in the list as act + args, to compare with what the POP panel offers. +const acts = (ev, sel) => JSON.parse(ev(`JSON.stringify([...document.querySelectorAll('${sel} [data-act]')].map(b=>b.dataset.act+' '+b.dataset.args))`)); +const has = (list, act, args) => list.includes(`${act} ${JSON.stringify(args)}`); + +for (const phone of [false, true]) { + test(`#336 the connection list offers downgrades and a chase (${phone ? 'phone' : 'desktop'})`, () => { + const { ev, errors } = setup(); + open(ev, phone); + const ix = ev('window.__ix'), a = acts(ev, '#connSec'); + assert.ok(has(a, 'downT', { id: 't1' }) && has(a, 'lagT', { id: 't1', d: -1 }), 'transit: smaller port, one member fewer'); + assert.ok(has(a, 'downP', { id: 'p1' }) && has(a, 'lagP', { id: 'p1', d: -1 }), 'PNI: smaller port, one member fewer'); + assert.ok(has(a, 'pniChase', { id: 'p2' }), 'a PNI on order can be chased'); + assert.ok(!has(a, 'pniChase', { id: 'p1' }) && !has(a, 'downP', { id: 'p2' }), 'no chase for a live PNI, no downgrade for one on order'); + assert.ok(has(a, 'downIx', { city: ix }) && has(a, 'lagIx', { city: ix, d: -1 }), 'IX: smaller port, one member fewer'); + assert.match(ev("document.getElementById('connSec').textContent"), /Downgrade 100G/); + assert.deepEqual(errors, []); + }); +} + +test('#336 the buttons in the list do what the POP panel buttons do', () => { + const { ev, errors } = setup(); + const ix = ev('window.__ix'); + open(ev, false); + const click = (act, args) => { + const ok = ev(`(()=>{const b=[...document.querySelectorAll('#connSec [data-act]')].find(b=>b.dataset.act===${JSON.stringify(act)}&&b.dataset.args===${JSON.stringify(JSON.stringify(args))});if(!b)return false;b.click();return true})()`); + assert.ok(ok, `${act} ${JSON.stringify(args)} is in the list`); + open(ev, false); + }; + click('downT', { id: 't1' }); + assert.equal(ev("S.transit[0].tier"), 1); + click('lagT', { id: 't1', d: -1 }); + assert.equal(ev("S.transit[0].n||1"), 1); + click('downP', { id: 'p1' }); + assert.equal(ev("S.pni.find(p=>p.id==='p1').tier"), 1); + click('lagP', { id: 'p1', d: -1 }); + assert.equal(ev("S.pni.find(p=>p.id==='p1').n||1"), 1); + click('downIx', { city: ix }); + assert.equal(ev(`S.ixp['${ix}']`), 1); + click('lagIx', { city: ix, d: -1 }); + assert.equal(ev(`(S.ixn||{})['${ix}']||1`), 1); + // A chase that lands takes a month off the wait, as from the POP panel. + const ready = ev("S.pni.find(p=>p.id==='p2').ready"); + ev("Math.random=()=>0"); + click('pniChase', { id: 'p2' }); + assert.equal(ev("S.pni.find(p=>p.id==='p2').ready"), Math.max(ev('S.day') + 1, ready - 30)); + // No more members to take away: those buttons go away. + const a = acts(ev, '#connSec'); + assert.ok(!has(a, 'lagT', { id: 't1', d: -1 }) && !has(a, 'lagP', { id: 'p1', d: -1 }) && !has(a, 'lagIx', { city: ix, d: -1 })); + assert.deepEqual(errors, []); +}); + +test('#336 the list offers the same downgrades as the POP panel', () => { + const { ev, errors } = setup(); + open(ev, false); + const dash = acts(ev, '#connSec').filter(x => /^(downT|lagT|downIx|lagIx) /.test(x) && !x.includes('"d":1')); + ev("UI.sel={type:'city',id:'fra'};UI.tab='up';renderPanel()"); + const panel = acts(ev, '#panelBody').filter(x => /^(downT|lagT) /.test(x) && !x.includes('"d":1')); + assert.ok(panel.length >= 2, `the POP panel shows the transit downgrades: ${panel}`); + for (const x of panel) assert.ok(dash.includes(x), `${x} is in the list too`); + assert.deepEqual(errors, []); +}); From 2b8bd1c4021fbf94610683b6e536bf600824bebc Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 11 Nov 2026 15:44:08 +0100 Subject: [PATCH 15/18] Start a link by typing the city it goes to (#343) A POP's Infra tab gets Link to a city: it opens the city finder in link mode, which offers only cities a link from there could end in, and picking one (or Enter) opens the same link window as dragging between the two on the map. Much easier than finding a far-away city on a crowded phone screen. Fixes #343 --- CHANGELOG.md | 1 + site/i18n/de.js | 3 + site/i18n/es.js | 3 + site/i18n/fr.js | 3 + site/i18n/it.js | 3 + site/i18n/pt.js | 3 + src/agent/20-commands.js | 2 + src/game/90-actions/10-interface.js | 3 + src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/80-find-city.js | 24 ++++---- src/i18n/en.js | 3 + tests/city-picker.test.js | 91 +++++++++++++++++++++++++++++ 12 files changed, 130 insertions(+), 11 deletions(-) create mode 100644 tests/city-picker.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c1a76ed..7f21af3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). - The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. +- You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). - The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). ## [3.4.0] — 2026-11-10 diff --git a/site/i18n/de.js b/site/i18n/de.js index 7c74d70..f40d866 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1035,6 +1035,7 @@ "city_panel.ix_members_on_ix_n":"IX-Mitglieder am {ix}: {n}", "city_panel.ix_switch":"{ix}-Switch", "city_panel.launch_broadband_cost":"Breitband starten {cost}", +"city_panel.link_to_a_city":"🔗 Link zu einer Stadt…", "city_panel.make_sacrificial_contains_floods_1_2":"Als Opfer-Link nutzen hält Fluten auf · ½ Kapazität", "city_panel.maxed_out_traffic_here_is_being":"Am Limit. Traffic wird hier verworfen.", "city_panel.model_level_lv":"{model} Level {lv}", @@ -2230,7 +2231,9 @@ "find.city_country_or_exchange":"Stadt, Land oder Austauschknoten", "find.find_a_city":"Stadt finden", "find.find_a_city_slash":"Stadt finden (/)", +"find.link_from_city":"Neuer Link ab {city}", "find.no_city_matches_q":"Keine Stadt passt zu „{q}“.", +"find.pick_where_the_link_goes":"Wähl, wohin der Link geht: genau wie das Ziehen von diesem POP zu der Stadt auf der Karte.", "find.press_slash_to_search_from":"Tipp: Drück irgendwo auf der Karte /, um zu suchen.", "find.type_a_city_a_country":"Gib eine Stadt, ein Land oder einen Austauschknoten ein.", "find.your_pop":"dein POP", diff --git a/site/i18n/es.js b/site/i18n/es.js index fb83a1a..fa8f3fe 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1033,6 +1033,7 @@ "city_panel.ix_members_on_ix_n":"Miembros del IX en {ix}: {n}", "city_panel.ix_switch":"Switch de {ix}", "city_panel.launch_broadband_cost":"Lanzar banda ancha {cost}", +"city_panel.link_to_a_city":"🔗 Enlace a una ciudad…", "city_panel.make_sacrificial_contains_floods_1_2":"Hacer de sacrificio contiene inundaciones · ½ de capacidad", "city_panel.maxed_out_traffic_here_is_being":"Al límite. Aquí se está descartando tráfico.", "city_panel.model_level_lv":"{model} nivel {lv}", @@ -2228,7 +2229,9 @@ "find.city_country_or_exchange":"Ciudad, país o punto de intercambio", "find.find_a_city":"Buscar una ciudad", "find.find_a_city_slash":"Buscar una ciudad (/)", +"find.link_from_city":"Nuevo enlace desde {city}", "find.no_city_matches_q":"Ninguna ciudad coincide con «{q}».", +"find.pick_where_the_link_goes":"Elige adónde va el enlace: igual que arrastrar desde este POP hasta esa ciudad en el mapa.", "find.press_slash_to_search_from":"Consejo: pulsa / en cualquier parte del mapa para buscar.", "find.type_a_city_a_country":"Escribe una ciudad, un país o un punto de intercambio.", "find.your_pop":"tu POP", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index a82d4bc..a0c5da4 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1033,6 +1033,7 @@ "city_panel.ix_members_on_ix_n":"Membres de l’IX sur {ix} : {n}", "city_panel.ix_switch":"Switch {ix}", "city_panel.launch_broadband_cost":"Lancer le haut débit {cost}", +"city_panel.link_to_a_city":"🔗 Lien vers une ville…", "city_panel.make_sacrificial_contains_floods_1_2":"Rendre sacrificiel contient les floods · ½ capacité", "city_panel.maxed_out_traffic_here_is_being":"Saturé. Du trafic est perdu ici.", "city_panel.model_level_lv":"{model} niveau {lv}", @@ -2228,7 +2229,9 @@ "find.city_country_or_exchange":"Ville, pays ou point d'échange", "find.find_a_city":"Trouver une ville", "find.find_a_city_slash":"Trouver une ville (/)", +"find.link_from_city":"Nouveau lien depuis {city}", "find.no_city_matches_q":"Aucune ville ne correspond à « {q} ».", +"find.pick_where_the_link_goes":"Choisissez où va le lien : comme si vous le tiriez de ce POP jusqu'à cette ville sur la carte.", "find.press_slash_to_search_from":"Astuce : appuyez sur / n'importe où sur la carte pour chercher.", "find.type_a_city_a_country":"Tapez une ville, un pays ou un point d'échange.", "find.your_pop":"votre POP", diff --git a/site/i18n/it.js b/site/i18n/it.js index 4175c0b..b91a205 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1033,6 +1033,7 @@ "city_panel.ix_members_on_ix_n":"Membri IX su {ix}: {n}", "city_panel.ix_switch":"Switch di {ix}", "city_panel.launch_broadband_cost":"Lancia la banda larga {cost}", +"city_panel.link_to_a_city":"🔗 Link verso una città…", "city_panel.make_sacrificial_contains_floods_1_2":"Rendi sacrificale contiene i flood · ½ capacità", "city_panel.maxed_out_traffic_here_is_being":"Al limite. Qui il traffico viene scartato.", "city_panel.model_level_lv":"{model} livello {lv}", @@ -2228,7 +2229,9 @@ "find.city_country_or_exchange":"Città, paese o exchange", "find.find_a_city":"Trova una città", "find.find_a_city_slash":"Trova una città (/)", +"find.link_from_city":"Nuovo link da {city}", "find.no_city_matches_q":"Nessuna città corrisponde a “{q}”.", +"find.pick_where_the_link_goes":"Scegli dove va il link: come trascinarlo da questo POP fino a quella città sulla mappa.", "find.press_slash_to_search_from":"Suggerimento: premi / ovunque sulla mappa per cercare.", "find.type_a_city_a_country":"Scrivi una città, un paese o un exchange.", "find.your_pop":"il tuo POP", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 6f55b36..351a39a 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1033,6 +1033,7 @@ "city_panel.ix_members_on_ix_n":"Membros do IX em {ix}: {n}", "city_panel.ix_switch":"Switch do {ix}", "city_panel.launch_broadband_cost":"Lançar banda larga {cost}", +"city_panel.link_to_a_city":"🔗 Link para uma cidade…", "city_panel.make_sacrificial_contains_floods_1_2":"Tornar sacrificial contém floods · ½ capacidade", "city_panel.maxed_out_traffic_here_is_being":"No limite. O tráfego aqui está sendo descartado.", "city_panel.model_level_lv":"{model} nível {lv}", @@ -2228,7 +2229,9 @@ "find.city_country_or_exchange":"Cidade, país ou exchange", "find.find_a_city":"Encontrar uma cidade", "find.find_a_city_slash":"Encontrar uma cidade (/)", +"find.link_from_city":"Novo link a partir de {city}", "find.no_city_matches_q":"Nenhuma cidade corresponde a “{q}”.", +"find.pick_where_the_link_goes":"Escolha para onde vai o link: o mesmo que arrastar deste POP até essa cidade no mapa.", "find.press_slash_to_search_from":"Dica: pressione / em qualquer lugar do mapa para pesquisar.", "find.type_a_city_a_country":"Digite uma cidade, um país ou um exchange.", "find.your_pop":"seu POP", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 0e7fdc6..66fdc51 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -537,6 +537,8 @@ const API_VIEW={ linkCheck:{args:[['id','entityId']],doc:'Open the redundancy check for a link: what a single cut would drop, without changing anything.'}, findOpen:{args:[],doc:'Open the city finder (the 🔍 in the top bar).'}, findGo:{args:[['city','cityId']],doc:'Close the finder and jump to a city.'}, + findLink:{args:[['city','cityId']],doc:'Open the city finder to pick where a new link from this POP goes (the "Link to a city" button in its panel).'}, + linkTo:{args:[['a','cityId'],['b','cityId']],doc:'From the link finder: open the new-link window from POP a to city b, as dragging between them would.'}, popStep:{args:[['d','integer']],doc:'Select and centre the previous (d<0) or next (d>0) of your POPs, by name: the [ and ] keys.'}, offerStep:{args:[],doc:'Select the next open offer (soonest to expire first), centre its city and mark it under Offers here: the $ key.'}, zoomStep:{args:[['d','integer']],doc:'Zoom the map out (d<0) or in (d>0) around its middle: the - and = keys.'}, diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 7a0715e..e80beef 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -49,6 +49,9 @@ const ACT={ logAll:()=>{UI.logAll=!UI.logAll;renderLeft();}, findOpen:()=>findOpen(), findGo:({city})=>{if(!isCity(city))return;closeModal();$('dash').hidden=true;ACT.focusCity({city});}, + // A link from one of your POPs to a city you type instead of dragging to (#343): the same window the drag opens. + findLink:({city})=>{if(!isCity(city)||!S.pops[city]||pzOn())return;findOpen(city);}, + linkTo:({a,b})=>{if(!isCity(a)||!isCity(b)||a===b||pzOn()||!linkFromOk(a)||!linkToOk(b))return;$('dash').hidden=true;sfx('click');openLinkModal(a,b);}, focusCity:({city})=>{selectCity(city);const C=CITY[city];cam.x=C.x;cam.y=C.y;cam.z=Math.max(cam.z,1.2);if(innerWidth<760)UI.leftOpen=false;renderLeft();}, popStep:({d})=>{const L=popOrder(),n=L.length;if(!n)return;const i=UI.sel&&UI.sel.type==='city'?L.indexOf(UI.sel.id):-1;$('dash').hidden=true;ACT.focusCity({city:L[i<0?(d>0?0:n-1):(i+(d>0?1:n-1))%n]});}, // The offer stays marked in its city's Offers here until something else is selected, so two offers in one city each get a press. diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 9838389..3dee74e 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -103,7 +103,7 @@ function cityPanel(c){ else h+=`
${NNI.map((N,i)=>portShown(i)?btn(tr('city_panel.port_port_price_mo_197d',{port:N.n,price:fmt$(N.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash`; h+=`
`;} h+=``;} - h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

`; + h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

${btn(tr('city_panel.link_to_a_city'),'findLink',{city:c},'sm')}
`; if(!ls.length)h+=`

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} diff --git a/src/game/93-ui/80-find-city.js b/src/game/93-ui/80-find-city.js index 4f14971..de0080f 100644 --- a/src/game/93-ui/80-find-city.js +++ b/src/game/93-ui/80-find-city.js @@ -9,22 +9,26 @@ function findIndex(){if(FIND_IX)return FIND_IX;let dn=null,en=null;try{dn=new In const cn=(d,cc)=>{try{return d?d.of(cc)||'':'';}catch(e){return '';}}; FIND_IX=Object.values(CITY).map(C=>{const land=cn(dn,C.cc)||C.cc||'';return {id:C.id,name:fold(C.name),land,ctry:fold(land+' '+cn(en,C.cc)+' '+(C.cc||'')),xtra:fold((C.ix||'')+' '+(C.dc||''))};});return FIND_IX;} // Best matches first: the name starts with it, a word of the name does, the name has it, then country, then exchange or DC. -function findCities(q){q=fold(q);const mine=c=>S&&S.pops&&S.pops[c]?0:1; - if(!q)return S&&S.pops?Object.keys(S.pops).filter(isCity).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).slice(0,FIND_N):[]; - const out=[];for(const e of findIndex()){const n=e.name; +// With from (#343, a link from that POP), only cities a link could end in: not from itself, and only those the map shows. +function findCities(q,from){q=fold(q);const mine=c=>S&&S.pops&&S.pops[c]?0:1,ok=c=>!from||(c!==from&&cityOn(c)); + if(!q)return S&&S.pops?Object.keys(S.pops).filter(c=>isCity(c)&&ok(c)).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).slice(0,FIND_N):[]; + const out=[];for(const e of findIndex()){const n=e.name;if(!ok(e.id))continue; const s=n.startsWith(q)?0:n.split(/[\s\-.'()]+/).some(w=>w.startsWith(q))?1:n.includes(q)?2:e.ctry.includes(q)?3:e.xtra.includes(q)?4:-1; if(s>=0)out.push([s,mine(e.id),-(CITY[e.id].P||0),e.id]);} return out.sort((a,b)=>a[0]-b[0]||a[1]-b[1]||a[2]-b[2]).slice(0,FIND_N).map(r=>r[3]);} -function findRows(q){const ids=findCities(q),land=c=>(findIndex().find(e=>e.id===c)||{}).land||''; +function findRows(q,from){const ids=findCities(q,from),land=c=>(findIndex().find(e=>e.id===c)||{}).land||''; if(!ids.length)return `

${q.trim()?tr('find.no_city_matches_q',{q:esc(q.trim())}):tr('find.type_a_city_a_country')}

`; return ids.map((c,i)=>{const C=CITY[c],p=S&&S.pops&&S.pops[c]; - return ``;}).join('');} -function findOpen(){if(!S||!UI.started)return; - openModal(`

🔍 ${tr('find.find_a_city')}

-
${findRows('')}
${isPhone()?'':`

${tr('find.press_slash_to_search_from')}

`}`,'find'); + return ``;}).join('');} +/* The same box picks where a new link from one of your POPs goes (#343): on a crowded phone map, dragging from a POP + to a city far away is fiddly, so you type the other end and get the link window the drag would have opened. */ +function findOpen(from){if(!S||!UI.started)return;from=from&&S.pops[from]?from:null;UI.findFrom=from; + const title=from?tr('find.link_from_city',{city:CITY[from].name}):tr('find.find_a_city'); + openModal(`

${from?'🔗':'🔍'} ${esc(title)}

+
${findRows('',from)}
${from?`

${tr('find.pick_where_the_link_goes')}

`:isPhone()?'':`

${tr('find.press_slash_to_search_from')}

`}`,'find'); const el=$('findIn');if(el)el.focus();} -document.addEventListener('input',e=>{if(e.target.id!=='findIn')return;const L=$('findList');if(L)L.innerHTML=findRows(e.target.value);}); +document.addEventListener('input',e=>{if(e.target.id!=='findIn')return;const L=$('findList');if(L)L.innerHTML=findRows(e.target.value,UI.findFrom);}); document.addEventListener('keydown',e=>{ - if(e.target.id==='findIn'){if(e.key==='Escape'){closeModal();return;}if(e.key==='Enter'){e.preventDefault();const c=findCities(e.target.value)[0];if(c)ACT.findGo({city:c});}return;} + if(e.target.id==='findIn'){if(e.key==='Escape'){closeModal();return;}if(e.key==='Enter'){e.preventDefault();const f=UI.findFrom,c=findCities(e.target.value,f)[0];if(c){if(f)ACT.linkTo({a:f,b:c});else ACT.findGo({city:c});}}return;} if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey||(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]')))return; if(!S||!UI.started||!$('modal').hidden)return;e.preventDefault();findOpen();}); diff --git a/src/i18n/en.js b/src/i18n/en.js index 4c089e8..1aaee9b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1034,6 +1034,7 @@ "city_panel.ix_members_on_ix_n":"IX members on {ix}: {n}", "city_panel.ix_switch":"{ix} switch", "city_panel.launch_broadband_cost":"Launch broadband {cost}", +"city_panel.link_to_a_city":"🔗 Link to a city…", "city_panel.make_sacrificial_contains_floods_1_2":"Make sacrificial contains floods · ½ capacity", "city_panel.maxed_out_traffic_here_is_being":"Maxed out. Traffic here is being dropped.", "city_panel.model_level_lv":"{model} level {lv}", @@ -2229,7 +2230,9 @@ "find.city_country_or_exchange":"City, country or exchange", "find.find_a_city":"Find a city", "find.find_a_city_slash":"Find a city (/)", +"find.link_from_city":"New link from {city}", "find.no_city_matches_q":"No city matches “{q}”.", +"find.pick_where_the_link_goes":"Pick where the link goes: the same as dragging from this POP to that city on the map.", "find.press_slash_to_search_from":"Tip: press / anywhere on the map to search.", "find.type_a_city_a_country":"Type a city, a country or an exchange.", "find.your_pop":"your POP", diff --git a/tests/city-picker.test.js b/tests/city-picker.test.js new file mode 100644 index 0000000..15099fd --- /dev/null +++ b/tests/city-picker.test.js @@ -0,0 +1,91 @@ +// #343: on a crowded phone map, dragging from a POP to a city far away is fiddly. A POP's panel can open the city +// finder in link mode: type the other end, pick it, and get the same link window the drag would have opened. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const start = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.nextFail=1e9;S.nextEvent=1e9;S.cash=1e9"; +const home = ev => ev("Object.keys(S.pops)[0]"); + +test('#343 a POP panel has a Link to a city button that opens the finder in link mode', () => { + const { ev, dom, errors } = load(); + ev(start); + const a = home(ev); + ev(`UI.sel={type:'city',id:${lit(a)}};UI.tab='links';renderPanel()`); + const doc = dom.window.document; + const b = [...doc.querySelectorAll('#panelBody [data-act="findLink"]')]; + assert.equal(b.length, 1, 'one button in the fiber section'); + assert.match(b[0].textContent, /Link to a city/); + b[0].click(); + assert.equal(ev("$('modal').hidden"), false); + assert.equal(ev("$('modal').className"), 'find'); + assert.match(doc.getElementById('modalCard').textContent, new RegExp(`New link from ${ev(`CITY[${lit(a)}].name`)}`)); + // Rows open the link window, not the map jump. + ev("$('findIn').value='sydney';$('findIn').dispatchEvent(new Event('input',{bubbles:true}))"); + const row = doc.querySelector('#findList .findrow'); + assert.equal(row.dataset.act, 'linkTo'); + assert.deepEqual(JSON.parse(row.dataset.args), { a, b: 'syd' }); + assert.deepEqual(errors, []); +}); + +test('#343 picking a city opens the same link window as dragging there, and Enter picks the first match', () => { + const { ev, dom, errors } = load(); + ev(start); + const a = home(ev), doc = dom.window.document; + const b = a === 'syd' ? 'tyo' : 'syd'; + ev(`ACT.findLink({city:${lit(a)}})`); + ev(`$('findIn').value=CITY[${lit(b)}].name;$('findIn').dispatchEvent(new Event('input',{bubbles:true}))`); + doc.querySelector('#findList .findrow').click(); + assert.deepEqual(JSON.parse(ev("JSON.stringify(UI.pending)")), { a, b }); + const viaPicker = doc.getElementById('modalCard').textContent; + assert.match(viaPicker, new RegExp(`${ev(`CITY[${lit(a)}].name`)} → ${ev(`CITY[${lit(b)}].name`)}`)); + ev(`closeModal();openLinkModal(${lit(a)},${lit(b)})`); + assert.equal(doc.getElementById('modalCard').textContent, viaPicker, 'exactly what the drag opens'); + // Typing without accents and pressing Enter. + ev(`closeModal();ACT.findLink({city:${lit(a)}});$('findIn').value='SAO PAULO'`); + doc.getElementById('findIn').dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + assert.deepEqual(JSON.parse(ev("JSON.stringify(UI.pending)")), { a, b: 'sao' }); + // The plain finder still jumps the map. + ev("closeModal();ACT.findOpen()"); + assert.equal(ev("UI.findFrom"), null); + ev("$('findIn').value='sydney';$('findIn').dispatchEvent(new Event('input',{bubbles:true}))"); + assert.equal(doc.querySelector('#findList .findrow').dataset.act, 'findGo'); + assert.deepEqual(errors, []); +}); + +test('#343 only cities a link could end in are offered: not the POP itself, not cities the map does not show', () => { + const { ev, errors } = load(); + ev(start); + const a = home(ev); + assert.equal(ev(`findCities(${lit(ev(`CITY[${lit(a)}].name`))},${lit(a)}).includes(${lit(a)})`), false, 'not itself'); + assert.equal(ev("cityOn('aju')"), false, 'Aracaju is off the map'); + assert.equal(ev(`findCities('aracaju',${lit(a)}).includes('aju')`), false); + assert.equal(ev("findCities('aracaju').includes('aju')"), true, 'the plain finder still finds it'); + // An empty box lists your other POPs. + ev("ACT.buildPop({city:'syd'})"); + assert.deepEqual(ev(`findCities('',${lit(a)}).join()`).split(',').filter(Boolean), ev(`Object.keys(S.pops).filter(c=>c!==${lit(a)}).sort((x,y)=>CITY[x].name.localeCompare(CITY[y].name)).join()`).split(',').filter(Boolean)); + // Typed orders that make no sense do nothing. + ev(`ACT.linkTo({a:${lit(a)},b:${lit(a)}})`); + assert.equal(ev("$('modal').hidden"), true); + ev("ACT.linkTo({a:'atlantis',b:'syd'})"); + assert.equal(ev("$('modal').hidden"), true); + ev(`ACT.linkTo({a:${lit(a)},b:'aju'})`); + assert.equal(ev("$('modal').hidden"), true, 'a city off the map takes no link'); + ev("ACT.findLink({city:'aju'})"); + assert.equal(ev("$('modal').hidden"), true, 'no finder from a city without a POP'); + assert.deepEqual(errors, []); +}); + +test('#343 the link finder works on a phone, in German', () => { + const { ev, dom, errors } = load({ lang: 'de' }); + ev(start + ";window.innerWidth=360"); + const a = home(ev); + ev(`UI.sel={type:'city',id:${lit(a)}};UI.tab='links';renderPanel()`); + const doc = dom.window.document; + assert.match(doc.getElementById('panelBody').textContent, /Link zu einer Stadt/); + ev(`ACT.findLink({city:${lit(a)}})`); + assert.match(doc.getElementById('modalCard').textContent, /Neuer Link ab/); + assert.ok(ev("findCities('deutschland'," + lit(a) + ").includes('fra')") || a === 'fra'); + assert.deepEqual(errors, []); +}); From 727c8f8500c1ebf12cfcaf62025e2f95999da979 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 11 Nov 2026 15:54:20 +0100 Subject: [PATCH 16/18] Connections list: look up the next port size in each port's own table nx() now takes the size table it should look in, so fabric ports ask NNI (up to 400G) instead of special-casing the 400G port. Adds the PR number to the #342 CHANGELOG bullet. --- CHANGELOG.md | 2 +- src/game/94-dashboard/40-connections.js | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f21af3..047e2a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). -- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. +- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342) - You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). - The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index 66ba6ae..7234dc8 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -15,7 +15,8 @@ function conns(){const out=[],pn=(tier,n)=>(n||1)>1?`${n}×${PORT[tier].n} LAG`: return out;} // Cancel straight from the list, with the same "Really?" step as the POP panel. // Grow a connection from the list: the next port size and one more LAG member, same actions and prices as the POP panel. -function connUp(r){if(r.mine)return '';const nx=t=>PORT[t+1]&&portShown(t+1)?t+1:-1;let h=''; +// nx looks up the next size in that kind of port's own table: fabric ports (NNI) stop at 400G. +function connUp(r){if(r.mine)return '';const nx=(t,T=PORT)=>T[t+1]&&portShown(t+1)?t+1:-1;let h=''; if(r.k==='t'){const t=S.transit.find(x=>x.id===r.id);if(!t)return '';const n=t.n||1,i=nx(t.tier); if(i>=0){const a={port:PORT[i].n,cost:fmt$(PORT[i].setup*n),mo:fmt$(PORT[i].tmo*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'buyTransit',{city:t.city,net:t.net,tier:i},'sm',S.cashPORT[t+1]&&portShown(t+1)?t+1 if(i>=0)h+=btn(tr('common.upgrade_port_price',{port:PORT[i].n,price:portMo(ixPortMo(c,i)*n)}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)); if(S.pops[city]&&!S.myIx[c]&&n=0){const c=NNI[i].mo*n;h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',{port:NNI[i].n,cost:fmt$(c),mo:fmt$(c)}):tr('common.upgrade_port_price_mo',{port:NNI[i].n,price:fmt$(c)}),'buyNni',{city,prov,tier:i},'sm',S.cash Date: Wed, 11 Nov 2026 15:59:04 +0100 Subject: [PATCH 17/18] Type a city to start a link, downgrade from the NOC dashboard, and fixes (3.5.0) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 047e2a1..5b54c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [3.5.0] — 2026-11-11 + - Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). - The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342) - You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). diff --git a/package-lock.json b/package-lock.json index 376d165..6ebb8ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "3.4.0", + "version": "3.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "3.4.0", + "version": "3.5.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index b87e2ae..ddb9b4a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "3.4.0", + "version": "3.5.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From 9c26d03952fdcb8ce650c6273b82ca19a92d7b8e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 11 Nov 2026 18:37:18 +0100 Subject: [PATCH 18/18] Conferences stop notifying once you are Tier 1 (#101) After the Tier 1 goal, the 30-day reminders, the report (and its coin sound) on the day and the sales engineer's booking notes are no longer shown or logged. Registering, sponsoring, the glow, raffles and capacity deals work as before, and the Deals tab still lists conferences. Fixes #101 --- CHANGELOG.md | 1 + src/game/60-features/30-conferences.js | 8 +++-- src/game/60-features/38-sales-desk.js | 2 +- tests/conference-quiet.test.js | 45 ++++++++++++++++++++++++++ tests/modes.test.js | 3 +- 5 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 tests/conference-quiet.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b54c7a..17e4bfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to this project are documented here. The project follows - The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342) - You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). - The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). +- Once you have made Tier 1, conferences stop sending notifications. No more 30-day reminders, reports from the hallway track or notes from your sales engineer about bookings; you can still register and sponsor from the Deals tab, and everything a conference does works as before (#101). ## [3.4.0] — 2026-11-10 diff --git a/src/game/60-features/30-conferences.js b/src/game/60-features/30-conferences.js index c3cc0eb..1fa63bd 100644 --- a/src/game/60-features/30-conferences.js +++ b/src/game/60-features/30-conferences.js @@ -11,12 +11,14 @@ function confKey(cf,y){return cf.n+'@'+cf.c+'@'+y;} // No conference season in Best Effort: nothing to register for, nothing in the panel, no invitations. function upcomingConfs(within){if(!confsOn())return [];const y0=cal(S.day).y-1,out=[];for(const y of [y0,y0+1])for(const cf of CONFS){const d=confDay(cf,y);if(d>=S.day&&d-S.day<=within)out.push({...cf,day:d,key:confKey(cf,y)});}return out.sort((a,b)=>a.day-b.day);} function confBoost(id){const cb=S.conf;if(!cb||!(cb.until>S.day))return 1;const n=NET[id];return n&&n.pops.some(c=>CITY[c]&&CITY[c].reg===cb.reg)?0.5:1;} -function confTick(d){S.confReg=S.confReg||{}; - for(const cf of upcomingConfs(30)){if(cf.day-d===30&&!S.confReg[cf.key])toast(tr('conferences.conf_comes_to_city_in_30',{conf:esc(cf.n),city:esc(CITY[cf.c].name)}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);} +// Once you have made Tier 1, conferences go quiet (#101): no reminders and no reports, only the Deals panel. +const confQuiet=()=>!!(S.done&&S.done.t1!==undefined); +function confTick(d){S.confReg=S.confReg||{};const q=confQuiet(); + for(const cf of upcomingConfs(30)){if(!q&&cf.day-d===30&&!S.confReg[cf.key])toast(tr('conferences.conf_comes_to_city_in_30',{conf:esc(cf.n),city:esc(CITY[cf.c].name)}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);} for(const cf of upcomingConfs(0)){if(cf.day!==d||!S.confReg[cf.key])continue;const reg=CITY[cf.c].reg,sp=S.confReg[cf.key]==='sp';S.conf={until:d+CONF_DAYS,reg,name:cf.n,sp};S.stats.confs=(S.stats.confs||0)+1;if(sp)S.stats.confSp=(S.stats.confSp||0)+1; if(cf.cap)S.capDeal={at:d+4+Math.floor(Math.random()*5),c:cf.c}; const r=Math.random();let extra='';if(r<0.3){const cash=5000+Math.floor(Math.random()*4)*5000;S.cash+=cash;extra=' '+tr('conferences.you_also_won_the_raffle_cash',{cash:fmt$(cash)});}else if(r<0.5)extra=' '+tr('conferences.someone_from_goggle_bought_you_a');if(cf.j)extra=' '+tr(cf.j)+(r<0.3?extra:''); - toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');} + if(!q){toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');}} capDealTick(d);} function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return ''; return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js index a76a30f..2333630 100644 --- a/src/game/60-features/38-sales-desk.js +++ b/src/game/60-features/38-sales-desk.js @@ -58,7 +58,7 @@ function salesDay(d){const L=S.sales;if(!L)return; if(L.vp&&d>=L.vp){L.p=null;L.vp=null;toast(tr('sales.vp_arrived'),'good',[{l:tr('sales.desk'),act:'salesOpen',args:{}}]);return;} const p=slP();if(!p)return; if(p==='eng')for(const cf of upcomingConfs(30)){if(cf.cap||cf.day-d!==30||(S.confReg||{})[cf.key])continue; - if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}} + if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;if(!confQuiet())toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}} if(p==='ceo'){if(!(L.golf>=d))L.golf=d+50+Math.floor(slR('golf|'+d)*30);else if(d===L.golf){salesGolf(d);L.golf=d+50+Math.floor(slR('golf|'+d)*30);} if(!(L.say>=d))L.say=d+20+Math.floor(slR('say|'+d)*15);else if(d===L.say){toast(tr('sales.ceo_says',{say:tr(SALES_SAY[Math.floor(slR('sayl|'+d)*SALES_SAY.length)])}),'');L.say=d+20+Math.floor(slR('say|'+d)*15);}}} // The golf course: the biggest internet customer this network can take, in its biggest city, at 30% off, signed on the spot. diff --git a/tests/conference-quiet.test.js b/tests/conference-quiet.test.js new file mode 100644 index 0000000..4ffcebd --- /dev/null +++ b/tests/conference-quiet.test.js @@ -0,0 +1,45 @@ +// #101: once you have made Tier 1, conferences stop announcing themselves: no 30-day reminders, no report when one +// happens, no note from the sales engineer who booked it. What they do is unchanged, and the Deals panel still lists them. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const setup = t1 => { + const r = load(); + r.ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + r.ev(t1 ? 'S.done.t1=1' : 'delete S.done.t1'); + // Record every notification the conference code raises (toasts land in the NOC log too, so this catches both). + r.ev("window.__t=[];const __o=toast;toast=(h,...a)=>{__t.push(String(h));return __o(h,...a)}"); + return r; +}; +// A non-capacity conference: the day 30 days before it, and the day itself. +const CF = "CONFS.find(c=>!c.cap)"; +const run = (ev, reg) => ev(`(()=>{const cf=${CF},d=confDay(cf,0),k=confKey(cf,0); + S.day=d-30;confTick(d-30);${reg ? "S.confReg[k]=true;" : ''}S.day=d;confTick(d);return JSON.stringify(window.__t)})()`); + +test('#101 before Tier 1, conferences still remind you and report back', () => { + const { ev, errors } = setup(false); + const t = JSON.parse(run(ev, true)); + assert.ok(t.some(h => /comes to .* in 30 days/.test(h)), 'the 30-day reminder'); + assert.ok(t.some(h => /You shook a lot of hands/.test(h)), 'the report on the day'); + assert.deepEqual(errors, []); +}); + +test('#101 after Tier 1, conferences say nothing, but attending still works and the Deals panel still lists them', () => { + const { ev, errors } = setup(true); + const t = JSON.parse(run(ev, true)); + assert.deepEqual(t, [], 'no reminder and no report'); + assert.ok(ev('!!(S.conf&&S.conf.until>S.day)'), 'the conference still gave its glow'); + assert.ok(ev(`(()=>{S.day=confDay(${CF},1)-20;return /Attend/.test(confSection())})()`), 'still listed in Deals'); + assert.deepEqual(errors, []); +}); + +test('#101 after Tier 1, a sales engineer still books conferences, without telling you each time', () => { + const { ev, errors } = setup(true); + // Hand the desk an engineer and run the desk on the day 30 days before the next conference. + const booked = ev(`(()=>{const cf=${CF},d=confDay(cf,1),k=confKey(cf,1);S.day=d-30; + S.sales={p:'eng'};S.confReg={};salesDay(d-30);return !!S.confReg[k]})()`); + assert.equal(booked, true, 'the booking still happens'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(window.__t)')), []); + assert.deepEqual(errors, []); +}); diff --git a/tests/modes.test.js b/tests/modes.test.js index 77fe3b1..99033bc 100644 --- a/tests/modes.test.js +++ b/tests/modes.test.js @@ -377,7 +377,8 @@ test('Flood Season: attacks keep coming, grow, and only count when service held' test('DKNOG in Copenhagen is on the conference calendar', () => { const { ev, errors } = load(); - ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0"); + // Not Tier 1 yet: after that, conferences no longer report back (#101). + ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1"); const cf = JSON.parse(ev("JSON.stringify(CONFS.find(c=>c.n==='DKNOG'))")); assert.equal(cf.c, 'cph'); assert.equal(ev(`MONTHS[${cf.m}]`), 'Mar', 'held in March, like the real one');