Merge origin/main into codex/ddos-scaling-and-mitigation

This commit is contained in:
Frederic Jung 2026-10-27 13:21:51 +00:00
commit e7ae3b18bf
154 changed files with 19102 additions and 14323 deletions

View file

@ -1,43 +1,66 @@
---
name: add-strings
description: Add or change player-facing text in Series of Tubes and keep every translation (site/i18n/*.js) complete.
description: Add or change player-facing text in Series of Tubes: labels in the code, English in src/i18n/en.js, and every translation (site/i18n/*.js) kept complete.
---
# Adding or changing player-facing text
The English text is the translation key. Every string a player can see must go
through the translation helpers and have an entry in every dictionary in `site/i18n/`
(currently `it.js`, Italian).
Text is keyed by **label** ([docs/adr/0003-translations-by-label.md](../../../docs/adr/0003-translations-by-label.md)).
The code says `tr('pnis.delivery_2_to_6_weeks')`; the English is in `src/i18n/en.js`; Italian, Portuguese
and French are `site/i18n/it.js`, `pt.js`, `fr.js`. Every label the code uses needs English, and every
language needs every label.
## In the code
- `tr('Text with {name}', {name})`: translate now and fill placeholders.
- `trn('{n} router', '{n} routers', n, vars)`: plurals; both forms are keys.
- `N_('Text')`: marks a literal kept in a table for later `tr()` (e.g. labels stored in
constants). Call `tr(x)` where it's shown.
- Static HTML: add `data-i18n` to the element; `aria-label` and `title` attributes are
collected automatically.
- Text must be a string literal inside the call, or the checker can't see it.
- Keep HTML (`<b>`, `<br>`, `<small>`) and `{placeholders}` identical in translations.
- Don't build sentences by concatenating translated fragments; translate whole sentences.
- `tr('area.label', {name})`: translate now and fill `{placeholders}`.
- `trn('area.label', n, vars)`: plurals. One label, whose entries are `{"one": "…", "other": "…"}`;
`{n}` is filled in for you.
- `N_('area.label')`: a label kept in a table or a save and translated where it is shown with
`tr(x)`. Anything stored in `S` must be an `N_()` label (or an index), never translated text and never
a label written any other way: the build shortens every label it sees in `tr()`/`trn()` to an id that
changes between releases, and keeps the `N_()` ones whole.
- The label is always a string literal, the first argument of `tr`/`trn`/`N_`. A label anywhere else
(`const x='pnis.ready'`) is an error in `npm run i18n:check`.
- Static HTML in `src/index.html`: `data-i18n="area.label"` on the element, with its English inside it;
`data-i18n-aria-label="…"` and `data-i18n-title="…"` next to those attributes.
- Keep HTML (`<b>`, `<br>`, `<small>`) and `{placeholders}` identical in every language.
- Don't build sentences from translated fragments; translate whole sentences.
## In the dictionary
## Naming a label
`site/i18n/it.js` is one object, `"English": "Italiano",` per line, ending with `};`.
Append new entries before the closing `};`. A small script avoids quoting mistakes:
`area.some_words`: the area is the file or topic it is shown in (`pnis`, `own_cable`, `dashboard`,
`page` for the static markup), or `common` for text used all over and short everyday words
(`common.close`, `common.customers`). The words are the first few words of the English, lower case,
`_` between them: `pnis.ready_in_about_n_days`. Labels are only for finding things; players never see
them. Reuse an existing label when the text and the meaning are the same (`grep -n '"Close"' src/i18n/en.js`).
```python
import json
it = {"New English text": "Nuovo testo italiano"}
q = 'site/i18n/it.js'; t = open(q).read().rstrip()
assert t.endswith('};')
t = t[:-2] + ''.join(json.dumps(k, ensure_ascii=False) + ':' + json.dumps(v, ensure_ascii=False) + ',\n'
for k, v in it.items() if json.dumps(k, ensure_ascii=False) + ':' not in t) + '};\n'
open(q, 'w').write(t)
## In the dictionaries
Every dictionary is one entry per line, **sorted by label**, so new text from different pull requests
lands on different lines. Don't edit them by hand; the script writes English and translations together:
```bash
cat > /tmp/strings.json <<'JSON'
{
"en": { "pnis.ready_in_about_n_days": "Ready in about {n} days",
"save.n_pop": { "one": "{n} POP", "other": "{n} POPs" } },
"it": { "pnis.ready_in_about_n_days": "Pronto tra circa {n} giorni",
"save.n_pop": { "one": "{n} POP", "other": "{n} POP" } },
"pt": { "pnis.ready_in_about_n_days": "Pronto em cerca de {n} dias" },
"fr": { "pnis.ready_in_about_n_days": "Prêt dans environ {n} jours" }
}
JSON
node scripts/i18n-add.js /tmp/strings.json # a string or {one, other} sets an entry, null removes it
node scripts/i18n-add.js --rename old.label new.label # in every dictionary and everywhere in src/
```
When you **change** English text, rename the key in every dictionary too; when you
remove text, delete its entry.
- **Changing English wording** (a typo, a clearer phrase, same meaning): change only the English. The
translations stay right.
- **Changing the meaning**: give the text a new label (`--rename`, then update the English and every
translation), so no language keeps a translation that now says something else.
- **Removing text**: `null` under `"en"` removes the label from every dictionary.
`npm run i18n:fix` re-sorts a dictionary that got out of order (a hand edit, a merge).
## Italian style
@ -48,6 +71,6 @@ into an Italian joke when one fits; otherwise keep the pun name and translate th
## Check
```bash
node scripts/i18n-check.js # must say: 0 missing, 0 unused, 0 broken
npm test # includes tests/i18n.test.js
node scripts/i18n-check.js # en.js: 0 problems; each language: 0 missing, 0 unused, 0 broken
npm test # includes tests/i18n.test.js (every screen in every language) and the shipped page
```

View file

@ -0,0 +1,67 @@
---
name: edit-the-game
description: Find, change and add game code in Series of Tubes, which lives in many small files under src/ that the build joins into one page. Use for any feature, fix or refactor in the game itself (anything in src/).
---
# Editing the game
The game's source is `src/`. The build (`scripts/lib/page.js`) pastes the files together, in path order,
into one `index.html` with one inline `<style>` and one inline `<script>`. That is exactly what players
load, so splitting code across files costs nothing at runtime. Why it works this way:
[docs/adr/0002-one-page-assembled-at-build.md](../../../docs/adr/0002-one-page-assembled-at-build.md).
```
src/index.html the shell: <head>, static markup, `<!-- @include styles -->`, `<!-- @include game -->`
src/styles/NN-*.css CSS, in order (phones last)
src/game/NN-area/NN-*.js the game script, in order (see the map in docs/ARCHITECTURE.md)
site/ static files copied as they are (dictionaries, icons, service worker)
```
## Find the code
Search by name, not by line: `grep -rn "function compute(" src/game`. Folder names say what lives
there: `10-catalog` prices and gear, `20-world` cities and cables, `30-networks` other ASes,
`70-rules` peering and market rules, `80-simulation` routing and the save gate, `85-incidents`,
`88-days` the daily tick, `90-actions` every player action, `93-ui` HUD and panels, `94-dashboard`,
`95-modals`, `96-map` the canvas. `docs/ARCHITECTURE.md` has the full table.
## Run it
```bash
npm run dev # http://localhost:8080, assembled on every request, reloads on save
npm test # all suites (assembles src/ in memory; no build needed)
npm test -- tests/peering.test.js # one suite
```
A browser error points at a line of the assembled page; the dev server prints the `src/` file and line
next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you want to look at it.
## Where new code goes
- **A new feature or system:** its own file in the folder of its topic, e.g.
`src/game/70-rules/85-route-servers.js`. Pick a number between its neighbours; gaps are there for this.
Small files that own one topic are what keep pull requests from conflicting.
- **Order matters at the top level.** Files run in path order. Top-level `const`/`let` values and
top-level statements may only use top-level values from earlier files. Functions are fine anywhere:
everything is one script, so function declarations are hoisted and are all defined by the time
anything runs after boot. When in doubt, put constants in an earlier file and logic in functions.
- **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only
`10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get
a new `NN-area.js` file of that second form.
- **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`.
- **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`.
- **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as
`CITY_LL` sorted by id, so two people adding cities touch different lines.
- **Static markup** goes in `src/index.html`; it is short and rarely changes.
- **Files that ship as they are** (icons, dictionaries, `sw.js`, `robots.txt`) live in `site/`.
`site/index.html` must not exist; the build refuses it.
Every partial ends with a newline and must not contain `</script>` or `</style>` at the start of a line.
File names are `NN-lower-case.js` / `.css`; `tests/build.test.js` checks both.
## Still the same rules
Everything in CLAUDE.md applies unchanged: translate every string (`add-strings`), sanitize saves,
phones first, a test with every change (`write-tests`), performance shown against `main`
(`performance`), hosting on GitHub Pages only (`github-pages`), a CHANGELOG bullet for players.
The CHANGELOG is the one file every change touches; a conflict there is expected: keep both bullets.

View file

@ -0,0 +1,52 @@
---
name: github-pages
description: Series of Tubes is hosted on GitHub Pages and nowhere else, non-negotiably. Use before any change to hosting, deploys, the build output, caching, the service worker, new runtime requests or anything that would need a server, and whenever someone suggests another host.
---
# GitHub Pages, always
Series of Tubes is served by GitHub Pages at https://seriesoftub.es and **only** there. This is settled
([docs/adr/0001-github-pages-only.md](../../../docs/adr/0001-github-pages-only.md)) and not up for
discussion: do not propose, prepare or "keep the door open" for another host, a CDN in front, a
backend or server-side rendering, even when asked to evaluate options. If a feature seems to need
one, redesign the feature.
## What that means for a change
- **The output is static files.** `npm run build` writes `_site/`: the assembled page, `site/`'s files,
`version.json`. No server code, no runtime secrets: everything there is public.
- **No HTTP headers, redirects or rewrites.** Pages ignores `_headers`, `_redirects`, `.htaccess`,
`vercel.json`, `netlify.toml`. Need a policy? Use a `<meta>` tag. Need a different URL? Add a
static file there.
- **Caching is Pages' (short, the same for every file) plus the service worker's.** Offline play and
updates are `site/sw.js`'s job; its cache name carries the version. When you add a file the game
needs offline, add it to `CORE` there.
- **Same origin.** The page, dictionaries, icons and data come from seriesoftub.es. Do not add CDN
libraries or third-party APIs the game needs to work; the web fonts and the analytics counter are
the only exceptions and the game runs without them.
- **More files are fine, from the same origin.** Pages serves many small files well over HTTP/2.
Still: the game page itself stays one assembled `index.html` (see
[ADR 0002](../../../docs/adr/0002-one-page-assembled-at-build.md)), and anything the first frame
needs must not add a round trip.
- **Limits:** about 1 GB for the whole site, 100 MB per file.
- **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get
`404.html`.
## How it deploys
Only releases deploy. Bumping `version` in `package.json` on `main` runs `auto-release.yml`, which tags,
publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 npm run build`,
`actions/upload-pages-artifact` with `./_site`, `actions/deploy-pages`. That job is the only one with
`pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the
steps.
## Before you hand back a change that touches the build, deploy or loading
```bash
npm run build && npm run serve # the production build, served as static files
npm test -- tests/pages.test.js # static-only, all references resolve, Pages-only deploy
```
`tests/pages.test.js` fails on host configuration files, files over the limits, local references
that do not exist in `_site/`, scripts loaded from other origins, and any workflow that deploys
anywhere else. Do not weaken it to make a change pass; change the change.

View file

@ -5,7 +5,7 @@ description: Measure and demonstrate the performance of every Series of Tubes ch
# Performance is always demonstrated
Every change to the game (anything in `site/`) shows its performance on a very large network,
Every change to the game (anything in `src/` or `site/`) shows its performance on a very large network,
compared with `main`, before it is merged or released. A speed claim without numbers does not
count, and neither does "it feels fine on my small game". Most players who complain about lag
have huge late-game networks, and most of them are on phones.
@ -13,11 +13,14 @@ have huge late-game networks, and most of them are on phones.
## Measure
```bash
git show origin/main:site/index.html > /tmp/base.html
npm run perf -- --base /tmp/base.html # headless only, a few minutes
npm run perf -- --base /tmp/base.html --browser # plus real Chromium, desktop and phone (what CI runs)
npm run perf -- --base-ref origin/main # headless only, a few minutes
npm run perf -- --base-ref origin/main --browser # plus real Chromium, desktop and phone (what CI runs)
```
`--base-ref` assembles that commit's page with its own scripts (`node scripts/lib/page.js --ref REF`;
for commits from before the split it reads their `site/index.html`). `--base FILE` takes a built page
instead. The head is always this checkout's `src/`, assembled the way the build does it.
`scripts/perf-bench.js` loads `tests/fixtures/big-network.json` (about 100 POPs, 150 links,
950 PNIs, 830 cache boxes, 110 IX ports, 170 customers) into the base and into this checkout and
times them in alternating turns, 15 runs each. It prints one table per environment:
@ -57,7 +60,7 @@ Without `--base` it just times this checkout. `--runs N`, `--md FILE`, `--json F
save and a file from the in-game menu's Export save work:
```bash
npm run perf -- --save ~/Downloads/series-of-tubes-save.json --base /tmp/base.html
npm run perf -- --save ~/Downloads/series-of-tubes-save.json --base-ref origin/main
```
Routing speed-ups must also keep the two equivalence tests green: `tests/speed.test.js` (the fast
@ -70,10 +73,10 @@ incidents and failures).
- **Every pull request**: the Performance workflow runs the same comparison and posts the table as a
comment on the PR (updated on every push). Read it before merging. Locally, paste the table into
the PR description or the commit summary you report.
- **Everything you hand back to Frederic** that touched `site/`: include the table, or at least the
- **Everything you hand back to Frederic** that touched `src/` or `site/`: include the table, or at least the
rows that moved, in your summary. Say plainly when something got slower.
- **Before a release**: compare the release against the previous tag
(`git show v<last>:site/index.html > /tmp/base.html`) and mention notable changes.
(`npm run perf -- --base-ref v<last>`) and mention notable changes.
## Read the table

View file

@ -7,8 +7,10 @@ description: Cut and ship a Series of Tubes release (patch or minor) from main v
Bumping `version` in `package.json` on `main` is the release button. The
`auto-release.yml` workflow tests, tags `v<version>`, publishes a GitHub release with
that version's CHANGELOG section as notes, and dispatches `release.yml`, which deploys
to GitHub Pages (https://seriesoftub.es).
that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds
`_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it
to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the
`github-pages` skill.
## Only release when Frederic says so
@ -53,7 +55,7 @@ gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.publish
- `package-lock.json` → top-level `"version"` and `packages[""].version`
4. `npm test` once more.
Then compare performance with the previous release and mention anything notable to Frederic:
`git show v<last>:site/index.html > /tmp/base.html && npm run perf -- --base /tmp/base.html`.
`npm run perf -- --base-ref v<last>`.
5. Commit on `main` as Frederic, with no attribution trailers:
```bash
git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \

View file

@ -5,8 +5,8 @@ description: Write deterministic jsdom tests for Series of Tubes features and fi
# Writing tests
Tests use `node:test` and `tests/harness.js`, which loads `site/index.html` in jsdom
with the animation loop off, a seeded `Math.random` and a recording fake canvas.
Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/`
(once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas.
Code runs inside the page through `ev()`.
## Pattern
@ -29,18 +29,24 @@ test('what the player should see happen', () => {
Pick the suite by topic: `game` (core loop), `build`, `persist` (save/import/migrate),
`services` (customers), `peering`, `issues` (GitHub issue regressions, name them
`#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`. A new file must be
added to the `test` script in `package.json`.
`#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`, `pages` (hosting).
For a new feature, prefer a new file named after it (`tests/route-servers.test.js`): every
`tests/*.test.js` runs on its own (`scripts/test.js`), and a file of your own never conflicts
with someone else's tests. Appending to the big suites (`issues`, `regions`) is where
pull requests collide. Run one file with `npm test -- tests/route-servers.test.js`.
## Rules
- **Text in assertions:** match what the player sees (`/Ready in about 3 days/`), or compare with
`ev("tr('pnis.ready_in_about_n_days',{n:3})")`. Tests run the source page, where labels are readable;
the shipped page (ids instead of labels) is covered by `tests/pages.test.js`.
- **Deterministic.** Never rely on luck. Use the default seed, `window.__reseed(n)`,
or set state directly (`S.day=…`, `S.ev.x=…`).
- **Force a specific random failure or event** by patching the picker:
```js
ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()");
```
Check the current source for the exact `pick` line first; it may differ.
Check the current source for the exact `pick` line first (`grep -rn "function fireFailure" src/game`); it may differ.
- **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`.
- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through
`parseSave()`/`migrate()`, and test that an *old* save without the new field still loads.

3
.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
# The assembler joins src/ byte for byte and refuses CR line endings; keep LF everywhere it reads.
src/** text eol=lf
site/i18n/*.js text eol=lf

View file

@ -8,8 +8,7 @@
## Performance
<!-- Changes to site/ must show their performance on a big network. The Performance check posts the
<!-- Changes to src/ must show their performance on a big network. The Performance check posts the
numbers as a comment on this PR. Locally:
git show origin/main:site/index.html > /tmp/base.html
npm run perf -- --base /tmp/base.html
npm run perf -- --base-ref origin/main
Explain anything marked slower. -->

View file

@ -6,7 +6,9 @@ name: Performance
on:
pull_request:
paths:
- 'src/**'
- 'site/**'
- 'scripts/lib/**'
- 'scripts/perf-*.js'
- 'tests/fixtures/**'
- 'tests/harness.js'
@ -32,7 +34,8 @@ jobs:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
git fetch --depth=1 origin "$BASE_SHA"
git show FETCH_HEAD:site/index.html > "$RUNNER_TEMP/base.html"
# The base's page, assembled by the base's own scripts (or its site/index.html from before the split).
node scripts/lib/page.js --ref FETCH_HEAD -o "$RUNNER_TEMP/base.html"
echo "BASE_ARG=--base $RUNNER_TEMP/base.html" >> "$GITHUB_ENV"
- name: Benchmark
# The runner image ships Google Chrome; playwright-core (a dev dependency) drives it, no browser download.

View file

@ -17,6 +17,10 @@ All notable changes to this project are documented here. The project follows
- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center.
- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation.
## [1.34.1] — 2026-10-27
- The game starts faster in Italian, Portuguese and French: their translations are about 40% smaller to download.
## [1.34.0] — 2026-10-27
- Choose your peering policy: Open to all, Selective or Closed. Open accepts everyone and keeps the route servers, Selective means fewer requests but you ask peers yourself, and Closed scares customers away.

View file

@ -1,30 +1,43 @@
# Series of Tubes: notes for Claude
A free cartoon browser game about how the internet works, live at
https://seriesoftub.es. The whole game is one static page: `site/index.html`
(HTML, CSS and JS in one file, no framework, no build step for development).
https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with no framework.
Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell
`src/index.html`); the build pastes them together, in path order, into a single `index.html`, the
same one-file page players have always loaded. Static files (dictionaries, icons, service worker)
live in `site/`.
Read these before larger changes:
- `docs/ARCHITECTURE.md`: how the code is laid out and how a day of simulation runs.
- `.claude/skills/`: step-by-step procedures (release, translations, tests).
- `docs/ARCHITECTURE.md`: where the code is, and how a day of simulation runs.
- `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build).
- `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release,
translations, tests, performance).
## Commands
```bash
npm ci # once: installs jsdom for the tests
npm test # node:test + jsdom, all suites, must stay green
node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken"
npm run build # builds _site/ (stamps version, bakes release notes)
npm run serve # build and serve locally
npm run perf -- --base /tmp/base.html # big-network benchmark vs another version (see `performance`)
npm run perf -- --base /tmp/base.html --browser # the same, also in real Chromium (desktop and phone)
npm run dev # play while developing: http://localhost:8080, reloads on save
npm test # node:test + jsdom, every tests/*.test.js, must stay green
node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries)
node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`)
npm run build # builds _site/ for GitHub Pages (assembles src/, stamps version, bakes release notes)
npm run serve # build and serve the production site locally
npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`)
npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone)
```
To play during development, open `site/index.html` directly or run `npm run serve`.
## Hard rules
- **GitHub Pages, always.** The game is hosted on GitHub Pages and nowhere else. This is not up
for discussion: never propose or prepare another host, a CDN in front, a backend, server-side
rendering, redirects or custom headers. The build output stays plain static files from one
origin. If a feature seems to need a server, redesign the feature. See the `github-pages` skill
and `docs/adr/0001-github-pages-only.md`.
- **No runtime cost for structure.** The page ships as one assembled `index.html`. Organise code
into files under `src/` freely (build time is cheap), but never in a way that adds requests or
work to page load or to the game loop.
- **Git:** work on `main`, no branches. Commits are authored and committed as
`Frederic Jung <frederic@jc-ix.net>`. Never add `Co-Authored-By`, `Claude-Session`
or any other attribution trailers.
@ -41,26 +54,35 @@ To play during development, open `site/index.html` directly or run `npm run serv
a real pun, or keep the plain word.
- **Easter eggs stay secret.** Never mention hidden jokes or easter eggs (for example
whatever `elephant()` does) in commit messages, release notes or the CHANGELOG.
- **Every player-facing string is translated.** Wrap it in `tr()`, `trn()` or `N_()`
and add the Italian to `site/i18n/it.js` in the same change (see `add-strings`).
- **Every player-facing string is translated, by label.** Code uses `tr('area.label')`,
`trn('area.label', n)` or `N_('area.label')` (anything stored in a save: `N_()`), never English text.
Add the English (`src/i18n/en.js`) and every translation (`site/i18n/*.js`) in the same change with
`scripts/i18n-add.js` (see `add-strings`).
- **Phones first.** About 70% of players are on phones. Every new panel, button and
modal must work at 360 px wide, in portrait and landscape, using the phone tab bar
and bottom sheets. Check `isPhone()` layouts, not just desktop.
- **Saves are sacred.** Old saves must keep loading. Any new state field gets a default
in `newGame()` and a check/repair in `sanitize()`; renamed fields are migrated there.
- **Performance is always demonstrated.** Every change to `site/` is measured on the big-network
fixture against `main` (`npm run perf -- --base /tmp/base.html`, see the `performance` skill),
- **Performance is always demonstrated.** Every change to `src/` or `site/` is measured on the big-network
fixture against `main` (`npm run perf -- --base-ref origin/main`, see the `performance` skill),
and the numbers go into the PR and into your summary. Every PR also gets them as a comment from
CI. Anything slower needs a reason or a fix.
- **Tests come with features.** Add or extend a test in `tests/` for every feature or
fix. Tests are seeded, so they must not depend on luck.
fix (a new feature gets its own `tests/<feature>.test.js`). Tests are seeded, so they must not
depend on luck.
- **CHANGELOG style:** plain English, written for players, one bullet per change,
issue numbers in parentheses like `(#37)`. No internal names, no jokes explained.
issue numbers in parentheses like `(#37)`. No internal names, no jokes explained. The CHANGELOG
is the one file every change touches; conflicts there are expected (keep both bullets).
## Style of the code
- Dense, single-file JavaScript. Match the surrounding style: short helper names,
arrow functions, template-literal HTML, no new dependencies.
- Dense JavaScript in small topic files under `src/game/` (see `edit-the-game`): a new feature gets
its own `NN-name.js` in the folder of its topic, actions go in the matching
`src/game/90-actions/*.js`. All files share one top-level scope; top-level values may only use
top-level values from earlier files. Match the surrounding style: short helper names, arrow
functions, template-literal HTML, no new dependencies.
- Lists people add to (cities, cables, networks, dictionaries) are one entry per line; id-keyed
objects and dictionaries stay sorted, so additions do not collide.
- UI is rebuilt from state: change `S`, then call `after()` (recompute, check goals,
re-render, save). Buttons are `btn(label, actName, args, cls, disabled)`, which
dispatch to `ACT[actName](args)` through `data-act`/`data-args`.

60
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,60 @@
# Code of Conduct
Series of Tubes is a cartoon game about how the internet works, built by people who
love networks and people who are just curious about them. Everyone is welcome here:
seasoned network engineers, students, translators, players who have never heard of BGP,
and people who just want to suggest a city with a funny data center name.
The short version: **be excellent to each other.**
## Where this applies
Everywhere people meet around this project: GitHub issues, pull requests, reviews and
discussions, the Series of Tubes Signal group, and anywhere else you represent the
project, online or at a conference bar after NANOG.
## What we want
- **Welcome people.** Newcomers are how every community stays alive. Nobody was born
knowing what a route reflector is. Explain things kindly, and assume the question is
sincere.
- **Be patient across languages.** Many of us write in our second or third language.
Judge the idea, not the grammar.
- **Disagree about ideas, not people.** Argue about peering policy, balance and puns as
hard as you like. Criticise the change, never the person who made it.
- **Assume good intent.** Text loses tone. If something reads badly, ask before you
react.
- **Give credit.** Thank people for reports, fixes and ideas, and say where an idea came
from.
- **Own your mistakes.** We all fat-finger a config now and then. Apologise, fix it,
move on.
- **Keep the jokes kind.** This game runs on puns. The target of a joke is a network,
a cable or a backhoe, never a person or a group of people.
## What we don't accept
- Harassment of any kind, in public or in private messages.
- Insults, slurs, or demeaning comments about anyone's gender, gender identity or
expression, sexual orientation, disability, appearance, body, age, race, ethnicity,
nationality, religion, experience level or anything else about who they are.
- Sexual language or imagery, and unwelcome attention of any kind.
- Threats, intimidation, stalking, or encouraging anyone else to do these things.
- Sharing someone's private information (an address, a phone number, a real name they
have not shared) without their permission.
- Trolling, deliberately derailing discussions, or flooding issues and chats.
- Continuing to contact someone after they have asked you to stop.
## If something happens
If someone makes you or others feel unwelcome or unsafe, tell the maintainer, Frederic,
in a private message in the Signal group. You do not need to be the person it happened
to, and you do not need proof or perfect wording. Reports are kept confidential.
We will listen, look at what happened, and do what fits: a friendly word, a request to
edit or delete something, a warning, or removing someone from the project's spaces for a
while or for good. Whoever reports in good faith will never be punished for it.
## Making it better
This document is for everyone here. If something is missing or unclear, open an issue
or a pull request, like for any other part of the project.

View file

@ -3,6 +3,9 @@
Thanks for wanting to help build the cartoon internet. Bug reports, ideas, puns,
translations and code are all welcome.
Everyone is welcome here, and everyone follows our [Code of Conduct](CODE_OF_CONDUCT.md).
The short version: be excellent to each other.
## Reporting bugs and ideas
Open an issue on GitHub and pick the form that fits: bug report, feature request,
@ -18,19 +21,52 @@ Not sure yet whether something is a bug or an idea worth an issue? Ask in the
## Development
The game is one static page, `site/index.html`, with no framework and no build step
while developing.
The game is one static page with no framework, hosted on GitHub Pages. Its source is split into
small files under `src/` (styles in `src/styles/`, the game script in `src/game/`), which the build
joins, in path order, into a single `index.html`. Static files such as the translations live in `site/`.
```bash
npm ci # installs jsdom for the tests
npm run serve # builds and serves the game locally
npm run dev # http://localhost:8080, reloads when you save a file
npm test # all tests must pass
node scripts/i18n-check.js # translations must be complete
node scripts/i18n-check.js # translations must be complete and sorted
npm run serve # the production build, as GitHub Pages will serve it
```
Opening `site/index.html` directly in a browser also works.
Where things are, and how a day of the simulation runs: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
A tour of the code is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
### Keeping pull requests apart
Many people work on the game at once. A few habits keep your pull request from colliding with theirs:
- Put a new feature in its own file in the folder of its topic (for example
`src/game/70-rules/85-route-servers.js`), and its tests in their own `tests/<feature>.test.js`.
New files in `src/` and `tests/` are picked up automatically; nothing needs registering.
- Add actions to the matching file in `src/game/90-actions/`, not wherever there is room.
- Lists (cities, cables, networks) take one entry per line; keep id-keyed tables sorted.
- Text is keyed by labels (`tr('pnis.ready_in_about_n_days')`, English in `src/i18n/en.js`). Add new
text with `node scripts/i18n-add.js` rather than by hand: it writes the English and the translations
and keeps every dictionary sorted, so your new strings don't land on the same lines as everyone
else's. Fixing English wording no longer touches the translations.
- The `CHANGELOG.md` bullet is the one place everybody writes. If it conflicts, keep both bullets.
### Your branch still edits `site/index.html`?
Until version 1.34 the whole game was one file, `site/index.html`. If your branch was started before
the split, merge `main` and let a script move your changes into `src/`:
```bash
git fetch origin
git merge origin/main # stops: site/index.html was deleted on main
node scripts/legacy/port-branch.js # moves your edits into the matching src/ files
git status # fix any conflict it lists, then
npm test && git commit
```
It splits your version of the page and the one you started from the same way `src/` was made (your
English text becomes labels too), merges each piece into `src/`, and applies your English and
dictionary changes entry by entry. It only reports conflicts
where your change and `main` touched the same lines.
## Pull requests
@ -42,11 +78,14 @@ A tour of the code is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
must not depend on luck.
- Add a bullet for players under `## [Unreleased]` in `CHANGELOG.md`, in plain English.
Releases are cut by the maintainer.
- Show the performance of changes to `site/` on a big network. The Performance check posts a table
- Show the performance of changes to `src/` on a big network. The Performance check posts a table
comparing your PR with `main` as a comment; to run it yourself:
`git show origin/main:site/index.html > /tmp/base.html && npm run perf -- --base /tmp/base.html`
`npm run perf -- --base-ref origin/main`
(add `--browser` to also time it in Chromium as a desktop and a phone, like CI does).
Anything marked slower needs an explanation.
- The game is hosted on GitHub Pages, and that will not change. Changes must work as plain static
files: no server code, no other host, no redirects or custom headers (see
[docs/adr/0001-github-pages-only.md](docs/adr/0001-github-pages-only.md)).
- Old saves must keep loading. New state needs a default for new games and a check in
`sanitize()`.
- Check your change on a phone-sized screen (about 360 px wide). Most players are on
@ -64,8 +103,9 @@ A tour of the code is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
## Translations
Every player-facing string goes through `tr()`, `trn()` or `N_()`. Dictionaries live
in `site/i18n/` (English text → translation). To add a language, copy `it.js`, translate
the values, register the language in the language list in `site/index.html`, and run
in `site/i18n/` (label → translation, one entry per line, sorted; the English for each label is in
`src/i18n/en.js`). To add a language, copy `it.js`, translate the values (`en.js` lists the same labels
in the same order), register the language in the language list in `src/index.html`, and run
`node scripts/i18n-check.js <lang>` until it reports nothing missing, unused or broken. The CI job "translations" runs the same check on every pull request, shows each language's coverage in the run summary, and also fails if a new language is not added to the language list or to the offline cache in `site/sw.js`.
Language pull requests must be reviewed by a human who speaks the language, and

View file

@ -36,10 +36,11 @@ an hour there than from a year of laying cartoon fiber here.
## Playing locally
It is a single static page with no build step for development:
It is a single static page, assembled from the files in `src/` by a small Node script:
```sh
open site/index.html # or: npm run serve
npm ci
npm run dev # http://localhost:8080
```
Progress is saved in your browser's local storage.
@ -51,35 +52,42 @@ and remembers the one you pick under Settings or on the title screen.
```sh
npm ci
npm run dev # development server: assembles src/ on every request, reloads on save
npm test # headless tests: boot, geography, a year of play, every incident, every panel
npm run build # writes the deployable site to _site/ with version and date stamped in
npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in
npm run i18n:check # lists text missing from (or stale in) the translations
```
```
site/ everything that is deployed
index.html the whole game (HTML, CSS and JS in one file)
i18n/it.js Italian translation, loaded only when the game runs in Italian
src/ the game page, in pieces (joined into one index.html at build)
index.html the shell: <head>, static markup, @include lines
i18n/en.js English for every label, inlined into the page
styles/ CSS
game/ the game script, by topic: world, networks, simulation, actions, UI, map…
site/ static files, deployed as they are
i18n/it.js Italian translation (label → text), loaded only when the game runs in Italian
i18n/pt.js Portuguese (Brazil) translation, loaded only when the game runs in Portuguese
i18n/fr.js French translation, loaded only when the game runs in French
images/og-image.png social preview (1200×630)
favicon.*, icon-* favicons, app icons, manifest
sw.js service worker (offline play)
robots.txt, sitemap.xml, llms.txt, 404.html, CNAME
scripts/build.sh copies site/ to _site/ and stamps __VERSION__ / __BUILD_DATE__
scripts/build.js builds _site/ for GitHub Pages: site/ + the assembled page, stamped
scripts/lib/page.js joins src/ into the page
tests/ node:test + jsdom
.github/workflows/ ci.yml (pushes to main and PRs) and release.yml (Pages deploy)
docs/ architecture and decisions (docs/adr/)
.github/workflows/ ci.yml (pushes to main and PRs) and release.yml (GitHub Pages deploy)
```
## Translations
English is the source text. Player-facing strings in `index.html` go through
`tr('Unlocks at level {n}.', {n})` (or `trn(one, other, n)` for plurals); static markup
uses `data-i18n`, and `aria-label`/`title` are translated at boot. Each language is a
`site/i18n/<lang>.js` file mapping the English text to its translation, plus an entry in
`SOT_LANGS` (the language loader at the top of the page). Missing entries fall back to
English, so new English text never breaks the game; `npm run i18n:check` lists what
needs translating, and the tests make sure every translation keeps its `{placeholders}`
and HTML tags.
Player-facing text is keyed by label, and English is a dictionary like the others. Code says
`tr('pnis.ready_in_about_n_days', {n})` (or `trn('save.n_pop', n)` for plurals); static markup uses
`data-i18n="label"`. The English is in `src/i18n/en.js`, inlined into the page; each other language is
a `site/i18n/<lang>.js` file mapping the same labels to its text, plus an entry in `SOT_LANGS` (the
language loader in `src/index.html`). Missing translations fall back to English, so new text never
breaks the game; `npm run i18n:check` lists what needs translating, and the tests make sure every
translation keeps its `{placeholders}`, HTML tags and plural forms.
## Releasing
@ -156,7 +164,7 @@ There are fewer backhoes there than in the real thing.
## Contributing
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). Everyone taking part follows the [Code of Conduct](CODE_OF_CONDUCT.md): be excellent to each other.
## License

View file

@ -1,50 +1,78 @@
# Architecture
Everything that runs in the browser lives in `site/index.html`. It is large (several
thousand lines), so find things by the section banners rather than by line number:
Series of Tubes is a static web game hosted on **GitHub Pages, and only there**
([ADR 0001](adr/0001-github-pages-only.md)). Its source is split into many small files under `src/`;
the build joins them into **one self-contained `index.html`** (one inline `<style>`, one inline
`<script>`), exactly the page players have always loaded ([ADR 0002](adr/0002-one-page-assembled-at-build.md)).
```
/* ================= PHONES ================= */ phone CSS
/* ================= LANGUAGE ================= */ tr(), trn(), N_(), dictionary loading
/* ================= ANALYTICS ================= */ privacy-friendly event counter
/* ================= CONSTANTS ================= */ prices, ports (PORT), routers (RG), optics
/* ================= WORLD ================= */ CITIES, CABLES, display nudges
/* ================= NETWORKS ================= */ NETS (other ASes), traffic shares (NSH)
/* ================= BUSINESSES ================= */ BIZ_T customer types, LEVELS + LV_REQ (13 levels, traffic eras)
/* ================= GOALS ================= */ GOALS checklist
/* ================= STATE ================= */ S, R, UI globals
/* ================= BANKS & LOANS ================= */
scenarios (SCN), conferences, tutorial, traceroute, share card
/* ================= HELPERS ================= */ formatting, geometry, small queries
/* ================= SIMULATION ================= */ RouteScript, compute(), costs, sanitize()
failures & events, daily tick, badges
/* ================= ACTIONS ================= */ the ACT map: every player action
/* ================= SAVE ================= */
/* ================= AUDIO ================= */
/* ================= DOM RENDER ================= */ HUD, left panel, side panel, modals, toasts
/* ================= PHONE ================= */ tab bar, bottom sheets
/* ================= INSTALL (PWA) ================= */
/* ================= CANVAS ================= */ map drawing, level of detail
/* ================= LOOP ================= */ frame(), boot()
src/ the game page, in pieces
index.html shell: <head>, static markup, the language loader, the @include lines
i18n/en.js the English for every label → inlined at the top of the page's <script>
styles/NN-*.css → pasted into the page's <style>, in path order
game/NN-area/NN-*.js → pasted into the page's <script>, in path order
site/ static files copied to the build as they are (dictionaries, icons, sw.js…)
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted
scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
```
Other files:
Because the partials are concatenated into one classic script, they share one top-level scope, just as
when they were one file: `S`, `CITY` or `compute()` are visible everywhere, function declarations are
hoisted across files, and top-level statements run in path order. Find code by name
(`grep -rn "function compute(" src/game`); the folders follow the game's layers:
| Folder under `src/game/` | What lives there |
| --- | --- |
| `00-core/` | `tr()`/`trn()`/`N_()` and the dictionary; version, release notes and the analytics counter |
| `10-catalog/` | Prices and gear: POP and port costs, routers (`RG`), supply chain, port slots, dark fiber systems and optics (`OPT`), reach and subsea upgrades |
| `20-world/` | Map projection, landmasses, coastline, city coordinates (`CITY_LL`), `CITIES`, `CABLES` |
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS` |
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()` |
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
| `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service |
| `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` |
| `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` |
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard, the bank, hints |
| `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals |
| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, `draw()`, the world layer, cities, input and click delegation |
| `99-loop.js` | `frame()` and `boot()` |
`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone.
Rules for the source (checked by `tests/build.test.js` and the assembler): files are named
`NN-lower-case.js`/`.css`, end with a newline and never close their `<script>`/`<style>`; top-level code
may only use top-level values from earlier files; tables people add to have one entry per line, the
id-keyed ones sorted. New features get their own file in the right folder (`edit-the-game` skill).
Development runs on `npm run dev` (assembles on every request, reloads on save);
`npm run page -- -o FILE` writes the assembled page.
## Other files
| Path | What it is |
| --- | --- |
| `site/i18n/it.js` | Italian dictionary: English text → Italian, loaded when the language is `it` |
| `site/i18n/pt.js` | Portuguese (Brazil) dictionary: English text → Portuguese, loaded when the language is `pt` |
| `site/i18n/fr.js` | French dictionary: English text → French, loaded when the language is `fr` |
| `src/i18n/en.js` | English: label → text, one entry per line, sorted; inlined into the page by `<!-- @include i18n -->` |
| `site/i18n/it.js`, `pt.js`, `fr.js` | Translations: label → text, the same layout; loaded only for that language |
| `site/sw.js` | Service worker: network-first for pages, stale-while-revalidate for assets. Cache name is stamped with the version |
| `site/site.webmanifest`, icons | PWA install metadata |
| `scripts/build.sh` | Copies `site/` to `_site/`, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` |
| `site/site.webmanifest`, icons, `404.html`, `CNAME`, `robots.txt`, `sitemap.xml`, `llms.txt` | PWA and GitHub Pages files, copied as they are |
| `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) |
| `scripts/lib/compile-labels.js` | Shrinks labels to short ids in the shipped page and dictionaries |
| `scripts/build.js` | Builds `_site/` for GitHub Pages: copies `site/`, writes the page, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` |
| `scripts/dev.js` | `npm run dev`: development server, no dependencies |
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
| `scripts/perf-bench.js`, `scripts/perf-browser.js`, `scripts/perf-stats.js`, `scripts/perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
| `scripts/i18n-check.js` | Compares every `tr`/`trn`/`N_` literal and `data-i18n` text with each dictionary |
| `tests/harness.js` | Loads the page in jsdom with a seeded `Math.random` and a fake canvas |
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas |
| `.github/workflows/ci.yml` | Tests and build on every push and PR |
| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy |
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages |
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) |
## Globals
@ -125,15 +153,22 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood.
## Translations
- `tr(text, vars)` looks up `DICT[text]` and fills `{placeholders}`; `trn(one, other, n)`
picks the plural; `N_(text)` marks a literal for the checker and translates later.
- Static markup uses `data-i18n`; `i18nDom()` swaps it at boot.
- The English text is the key, so changing English text means updating the key in
every dictionary.
Text is keyed by label ([ADR 0003](adr/0003-translations-by-label.md)):
- `tr('area.label', vars)` looks up `DICT['area.label']` and fills `{placeholders}`; `trn('area.label', n)`
picks `one` or `other` of a plural; `N_('area.label')` marks a label kept in a table or a save, translated
where it is shown.
- `DICT` is the English (`src/i18n/en.js`, inlined into the page) with the player's language
(`site/i18n/<lang>.js`) laid over it. English text from saves of 1.33 and older still finds its translation.
- Static markup uses `data-i18n="label"`, `data-i18n-aria-label`, `data-i18n-title`; `i18nDom()` swaps it at boot.
- The build swaps labels for short ids in the shipped page and dictionaries (`scripts/lib/compile-labels.js`);
`N_()` labels stay whole because saves keep them.
- `npm run i18n:check` checks the English against the code and every translation against the English.
## Tests
`tests/*.test.js` use `node:test` and `tests/harness.js`:
`tests/*.test.js` use `node:test` and `tests/harness.js`, which assembles `src/` in memory, so tests
never run a stale build. `npm test` runs every file in `tests/`; a new suite needs no registration:
```js
const { load } = require('./harness');

View file

@ -0,0 +1,54 @@
# ADR 0001: Series of Tubes is hosted on GitHub Pages, and only there
- Status: accepted, not open for renegotiation
- Date: 2026-10-27
- Decided by: Frederic Jung
## Decision
The game is served by **GitHub Pages**, from the custom domain in `site/CNAME`
(https://seriesoftub.es). That is the only hosting. There is no second host, no fallback host and no
plan to move.
Every change has to keep working there. A change that only works with a server, a different host,
a CDN in front, edge functions, rewrites or custom response headers is the wrong design for this
project, however good it is otherwise. Change the design, not the host.
## What GitHub Pages gives us, and what it does not
| We can rely on | We cannot have |
| --- | --- |
| Static files over HTTPS from one origin, with gzip | Any server code: no API routes, no SSR, no PHP, no edge or serverless functions |
| The deploy in `release.yml` (`actions/upload-pages-artifact` + `actions/deploy-pages`) | Custom HTTP headers (`Cache-Control`, CSP, COOP/COEP): use `<meta>` tags or do without |
| `404.html` for unknown paths | Redirect or rewrite rules (`_redirects`, `.htaccess`, `vercel.json`, `netlify.toml`) |
| `CNAME` for the domain | Per-file caching rules: Pages sets its own short cache lifetime for everything |
| A size limit of about 1 GB for the site and 100 MB per file | Secrets at runtime: everything in `_site/` is public |
Anything that needs data at runtime fetches it from the same origin as a static file
(`version.json`), from the player's own browser (`localStorage`), or not at all.
## Consequences
- **The build is the place for work.** Anything clever (assembling the page from `src/`, stamping the
version, baking release notes) happens in `scripts/build.js`, at build time, in GitHub Actions.
The build may get slower; what it produces must stay plain static files. See
[ADR 0002](0002-one-page-assembled-at-build.md).
- **Same origin for everything the game loads.** The page, the dictionaries, icons and the service
worker all come from seriesoftub.es. The only cross-origin requests are the web fonts and the
privacy-friendly analytics counter (its script and its endpoint), and the game works without both.
Don't add more: no CDN-hosted libraries, no third-party APIs the game depends on.
- **The service worker is the cache policy.** Since Pages decides HTTP caching, `site/sw.js` decides
what is cached for offline play, versioned by the release.
- **Deploys only come from releases.** `release.yml` is the only workflow with `pages: write`. Pushes to
`main` never deploy.
- **Tests guard it.** `tests/pages.test.js` checks that a build is plain static files that GitHub
Pages can serve as they are: no server or host configuration files, every local reference resolving
inside `_site/`, nothing over the size limits, `CNAME` and `404.html` in place, and the deploy going
through the official Pages actions.
## Proposals that are out of scope
Moving to Netlify, Vercel, Cloudflare Pages or a VPS; putting a CDN or proxy in front; adding a
backend for accounts, leaderboards or cloud saves; server-side rendering. Features in that direction
must be built from static files and the browser (for example, an exported save file instead of a cloud
save), or not at all.

View file

@ -0,0 +1,68 @@
# ADR 0002: Source in many files, shipped as one page assembled at build
- Status: accepted
- Date: 2026-10-27
## Context
Until 1.34 the whole game was `site/index.html`: about 900 KB and 5,100 lines of HTML, CSS and JavaScript
in one file, edited by many contributors at once. Nearly every pull request touched that file, so
pull requests conflicted with each other all the time, reviews meant scrolling a 900 KB file, and
nobody could tell from a diff's file list what a change was about.
What had to stay: hosting on GitHub Pages ([ADR 0001](0001-github-pages-only.md)), load time and in-game
speed (most players are on phones), saves, the tests that reach into the page's globals (`S`, `R`,
`ACT`, `compute()`), and no new runtime dependencies.
## Decision
- The page's source lives in `src/`: a shell (`src/index.html`) with `<!-- @include DIR -->` lines,
the styles in `src/styles/*.css` and the game script in `src/game/**/*.js`.
- `scripts/lib/page.js` assembles them by **plain concatenation in path order** into the same single,
self-contained `index.html` as before: one inline `<style>`, one inline classic `<script>`.
The numeric prefixes (`10-`, `20-`…) set that order; gaps leave room to add files in between.
- `scripts/build.js` builds `_site/` from that page plus the static files in `site/`.
- Nothing else changes at runtime. When the split landed, the assembled page was byte-for-byte the old
`site/index.html`.
## Why concatenation, and not ES modules or a bundler
- **Zero runtime cost.** One HTML request, as before. ES modules would mean many requests (or a bundler),
module graph evaluation and a new loading order; at best they break even.
- **The code is one script on purpose.** The partials share top-level names (`S`, `R`, `UI`, `CITY`,
`tr`…) and function declarations are hoisted across the whole script. Concatenated, every partial
sees exactly what it saw before, with no `import`/`export` lists to keep in sync (another source of
conflicts) and no circular-import pitfalls.
- **Tests keep working.** jsdom loads the assembled page, and tests still call into its globals and
patch functions by their source text.
- **No dependencies.** The assembler is about a hundred lines of Node with nothing to install, so it
runs anywhere `npm test` does, including GitHub Actions.
- **It is reversible.** If a bundler is ever worth it, the partials are already the modules it needs.
## Rules that come with it
- **Order matters for top-level code.** `const`/`let` and statements at the top level of a partial run
in path order, so a partial can only use top-level *values* from partials that come before it (or
inside functions that run later, after boot). Functions can be called from anywhere once the page
has loaded.
- **A partial is a complete set of statements.** Each file ends with a newline and never closes the
`<script>`/`<style>` it is pasted into; the assembler refuses files that break this.
- **Put new code where its topic is.** A new feature gets its own partial in the right folder (for
example `src/game/70-rules/85-my-feature.js`), its actions go in the matching
`src/game/90-actions/*.js`, its panel in `src/game/93-ui/` or `src/game/94-dashboard/`. Small files
that own one topic are what keep pull requests apart.
- **Keep lists one entry per line.** Tables people add to (cities, cables, networks, dictionaries) have
one entry per line, and the id-keyed ones are sorted, so additions land in different places.
- **The CHANGELOG is the one shared file every change touches**, on purpose: one bullet per change under
`## [Unreleased]`. A conflict there is expected and easy: keep both bullets.
## Consequences
- Development needs one command: `npm run dev` serves the page assembled on every request and reloads
the browser on save. Opening a file straight from disk no longer runs the game.
- Error line numbers in the browser refer to the assembled page; the dev server prints the matching
`src/` file and line in the console.
- Branches started before the split are carried over with `scripts/legacy/port-branch.js`
(see CONTRIBUTING.md).
- The performance workflow builds the base's page from git with that commit's own assembler
(`node scripts/lib/page.js --ref REF`), so base and head are always compared as players get them.

View file

@ -0,0 +1,57 @@
# ADR 0003: Translations are keyed by labels, not by English text
- Status: accepted
- Date: 2026-10-27
## Context
Until 1.34 the English text was the key: code said `tr('Delivery: 2 to 6 weeks')`, and every dictionary
repeated that English as its key, `"Delivery: 2 to 6 weeks":"Consegna: da 2 a 6 settimane"`. So each of
the ~2,900 strings existed four times (code, it, pt, fr), and more with every language. Fixing a typo in
English meant renaming the key in every dictionary in the same change, or every translation silently
fell back to English. Long sentences as keys made dictionary diffs hard to read and easy to conflict.
## Decision
- Code uses **labels**: `tr('pnis.delivery_2_to_6_weeks')`, `trn('save.n_pop', n)`, `N_('common.optics')`.
A label is `area.words`: the area is where the text is used (`pnis`, `own_cable`, `page`, or `common`
for text used in several places and short shared words), the words are a few of its first words.
- **English is a dictionary too**, `src/i18n/en.js`, in the same format as the translations. It is part of
the page source: the build inlines it into the game script, so English players load nothing extra
(see [ADR 0002](0002-one-page-assembled-at-build.md)). Translations stay static files,
`site/i18n/<lang>.js`, loaded only for that language.
- **Plurals are one label** with `{"one": …, "other": …}` in every language: `trn('save.n_pop', n, vars)`.
- **Static markup** says `data-i18n="label"` (and `data-i18n-aria-label`, `data-i18n-title`) and keeps its
English text, so the page still reads in English without JavaScript and for search engines. The checker
makes sure that English matches `en.js`.
- At runtime, `DICT` is the English with the player's language laid over it: a missing translation shows
the English, an unknown label shows itself (the checker makes sure there are none).
## Consequences
- **Changing English wording is one line** in `en.js`. If the meaning changes, give it a new label
instead (`scripts/i18n-add.js --rename` moves one everywhere), so translators see it as new and the
old translation does not linger with the wrong meaning.
- **`npm run i18n:check`** verifies that every label used in `src/` is defined in English, every
English label is used, every translation keeps its English's placeholders, HTML tags and plural forms,
and every dictionary is sorted.
- **Saves:** a few things in a save hold text to show later (the peering inbox log, sold-out reasons,
attack names). New saves hold labels. Saves from before labels (1.34 and older) hold the English text; `tr()` maps it
back to its label the first time it sees one, so old saves still show the player's language.
- **Translators** read `src/i18n/en.js` next to their file; both are sorted by the same labels, so the
same line numbers line up.
- **The shipped page uses short ids, not labels.** Shipped as written, every label would be in the page
twice (in the code and as a key of the inlined English): about 20% more page after compression. So
the build (`scripts/lib/compile-labels.js`) gives every label a short id (`tr('1a')`) in the code, the
markup and every dictionary. Labels passed to `N_()` keep their name in the shipped page, because the
game stores those in saves and an id would mean something else in the next release. The checker
rejects a label that is not the first argument of `tr()`/`trn()`/`N_()`, since the build cannot see it.
`src/`, `npm run dev` and the tests all use the readable labels; `tests/pages.test.js` plays the
shipped page in English, Italian and French.
- **Performance:** measured against 1.34 on the big-network save, routing, a game day, panels, the
dashboard and the map are all unchanged, and boot time too. The page is about 4% bigger after
compression (321 → 335 KB): the English moved from the code into its own dictionary, with an id each.
The translation files are about 40% smaller (it.js 143 → 85 KB), so Italian, Portuguese and French
players download less than before. `tr()` is still one property lookup.
- Branches from before this change are converted by `scripts/legacy/port-branch.js` like the rest of the
split: their English-keyed calls and dictionaries get the same labels.

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "seriesoftubes",
"version": "1.34.0",
"version": "1.34.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "seriesoftubes",
"version": "1.34.0",
"version": "1.34.1",
"license": "MIT",
"devDependencies": {
"jsdom": "24.1.3",

View file

@ -1,6 +1,6 @@
{
"name": "seriesoftubes",
"version": "1.34.0",
"version": "1.34.1",
"description": "A cartoon browser game about building the internet.",
"private": true,
"license": "MIT",
@ -10,9 +10,12 @@
"url": "git+https://github.com/fjaeckel/seriesoftubes.git"
},
"scripts": {
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/inbox.test.js tests/latency.test.js tests/supply.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js tests/routing-reference.test.js tests/perf.test.js tests/sea-routing.test.js tests/subsea-upgrade-timing.test.js",
"build": "bash scripts/build.sh",
"test": "node scripts/test.js",
"build": "node scripts/build.js",
"i18n:check": "node scripts/i18n-check.js",
"i18n:fix": "node scripts/i18n-check.js --fix",
"dev": "node scripts/dev.js",
"page": "node scripts/lib/page.js",
"serve": "npm run build && npx --yes serve@14.2.4 _site",
"perf": "node scripts/perf-bench.js"
},

56
scripts/build.js Normal file
View file

@ -0,0 +1,56 @@
#!/usr/bin/env node
// Builds the deployable site into _site/ (or $OUT) for GitHub Pages: copies the static files in site/,
// assembles the game page from src/ into one index.html, and stamps the version (from package.json) and
// the build date into the files that carry them. The output is plain static files and nothing else,
// because GitHub Pages is where the game lives (docs/adr/0001-github-pages-only.md).
//
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { shipped, ROOT } = require('./lib/page');
const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version;
const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10);
const OUT = path.resolve(ROOT, process.env.OUT || '_site');
const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
fs.rmSync(OUT, { recursive: true, force: true });
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/');
// The page and the translations ship with labels shrunk to short ids (docs/adr/0003-translations-by-label.md).
const D = require('./lib/dict');
const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict])));
fs.writeFileSync(path.join(OUT, 'index.html'), page0);
for (const [lang, dict] of Object.entries(dicts)) fs.writeFileSync(path.join(OUT, 'i18n', `${lang}.js`), D.format(lang, '', dict));
for (const f of ['index.html', 'sitemap.xml', 'llms.txt', 'sw.js']) {
const p = path.join(OUT, f);
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replaceAll('__VERSION__', VERSION).replaceAll('__BUILD_DATE__', BUILD_DATE));
}
// Release notes for this version, baked into the page ("What's new") and published as version.json so
// open games can spot a newer release.
const notes = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION], { encoding: 'utf8' });
if (process.env.REQUIRE_NOTES === '1' && notes === '[]') die(`CHANGELOG.md has no '## [${VERSION}]' section with bullets (still under [Unreleased]?)`);
const page = path.join(OUT, 'index.html'), PH = '/*__RELEASE_NOTES__*/[]', html = fs.readFileSync(page, 'utf8');
if (!html.includes(PH)) die('release-notes placeholder missing from the page');
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')));
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes) }, null, 2) + '\n');
// Nothing may ship half-stamped.
const left = [];
const scan = (dir) => { for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) scan(p);
else if (/__VERSION__|__BUILD_DATE__/.test(fs.readFileSync(p, 'latin1'))) left.push(path.relative(OUT, p));
} };
scan(OUT);
if (left.length) die(`unreplaced placeholders left in ${left.join(', ')}`);
console.log(`Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${path.relative(ROOT, OUT) || OUT}/`);

View file

@ -1,44 +0,0 @@
#!/usr/bin/env bash
# Builds the deployable site into _site/ (or $OUT): copies site/ and stamps the
# version (from package.json) and the build date into the pages that carry them.
# Set REQUIRE_NOTES=1 to fail when CHANGELOG.md has no bullets for this version.
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION="${VERSION:-$(node -p "require('./package.json').version")}"
BUILD_DATE="${BUILD_DATE:-$(date -u +%Y-%m-%d)}"
OUT="${OUT:-_site}"
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$ ]]; then
echo "error: VERSION '$VERSION' is not a semantic version" >&2
exit 1
fi
rm -rf "$OUT"
cp -R site "$OUT"
for f in "$OUT/index.html" "$OUT/sitemap.xml" "$OUT/llms.txt" "$OUT/sw.js"; do
sed -i.bak -e "s/__VERSION__/${VERSION}/g" -e "s/__BUILD_DATE__/${BUILD_DATE}/g" "$f"
rm -f "$f.bak"
done
# Release notes for this version, baked into the page ("What's new") and
# published as version.json so open games can spot a newer release.
NOTES="$(node scripts/release-notes.js "$VERSION")"
if [ "${REQUIRE_NOTES:-}" = "1" ] && [ "$NOTES" = "[]" ]; then
echo "error: CHANGELOG.md has no '## [$VERSION]' section with bullets (still under [Unreleased]?)" >&2
exit 1
fi
node -e '
const fs=require("fs"),[,out,v,d,notes]=process.argv;
const f=out+"/index.html",ph="/*__RELEASE_NOTES__*/[]",html=fs.readFileSync(f,"utf8");
if(!html.includes(ph)){console.error("error: release-notes placeholder missing from index.html");process.exit(1);}
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
fs.writeFileSync(f,html.replace(ph,()=>notes.replace(/</g,"\\u003c")));
fs.writeFileSync(out+"/version.json",JSON.stringify({version:v,date:d,notes:JSON.parse(notes)},null,2)+"\n");
' "$OUT" "$VERSION" "$BUILD_DATE" "$NOTES"
if grep -rl "__VERSION__\|__BUILD_DATE__" "$OUT" >/dev/null; then
echo "error: unreplaced placeholders left in $OUT" >&2
exit 1
fi
echo "Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${OUT}/"

59
scripts/dev.js Normal file
View file

@ -0,0 +1,59 @@
#!/usr/bin/env node
// Development server: http://localhost:8080 (PORT=… to change). The page is assembled from src/ on every
// request, static files come straight from site/, and the browser reloads itself when you save a file.
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has.
// No dependencies: plain node:http. For the production build as GitHub Pages will serve it: npm run serve.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { assemble, ROOT } = require('./lib/page');
const PORT = +process.env.PORT || 8080;
const SITE = path.join(ROOT, 'site');
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json' };
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
const clients = new Set();
function page() {
const { html, map } = assemble();
// Errors report a line of the assembled page; the console also says which file under src/ that is.
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${JSON.stringify(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
return html.replace('</body>', `${hint}${RELOAD}</body>`);
}
http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/__dev') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(': hi\n\n');
clients.add(res);
req.on('close', () => clients.delete(res));
return;
}
try {
if (url.pathname === '/' || url.pathname === '/index.html') {
res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' });
return res.end(page());
}
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
res.writeHead(404, { 'content-type': TYPES['.html'] });
return res.end(fs.readFileSync(path.join(SITE, '404.html')));
}
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
fs.createReadStream(file).pipe(res);
} catch (e) {
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
res.end(String(e && e.stack || e));
}
}).listen(PORT, () => console.log(`Series of Tubes (dev): http://localhost:${PORT}/ — edits in src/ and site/ reload the page`));
let timer = null;
for (const dir of ['src', 'site']) {
fs.watch(path.join(ROOT, dir), { recursive: true }, () => {
clearTimeout(timer);
timer = setTimeout(() => { for (const c of clients) c.write('data: reload\n\n'); }, 100);
});
}

69
scripts/i18n-add.js Normal file
View file

@ -0,0 +1,69 @@
#!/usr/bin/env node
// Adds, changes, renames or removes labels, keeping every dictionary sorted (scripts/lib/dict.js).
// English is src/i18n/en.js; translations are site/i18n/<lang>.js.
//
// node scripts/i18n-add.js changes.json {"en": {"pnis.ready": "Ready in {n} days"},
// "it": {"pnis.ready": "Pronto tra {n} giorni"},
// "fr": {"pnis.old_label": null}}
// a string sets the text, {"one":…,"other":…} sets a plural,
// null removes it (null under "en" removes it from every language)
// node scripts/i18n-add.js - the same JSON from stdin
// node scripts/i18n-add.js --rename old.label new.label in every dictionary and everywhere in src/
const fs = require('node:fs');
const path = require('node:path');
const D = require('./lib/dict');
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
const all = () => ['en', ...D.langs()];
const die = (m) => { console.error(m); process.exit(1); };
const args = process.argv.slice(2);
if (args[0] === '--rename') {
const [, from, to] = args;
if (!LABEL.test(from || '') || !LABEL.test(to || '')) die('usage: i18n-add.js --rename old.label new.label');
for (const lang of all()) {
const { header, dict } = D.read(lang);
if (!(from in dict)) continue;
if (to in dict) die(`${lang}: already has ${to}`);
dict[to] = dict[from];
delete dict[from];
D.write(lang, dict, header);
}
// The code: quoted labels in tr()/trn()/N_() calls and tables, and data-i18n attributes.
const { listFiles } = require('./lib/page');
const src = path.join(__dirname, '..', 'src');
let n = 0;
for (const f of listFiles(src)) {
if (f === 'i18n/en.js') continue;
const p = path.join(src, f), t = fs.readFileSync(p, 'utf8');
const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/\./g, '\\.')}\1`, 'g'), (m, q) => { n++; return q + to + q; });
if (u !== t) fs.writeFileSync(p, u);
}
console.log(`renamed ${from} → ${to} in every dictionary and ${n} place(s) in src/`);
process.exit(0);
}
if (args.length !== 1) die('usage: i18n-add.js changes.json | - | --rename old.label new.label');
const changes = JSON.parse(fs.readFileSync(args[0] === '-' ? 0 : args[0], 'utf8'));
const en = D.read('en').dict;
const order = Object.keys(changes).sort((a, b) => (a === 'en' ? -1 : b === 'en' ? 1 : 0)); // English first
for (const lang of order) {
if (!all().includes(lang)) die(`no dictionary for ${lang} (English is src/i18n/en.js, translations site/i18n/<lang>.js)`);
const { header, dict } = lang === 'en' ? { header: D.read('en').header, dict: en } : D.read(lang);
let set = 0, del = 0;
for (const [label, v] of Object.entries(changes[lang])) {
if (!LABEL.test(label)) die(`${lang}: ${JSON.stringify(label)} is not a label like 'area.some_words'`);
if (v === null) {
if (label in dict) { delete dict[label]; del++; }
if (lang === 'en') for (const l of D.langs()) { const d = D.read(l); if (label in d.dict) { delete d.dict[label]; D.write(l, d.dict, d.header); } }
continue;
}
const ok = typeof v === 'string' ? !!v.trim() : v && typeof v.one === 'string' && typeof v.other === 'string' && v.one.trim() && v.other.trim();
if (!ok) die(`${lang}: ${label}: give a non-empty string, or {"one": …, "other": …}`);
if (lang !== 'en' && !(label in en)) die(`${lang}: ${label} has no English yet; add it under "en" first`);
if (lang !== 'en' && (typeof v === 'string') !== (typeof en[label] === 'string')) die(`${lang}: ${label} must be ${typeof en[label] === 'string' ? 'a string' : 'a plural {one, other}'} like its English`);
dict[label] = v; set++;
}
D.write(lang, dict, header);
console.log(`${lang}: ${set} set, ${del} removed`);
}

View file

@ -1,69 +1,110 @@
#!/usr/bin/env node
// Checks a translation against the English text in site/index.html: every tr()/trn()/N_() literal and
// every data-i18n text, aria-label and title in the static markup should have an entry, no stale entry
// should linger, and each translation must keep the {placeholders} and HTML tags of its English key.
// Usage: node scripts/i18n-check.js [lang ...] [--summary FILE] (default: every site/i18n/*.js)
// It also checks that each language is offered in the game and cached for offline play, and with --summary
// appends a Markdown coverage table (the CI job writes it to the run's summary page).
// Checks the translations. Text is keyed by label: tr('area.some_label') in src/ and data-i18n="…"
// (data-i18n-aria-label, data-i18n-title) in src/index.html, with the English in src/i18n/en.js.
//
// node scripts/i18n-check.js [lang ...] [--summary FILE] [--fix] (default: every site/i18n/*.js)
//
// English: every label the code uses is defined, every defined label is used, labels look like
// `area.words`, and the English left in the static markup matches en.js.
// Each translation: nothing missing, nothing stale, and every entry keeps the {placeholders}, HTML tags and
// plural forms of its English. Every dictionary is sorted, one entry per line (--fix sorts them), each
// language is offered in the game and cached for offline play. --summary appends a Markdown coverage table
// (the CI job writes it to the run's summary page).
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const D = require('./lib/dict');
const { CALL } = require('./legacy/labels');
const SITE = path.join(__dirname, '..', 'site');
const LIT = String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`;
const CALL = new RegExp(String.raw`(?<![\w$.])(tr|trn|N_)\(\s*(${LIT})(?:\s*,\s*(${LIT}))?`, 'g');
const CTX = vm.createContext({});
const literal = (s) => vm.runInContext(s, CTX);
const page = () => require('./lib/page').assemble().html;
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
// English keys used by the game. Calls whose text is not a literal cannot be checked and are skipped.
function sourceKeys(html) {
const keys = new Set();
// The labels the game uses, with problems in how they are used.
function sourceLabels(html) {
const labels = new Set(), problems = [];
const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
for (const m of scripts.matchAll(CALL)) {
keys.add(literal(m[2]));
if (m[1] === 'trn' && m[3]) keys.add(literal(m[3]));
const l = m[2].slice(1, -1);
if (!LABEL.test(l)) problems.push(`${m[1]}(${m[2].slice(0, 60)}…): not a label like 'area.some_words'`);
else labels.add(l);
if (m[1] === 'trn' && m[3]) problems.push(`trn(${m[2]}, ${m[3].slice(0, 30)}…): plurals take one label, trn('area.label', n)`);
}
// A label the build cannot see (a bare string, not the first argument of tr/trn/N_) would not be shrunk
// along with its dictionary entry, and would show as raw text in the shipped game.
const code = scripts.replace(/\(window\.I18N=window\.I18N\|\|\{\}\)\.en=\{[\s\S]*?\n\};\n/, '');
const seen = new Set();
for (const m of code.matchAll(CALL)) seen.add(m.index + m[0].indexOf(m[2]));
for (const m of code.matchAll(/(['"\x60])([a-z0-9_]+(?:\.[a-z0-9_]+)+)\1/g)) {
if (!seen.has(m.index) && /_|\.[a-z]+\./.test(m[2]) && !/\.(js|json|html|css|png|svg|es)$/.test(m[2])) problems.push(`label ${m[2]} outside tr()/trn()/N_(): wrap it in N_() so the build can see it`);
}
const { JSDOM } = require('jsdom');
const doc = new JSDOM(html).window.document;
for (const el of doc.querySelectorAll('[data-i18n]')) keys.add(el.textContent);
for (const a of ['aria-label', 'title']) for (const el of doc.querySelectorAll(`[${a}]`)) keys.add(el.getAttribute(a));
return keys;
const markup = [];
for (const el of doc.querySelectorAll('[data-i18n]')) markup.push([el.dataset.i18n, el.textContent, 'text']);
for (const a of ['aria-label', 'title']) for (const el of doc.querySelectorAll(`[data-i18n-${a}]`)) markup.push([el.getAttribute(`data-i18n-${a}`), el.getAttribute(a), a]);
for (const el of doc.querySelectorAll('[aria-label]:not([data-i18n-aria-label]),[title]:not([data-i18n-title])')) {
if (!el.closest('noscript')) problems.push(`<${el.tagName.toLowerCase()} ${el.hasAttribute('title') ? 'title' : 'aria-label'}="…"> in the markup has no data-i18n-${el.hasAttribute('title') ? 'title' : 'aria-label'} label`);
}
for (const [l] of markup) LABEL.test(l) ? labels.add(l) : problems.push(`data-i18n="${l}": not a label`);
return { labels, markup, problems };
}
function loadDict(file) {
const window = {};
vm.runInNewContext(fs.readFileSync(file, 'utf8'), { window });
const lang = path.basename(file, '.js');
return (window.I18N || {})[lang] || {};
return D.parse(fs.readFileSync(file, 'utf8'), lang);
}
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(' ');
const tags = (s) => (s.match(/<\/?[a-z][a-z0-9]*/gi) || []).map((t) => t.toLowerCase()).sort().join(' ');
const forms = (v) => (typeof v === 'string' ? [['', v]] : v && typeof v === 'object' ? [['one', v.one], ['other', v.other]] : [['', v]]);
// Entries whose translation drops or invents a {placeholder} or an HTML tag, or is empty.
function brokenEntries(dict) {
return Object.entries(dict).filter(([en, xx]) => typeof xx !== 'string' || !xx.trim() ||
placeholders(en) !== placeholders(xx) || tags(en) !== tags(xx)).map(([en]) => en);
// Entries whose translation is empty, has the wrong shape (plural or not), or drops or invents a
// {placeholder} or an HTML tag. Without `en`, an entry is compared with itself (shape and emptiness only).
function brokenEntries(dict, en = null) {
return Object.entries(dict).filter(([l, xx]) => {
const e = en ? en[l] : xx;
if (e === undefined) return false; // stale, reported as unused
if ((typeof e === 'string') !== (typeof xx === 'string')) return true;
const ef = forms(e), xf = forms(xx);
return xf.some(([k, x], i) => typeof x !== 'string' || !x.trim() || placeholders(ef[i][1]) !== placeholders(x) || tags(ef[i][1]) !== tags(x)) ||
ef.some(([k]) => k && typeof xx[k] !== 'string');
}).map(([l]) => l);
}
function check(keys, dict) {
function check(en, dict) {
return {
missing: [...keys].filter((k) => !(k in dict)),
unused: Object.keys(dict).filter((k) => !keys.has(k)),
broken: brokenEntries(dict),
missing: Object.keys(en).filter((k) => !(k in dict)),
unused: Object.keys(dict).filter((k) => !(k in en)),
broken: brokenEntries(dict, en),
};
}
module.exports = { loadDict, brokenEntries };
// The English dictionary against the code.
function checkEnglish(src, en) {
const out = [...src.problems];
for (const l of src.labels) if (!(l in en)) out.push(`label used but not in src/i18n/en.js: ${l}`);
for (const l of Object.keys(en)) {
if (!src.labels.has(l)) out.push(`in src/i18n/en.js but never used: ${l}`);
if (!LABEL.test(l)) out.push(`not a label like 'area.some_words': ${l}`);
}
for (const [l, text, where] of src.markup) {
if (typeof en[l] === 'string' && en[l] !== text) out.push(`markup ${where} for ${l} says ${JSON.stringify(text)}, en.js says ${JSON.stringify(en[l])}`);
}
for (const l of brokenEntries(en)) out.push(`empty or malformed English: ${l}`);
if (!D.tidy('en')) out.push('src/i18n/en.js is not sorted one entry per line: run npm run i18n:fix');
return out;
}
module.exports = { loadDict, brokenEntries, sourceLabels };
// A language file only works if the game offers it and the offline cache keeps it.
function registration(lang) {
const html = fs.readFileSync(path.join(SITE, 'index.html'), 'utf8');
function registration(lang, html) {
const sw = fs.readFileSync(path.join(SITE, 'sw.js'), 'utf8');
const out = [];
const m = html.match(/SOT_LANGS=\{([^}]*)\}/);
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in site/index.html)');
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)');
if (!sw.includes(`/i18n/${lang}.js`)) out.push('not cached for offline play (CORE in site/sw.js)');
if (!D.tidy(lang)) out.push('not sorted one entry per line: run npm run i18n:fix');
return out;
}
@ -71,20 +112,29 @@ if (require.main === module) {
const args = process.argv.slice(2);
const si = args.indexOf('--summary');
const summary = si >= 0 ? args.splice(si, 2)[1] : null; // append a Markdown table here (CI: $GITHUB_STEP_SUMMARY)
const keys = sourceKeys(fs.readFileSync(path.join(SITE, 'index.html'), 'utf8'));
const files = (args.length ? args.map((l) => `${l}.js`) : fs.readdirSync(path.join(SITE, 'i18n')))
.map((f) => path.join(SITE, 'i18n', f));
let bad = false;
const rows = [];
for (const file of files) {
const lang = path.basename(file, '.js');
const r = check(keys, loadDict(file));
const reg = registration(lang);
const cov = keys.size ? (keys.size - r.missing.length) / keys.size : 1;
const fi = args.indexOf('--fix');
if (fi >= 0) {
args.splice(fi, 1);
for (const lang of ['en', ...(args.length ? args : D.langs())]) { const { header, dict } = D.read(lang); D.write(lang, dict, header); }
}
const html = page();
const en = D.read('en').dict;
const src = sourceLabels(html);
const enProblems = checkEnglish(src, en);
const n = Object.keys(en).length;
console.log(`en.js: ${n} labels, ${enProblems.length} problems`);
for (const p of enProblems) console.log(` ${p}`);
let bad = enProblems.length > 0;
const langs = args.length ? args : D.langs();
const rows = [], results = {};
for (const lang of langs) {
const r = results[lang] = check(en, loadDict(D.fileOf(lang)));
const reg = registration(lang, html);
const cov = n ? (n - r.missing.length) / n : 1;
const pctTxt = `${(Math.floor(cov * 1000) / 10).toFixed(1)}%`;
console.log(`${path.basename(file)}: ${r.missing.length} missing, ${r.unused.length} unused, ${r.broken.length} broken (${pctTxt} of ${keys.size} strings)`);
console.log(`${lang}.js: ${r.missing.length} missing, ${r.unused.length} unused, ${r.broken.length} broken (${pctTxt} of ${n} labels)`);
for (const [label, list] of [['missing', r.missing], ['unused', r.unused], ['broken', r.broken], ['registration', reg]]) {
for (const k of list) console.log(` ${label}: ${JSON.stringify(k)}`);
for (const k of list) console.log(` ${label}: ${k}${label === 'missing' ? ` (${JSON.stringify(forms(en[k])[0][1]).slice(0, 80)})` : ''}`);
}
const ok = r.missing.length + r.unused.length + r.broken.length + reg.length === 0;
bad ||= !ok;
@ -92,9 +142,10 @@ if (require.main === module) {
}
if (summary) {
const list = (title, items) => items.length ? `\n<details><summary>${title} (${items.length})</summary>\n\n${items.slice(0, 200).map((k) => '- `' + k.replace(/`/g, "'") + '`').join('\n')}\n</details>\n` : '';
let md = `## Translations\n\n${keys.size} English strings in the game.\n\n| Language | Coverage | Missing | Unused | Broken | Registered | |\n|---|---|---|---|---|---|---|\n${rows.join('\n')}\n`;
for (const file of files) {
const r = check(keys, loadDict(file)), lang = path.basename(file, '.js');
let md = `## Translations\n\n${n} labels in the game${enProblems.length ? `, ${enProblems.length} problems with the English` : ''}.\n\n| Language | Coverage | Missing | Unused | Broken | Registered | |\n|---|---|---|---|---|---|---|\n${rows.join('\n')}\n`;
md += list('English: problems', enProblems);
for (const lang of langs) {
const r = results[lang];
md += list(`${lang}: missing`, r.missing) + list(`${lang}: broken`, r.broken) + list(`${lang}: unused`, r.unused);
}
fs.appendFileSync(summary, md + '\n');

138
scripts/legacy/labels.js Normal file
View file

@ -0,0 +1,138 @@
// Turns English-keyed translation calls into label-keyed ones, for code written before labels (1.34 and
// older): tr('Delivery: about a month') → tr('pnis.delivery_about_a_month'), trn('{n} POP','{n} POPs',n)
// → trn('common.n_pop',n), and data-i18n markup → data-i18n="page.…". It is how src/ got its labels, and
// transforms.js runs it on old branches so their work lines up with src/ (see port-branch.js).
//
// Labels for text that already has one come from `known` (the English dictionary, src/i18n/en.js);
// new text gets a label made from its first words and where it is used, the same way every time.
const vm = require('node:vm');
const LIT = String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`;
const CALL = new RegExp(String.raw`(?<![\w$.])(tr|trn|N_)\(\s*(${LIT})(?:\s*,\s*(${LIT}))?`, 'g');
const CTX = vm.createContext({});
const literal = (s) => vm.runInContext(s, CTX);
const hash = (t) => { let h = 2166136261; for (let i = 0; i < t.length; i++) { h ^= t.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(16).padStart(8, '0'); };
// "<b>Laser shortage!</b> {n} days…" → "laser_shortage_n_days"
function slug(text) {
const words = text.replace(/<[^>]*>/g, ' ').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
.replace(/[^a-z0-9]+/g, ' ').trim().split(' ').filter(Boolean);
let s = '';
for (const w of words) { if (s && (s + '_' + w).length > 36) break; s = s ? s + '_' + w : w; if (s.split('_').length >= 6) break; }
return s || 'x';
}
// "game/70-rules/30-pnis.js" → "pnis"; the shell → "page".
const areaOf = (file) => file === 'index.html' ? 'page' : file.split('/').pop().replace(/^\d+-/, '').replace(/\.[a-z]+$/, '').replace(/-/g, '_');
const folderOf = (file) => file === 'index.html' ? 'page' : file.split('/').slice(0, -1).pop().replace(/^\d+-/, '').replace(/-/g, '_');
// A plural is keyed by both forms.
const pkey = (one, other) => `${one}\u0000${other}`;
const ENT = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", apos: "'", nbsp: ' ' };
const decode = (s) => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (m, e) => ENT[e]);
// Every translatable text in the partials: [{file, kind:'call'|'markup'|'attr', key, one, other, …}].
function scan(parts) {
const out = [];
for (const [file, text] of parts) {
if (file.endsWith('.js') || file === 'index.html') {
for (const m of text.matchAll(CALL)) {
if (file === 'index.html' && !inScript(text, m.index)) continue;
if (m[1] === 'trn') {
if (!m[3]) throw new Error(`${file}: trn() needs two literal forms: ${m[0].slice(0, 60)}`);
const one = literal(m[2]), other = literal(m[3]);
out.push({ file, kind: 'call', fn: 'trn', key: pkey(one, other), one, other, at: m.index + m[0].indexOf(m[2]), end: m.index + m[0].length });
} else {
const t = literal(m[2]);
out.push({ file, kind: 'call', fn: m[1], key: t, text: t, at: m.index + m[0].indexOf(m[2]), end: m.index + m[0].indexOf(m[2]) + m[2].length });
}
}
}
if (file === 'index.html') {
for (const m of text.matchAll(/<([a-z][a-z0-9]*)\b([^>]*?)\sdata-i18n>([^<]*)<\/\1>/g)) {
out.push({ file, kind: 'markup', key: decode(m[3]), text: decode(m[3]), at: m.index + m[0].indexOf(' data-i18n>'), end: m.index + m[0].indexOf(' data-i18n>') + ' data-i18n'.length });
}
for (const m of text.matchAll(/<[a-z][a-z0-9]*\b[^>]*>/g)) {
if (inScript(text, m.index)) continue;
for (const a of m[0].matchAll(/\s(aria-label|title)="([^"]*)"/g)) {
const pos = m.index + a.index + a[0].length;
out.push({ file, kind: 'attr', attr: a[1], key: decode(a[2]), text: decode(a[2]), at: pos, end: pos });
}
}
}
}
return out;
}
// Inside one of the shell's <script> elements (the language loader), where text is code, not markup.
function inScript(html, i) {
const open = html.lastIndexOf('<script', i), close = html.lastIndexOf('</script>', i);
return open > close;
}
// Labels for every text in the scan: known ones from `known` (Map key → label), new ones made here.
function assign(items, known) {
const labels = new Map(known), taken = new Set(known.values());
const files = new Map();
for (const it of items) { if (!files.has(it.key)) files.set(it.key, new Set()); files.get(it.key).add(it.file); }
for (const it of items) {
if (labels.has(it.key)) continue;
const fs = [...files.get(it.key)];
const folders = new Set(fs.map(folderOf));
// Short, plain words ("Off", "Close", "Customers") are shared vocabulary wherever they appear.
const short = !/[{<]/.test(it.one ?? it.text) && slug(it.one ?? it.text).split('_').length <= 2;
const area = short ? 'common' : fs.length === 1 ? areaOf(fs[0]) : folders.size === 1 ? [...folders][0] : 'common';
const base = `${area}.${slug(it.one ?? it.text)}`;
let l = base;
if (taken.has(l)) l = `${base}_${hash(it.key).slice(0, 4)}`;
if (taken.has(l)) l = `${base}_${hash(it.key)}`;
labels.set(it.key, l);
taken.add(l);
}
return labels;
}
// Rewrites the partials to use labels. Returns {parts, en}: en maps each label to its English
// (a string, or {one, other} for plurals), for every text these partials use.
function labelize(parts, known = new Map()) {
const items = scan(parts);
const labels = assign(items, known);
const en = new Map();
const byFile = new Map();
for (const it of items) {
const l = labels.get(it.key);
en.set(l, it.fn === 'trn' ? { one: it.one, other: it.other } : it.text);
if (!byFile.has(it.file)) byFile.set(it.file, []);
byFile.get(it.file).push({ ...it, label: l });
}
const out = parts.map(([file, text]) => {
const list = (byFile.get(file) || []).sort((a, b) => b.at - a.at);
for (const it of list) {
const rep = it.kind === 'call' ? `'${it.label}'`
: it.kind === 'markup' ? ` data-i18n="${it.label}"`
: ` data-i18n-${it.attr}="${it.label}"`;
text = text.slice(0, it.at) + rep + text.slice(it.end);
}
return [file, text];
});
return { parts: out, en, labels };
}
// The `known` map from an English dictionary object {label: text | {one, other}}.
function knownFrom(enDict) {
const k = new Map();
for (const [l, v] of Object.entries(enDict || {})) k.set(typeof v === 'string' ? v : pkey(v.one, v.other), l);
return k;
}
// A dictionary keyed by English text (it.js before labels) → keyed by label, using the labels made above.
function relabelDict(old, labels) {
const out = {};
for (const [key, l] of labels) {
if (key.includes('\u0000')) {
const [one, other] = key.split('\u0000');
if (typeof old[one] === 'string' && typeof old[other] === 'string') out[l] = { one: old[one], other: old[other] };
} else if (typeof old[key] === 'string') out[l] = old[key];
}
return out;
}
module.exports = { labelize, knownFrom, relabelDict, scan, slug, pkey, CALL, LIT };

View file

@ -0,0 +1,134 @@
#!/usr/bin/env node
// Carries a branch that still edits site/index.html (started before the page was split into src/) over
// to the src/ layout. Run it in the middle of merging main into that branch:
//
// git checkout my-branch
// git merge origin/main # stops: site/index.html was deleted on main
// node scripts/legacy/port-branch.js # moves your edits into src/, merges the dictionaries
// git status # fix any conflict markers it reports, then
// git commit
//
// How: your branch's site/index.html and the one you started from are both split with the same rules
// that made src/ (split-index-html.js + transforms.js), and each partial gets a three-way merge
// (git merge-file) into the src/ file from main. Your dictionary changes (site/i18n/*.js) are applied
// entry by entry onto main's sorted dictionaries, so appended lines never conflict. Text keyed by English
// (1.34 and older) gets the labels src/ uses, and new text gets new labels in src/i18n/en.js (labels.js).
//
// It also works the other way round, merging commits made on the old layout into a branch that has src/.
// Options: --base REF (the pre-split commit the old-layout side started from; default: merge-base of HEAD
// and MERGE_HEAD) and --theirs REF (the old-layout side; default: whichever side has site/index.html).
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const { split } = require('./split-index-html');
const { transformFull } = require('./transforms');
const { relabelDict } = require('./labels');
const D = require('../lib/dict');
const ROOT = path.join(__dirname, '..', '..');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const git = (...a) => execFileSync('git', a, { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] });
const show = (ref, p) => { try { return git('show', `${ref}:${p}`); } catch { return null; } };
const die = (m) => { console.error(`port-branch: ${m}`); process.exit(1); };
let mergeHead = null;
try { mergeHead = git('rev-parse', '-q', '--verify', 'MERGE_HEAD').trim(); } catch {}
// Works in both directions: merging main into an old branch, or old-layout commits into a src/ branch.
// "theirs" is the side that still has site/index.html; the other side (with src/) is the target.
const hasSrc = (ref) => show(ref, 'src/index.html') !== null;
const theirs = opt('--theirs', null) || (mergeHead && hasSrc('HEAD') ? mergeHead : 'HEAD');
const target = mergeHead ? (theirs === mergeHead ? 'HEAD' : mergeHead) : null;
const base = opt('--base', null) || (mergeHead ? git('merge-base', 'HEAD', mergeHead).trim() : null);
if (!base) die('no merge in progress: run `git merge origin/main` first, or pass --base REF');
if (!fs.existsSync(path.join(ROOT, 'src', 'index.html'))) die('src/ is missing: merge main (which has src/) first');
const basePage = show(base, 'site/index.html'), theirPage = show(theirs, 'site/index.html');
if (!basePage) die(`${base} has no site/index.html; is it from before the split?`);
if (!theirPage) die(`${theirs} has no site/index.html; nothing to port`);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-port-'));
const parts = (html, label) => {
try { const r = transformFull(split(html)); return Object.assign(new Map(r.parts), { labels: r.labels }); }
catch (e) { die(`could not split ${label}'s site/index.html the way src/ was made: ${e.message}`); }
};
const B = parts(basePage, 'the base'), T = parts(theirPage, 'your branch');
let changed = 0;
const conflicts = [];
// Applies the entries that changed between two dictionaries onto a third, reporting entries changed on both sides.
const same = (x, y) => JSON.stringify(x) === JSON.stringify(y); // plurals are objects
function applyDelta(db, dt, dict, rel) {
let n = 0;
for (const k of new Set([...Object.keys(db), ...Object.keys(dt)])) {
if (same(db[k], dt[k])) continue;
if (k in dict && !same(db[k], dict[k]) && !same(dict[k], dt[k]) && k in dt) conflicts.push(`${rel}: ${JSON.stringify(k)} changed on both sides (kept yours)`);
if (k in dt) dict[k] = dt[k]; else delete dict[k];
n++;
}
return n;
}
for (const [file, t] of T) {
const b = B.get(file);
if (b === t) continue; // you did not touch this part
if (file === 'i18n/en.js') {
// English is merged entry by entry, like the translations below.
const e = D.read('en');
const n = applyDelta(b ? D.parse(b, 'en') : {}, D.parse(t, 'en'), e.dict, 'src/i18n/en.js');
D.write('en', e.dict, e.header);
git('add', 'src/i18n/en.js');
console.log(`src/i18n/en.js: ${n} of your entries applied`);
continue;
}
const ours = path.join(ROOT, 'src', file);
if (!fs.existsSync(ours)) { conflicts.push(`${file} (no longer exists on main; apply your change by hand)`); continue; }
const fb = path.join(tmp, 'base'), ft = path.join(tmp, 'theirs');
fs.writeFileSync(fb, b || '');
fs.writeFileSync(ft, t);
const r = spawnSync('git', ['merge-file', '-L', 'main', '-L', 'base', '-L', 'your branch', ours, fb, ft], { cwd: ROOT });
changed++;
if (r.status !== 0) conflicts.push(`src/${file}`);
}
// Text your side still uses (for example inside a conflict) whose English main has since changed or dropped:
// keep its English, so whichever side of the conflict you keep has its text.
{
const tEn = T.get('i18n/en.js') ? D.parse(T.get('i18n/en.js'), 'en') : {};
const e = D.read('en');
const used = new Set();
for (const f of require('../lib/page').listFiles(path.join(ROOT, 'src'))) {
if (f === 'i18n/en.js') continue;
for (const m of fs.readFileSync(path.join(ROOT, 'src', f), 'utf8').matchAll(/['"]([a-z0-9_]+(?:\.[a-z0-9_]+)+)['"]/g)) used.add(m[1]);
}
const back = [...used].filter((l) => !(l in e.dict) && l in tEn);
if (back.length) { for (const l of back) e.dict[l] = tEn[l]; D.write('en', e.dict, e.header); git('add', 'src/i18n/en.js'); }
}
// Dictionaries: your additions, edits and removals, applied onto main's sorted files.
for (const lang of D.langs()) {
const rel = `site/i18n/${lang}.js`;
const tb = show(base, rel), tt = show(theirs, rel);
if (!tt || tb === tt) continue;
// Old dictionaries are keyed by English text: give them the same labels the code got.
const old = (t, labels) => { const d = D.parse(t, lang); return Object.keys(d).some((k) => /\s/.test(k)) ? relabelDict(d, labels) : d; };
const db = tb ? old(tb, B.labels) : {}, dt = old(tt, T.labels);
const main = target ? show(target, rel) : null;
// During a merge the working file may hold conflict markers, so start from main's own copy.
const { header, dict } = main ? { header: main.slice(0, main.indexOf('(window.I18N')), dict: D.parse(main, lang) } : D.read(lang);
const n = applyDelta(db, dt, dict, rel);
D.write(lang, dict, header);
git('add', rel);
console.log(`${rel}: ${n} of your entries applied`);
}
if (fs.existsSync(path.join(ROOT, 'site', 'index.html'))) fs.rmSync(path.join(ROOT, 'site', 'index.html'));
try { git('rm', '-q', '--cached', '--ignore-unmatch', 'site/index.html'); } catch {}
fs.rmSync(tmp, { recursive: true, force: true });
console.log(`Ported your site/index.html changes into ${changed} file(s) under src/.`);
if (conflicts.length) {
console.log('Resolve these by hand (look for <<<<<<< markers), then git add them:');
for (const c of conflicts) console.log(` ${c}`);
process.exit(1);
}
git('add', 'src');
console.log('No conflicts. Run npm test, then git commit.');

View file

@ -0,0 +1,187 @@
#!/usr/bin/env node
// Splits a pre-split site/index.html (one file: HTML, CSS and JS) into the src/ layout.
//
// This is how src/ was made, and it stays around for work that was started before the split: a branch
// or pull request that still edits site/index.html. scripts/legacy/port-branch.js uses it to carry those
// edits over to src/ (see CONTRIBUTING.md, "Your branch still edits site/index.html?").
//
// node scripts/legacy/split-index-html.js INDEX_HTML OUT_DIR writes OUT_DIR/index.html and partials
//
// The cut points are found by content, not line numbers, so the same rules split any version from around
// the split (1.33.x–1.34.x). Comments directly above a cut point travel with the code below them.
const fs = require('node:fs');
const path = require('node:path');
// [partial, first line of it]. Each regex is looked for after the previous cut.
const CSS = [
['styles/00-base.css', /^\/\* Layout: full-bleed/],
['styles/10-hud.css', /^\/\* HUD \*\/$/],
['styles/20-drawers.css', /^\/\* drawers \*\/$/],
['styles/30-toasts.css', /^\/\* toasts \*\/$/],
['styles/40-modal.css', /^\/\* modal \*\/$/],
['styles/50-tablet.css', /^\/\* Tablets in landscape/],
['styles/60-phone.css', /^\/\* =+ PHONES/],
];
const JS = [
['game/00-core/10-language.js', /^\/\* =+ LANGUAGE/],
['game/00-core/20-analytics.js', /^\/\* =+ ANALYTICS/],
['game/10-catalog/10-economy.js', /^\/\* =+ CONSTANTS/],
['game/10-catalog/20-routers.js', /^const RG=\[/],
['game/10-catalog/30-supply-chain.js', /^\/\* -+ Supply chain/],
['game/10-catalog/40-ports.js', /^\/\* Ports are finite/],
['game/10-catalog/50-dark-fiber.js', /^\/\/ dark fiber & optical gear/],
['game/10-catalog/60-reach-and-subsea.js', /^\/\* Reach \(#17/],
['game/20-world/10-projection.js', /^\/\* =+ WORLD/],
['game/20-world/20-landmasses.js', /^const LANDS_LL=/],
['game/20-world/30-coastline.js', /^\/\/ Drawn coastline/],
['game/20-world/40-city-coords.js', /^const CITY_LL=/],
['game/20-world/50-cities.js', /^const CITIES=\[/],
['game/20-world/60-cables.js', /^const CABLES=\[/],
['game/30-networks/10-networks.js', /^\/\* =+ NETWORKS/],
['game/30-networks/20-rival-exchanges.js', /^\/\* Rival exchanges/],
['game/30-networks/30-long-tail.js', /^\/\* The long tail/],
['game/30-networks/40-traffic-shares.js', /^const NET=Object\.fromEntries/],
['game/40-progress/10-businesses.js', /^\/\* =+ BUSINESSES/],
['game/40-progress/20-goals.js', /^\/\* =+ GOALS/],
['game/50-state.js', /^\/\* =+ STATE/],
['game/60-features/10-banks.js', /^\/\* =+ BANKS & LOANS/],
['game/60-features/20-scenarios.js', /^\/\* Seeded games/],
['game/60-features/30-conferences.js', /^\/\* -+ conference season/],
['game/60-features/40-tutorial.js', /^\/\* -+ guided first game/],
['game/60-features/50-traceroute.js', /^\/\* -+ traceroute and looking glass/],
['game/60-features/60-share-card.js', /^\/\* -+ share card/],
['game/60-features/70-scenario-progress.js', /^function scnTick\(/],
['game/60-features/80-new-game.js', /^function newGame\(/],
['game/70-rules/10-helpers.js', /^\/\* =+ HELPERS/],
['game/70-rules/20-exchanges.js', /^\/\* Australian exchanges follow/],
['game/70-rules/30-pnis.js', /^\/\* -+ PNIs with the big networks/],
['game/70-rules/40-peering-inbox.js', /^\/\* -+ The peering inbox/],
['game/70-rules/50-peering-policy.js', /^\/\* Big networks sometimes refuse/],
['game/70-rules/60-de-kicks.js', /^\/\* DE-KICKS Group/],
['game/70-rules/70-sold-out.js', /^\/\* Sold out:/],
['game/70-rules/80-hot-ports-and-rank.js', /^const HOT=/],
['game/80-simulation/10-dijkstra.js', /^\/\* =+ SIMULATION/],
['game/80-simulation/20-routescript.js', /^\/\* -+ RouteScript/],
['game/80-simulation/30-compute.js', /^const LABS=new Map/],
['game/80-simulation/40-billing.js', /^function p95\(/],
['game/80-simulation/50-sanitize.js', /^const own=/],
['game/80-simulation/60-requirements.js', /^const GRACE_DAYS=/],
['game/80-simulation/70-customers-and-events.js', /^function bizSf\(/],
['game/80-simulation/80-geography-and-latency.js', /^function cnOk\(/],
['game/80-simulation/90-sites-and-service.js', /^const RT=\{/],
['game/85-incidents/10-incidents-and-ddos.js', /^\/\* -+ failures & events/],
['game/85-incidents/20-failures.js', /^function fireFailure\(/],
['game/85-incidents/30-events.js', /^function fireEvent\(/],
['game/88-days/10-day-tick.js', /^\/\* -+ daily tick/],
['game/88-days/20-badges.js', /^const RARITY=/],
['game/90-actions/00-actions.js', /^\/\* =+ ACTIONS/],
['game/90-actions/90-action-helpers.js', /^function landTrenches\(/],
['game/91-save.js', /^\/\* =+ SAVE/],
['game/92-audio.js', /^\/\* =+ AUDIO/],
['game/93-ui/10-dom.js', /^\/\* =+ DOM RENDER/],
['game/93-ui/20-phone.js', /^\/\* =+ PHONE =/],
['game/93-ui/30-install.js', /^\/\* =+ INSTALL/],
['game/93-ui/40-hud-and-panels.js', /^function fitHud\(/],
['game/93-ui/50-city-panel.js', /^function cityPanel\(/],
['game/93-ui/60-decommission.js', /^\/\* Decommissioning POPs/],
['game/93-ui/70-link-panels.js', /^const portMo=/],
['game/94-dashboard/10-progress.js', /^\/\* -+ scenario and level progress/],
['game/94-dashboard/20-meet-a-network.js', /^\/\* -+ where to meet a network/],
['game/94-dashboard/30-customers.js', /^\/\* -+ customers overview/],
['game/94-dashboard/40-connections.js', /^\/\* -+ connections overview/],
['game/94-dashboard/50-lease-swaps.js', /^\/\* Leased lines you could swap/],
['game/94-dashboard/60-dashboard.js', /^function dashTabs\(/],
['game/94-dashboard/70-bank.js', /^function loanSummary\(/],
['game/94-dashboard/80-hint.js', /^function renderHint\(/],
['game/95-modals/10-toasts.js', /^\/\* -+ toasts & modals/],
['game/95-modals/20-notifications.js', /^\/\* -+ notifications:/],
['game/95-modals/30-modal-and-names.js', /^function openModal\(/],
['game/95-modals/40-title.js', /^function showTitle\(/],
['game/95-modals/50-release-notes.js', /^\/\* In-app notes stay short/],
['game/95-modals/60-help.js', /^function showHelp\(/],
['game/95-modals/70-link-modal.js', /^function openLinkModal\(/],
['game/95-modals/80-own-cable.js', /^\/\* Your own subsea cable/],
['game/95-modals/90-fiber-modals.js', /^function dfModalBody\(/],
['game/96-map/10-canvas.js', /^\/\* =+ CANVAS/],
['game/96-map/20-land-and-clouds.js', /^function rng\(seed\)/],
['game/96-map/30-settings.js', /^function i18nDom\(/],
['game/96-map/40-level-of-detail.js', /^\/\* Level of detail/],
['game/96-map/50-link-geometry.js', /^\/\* Parallel waves on the same cable/],
['game/96-map/60-draw.js', /^function draw\(now\)/],
['game/96-map/70-world-layer.js', /^\/\* The land is never drawn/],
['game/96-map/80-cities.js', /^const LBLW=/],
['game/96-map/90-input.js', /^\/\* -+ hit tests & input/],
['game/96-map/95-clicks.js', /^\/\* -+ click delegation/],
['game/99-loop.js', /^\/\* =+ LOOP/],
];
// Moves a cut up over the comment directly above it, so a comment stays with the code it describes.
function liftOverComments(lines, i, floor) {
for (;;) {
const prev = lines[i - 1];
if (i - 1 <= floor || prev === undefined) return i;
if (/^\/\//.test(prev)) { i--; continue; }
if (/\*\/\s*$/.test(prev)) {
// A block comment ending just above: find the "/*" line it starts on, with no other "*/" in between.
let j = i - 1;
while (j > floor && !/^\/\*/.test(lines[j])) j--;
if (j > floor && !lines.slice(j, i - 1).some((l) => l.includes('*/'))) { i = j; continue; }
}
return i;
}
}
// Cuts lines[from, to) into [file, text] pairs by the spec.
function cut(lines, from, to, spec, what) {
// Older versions lack some later sections: a part whose marker is missing is left out, and its code (if
// any) stays in the part before it. The first part of each section is required.
const found = [];
let at = from;
for (const [file, re] of spec) {
let i = at;
while (i < to && !re.test(lines[i])) i++;
if (i >= to) {
if (!found.length) throw new Error(`${what}: no line matches ${re} (for ${file})`);
continue;
}
found.push([file, found.length ? liftOverComments(lines, i, found[found.length - 1][1]) : from]);
at = i + 1;
}
return found.map(([file, s], k) => [file, lines.slice(s, k + 1 < found.length ? found[k + 1][1] : to).map((l) => l + '\n').join('')]);
}
function split(html) {
if (html.includes('\r')) html = html.replace(/\r\n/g, '\n');
const lines = html.split('\n');
const find = (re, from = 0) => { const i = lines.findIndex((l, k) => k >= from && re.test(l)); if (i < 0) throw new Error(`no line matches ${re}`); return i; };
const styleOpen = find(/^<style>$/), styleClose = find(/^<\/style>$/, styleOpen);
// The game script is the last inline <script>, opened with 'use strict'.
const gameOpen = find(/^'use strict';$/), gameClose = find(/^<\/script>$/, gameOpen);
const files = [
...cut(lines, styleOpen + 1, styleClose, CSS, 'styles'),
...cut(lines, gameOpen + 1, gameClose, JS, 'game'),
];
const shell = [
...lines.slice(0, styleOpen + 1), '<!-- @include styles -->',
...lines.slice(styleClose, gameOpen + 1), '<!-- @include game -->',
...lines.slice(gameClose),
].join('\n');
return [['index.html', shell], ...files];
}
module.exports = { split };
if (require.main === module) {
const [input, out] = process.argv.slice(2);
if (!input || !out) { console.error('usage: split-index-html.js INDEX_HTML OUT_DIR'); process.exit(2); }
const parts = split(fs.readFileSync(input, 'utf8'));
// The post-split tidying (see transforms.js) is part of the layout, so ported work lines up with src/.
const { transform } = require('./transforms');
for (const [file, text] of transform(parts)) {
const p = path.join(out, file);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, text);
}
console.log(`Split ${input} into ${parts.length} files under ${out}/`);
}

View file

@ -0,0 +1,120 @@
// Tidying applied right after the split, to cut down merge conflicts. Each one keeps behaviour the same
// and only changes where code sits or how a literal is laid out. They run as part of
// split-index-html.js, so work from older branches lines up with src/ when it is ported.
//
// 1. The ACT map (every player action) becomes one file per area under game/90-actions/: the first file
// declares `const ACT={…}` and the others add to it with Object.assign. Two people adding actions in
// different areas no longer touch the same lines.
// 2. Coordinate tables that lived on one very long line (CITY_LL, CITY_NUDGE, LANDS_LL) get one entry per
// line, CITY_LL and CITY_NUDGE sorted by id: adding a city no longer edits a 4,000-character line
// that everyone else is editing too.
// 3. Translations are keyed by labels, not by English text (labels.js): tr('pnis.delivery_month') with the
// English in src/i18n/en.js, inlined into the page by an `<!-- @include i18n -->` line in the shell.
// [file, first action in it]. A group runs until the next group's first action.
const ACT_GROUPS = [
['game/90-actions/10-interface.js', 'speed'],
['game/90-actions/20-pops-transit-ix.js', 'buildPop'],
['game/90-actions/30-route-script-and-tools.js', 'teEdit'],
['game/90-actions/40-sites-peering-caches.js', 'addSite'],
['game/90-actions/50-customers.js', 'advertise'],
['game/90-actions/60-links.js', 'upLink'],
['game/90-actions/70-dashboard-lists.js', 'custGo'],
['game/90-actions/80-security-and-china.js', 'applyCn'],
['game/90-actions/85-routing-and-routers.js', 'via'],
['game/90-actions/87-fiber-and-hardware.js', 'dfMode'],
['game/90-actions/89-game-and-settings.js', 'randomName'],
];
function splitActions(text) {
const lines = text.split('\n');
if (lines[lines.length - 1] === '') lines.pop();
const open = lines.indexOf('const ACT={'), close = lines.lastIndexOf('};');
if (open < 0 || close < open) throw new Error('90-actions: no `const ACT={ … };` block');
// Old versions without the action-helpers cut keep that code here; it stays after the last group.
const after = lines.slice(close + 1);
const keyAt = (k) => lines.findIndex((l, i) => i > open && i < close && l.startsWith(` ${k}:`));
// A group whose first action does not exist (yet, in an older version) is left out.
const groups = ACT_GROUPS.map(([file, k], g) => [file, g ? keyAt(k) : 0]).filter(([, i]) => i >= 0);
const starts = groups.map(([, i]) => i);
if (starts.some((s, i) => i && s <= starts[i - 1])) throw new Error('90-actions: actions are out of the expected order');
return groups.map(([file], g) => {
const from = g ? starts[g] : 0, to = g + 1 < starts.length ? starts[g + 1] : close;
const body = lines.slice(from, to);
const out = g ? ['Object.assign(ACT,{', ...body, '});'] : [...body, '};'];
if (g === groups.length - 1) out.push(...after);
return [file, out.join('\n') + '\n'];
});
}
// The top-level entries of an array or object literal source "a,b,c" (no brackets around it).
function entries(src) {
const out = [];
let depth = 0, q = null, start = 0;
for (let i = 0; i < src.length; i++) {
const c = src[i];
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
if (c === '"' || c === "'" || c === '`') q = c;
else if ('[{('.includes(c)) depth++;
else if (']})'.includes(c)) depth--;
else if (c === ',' && depth === 0) { out.push(src.slice(start, i).trim()); start = i + 1; }
}
if (depth || q) throw new Error('unbalanced literal');
const last = src.slice(start).trim();
if (last) out.push(last);
return out;
}
const idOf = (e) => e.match(/^["']?([\w$]+)["']?\s*:/)[1];
const byId = (a, b) => (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0);
// `HEAD{entries}TAIL` on one line → HEAD, one entry per line, TAIL. Lines that don't match stay as they are.
function oneLine(text, re, { sort = false, indent = ' ' } = {}) {
return text.split('\n').map((l) => {
const m = re.exec(l);
if (!m) return l;
let es = entries(m[2]);
if (sort) {
// Sorting is only safe without duplicate keys (with duplicates, the last one wins).
const ids = es.map(idOf);
if (new Set(ids).size !== ids.length) throw new Error(`duplicate keys in ${m[1]}`);
es = es.slice().sort(byId);
}
return [m[1], ...es.map((e) => indent + e + ','), m[3]].join('\n');
}).join('\n');
}
function tidy(parts) {
const out = [];
for (const [file, text] of parts) {
if (file === 'game/90-actions/00-actions.js') out.push(...splitActions(text));
else if (file === 'game/20-world/40-city-coords.js') out.push([file, oneLine(text, /^(const CITY_LL=\{)(.*)(\};)$/, { sort: true })]);
else if (file === 'game/20-world/50-cities.js') out.push([file, oneLine(text, /^(const CITY_NUDGE=\{)(.*)(\};)$/, { sort: true })]);
else if (file === 'game/20-world/20-landmasses.js') {
out.push([file, oneLine(oneLine(text, /^(const LANDS_LL=\[)(.*)(\];)$/), /^(LANDS_LL\.push\()(.*)(\);)$/)]);
} else out.push([file, text]);
}
return out;
}
const EN_HEADER = `// English: the text of every label the game uses (in tr(), trn() and N_() calls in src/, and data-i18n in src/index.html).
// Inlined into the page at build. One entry per line, sorted by label; plurals are {"one":…,"other":…}.
// Add or change text with scripts/i18n-add.js, check with npm run i18n:check.
`;
// All the tidying, plus labels. `known` maps English text to the labels src/ already has, so text that
// exists today keeps its label (default: the current src/i18n/en.js). Returns the parts and the labels used.
function transformFull(parts, known) {
const D = require('../lib/dict');
const { labelize, knownFrom } = require('./labels');
if (!known) known = knownFrom(require('node:fs').existsSync(D.fileOf('en')) ? D.read('en').dict : {});
const { parts: labelled, en, labels } = labelize(tidy(parts), known);
const out = labelled.map(([file, text]) => file === 'index.html'
? [file, text.replace('<!-- @include game -->', '<!-- @include i18n -->\n<!-- @include game -->')] : [file, text]);
out.push(['i18n/en.js', D.format('en', EN_HEADER, Object.fromEntries(en))]);
return { parts: out, labels };
}
const transform = (parts, known) => transformFull(parts, known).parts;
module.exports = { transform, transformFull, tidy, entries };

View file

@ -0,0 +1,52 @@
// Shrinks labels for the shipped page (docs/adr/0003-translations-by-label.md, "Performance").
//
// In src/ a label is readable: tr('pnis.delivery_2_to_6_weeks'). Shipped like that, every label would
// sit in the page twice (in the code and as a key in the inlined English), about 20% more page after
// compression. So the build gives each label a short id ('a', 'b', … '2kq'), in the code, in the
// static markup, in the inlined English and in every translation file, and the page ends up about the
// size it was when the English text itself was the key.
//
// Labels passed to N_() are kept whole: those are the ones the game stores (in saves, in the inbox log)
// and shows later, and an id would mean something else in the next release.
const { CALL } = require('../legacy/labels');
const D = require('./dict');
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
const EN_OPEN = '(window.I18N=window.I18N||{}).en={';
// {map: label → id for every label that gets one, kept: labels that stay whole}.
function plan(html, en) {
const kept = new Set();
for (const m of html.matchAll(CALL)) if (m[1] === 'N_') kept.add(m[2].slice(1, -1));
const map = new Map();
let n = 0;
for (const l of Object.keys(en).sort(D.cmp)) if (!kept.has(l)) map.set(l, (n++).toString(36));
return { map, kept };
}
const rekey = (dict, map) => Object.fromEntries(Object.entries(dict).map(([k, v]) => [map.get(k) || k, v]));
// The page and the dictionaries with short ids. `dicts` is {lang: dict} for the translations.
function compile(html, en, dicts) {
const { map } = plan(html, en);
// English: the inlined dictionary, swapped whole.
const a = html.indexOf(EN_OPEN), b = html.indexOf('\n};\n', a);
if (a < 0 || b < 0) throw new Error('compile-labels: the inlined English dictionary is missing from the page');
const head = html.lastIndexOf('\n', a) + 1;
let out = html.slice(0, head) + D.format('en', '', rekey(en, map)) + html.slice(b + 4);
// Code: the first argument of tr() and trn(); N_() keeps its label.
out = out.replace(CALL, (m, fn, lit) => {
if (fn === 'N_') return m;
const l = lit.slice(1, -1);
return map.has(l) ? m.replace(lit, `'${map.get(l)}'`) : m;
});
// Static markup.
out = out.replace(/ data-i18n(-aria-label|-title)?="([^"]+)"/g, (m, attr, l) => (map.has(l) ? ` data-i18n${attr || ''}="${map.get(l)}"` : m));
const left = [...out.matchAll(/(?<![\w$.])(tr|trn)\(\s*'([^']*)'/g)].map((m) => m[2]).filter((l) => LABEL.test(l) && !map.has(l) && !(l in en));
if (left.length) throw new Error(`compile-labels: labels with no English: ${[...new Set(left)].slice(0, 5).join(', ')}`);
const compiled = {};
for (const [lang, d] of Object.entries(dicts)) compiled[lang] = rekey(d, map);
return { html: out, dicts: compiled, map };
}
module.exports = { compile, plan };

49
scripts/lib/dict.js Normal file
View file

@ -0,0 +1,49 @@
// Reads and writes the dictionaries: English in src/i18n/en.js, translations in site/i18n/<lang>.js.
// Each maps a label to its text, or for plurals to {"one": …, "other": …}.
//
// Every dictionary is kept in one canonical layout: the header comment, then one `"label":"Text",`
// entry per line, sorted by label. Sorted entries spread new strings across the file instead of
// piling them up at the end, so two pull requests that each add strings rarely touch the same lines.
// `npm run i18n:check` reports a dictionary that is out of order; `npm run i18n:fix` puts it back.
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
// English lives with the source (it is inlined into the page); translations are static files in site/i18n/.
const DIR = path.join(__dirname, '..', '..', 'site', 'i18n');
const EN = path.join(__dirname, '..', '..', 'src', 'i18n', 'en.js');
const fileOf = (lang) => (lang === 'en' ? EN : path.join(DIR, `${lang}.js`));
const langs = () => fs.readdirSync(DIR).filter((f) => f.endsWith('.js')).map((f) => path.basename(f, '.js')).sort();
// Plain code-unit order: the same on every machine, whatever its locale.
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
function parse(text, lang) {
const window = {};
vm.runInNewContext(text, { window });
return (window.I18N || {})[lang] || {};
}
function read(lang) {
const text = fs.readFileSync(fileOf(lang), 'utf8');
const open = text.indexOf(`(window.I18N=window.I18N||{}).${lang}={`);
if (open < 0) throw new Error(`${lang}.js: missing the (window.I18N=window.I18N||{}).${lang}={ line`);
return { text, header: text.slice(0, open), dict: parse(text, lang) };
}
function format(lang, header, dict) {
const keys = Object.keys(dict).sort(cmp);
return `${header}(window.I18N=window.I18N||{}).${lang}={\n${keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(dict[k])},\n`).join('')}};\n`;
}
// True when the file is already in the canonical layout.
function tidy(lang) {
const { text, header, dict } = read(lang);
return text === format(lang, header, dict);
}
function write(lang, dict, header = read(lang).header) {
fs.writeFileSync(fileOf(lang), format(lang, header, dict));
}
module.exports = { DIR, EN, fileOf, langs, read, write, format, tidy, parse, cmp };

111
scripts/lib/page.js Normal file
View file

@ -0,0 +1,111 @@
// Assembles the game page from src/: src/index.html is the shell, and every line that is exactly
// `<!-- @include DIR -->` is replaced by the files under src/DIR, concatenated in path order.
// The result is the same single, self-contained index.html the game has always shipped: one request,
// no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/.
//
// node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default)
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests and npm run dev use)
// node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref
//
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
// the split (when the page was site/index.html) are read as they are.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const ROOT = path.join(__dirname, '..', '..');
const INCLUDE = /^<!-- @include ([\w./-]+) -->$/;
// Every file under dir, as paths relative to dir with '/' separators, in a stable order
// (plain code-unit comparison, so the order never depends on the machine's locale).
function listFiles(dir, rel = '') {
const out = [];
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
if (e.name.startsWith('.')) continue;
const r = rel ? rel + '/' + e.name : e.name;
if (e.isDirectory()) out.push(...listFiles(dir, r));
else out.push(r);
}
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
}
// The partials that make up one include, in order: [{file, text}].
function partials(src, dir) {
const base = path.join(src, dir);
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
return listFiles(base).map((r) => {
const file = path.join(base, r);
const text = fs.readFileSync(file, 'utf8');
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
if (text && !text.endsWith('\n')) throw new Error(`${path.relative(ROOT, file)}: must end with a newline`);
if (/^<\/(script|style)/im.test(text)) throw new Error(`${path.relative(ROOT, file)}: must not close its <script>/<style>`);
return { file: dir + '/' + r, text };
});
}
// The assembled page as a string, plus a map of which output line came from which source file.
function assemble({ src = path.join(ROOT, 'src') } = {}) {
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
const out = [], map = [];
let line = 1;
const lines = shell.split('\n');
lines.forEach((l, i) => {
const m = INCLUDE.exec(l);
if (!m) {
out.push(l + (i < lines.length - 1 ? '\n' : ''));
line++;
return;
}
for (const p of partials(src, m[1])) {
const n = p.text.split('\n').length - 1;
map.push({ file: p.file, from: line, to: line + n - 1 });
out.push(p.text);
line += n;
}
});
return { html: out.join(''), map };
}
// Which source file (and line in it) an assembled-page line comes from: for stack traces and errors.
function locate(map, line) {
const m = map.find((x) => line >= x.from && line <= x.to);
return m ? { file: m.file, line: line - m.from + 1 } : { file: 'index.html (shell)', line };
}
// The page at a git ref: that commit's src/ through its own assembler, or site/index.html before the split.
function assembleRef(ref, cwd = ROOT) {
const git = (...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] });
const has = (p) => { try { git('cat-file', '-e', `${ref}:${p}`); return true; } catch { return false; } };
if (!has('src/index.html')) return git('show', `${ref}:site/index.html`);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-ref-'));
try {
const tar = execFileSync('git', ['archive', '--format=tar', ref, 'src', 'scripts'], { cwd, maxBuffer: 1 << 28 });
execFileSync('tar', ['-x', '-C', tmp], { input: tar });
return execFileSync(process.execPath, [path.join(tmp, 'scripts', 'lib', 'page.js')], { cwd: tmp, encoding: 'utf8', maxBuffer: 1 << 28 });
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
}
// The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped.
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids.
function shipped(dicts = {}) {
const D = require('./dict');
return require('./compile-labels').compile(assemble().html, D.read('en').dict, dicts);
}
// The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head).
function pageFile(file = path.join(os.tmpdir(), `tubes-page-${process.pid}.html`)) {
fs.writeFileSync(file, shipped().html);
return file;
}
module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, ROOT };
if (require.main === module) {
const args = process.argv.slice(2);
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble().html : shipped().html;
const out = opt('-o');
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
else process.stdout.write(html);
}

View file

@ -2,7 +2,8 @@
// Performance benchmark on a very large network (tests/fixtures/big-network.json).
//
// node scripts/perf-bench.js time this checkout
// node scripts/perf-bench.js --base OLD.html compare OLD.html (e.g. main) with this checkout
// node scripts/perf-bench.js --base-ref origin/main compare main with this checkout (builds main's page)
// node scripts/perf-bench.js --base OLD.html compare a built page (e.g. a release's) with this checkout
// node scripts/perf-bench.js --base OLD.html --md out.md --summary "$GITHUB_STEP_SUMMARY"
// node scripts/perf-bench.js --save my-export.json --base OLD.html a player's save (plain or exported from the menu)
// node scripts/perf-bench.js --base OLD.html --browser also in real Chromium, as a desktop and as a phone
@ -19,8 +20,14 @@ const { load } = require('../tests/harness');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const ROOT = path.join(__dirname, '..');
const HEAD = opt('--head', path.join(ROOT, 'site', 'index.html'));
const BASE = opt('--base', null);
const page = require('./lib/page');
// Pages as files: the browser run opens them from disk.
const HEAD = opt('--head', null) || page.pageFile();
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
const f = path.join(require('node:os').tmpdir(), `tubes-base-${process.pid}.html`);
fs.writeFileSync(f, page.assembleRef(opt('--base-ref', null)));
return f;
})());
const RUNS = +opt('--runs', 15);
// A plain save, or a file from the in-game "Export save", which wraps it as {app, version, exported, S}.
const RAW = JSON.parse(fs.readFileSync(opt('--save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')), 'utf8'));

16
scripts/test.js Normal file
View file

@ -0,0 +1,16 @@
#!/usr/bin/env node
// Runs every tests/*.test.js, one file at a time. New test files are picked up on their own, so adding
// one never touches package.json (and never conflicts with someone else adding theirs).
//
// npm test everything
// npm test -- tests/peering.test.js just these files (other arguments go to node --test)
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const dir = path.join(__dirname, '..', 'tests');
const args = process.argv.slice(2);
const files = args.some((a) => a.endsWith('.test.js')) ? [] :
fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => path.join('tests', f));
const r = spawnSync(process.execPath, ['--test', '--test-concurrency=1', ...args, ...files], { stdio: 'inherit', cwd: path.join(__dirname, '..') });
process.exit(r.status ?? 1);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,18 @@
/* ================= LANGUAGE =================
Text is looked up by label: tr('pnis.delivery_2_to_6_weeks',vars) returns the player's language, or the
English from src/i18n/en.js (inlined above the game) when a translation is missing, and fills {placeholders}.
trn(label,n,vars) picks the "one" or "other" form of a plural. N_() marks a label kept in a table or a
save, translated where it is shown. A label that is not in any dictionary comes back as it is. */
// English when the dictionary did not load (offline, or a copy without the i18n folder).
const LANGS=window.SOT_LANGS,LANG=window.I18N?.[window.SOT_LANG]?window.SOT_LANG:'en';
document.documentElement.lang=LANG;
const EN=window.I18N.en,DICT=Object.assign(Object.create(null),EN,LANG!=='en'&&window.I18N[LANG]);
// Saves from before labels (1.34 and older) hold English text where newer ones hold a label: map it on first use.
let EN_TEXT=null;
function trKey(k){const o=DICT[k];if(o!==undefined)return o;
if(!EN_TEXT){EN_TEXT=new Map();for(const l in EN){const e=EN[l],t=DICT[l];if(typeof e==='string')EN_TEXT.set(e,t);else{EN_TEXT.set(e.one,t.one||e.one);EN_TEXT.set(e.other,t.other||e.other);}}}
return EN_TEXT.get(k)??k;}
const fillIn=(o,v)=>v?o.replace(/\{(\w+)\}/g,(m,k)=>k in v?v[k]:m):o;
function tr(k,v){const o=trKey(k);return fillIn(typeof o==='string'?o:o.other,v);}
function trn(k,n,v){const o=trKey(k);return fillIn(typeof o==='string'?o:n===1?o.one:o.other,{n,...v});}
function N_(s){return s;}

View file

@ -0,0 +1,21 @@
/* ================= ANALYTICS (ridiculytics) =================
Off unless ANALYTICS.host is set. Fill in your collector when you self-host the game.
Inside the claude.ai viewer outside requests are blocked, so it only reports from your own domain. */
const APP_VERSION='__VERSION__';
// Filled in by scripts/build.sh from CHANGELOG.md for this version.
const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
const IS_DEV=APP_VERSION.startsWith('__');
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){
try{
window.ridiculytics=window.ridiculytics||function(){const q=window.ridiculytics.q=window.ridiculytics.q||[];if(q.length<100)q.push(arguments);};
if(!ANALYTICS.host)return;
const sc=document.createElement('script');sc.defer=true;sc.src='https://cdn.jsdelivr.net/npm/ridiculytics@1.0.1/web/counter.min.js';
sc.setAttribute('data-host',ANALYTICS.host);if(ANALYTICS.site)sc.setAttribute('data-site',ANALYTICS.site);sc.setAttribute('data-spa','false');sc.integrity='sha384-uNCU8e2RB7Yn6lVNut2gupQsJwKwXPZu2i4t/Eg6Q59ki0kchBR4L4yoS3ZxxjEX';sc.crossOrigin='anonymous';sc.referrerPolicy='no-referrer';
document.head.appendChild(sc);
}catch(e){}
})();
const TRACKED=new Set();
function track(name,once){if(!ANALYTICS.host)return;if(once){if(TRACKED.has(name))return;TRACKED.add(name);}try{window.ridiculytics(name);}catch(e){}}
const PLAY_MARKS=[1,5,15,30,60,120];

View file

@ -0,0 +1,54 @@
/* ================= CONSTANTS ================= */
const W=2000, H=1000, KM=14;
const POP_COST=20000, POP_MO=1500, EYE_RATE=150, CACHE_CAP=100, CACHE_MO=400;
const DAY_MS=2500, ROUTER_COST=15000, ROUTER_MO=1500, GEN_COST=12000, GEN_MO=600, DIVERSE=1.4;
const RU_BOX=40000, RU_BOX_MO=2000;
const UAE_LIC=15000,KSA_LIC=25000;
// Korea: "sender pays" interconnection makes transit into Seoul about four times the usual price.
const KR_TRANSIT=4;
/* Australia: a long way from everywhere. Every gigabit out of the country rides a long, thin subsea
cable, so transit and waves cost more than almost anywhere else. IX ports are the exception: a
nonprofit exchange sells 10G for about AUD 350 a month. Retail broadband is dear, but the national
wholesale network keeps roughly half of every home bill (about AUD 50 a month per home). */
const AU_TRANSIT=3,AU_WAVE={land:1.8,sub:2.6,ew:1.3},AU_IX=0.8,AU_ARPU=1.8,AU_WHOLESALE=0.45;
// Fibre to the Basement: on your own fibre you skip the wholesale cut, but competing networks pay the
// Regional Broadband Scheme levy instead (about $7 a month on a ~$90 bill).
const AU_LEVY=0.08;
const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000;
const SITE2_N=[tr('economy.the_other_building'),tr('economy.campus_b_the_one_with_parking'),tr('economy.across_the_river_dc'),tr('common.the_annex'),tr('economy.suburban_mega_shed'),tr('economy.the_cheaper_one'),tr('economy.formerly_a_shopping_mall'),tr('common.bunker_two')];
// A city's buildings: '#' becomes a site number from 1 to dcN (dc2N for the second building) that stays put for this network.
const siteNo=(name,n)=>name.replace('#',1+((S&&S.asn)|0)%(n||1));
const siteName=(c,s)=>s==='b'?CITY[c].dc2?siteNo(CITY[c].dc2,CITY[c].dc2N):SITE2_N[hstr(c)%SITE2_N.length]:siteNo(CITY[c].dc,CITY[c].dcN);
const BE_TAPE=30000;
const popCost=c=>POP_COST+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0);
const CN_LIC=150000, CN_JV_MO=6000;
// Scrubbing centers come in tiers by clean bandwidth. Always-on diverts instantly; on-demand is cheaper
// but takes a couple of days to engage. A clean-pipe add-on on a transit scrubs upstream, per port.
const SCRUB_TIERS=[{n:'100G',g:100,cost:60000,mo:5000,lvl:1},{n:'1T',g:1000,cost:180000,mo:15000,lvl:3},{n:'10T',g:10000,cost:500000,mo:40000,lvl:4},{n:'100T',g:100000,cost:1500000,mo:110000,lvl:10}];
const SCRUB_DELAY=2, SLA_PEN=20000;
const scrubMo1=x=>Math.round(SCRUB_TIERS[x.tier||0].mo*(S.scrubMode==='ondemand'?0.6:1)),scrubMo=()=>S.scrubs.reduce((a,x)=>a+scrubMo1(x),0);
const hasScrub=()=>!!(S&&S.scrubs&&S.scrubs.length),SCRUB_FAR_MS=30;
const cleanMo=t=>Math.round(PORT[t.tier].g*(t.n||1)*5);
// DDoS has a shape now: a vector, a size and an entry point. A vector's `fs` is whether Flowspec can drop
// it at the edge — it catches the known volumetric UDP floods, but an application-layer HTTP flood sails
// through. Whether a POP can run Flowspec at all is a router-model property (`fs` on RG): the rules live in
// hardware TCAM, and the budget differs by platform. FS_RES is the junk left after filtering, by capability
// (0 none → no help · 1 basic merchant/whitebox → 40% leaks · 2 full big iron → 15% leaks).
const FS_RES=[1,0.4,0.15];
const DDOS_VEC={
dns:{n:tr('common.dns_reflection'),fs:true},
ntp:{n:tr('common.ntp_amplification'),fs:true},
memcached:{n:tr('common.memcached_amplification'),fs:true},
ack:{n:tr('common.ack_flood'),fs:false},
cldap:{n:tr('common.cldap_flood'),fs:true},
syn:{n:tr('common.syn_flood'),fs:true},
http:{n:tr('common.http_flood'),fs:false},
racknet:{n:tr('common.racknet'),fs:false,gaming:true},
teamspooked:{n:tr('common.teamspooked'),fs:false,gaming:true},
};
const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000;
// Your own exchange's switching fabric. Bigger fabrics carry more and attract more members.
const MYIX_FAB=[{n:'400G',g:400,cost:0,mo:3000,max:12},{n:'1.6T',g:1600,cost:60000,mo:6000,max:20,lvl:2},{n:'6.4T',g:6400,cost:200000,mo:12000,max:30,lvl:3},{n:'25.6T',g:25600,cost:600000,mo:25000,max:45,lvl:4},{n:'102.4T',g:102400,cost:1800000,mo:60000,max:60,lvl:9}];
const myFab=c=>MYIX_FAB[Math.min(MYIX_FAB.length-1,Math.max(0,(S.myIx[c]&&S.myIx[c].fab)|0))];
const LT=[{n:'10G',g:10,m:1},{n:'100G',g:100,m:2.8},{n:'400G',g:400,m:6},{n:'800G',g:800,m:9},{n:'1.6T',g:1600,m:13},{n:'6.4T',g:6400,m:28,car:1600,note:tr('economy.handed_off_as_4_1_6t')},{n:'12.8T',g:12800,m:45,car:3200,note:tr('economy.handed_off_as_4_3_2t')}];
const PORT=[{n:'10G',g:10,setup:500,tmo:150,ix:400,pni:200},{n:'100G',g:100,setup:1500,tmo:400,ix:1500,pni:350},{n:'400G',g:400,setup:4000,tmo:900,ix:4000,pni:600},{n:'800G',g:800,setup:8000,tmo:1600,ix:7000,pni:1000},{n:'1.6T',g:1600,setup:16000,tmo:2800,ix:12000,pni:1600},{n:'3.2T',g:3200,setup:32000,tmo:5000,ix:20000,pni:2600}];

View file

@ -0,0 +1,24 @@
const RG=[
{n:'Rusty Router 9000',pn:'100G',cap:400,cost:0,mo:0,maxLT:1,maxP:1,ports:8,cls:0,lvl:1,boot:6,slowP:10,fs:0,chip:tr('routers.a_mystery_asic'),blurb:tr('routers.bought_used_on_ebuy_the_fans')},
{n:'Edge Lord 400',pn:'400G',cap:3200,cost:30000,mo:1000,maxLT:2,maxP:2,ports:24,cls:1,lvl:2,boot:11,slowP:20,fs:1,chip:tr('common.merchant_silicon'),blurb:tr('routers.sharp_edgy_and_finally_speaks_400g')},
{n:'Chonk 800',pn:'800G',cap:12800,cost:90000,mo:3000,maxLT:3,maxP:3,ports:36,cls:2,lvl:3,boot:25,slowP:45,fs:2,chip:'Junipurr PacketOinker™',blurb:tr('routers.an_absolute_unit_with_800g_ports')},
{n:'Absolute Unit 1.6T',pn:'1.6T',cap:51200,cost:250000,mo:8000,maxLT:5,maxP:4,ports:40,cls:3,lvl:4,boot:40,slowP:60,fs:2,chip:tr('routers.packetoinker2_two_pigs_one_chassis'),blurb:tr('routers.1_6t_ports_its_own_weather')},
{n:'Mikrowtik CCR',pn:'100G',cap:300,cost:4000,mo:150,maxLT:1,maxP:1,ports:16,cls:0,lvl:1,boot:2,slowP:5,badge:'M',fs:1,chip:tr('routers.a_few_dozen_arm_cores'),blurb:tr('routers.costs_less_than_lunch_and_has')},
{n:'Sonic the Whitebox 32',pn:'400G',cap:3200,cost:14000,mo:400,maxLT:2,maxP:2,ports:32,cls:1,lvl:2,boot:9,slowP:25,flaky:true,badge:'W',fs:1,chip:tr('routers.tomahack_merchant_silicon'),blurb:tr('routers.a_bare_metal_switch_running_open')},
{n:'Arrrhipster 7280R',pn:'400G',cap:4800,cost:42000,mo:1300,maxLT:2,maxP:2,ports:48,cls:1,lvl:2,boot:3,slowP:2,badge:'A',fs:2,chip:tr('routers.jerry_cho_deep_buffer_silicon'),blurb:tr('routers.fixed_config_deep_buffers_a_well')},
{n:'Arrrhipster 7800R',pn:'800G',cap:16000,cost:130000,mo:4200,maxLT:3,maxP:3,ports:96,cls:2,lvl:3,boot:7,slowP:4,badge:'A',fs:2,chip:tr('routers.jerry_cho3_deep_buffer_silicon'),blurb:tr('routers.the_modular_one_ninety_six_800g')},
{n:'Disco 8K',pn:'800G',cap:12800,cost:80000,mo:4800,maxLT:3,maxP:3,ports:64,cls:2,lvl:3,boot:20,slowP:35,badge:'D',fs:2,chip:'Silly-con One',blurb:tr('routers.cheap_to_buy_expensive_to_own')},
{n:'Knockia 7750',pn:'1.6T',cap:40000,cost:200000,mo:7000,maxLT:5,maxP:4,ports:56,cls:3,lvl:4,boot:30,slowP:15,badge:'K',fs:2,chip:tr('routers.fin_p_network_processor'),blurb:tr('routers.finnish_engineering_indestructible')},
{n:'Sonic the Whitebox 64',pn:'1.6T',cap:25600,cost:60000,mo:1500,maxLT:5,maxP:4,ports:64,cls:3,lvl:5,boot:9,slowP:25,flaky:true,badge:'W',fs:1,chip:tr('routers.tomahack_5_merchant_silicon'),blurb:tr('routers.sixty_four_1_6t_ports_on')},
{n:'Disco 8K Ultra',pn:'1.6T',cap:51200,cost:140000,mo:11000,maxLT:5,maxP:4,ports:72,cls:3,lvl:6,boot:22,slowP:35,badge:'D',fs:2,chip:'Silly-con One G3',blurb:tr('routers.cheap_chassis_eternal_subscription')},
{n:'Absolute Unit 3.2T',pn:'3.2T',cap:204800,cost:600000,mo:18000,maxLT:6,maxP:5,ports:48,cls:4,lvl:7,boot:50,slowP:60,fs:2,chip:tr('routers.packetoinker3_a_whole_litter'),blurb:tr('routers.3_2t_ports_and_12_8t')},
{n:'Arrrhipster 7800R5',pn:'3.2T',cap:160000,cost:450000,mo:14000,maxLT:6,maxP:5,ports:144,cls:4,lvl:9,boot:8,slowP:4,badge:'A',fs:2,chip:tr('routers.jerry_cho5_deep_buffer_silicon'),blurb:tr('routers.a_hundred_and_forty_four_3')},
{n:'Knockia 7950 XRS',pn:'3.2T',cap:180000,cost:520000,mo:15000,maxLT:6,maxP:5,ports:96,cls:4,lvl:10,boot:32,slowP:15,badge:'K',fs:2,chip:tr('routers.fin_p6_network_processor'),blurb:tr('routers.built_like_a_sauna_door_heavy')},
{n:'Mikrowtik CCR 3.2T',pn:'3.2T',cap:51200,cost:45000,mo:900,maxLT:6,maxP:5,ports:32,cls:4,lvl:11,boot:3,slowP:5,flaky:true,badge:'M',fs:1,chip:tr('routers.several_hundred_arm_cores_and_a'),blurb:tr('routers.a_3_2t_router_for_the')},
{n:'The Router at the End of the Universe',pn:'3.2T',cap:819200,cost:3000000,mo:60000,maxLT:6,maxP:5,ports:256,cls:4,lvl:13,boot:42,slowP:42,badge:'U',fs:2,chip:tr('routers.forty_two_of_them'),blurb:tr('routers.two_hundred_and_fifty_six_3')}
];
/* Some routers take forever to boot. Each POP's chassis has a personality per model: most come
back in minutes, a few sit through every line card self-test known to the vendor. */
const SLOW_BOOT=[tr('routers.is_oinking_through_the_self_test'),tr('routers.is_running_fsck_on_a_compact'),tr('routers.found_a_newer_firmware_on_the'),tr('routers.is_counting_to_2_million_routes'),tr('routers.is_waiting_for_the_line_cards'),tr('routers.booted_panicked_about_a_missing_fan'),tr('routers.is_synchronising_the_routing_engines')];
function slowBoot(c){const p=S.pops[c];if(!p)return false;const g=p.rgen||0;return hstr(c+'|boot|'+g+'|'+S.asn)%100<RG[g].slowP;}
function bootMin(c){const p=S.pops[c],G=RG[(p&&p.rgen)||0];return slowBoot(c)?G.boot*9+40:G.boot;}

View file

@ -0,0 +1,30 @@
/* ---------- Supply chain: hardware gets dearer over the years, with shortages that come and go ----------
Transit keeps getting cheaper (it really does), but routers, optics and new builds drift the other way: free for
the first six months, then +4% a year, capped at +30%. Only new purchases pay it; what you own costs what it cost.
Now and then a shortage hits one kind of hardware for a month or two. Spares on the shelf and a yearly price lock
with your vendor are the ways around it. */
const HW_YR=0.04,HW_CAP=1.3,HW_FREE=180,HW_LOCK_DAYS=365;
const HW_SHOCK={opt:{mul:1.5,n:N_('common.optics'),msg:N_('supply_chain.laser_shortage_the_factory_that')},
rt:{mul:1.4,n:N_('common.routers'),msg:N_('supply_chain.chip_shortage_every_router_vendor_is')},
build:{mul:1.3,n:N_('supply_chain.new_fiber_and_cable_builds'),msg:N_('supply_chain.every_cable_ship_is_booked')}};
const hwTrend=d=>Math.min(HW_CAP,1+HW_YR*Math.max(0,(d-HW_FREE)/365));
const hwShock=()=>{const s=S&&S.hw&&S.hw.shock;return s&&s.until>S.day?s:null;},hwLock=()=>{const l=S&&S.hw&&S.hw.lock;return l&&l.until>S.day?l:null;};
function hwMul(k){if(!S)return 1;const l=hwLock();if(l)return l.mul;const s=hwShock();return hwTrend(S.day)*(s&&s.k===k?s.mul:1);}
// A lock costs a little more for a bigger network, and twice as much in the middle of a shortage.
const hwLockCost=()=>Math.round((80000+30000*Object.keys(S.pops).length)*(hwShock()?2:1)/1000)*1000;
function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math.random()*31);S.hw=S.hw||{};S.hw.shock={k,until:S.day+n,mul:HW_SHOCK[k].mul};
toast(tr(HW_SHOCK[k].msg,{n})+(hwLock()?'<br>'+tr('supply_chain.your_price_lock_covers_you_until',{date:dateStr(hwLock().until)}):''),hwLock()?'':'bad');sfx('alert');}
function hwCard(){if(!S||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day),s=hwShock(),l=hwLock();
return `<div class="ibx"><div class="nm">📦 ${tr('common.supply_chain')}</div>
<div class="kv"><span>${tr('common.hardware_prices')}</span><b>${t>1.005?tr('supply_chain.p_since_you_started',{p:pct(t-1)}):tr('supply_chain.as_when_you_started')}</b></div>
${s?`<div class="kv"><span>${tr('common.shortage')}</span><b>${tr('supply_chain.what_p_n_days_left',{what:tr(HW_SHOCK[s.k].n),p:pct(s.mul-1),n:s.until-S.day})}</b></div>`:''}
${l?`<div class="kv"><span>${tr('common.price_lock')}</span><b>${tr('supply_chain.until_date_at_p',{date:dateStr(l.until),p:pct(l.mul-1)})}</b></div>`
:`<p class="meta">${tr('supply_chain.routers_optics_and_new_builds_at')}</p><div class="btns">${btn(tr('supply_chain.lock_prices_for_a_year_cost',{cost:fmt$(hwLockCost())}),'hwLock',{},'sm',S.cash<hwLockCost())}</div>`}</div>`;}
const routerCost=g=>Math.round((ROUTER_COST+RG[g].cost*0.8)*hwMul('rt'));
// Old routers go on eBuy when you swap models or remove one (#82), like spare optics (#45). Chassis age faster.
const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCost=(c,g)=>{const p=S.pops[c],rt=p.routers||1;return Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt'))-tradeIn(p.rgen||0,rt));};
const RMAX=6;
// The plain, badge-less model of each class is the default upgrade path; the others are side-grades.
const mainRG=k=>RG.findIndex(r=>r.cls===k&&!r.badge);
// Ports and waves beyond 1.6T / 6.4T only show once a router that takes them is unlocked.
const portShown=i=>i<=4||RG.some(r=>r.lvl<=lvl()&&r.maxP>=i),waveShown=i=>i<=5||RG.some(r=>r.lvl<=lvl()&&r.maxLT>=i);

View file

@ -0,0 +1,22 @@
/* Ports are finite. Every transit, IX, PNI and cache port, every wave and every fibre channel
takes a router port. 10G ports ride a breakout cable, four to a port. */
const PORT_SLOT=i=>i===0?0.25:1;
function portsUsed(c){let u=0;
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;u+=l.kind==='df'?(l.ch||[]).length:1;}
for(const t of S.transit)if(t.city===c)u+=PORT_SLOT(t.tier)*(t.n||1);
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
if(S.myIx[c])u+=1;
u+=S.caches.filter(x=>x.city===c).length+(S.nni||[]).filter(x=>x.city===c).length;
return u;}
function portsMax(c,g,rt){const p=S.pops[c];if(!p)return 0;return RG[g===undefined?(p.rgen||0):g].ports*(rt||p.routers||1);}
function portGate(c,add){if(!S.pops[c]||add<=0)return true;const u=portsUsed(c),m=portsMax(c);if(u+add<=m+1e-9)return true;
toast(tr('ports.no_free_router_ports_in_city',{city:esc(CITY[c].name),u:fmtPorts(u),m}),'bad');sfx('err');return false;}
// Nothing depends on this POP yet: no broadband, nothing plugged in, no customer. Work here bothers nobody (#105).
const popIdle=c=>{const p=S.pops[c];return !!p&&!p.bb&&portsUsed(c)===0&&!S.biz.some(b=>b.city===c||b.city2===c||(b.sites||[]).includes(c));};
const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,'');
function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return '';
if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn});
if([...S.transit,...S.pni].some(t=>t.city===c&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn});
if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='df'&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this');
if(portsUsed(c)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';}

View file

@ -0,0 +1,39 @@
// dark fiber & optical gear
const DF_SYS={
lite:{n:'Rainbow-in-a-Box DWDM',max:16,cost:25000,lvl:2,blurb:tr('dark_fiber.fixed_mux_plus_amplifiers_up_to')},
roadm:{n:'ROADMaster 9000',max:64,cost:60000,lvl:3,blurb:tr('dark_fiber.full_c_band_remotely_reconfigurable')},
cl:{n:'ROADMaster 9000 C+L',max:128,cost:140000,lvl:6,blurb:tr('dark_fiber.lights_the_l_band_as_well')},
};
const AMP_EVERY=100, AMP_COST=8000, AMP_MO=300;
/* Your own trench holds more than one fiber pair (#35). Once a ROADMaster is full you can light the next pair:
another ROADMaster and another chain of amplifiers, 64 more channels. Regen huts are shared. */
const isRdm=y=>y==='roadm'||y==='cl';
const PAIRS_MAX=4,PAIRS_BIG=8,PAIRS_LV=12,SUB_PAIRS_MAX=8,SUB_PAIR_UP=1500000,pairsMax=l=>l.sub?SUB_PAIRS_MAX:lvl()>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,chMax=l=>DF_SYS[l.sys].max*(isRdm(l.sys)&&l.own?Math.max(1,l.pairs|0):1),
pairCost=l=>DF_SYS[isRdm(l.sys)?l.sys:'roadm'].cost+(l.sub?SUB_PAIR_UP:ampCount(l.km)*AMP_COST);
const OPT={
zr4:{n:'Ackackia 400ZR+',g:400,cost:12000,reach:1500,modes:[[400,1500],[200,3000]],rg:1,lvl:2,sys:'lite',blurb:tr('dark_fiber.coherent_pluggable_in_the_router_no')},
zr8:{n:'Sizzle 800ZR+',g:800,cost:22000,reach:900,modes:[[800,900],[400,1800],[200,3600]],rg:2,lvl:3,sys:'lite',blurb:tr('dark_fiber.twice_the_speed_shorter_reach')},
tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,modes:[[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:2,lvl:4,sys:'roadm',blurb:tr('dark_fiber.big_shelf_big_reach_big_invoice')},
tp32:{n:'Sienna WaveMagic 3.2T',g:3200,cost:130000,reach:1500,modes:[[3200,1500],[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:4,lvl:8,sys:'roadm',blurb:tr('dark_fiber.twice_the_wavemagic_full_speed_only')},
};
const dfLeaseMo=km=>Math.round(400+km*1.0);
const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build'));
const dfBuildDays=km=>Math.round(120+km*0.25);
const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY));
const fmtCap=g=>g>=1000?(+(g/1000).toFixed(1))+'T':g+'G';
const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','G&T (Gin and Transit)'];
const MONTHS=[tr('common.jan'),tr('common.feb'),tr('common.mar'),tr('common.apr'),tr('common.may'),tr('common.jun'),tr('common.jul'),tr('common.aug'),tr('common.sep'),tr('common.oct'),tr('common.nov'),tr('common.dec')];
const REG={AM:tr('common.americas'),SA:tr('common.south_america'),EU:tr('common.europe'),AF:tr('common.africa'),AS:tr('common.asia'),OC:tr('common.oceania')};
const waveMo=(km,sub,tier)=>Math.round((300+km*1.2)*LT[tier].m*(sub?1.8:1));
const FABS=[
{id:'mgp',name:'Megapork',col:'#FF5A1F',cities:['mel','bne','per','adl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','mrs','sto','mad','sin','hkg','tok','syd','jnb'],blurb:tr('dark_fiber.elastic_interconnection_now_with')},
{id:'pkf',name:'PocketFabric',col:'#00A896',cities:['sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra'],blurb:tr('dark_fiber.a_whole_network_fabric_that_fits')},
{id:'ccn',name:'Consolation Connect',col:'#8E44AD',cities:['icn','lon','fra','ams','mrs','bom','sin','hkg','tok','syd','lag','jnb'],blurb:tr('dark_fiber.strong_in_asia_and_africa_every')},
];
const FAB=Object.fromEntries(FABS.map(f=>[f.id,f]));
const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}];
const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}];
const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1));
const MET={prefer:{l:tr('common.prefer'),f:0.5},normal:{l:tr('common.normal'),f:1},avoid:{l:tr('common.avoid'),f:4},backup:{l:tr('common.backup_only'),f:60}};
const PREF={high:tr('common.prefer'),normal:tr('common.normal'),low:tr('common.backup_only')};
const edgeKey=l=>l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;

View file

@ -0,0 +1,63 @@
/* Reach (#17, #30). Coherent optics trade speed for distance: past full-rate reach they drop to a
slower, more robust modulation, and a bigger optic can always fall back to anything a smaller one does (#107). Regeneration sites go further: each one turns the light back into
bits and sends it on fresh, so every optical span is shorter. Each site needs a regen card per channel. */
const REGEN_COST=30000,REGEN_MO=900,REGEN_CH=0.5,REGEN_MAX=8;
const spanKm=l=>Math.ceil(l.km/((l.regen|0)+1));
/* Subsea glass is engineered end to end for one route: ultra-low-loss, large-area fiber and a repeater every
~70 km, no regens (#66, #68). Optics reach about half as far again as on land, and the same physics caps
every wave on a cable, leased or your own: transatlantic gets 1.6T, transpacific 800G. */
const SUB_REACH=1.5,reachOn=(r,sub)=>sub?Math.round(r*SUB_REACH):r;
const SUB_MAXKM=()=>subReach(1,1);
// Upgrades improve long-haul modes, not the nominal 1.6T/3.2T rate.
const SUB_UPGRADES={terminal:{n:N_('reach_and_subsea.premium_submarine_terminals'),cost:5000000,days:30},engineering:{n:N_('common.optical_engineering'),cost:12000000,days:180}};
const subUpgradeReady=(l,k)=>l.kind==='df'&&l.sub&&l.own&&Number.isFinite(l['sub'+k])&&l['sub'+k]<=S.day;
const subUpgradeCost=(l,k)=>SUB_UPGRADES[k].cost+(k==='engineering'?Math.round(l.km*1000):0);
// Pending transmission work follows the construction schedule. Keep the actual
// shift (the last crew purchase can save fewer than 30 days) and completed work.
function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;
if(l.kind==='df'&&l.own&&l.sub)for(const k of Object.keys(SUB_UPGRADES)){
const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift);
}l.ready=ready;
}
const crewCost=l=>Math.round(15000+l.km*6);
const crewSteps=l=>Math.max(0,Math.ceil((l.ready-S.day-1)/30));
// Old saves lack purchase dates. Only shorten dates beyond any valid remaining
// commissioning window. Credit elapsed time since the actual cable finish;
// recent purchases and installed upgrades stay untouched.
function repairSubUpgradeDates(l,day){if(l.kind!=='df'||!l.own||!l.sub)return;
for(const [k,U] of Object.entries(SUB_UPGRADES)){const f='sub'+k;
if(Number.isFinite(l[f])&&l[f]>Math.max(day,l.ready)+U.days)l[f]=l.ready+U.days;
}
}
function optModes(o,l){return (OPT[o].modes||[[OPT[o].g,OPT[o].reach]]).map(([g,r])=>{
let reach=reachOn(r,l.sub);
if(l.sub&&['tp16','tp32'].includes(o)&&g<=1200){
if(subUpgradeReady(l,'terminal'))reach=Math.max(reach,({1200:9000,800:13500,400:20000})[g]||reach);
if(subUpgradeReady(l,'engineering'))reach=Math.round(reach*1.25);
}
return [g,reach];});}
function optMode(o,l){const km=spanKm(l);for(const [g,r] of optModes(o,l))if(km<=r)return {g,reach:r,full:g===OPT[o].g};return null;}
// The longest subsea span any optic lights with these upgrades in service, and the cheapest upgrades a length needs
// (null: nothing can light it). The length limit, the order screen and refunds all use these, so they agree.
const SUBR=[],subReach=(t,e)=>SUBR[(t?1:0)+(e?2:0)]??(SUBR[(t?1:0)+(e?2:0)]=Math.max(...Object.keys(OPT).flatMap(o=>optModes(o,{kind:'df',own:true,sub:true,subterminal:t?0:undefined,subengineering:e?0:undefined}).map(m=>m[1])))),
subNeed=km=>km<=subReach(0,0)?[]:km<=subReach(1,0)?['terminal']:km<=subReach(0,1)?['engineering']:km<=subReach(1,1)?['terminal','engineering']:null;
// Upgrades a cable of this length still needs on top of the chosen ones; ['design'] when nothing can light it.
const seaLack=(km,up)=>{const n=subNeed(km);return n?n.filter(k=>!up[k]):['design'];};
const submarineRate=l=>Math.max(0,...Object.keys(OPT).filter(o=>OPT[o].lvl<=lvl()&&(OPT[o].sys!=='roadm'||isRdm(l.sys||'roadm'))).map(o=>optG(o,l)));
// The fastest single carrier any optic can run over this much subsea cable.
const subCarrier=km=>Math.max(0,...Object.values(OPT).map(O=>{const m=(O.modes||[[O.g,O.reach]]).find(([,r])=>km<=reachOn(r,true));return m?m[0]:0;}));
// A big leased wave is several carriers (6.4T = 4×1.6T), so each carrier has to make it across on its own.
const waveCar=i=>LT[i].car||LT[i].g;
function subWaveWhy(i,km,sub){if(!sub)return '';const c=subCarrier(km);return waveCar(i)>c?tr('common.km_km_of_cable_carries_at',{km:Math.round(km).toLocaleString(),g:fmtCap(c)}):'';}
const subMaxTier=km=>{let t=0;LT.forEach((T,i)=>{if(!subWaveWhy(i,km,true))t=i;});return t;};
// What an optic carries depends only on the optic, the span length and subsea or not; the map and compute() ask a lot.
// Cached per optic, span and cable state: subsea, and which submarine upgrades are in service (#78).
const OPTG={};const optG=(o,l)=>{const km=spanKm(l),fl=l.sub?1+(subUpgradeReady(l,'terminal')?2:0)+(subUpgradeReady(l,'engineering')?4:0):0,c=OPTG[o]||(OPTG[o]=[]),m=c[fl]||(c[fl]=new Map());let g=m.get(km);if(g===undefined){const x=optMode(o,l);m.set(km,g=x?x.g:0);}return g;};
const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/OPT[o].reach)-1);
const dfCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1);
// A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears.
const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]});
const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;};
const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n;

View file

@ -0,0 +1,7 @@
/* ================= WORLD ================= */
// Simplified real geography: lon/lat outlines, equirectangular, with gentle "magnifying lenses" over the busy regions.
const LENSES=[{lon:102.5,lat:2.6,r:22,m:1.1},{lon:52.5,lat:25.3,r:45,m:1.5},{lon:78.5,lat:15,r:48,m:1.1},{lon:-44.5,lat:-23.5,r:30,m:1.2},{lon:9,lat:49,r:170,m:1.25},{lon:121,lat:32,r:120,m:0.45},{lon:-80,lat:40,r:110,m:0.5}];
function proj0(lon,lat){return [(lon+180)/360*W,(84-lat)*6.4];}
for(const L of LENSES){const q=proj0(L.lon,L.lat);L.x=q[0];L.y=q[1];}
function proj(lon,lat){const q=proj0(lon,lat);let dx=0,dy=0;for(const L of LENSES){let ex=q[0]-L.x;ex-=W*Math.round(ex/W);const ey=q[1]-L.y,f=L.m*Math.exp(-(ex*ex+ey*ey)/(L.r*L.r));dx+=ex*f;dy+=ey*f;}return [q[0]+dx,q[1]+dy];}
function hav(lo1,la1,lo2,la2){const r=Math.PI/180,dLa=(la2-la1)*r,dLo=(lo2-lo1)*r,a=Math.sin(dLa/2)**2+Math.cos(la1*r)*Math.cos(la2*r)*Math.sin(dLo/2)**2;return 2*6371*Math.asin(Math.min(1,Math.sqrt(a)));}

View file

@ -0,0 +1,45 @@
const LANDS_LL=[
{id:'am',ll:[[-166,68],[-157,71.2],[-141,69.8],[-128,70],[-115,68.5],[-97,68],[-94,62],[-92.5,57.5],[-85,55.2],[-80,51.5],[-78.5,58],[-77,62],[-70,61],[-64.5,60],[-61.5,56.5],[-57,52],[-55.6,49.5],[-53,47],[-59,46.5],[-61,45.2],[-63.2,44.4],[-66,44.5],[-70,43.3],[-70,42],[-74,40.6],[-76,38],[-75.8,35.5],[-77.5,34.5],[-79,33],[-81,31],[-80.05,27],[-80.1,25.3],[-81.5,25],[-82.7,27.5],[-84,30],[-89,30.2],[-94,29.5],[-97,28],[-97.5,25],[-97.7,22],[-96,19],[-94,18.3],[-91,18.5],[-90.4,21],[-87,21.5],[-88,17],[-88.5,15.8],[-84,15.8],[-83.4,12],[-83.7,10.5],[-81.5,9],[-79.5,9.5],[-77.5,8.6],[-75,10.8],[-71.5,12.3],[-68,10.6],[-62,10.5],[-60,8],[-57,6],[-52,5],[-50,1.5],[-48,-1],[-44,-2.5],[-39,-3.5],[-35,-5.5],[-35,-9],[-37.5,-12.5],[-39,-15],[-39.7,-19],[-41,-22],[-44,-23],[-48,-26],[-48.6,-28.5],[-51,-31],[-53,-34],[-58,-34.5],[-57,-37],[-62,-39],[-65,-41],[-64,-43],[-67.5,-46],[-66,-48],[-69,-51],[-68.5,-53],[-70,-55],[-73,-53],[-75,-48],[-73.5,-43],[-73.5,-37],[-71.5,-32],[-71.3,-27],[-70.5,-20],[-71.5,-17],[-76,-14],[-78,-10],[-81,-6],[-80.5,-3],[-80,0],[-79,1.5],[-77.5,4],[-77.4,7.5],[-80,7.3],[-82.5,8.2],[-85.7,10],[-87,12.5],[-91,14],[-94,16],[-96.5,15.7],[-100,17],[-105.5,20],[-105.5,22.5],[-108,25.5],[-110.8,27.9],[-113,31.3],[-114.7,31.7],[-113.5,29],[-112,26.5],[-110,24],[-109.5,23],[-112,24.8],[-114,27.5],[-115.5,29.8],[-117,32.5],[-118.5,34],[-120.6,34.6],[-122.5,37.5],[-124,40.5],[-124.5,43],[-124,46.2],[-124.7,48.4],[-123,49],[-126,50.5],[-130,54.5],[-133,57.5],[-137,58.5],[-141,60],[-146,61],[-150,59.5],[-152,58.5],[-156,57.5],[-158,56.8],[-162,55.5],[-164.5,54.5],[-158,58.5],[-162,60],[-165,61.5],[-166,64],[-164,65.5]]},
{id:'eu',ll:[[-9,39],[-9.5,43],[-8,43.7],[-1.8,43.4],[-1.2,46],[-2.5,47.3],[-4.5,48],[-1.6,48.6],[1.5,50.2],[3,51.2],[4.5,52.5],[5,53.4],[7,53.6],[8.6,54],[8.2,55.5],[8.1,57],[10.5,57.7],[10.5,56.5],[11.2,56],[12.6,56.1],[12.7,55.6],[12.1,54.9],[11,54.3],[14,54],[18.5,54.8],[21,55.3],[21,57],[24,57.5],[24,59.2],[28,59.5],[30,60],[28,60.5],[25,60.1],[22.5,60.3],[21.5,61.5],[21.5,63],[25,65],[25.5,65.6],[22,65.8],[20.5,63.5],[18,62.5],[17.4,61],[19,59.8],[18,59],[16.5,57],[16,56.2],[14.2,55.4],[13,55.4],[12.9,56.5],[11.5,58],[10.5,59.3],[8,58],[5.5,58.5],[5,60],[5,62],[7,63],[10,64],[12.5,66],[15,68.5],[18,69.8],[21.5,70.2],[26,71],[30,70],[33,69.3],[41,67],[44,68.5],[53,68.5],[58,69],[68,69],[69,72.8],[73,72.5],[80,73.5],[87,74.8],[100,76],[104,77.7],[112,74],[113.5,73.5],[127,73.5],[132,71.5],[140,72.5],[150,71.5],[160,70],[170,70],[180,69],[190,66.5],[186,64.5],[182,65],[178,62.5],[173,61],[170,60],[164,60],[164,57],[162,55],[159,52],[156.7,51],[156,55.5],[157,58],[155,59.5],[150,59.5],[143,59.3],[137,54.5],[141,53],[140,48.5],[135,43.5],[131,42.7],[129.5,41],[129.4,37],[129.4,35.5],[127.5,34.6],[126.3,34.8],[126.5,37],[125,37.8],[124.5,39.7],[121.5,39],[121.7,40.8],[119,39.3],[117.8,38.5],[119,37.2],[122.5,37.3],[120.5,36],[119.2,35],[121,32],[121.9,30.8],[121.5,28],[119.5,25.5],[116.5,23],[114.3,22.1],[111,21.5],[109.7,20.5],[108.5,21.6],[106.5,20],[106,18],[108.5,15],[109.3,12],[107,10.5],[105,8.6],[104.8,10.3],[103,11],[100.9,12.6],[100,13.4],[99.3,10.5],[100.3,7],[101,6.8],[103.4,4],[104.3,1.4],[103.6,1.25],[101.3,2.8],[100.2,5.3],[98.3,8],[98.6,13],[97.7,16.5],[94.4,16.2],[94.2,18.8],[92.3,20.6],[91.8,22.6],[90,22],[88.3,21.6],[86.9,20.6],[85,19.5],[82.3,16.6],[80.3,15.8],[80.3,13.5],[79.8,10.3],[78.3,8.9],[77.5,8.1],[76.5,8.9],[75.8,11.5],[74.8,12.9],[73.5,16],[72.8,19],[72.7,21.2],[70,22.5],[68.5,23.5],[66.6,25.4],[61.6,25.2],[57.3,25.8],[56.4,27.1],[54.7,26.5],[51.5,27.9],[50,30],[48,30],[48.4,28.5],[49.5,26.7],[50.8,24.8],[50.85,25.6],[51.2,26.15],[51.62,25.9],[51.62,24.6],[52.6,24.2],[54.3,24.6],[55.3,25.3],[55.9,25.75],[56.1,26.1],[56.35,26.38],[56.42,25.8],[56.38,25.0],[56.5,24.6],[57.8,23.8],[58.8,22.5],[59.8,22.4],[58.5,20.5],[57.7,19],[55.4,17.7],[52.2,15.7],[48.7,14],[45,12.8],[43.4,12.6],[42.7,15.7],[42.5,17.2],[41,19.5],[39.1,21.6],[38.4,23.6],[37,25.5],[35.2,28],[34.9,29.5],[34.3,27.8],[33,28.8],[32.6,30],[32.3,31.2],[34.2,31.3],[34.9,32.8],[35.6,34.5],[36,35.8],[36.2,36.7],[34.5,36.8],[32.5,36.1],[30.5,36.4],[29,36.6],[27.3,37.4],[26.3,38.6],[26.5,40],[26.2,40.6],[24,40.8],[22.6,40.4],[24.1,38.2],[24,37.6],[23.2,37.5],[22.3,36.5],[21.7,36.8],[21.2,38.4],[19.5,40],[19.5,41.8],[18.5,42.5],[16,43.5],[13.7,45.6],[12.3,45.3],[12.4,44.2],[13.6,43.5],[15.9,41.6],[18.5,40.2],[17,39],[16.6,38],[15.6,38],[15.3,37],[15.1,36.65],[12.4,37.8],[13.3,38.25],[15.55,38.3],[16.1,39],[15.6,40.1],[14.3,40.6],[12.5,41.6],[11,42.5],[10.2,43.9],[8.8,44.4],[7.5,43.8],[6,43.1],[4,43.5],[3.1,43.1],[3.2,41.9],[0.8,41],[0,39.5],[-0.3,38.4],[-0.8,37.6],[-2.1,36.7],[-4.4,36.7],[-5.6,36],[-6.3,36.8],[-7.4,37.2],[-8.9,37],[-8.8,38.4],[-9.5,38.6]]},
{id:'af',ll:[[-17.5,14.7],[-17,21],[-16,24],[-13,27.5],[-9.8,30],[-9.2,32.5],[-6.8,34],[-5.9,35.8],[-2,35.1],[1,36.5],[5,36.8],[9.8,37.3],[11,36.9],[10.2,35.2],[11.1,33.3],[15.2,32.3],[19,30.3],[20.1,32],[23,32.6],[25,31.7],[29,30.9],[32.2,31.3],[32.6,30],[33.5,28],[35.5,24],[37.2,21],[38.5,18],[39.6,15.5],[41.6,13.5],[43.3,12.4],[44,10.4],[47,11.1],[51.2,11.8],[51,10.4],[49.5,7],[47.8,4.5],[45,1.6],[42,-1],[40.2,-2.8],[39.3,-4.8],[38.8,-6.5],[39.6,-10],[40.5,-11],[40.6,-14.6],[37,-17.5],[35.4,-22],[35.5,-24],[32.9,-25.9],[32.5,-28.6],[31,-29.9],[28,-32.7],[25.6,-33.9],[22.5,-34],[20,-34.8],[18.4,-34],[17.9,-32.5],[16.5,-28.6],[15.2,-27],[14.4,-23],[12.8,-19],[11.8,-16.8],[12.2,-14.5],[13.6,-12.2],[13.2,-8.8],[12.3,-6],[11.8,-3.5],[9.5,-1],[9.4,1],[9.8,3.2],[8.9,4.5],[6,4.3],[4.3,6.3],[1.6,6.2],[-2,4.8],[-4.6,5.2],[-7.5,4.4],[-9.4,5.4],[-11.5,6.9],[-13.2,8.7],[-15,10.9],[-16.7,12.4]]},
{id:'uk',ll:[[-5.7,50.1],[-3,50.6],[1.4,51.2],[1.7,52.7],[0.3,53.4],[-0.2,54.3],[-1.6,55.6],[-2,56.4],[-1.8,57.6],[-3.4,58.6],[-5,58.6],[-6.2,57.5],[-5.6,56.3],[-5,55],[-3.2,54.9],[-3.4,54],[-3,53.4],[-4.6,53.3],[-4.2,52.2],[-5.2,51.7],[-3.2,51.4],[-4.6,51]]},
{id:'ie',ll:[[-6,52.2],[-6.2,53.5],[-5.6,54.6],[-6.4,55.2],[-7.4,55.4],[-8.5,54.5],[-10,54.2],[-9.6,53.2],[-10.2,51.9],[-9.6,51.5],[-8.2,51.8]]},
{id:'is',ll:[[-22.5,63.9],[-24,65.5],[-22,66.4],[-16,66.5],[-14.5,65.3],[-14.6,64.4],[-18,63.4]]},
{id:'jp',ll:[[129.6,33.3],[130.2,31.3],[131.4,31.5],[132,33],[133.5,33.4],[135.2,33.6],[136.8,34.3],[138.8,34.6],[140,35],[140.8,35.7],[141,38.2],[141.9,39.5],[141.4,41.4],[140,41.4],[139.9,40.3],[139.8,38.5],[138.8,37.8],[137.3,36.9],[136,36],[135.4,35.6],[133,35.5],[131.5,34.6],[130.9,34]]},
{id:'oc',ll:[[113.5,-22],[114,-26.5],[115,-30],[115.7,-33.6],[115,-34.3],[117.9,-35.1],[123.5,-33.9],[126,-32.3],[131,-31.5],[134,-32.8],[135.6,-34.8],[137.6,-35.6],[138.3,-34.5],[139.6,-36.9],[141.5,-38.4],[144.9,-37.9],[146.4,-39.1],[150,-37.5],[150.8,-34.5],[152.5,-32.4],[153.6,-28.5],[153,-25],[150.8,-22.5],[149,-20.6],[146.3,-18.9],[145.4,-16],[145.3,-14.9],[143.5,-12.3],[142.5,-10.7],[141.6,-12.8],[141.6,-16],[140.6,-17.6],[139.3,-17.4],[137,-15.9],[135.8,-15],[136.8,-12.2],[135,-12],[132.6,-11.5],[131,-12.2],[129.5,-14.9],[128,-15.4],[126.5,-13.9],[124.5,-16.5],[122.2,-18.2],[121,-19.7],[118.5,-20.3],[116.7,-20.6],[114.6,-21.8]]},
{id:'tas',ll:[[144.6,-40.7],[146.5,-41.1],[148.3,-40.9],[148.3,-42.2],[147.9,-43.2],[146.9,-43.6],[146,-43.5],[145.2,-42.2],[144.7,-41.2]]},
{id:'nz',ll:[[172.7,-34.4],[174.5,-36],[175.9,-37.5],[178.5,-37.7],[177.9,-39.2],[176.9,-39.6],[175.2,-41.6],[174.6,-41.2],[174.9,-39.9],[173.8,-39.3],[174.6,-38.1],[174.5,-37.3],[173.1,-35.3]]},
{id:'nzs',ll:[[172.6,-40.5],[174.3,-41.0],[174.2,-41.7],[173.3,-42.9],[172.8,-43.9],[171.3,-44.4],[170.7,-45.8],[169.3,-46.6],[168.3,-46.6],[166.5,-46.0],[166.8,-45.3],[168.2,-44.0],[170.6,-43.0],[171.4,-41.8],[172.1,-40.9]]},
{id:'idn',ll:[[105.2,-6.8],[106.8,-6.1],[108.5,-6.4],[110.5,-6.9],[112.6,-6.9],[114.6,-7.7],[114.4,-8.7],[111,-8.3],[108,-7.8],[105.5,-7]]},
{id:'ph',ll:[[120.6,18.5],[122.2,18.5],[122,16.5],[121.6,14.2],[124,13.8],[124,12.5],[123.3,13],[121,13.6],[120.6,14.5],[119.8,16.2]]},
];
// South America is drawn as part of 'am' but counts as its own landmass: nothing crosses the Darién Gap.
// Atlantic islands, each its own landmass too.
LANDS_LL.push(
{id:'bm',ll:[[-65.18,32.59],[-64.38,32.59],[-64.38,31.99],[-65.18,31.99]]},
{id:'az',ll:[[-26.07,38.04],[-25.27,38.04],[-25.27,37.44],[-26.07,37.44]]},
{id:'ic',ll:[[-16.65,28.76],[-15.85,28.76],[-15.85,28.16],[-16.65,28.16]]},
{id:'cv',ll:[[-23.91,15.22],[-23.11,15.22],[-23.11,14.62],[-23.91,14.62]]},
{id:'sh',ll:[[-6.12,-15.63],[-5.32,-15.63],[-5.32,-16.23],[-6.12,-16.23]]},
);
// Pacific islands, each its own landmass.
LANDS_LL.push(
{id:'hi',ll:[[-158.26,21.61],[-157.46,21.61],[-157.46,21.01],[-158.26,21.01]]},
{id:'gu',ll:[[144.35,13.77],[145.15,13.77],[145.15,13.17],[144.35,13.17]]},
{id:'pw',ll:[[134.08,7.64],[134.88,7.64],[134.88,7.04],[134.08,7.04]]},
{id:'mh',ll:[[170.98,7.39],[171.78,7.39],[171.78,6.79],[170.98,6.79]]},
{id:'pg',ll:[[146.78,-9.14],[147.58,-9.14],[147.58,-9.74],[146.78,-9.74]]},
{id:'sb',ll:[[159.55,-9.13],[160.35,-9.13],[160.35,-9.73],[159.55,-9.73]]},
{id:'nc',ll:[[166.06,-21.97],[166.86,-21.97],[166.86,-22.57],[166.06,-22.57]]},
{id:'fj',ll:[[178.04,-17.84],[178.84,-17.84],[178.84,-18.44],[178.04,-18.44]]},
{id:'to',ll:[[-175.60,-20.84],[-174.80,-20.84],[-174.80,-21.44],[-175.60,-21.44]]},
{id:'ws',ll:[[-172.16,-13.53],[-171.36,-13.53],[-171.36,-14.13],[-172.16,-14.13]]},
{id:'as',ll:[[-171.10,-13.98],[-170.30,-13.98],[-170.30,-14.58],[-171.10,-14.58]]},
{id:'pf',ll:[[-149.97,-17.23],[-149.17,-17.23],[-149.17,-17.83],[-149.97,-17.83]]},
);
LANDS_LL.push(
{id:'lk',ll:[[79.9, 9.8], [80.6, 9.6], [81.4, 8.5], [81.9, 7.4], [81.6, 6.4], [80.6, 5.9], [80.0, 6.2], [79.75, 7.2], [79.75, 8.3]]},
{id:'sa',hide:true,ll:[[-77.5, 8.6], [-75, 10.8], [-71.5, 12.3], [-68, 10.6], [-62, 10.5], [-60, 8], [-57, 6], [-52, 5], [-50, 1.5], [-48, -1], [-44, -2.5], [-39, -3.5], [-35, -5.5], [-35, -9], [-37.5, -12.5], [-39, -15], [-39.7, -19], [-41, -22], [-44, -23], [-48, -26], [-48.6, -28.5], [-51, -31], [-53, -34], [-58, -34.5], [-57, -37], [-62, -39], [-65, -41], [-64, -43], [-67.5, -46], [-66, -48], [-69, -51], [-68.5, -53], [-70, -55], [-73, -53], [-75, -48], [-73.5, -43], [-73.5, -37], [-71.5, -32], [-71.3, -27], [-70.5, -20], [-71.5, -17], [-76, -14], [-78, -10], [-81, -6], [-80.5, -3], [-80, 0], [-79, 1.5], [-77.5, 4], [-77.4, 7.5]]},
{id:'tw',ll:[[121.5, 25.35], [122.05, 25.0], [121.85, 24.3], [121.4, 23.0], [120.85, 21.9], [120.6, 22.3], [120.15, 22.9], [120.1, 23.6], [120.55, 24.5], [121.0, 25.1]]},
);
const LANDS=LANDS_LL.map(l=>({id:l.id,hide:true,pts:l.ll.map(q=>proj(q[0],q[1]))}));

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,204 @@
const CITY_LL={
"abj":[-4.03,5.32],
"acc":[-0.19,5.6],
"add":[38.75,9.03],
"adl":[138.6,-34.93],
"aju":[-37.07,-10.91],
"akl":[174.76,-36.85],
"alg":[3.06,36.75],
"ams":[4.9,52.37],
"apw":[-171.76,-13.83],
"ash":[-77.49,39.04],
"asu":[-57.58,-25.26],
"ath":[23.73,37.98],
"atn":[-84.39,33.75],
"auh":[54.37, 24.45],
"bcn":[2.17,41.39],
"bda":[-64.78,32.29],
"bde":[-4.54,50.83],
"beg":[20.46,44.79],
"bel":[-48.5,-1.46],
"ber":[13.4,52.52],
"bet":[6.1,49.52],
"bhz":[-43.94,-19.92],
"bkk":[100.5, 13.76],
"blr":[77.59, 12.97],
"bne":[153.03, -27.47],
"bog":[-74.07, 4.71],
"bom":[72.88,19.08],
"bos":[-71.06,42.36],
"bru":[4.35,50.85],
"bsb":[-47.88,-15.79],
"bud":[19.04, 47.5],
"bue":[-58.38, -34.6],
"buh":[26.1, 44.43],
"bvb":[-60.67,2.82],
"cac":[-53.46,-24.96],
"cai":[31.24,30.04],
"cal":[-114.07,51.05],
"cas":[-7.59,33.57],
"cau":[-35.98,-8.28],
"cbo":[80.0, 6.95],
"cbr":[149.13,-35.28],
"ccs":[-66.9,10.49],
"cgb":[-56.1,-15.6],
"cgr":[-54.65,-20.47],
"chc":[172.55,-43.53],
"chi":[-87.63,41.88],
"cor":[-64.18,-31.42],
"cph":[12.57,55.68],
"cpq":[-47.06,-22.91],
"cpt":[18.42, -33.92],
"cpv":[-35.88,-7.23],
"cwb":[-49.27,-25.43],
"cxj":[-51.18,-29.17],
"dac":[90.41, 23.81],
"dal":[-96.8,32.78],
"dar":[39.28,-6.79],
"del":[77.21, 28.61],
"den":[-104.99,39.74],
"dkr":[-17.45,14.69],
"dla":[9.7,4.05],
"doh":[51.45,25.28],
"drw":[131.05,-12.46],
"dub":[-6.26,53.35],
"dur":[31.03,-29.86],
"dus":[6.78,51.22],
"dxb":[55.27,25.2],
"edi":[-3.19,55.95],
"fec":[-38.97,-12.27],
"fih":[15.27,-4.33],
"fln":[-48.55,-27.6],
"for":[-38.54, -3.73],
"fra":[8.68,50.11],
"fuj":[56.15,25.07],
"gbe":[25.91,-24.65],
"gdl":[-103.35,20.67],
"gua":[-90.51,14.63],
"gum":[144.75,13.47],
"gyn":[-49.25,-16.69],
"ham":[9.99,53.55],
"hba":[147.25,-42.85],
"hel":[24.94,60.17],
"hfx":[-63.62,44.68],
"hir":[159.95,-9.43],
"hkg":[114.17,22.32],
"hnl":[-157.86,21.31],
"hou":[-95.37,29.76],
"hre":[31.05,-17.83],
"hyd":[78.49, 17.39],
"icn":[126.98,37.57],
"igu":[-54.59,-25.55],
"ist":[28.98, 41.01],
"ivc":[168.35,-46.41],
"jam":[-5.72,-15.93],
"jed":[39.25,21.55],
"jib":[43.15,11.59],
"jkt":[106.85,-6.2],
"jnb":[28.05,-26.2],
"jpa":[-34.86,-7.12],
"kcy":[-94.58,39.1],
"kgl":[30.06,-1.95],
"khi":[67.14,25.0],
"kla":[32.58,0.35],
"kul":[101.69, 3.14],
"kyv":[30.52,50.45],
"lad":[13.23,-8.84],
"lag":[3.38,6.52],
"lax":[-118.24,34.05],
"ldb":[-51.16,-23.31],
"lim":[-76.85,-12.05],
"lis":[-9.14,38.72],
"ljd":[-51.96,-29.47],
"lon":[-0.13,51.51],
"lpb":[-68.15,-16.5],
"lun":[28.32,-15.39],
"maa":[80.18,13.25],
"mad":[-3.7,40.42],
"maj":[171.38,7.09],
"man":[-2.24,53.48],
"mao":[-60.02,-3.12],
"mba":[39.67,-4.04],
"mcp":[-51.07,0.03],
"mcz":[-35.74,-9.67],
"mde":[-75.57,6.24],
"mel":[144.96, -37.81],
"mex":[-99.13,19.43],
"mgf":[-51.94,-23.42],
"mia":[-80.19,25.76],
"mil":[9.19,45.46],
"mnl":[120.98,14.6],
"mos":[37.62,55.76],
"mpm":[32.57,-25.97],
"mrs":[5.37,43.3],
"mtl":[-73.57,45.5],
"mty":[-100.31,25.69],
"muc":[11.58,48.14],
"mvd":[-56.16,-34.9],
"nat":[-35.21,-5.79],
"nbo":[36.82,-1.29],
"nou":[166.46,-22.27],
"nyc":[-74.0,40.71],
"oos":[3.23,51.15],
"osa":[135.5, 34.69],
"osl":[10.75,59.91],
"ott":[-75.7,45.42],
"pan":[-79.52, 8.98],
"par":[2.35,48.86],
"pdl":[-25.67,37.74],
"pek":[116.4,39.9],
"per":[115.86,-31.95],
"phx":[-112.07,33.45],
"pmo":[13.36,38.12],
"pmw":[-48.33,-10.18],
"poa":[-51.23,-30.03],
"pom":[147.18,-9.44],
"ppg":[-170.7,-14.28],
"ppt":[-149.57,-17.53],
"prg":[14.42, 50.08],
"pvh":[-63.9,-8.76],
"qro":[-100.39,20.59],
"rai":[-23.55,14.98],
"rao":[-47.81,-21.18],
"rbr":[-67.81,-9.97],
"rec":[-34.88,-8.05],
"rek":[-21.94,64.15],
"ria":[-53.81,-29.68],
"rio":[-43.11,-22.57],
"rom":[12.5,41.9],
"ror":[134.48,7.34],
"ruh":[46.72,24.71],
"sao":[-46.63,-23.55],
"scl":[-70.67, -33.45],
"sea":[-122.33,47.61],
"sgn":[106.66, 10.76],
"sha":[121.47,31.23],
"sin":[103.82,1.35],
"sjc":[-121.89,37.34],
"sjo":[-84.09,9.93],
"sjp":[-49.38,-20.81],
"slc":[-111.89,40.76],
"slz":[-44.3,-2.53],
"sof":[23.32,42.7],
"ssa":[-38.5,-12.97],
"stg":[9.18,48.78],
"sto":[18.07,59.33],
"suv":[178.44,-18.14],
"svg":[5.73,58.97],
"syd":[151.21,-33.87],
"tbu":[-175.2,-21.14],
"tci":[-16.3,28.44],
"the":[-42.8,-5.09],
"tll":[24.45,58.9],
"tok":[139.69,35.69],
"tor":[-79.38,43.65],
"tpe":[121.56, 25.03],
"tun":[10.18,36.81],
"uio":[-78.47,-0.18],
"van":[-123.12,49.28],
"vie":[16.37, 48.21],
"vix":[-40.31,-20.32],
"waw":[21.01, 52.23],
"wdh":[17.08,-22.56],
"zrh":[8.54,47.37],
};

View file

@ -0,0 +1,271 @@
const CITIES=[
{id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',P:300,ix:'Sea-IX',dc:'Westerly Carrier Hotel'},
{id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV'},
{id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',P:450,ix:'Yee-Haw-IX',dc:'Infomaniac Building'},
{id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',P:600,ix:'Windy-IX',dc:'350 Cermak'},
{id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:tr('cities.the_data_center_capital_rumor_says')},
{id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',P:1200,ix:'NY-Yikes',dc:'60 Hudson'},
{id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',P:400,ix:'Miam-IX',dc:'Nap of the Americas',note:tr('cities.cable_landing_hub_for_south_america')},
{id:'sao',name:'São Paulo',x:640,y:730,land:'sa',reg:'SA',P:900,br:true,andes:'e',ix:'IX.brrr',ixCheap:0.3,dc:'Digital Reality SP',note:tr('cities.south_america_s_biggest_market_and')},
{id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',P:1000,ix:'LYNX',dc:'Telly-House Docklands',note:tr('cities.on_an_island_so_every_link')},
{id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',P:350,ix:'HAMS-IX',dc:'Science Park'},
{id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',P:600,ix:'DE-KICKS',dc:'Kleyerstraße Campus',note:tr('cities.europe_s_crossroads_lots_of_networks')},
{id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',P:900,ix:'Fromage-IX',dc:'Interaction PAR'},
{id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:tr('cities.subsea_cables_to_africa_and_asia')},
{id:'tor',name:'Toronto',ca:true,x:548,y:252,land:'am',reg:'AM',P:500,ix:'Sorry-IX',dc:'151 Front Street',note:tr('cities.canada_s_hub_polite_packets_long')},
{id:'bru',name:'Brussels',x:0,y:0,land:'eu',reg:'EU',P:150,be:true,tape:true,ix:'Frites-IX',dc:'Digital Unreality BRU1',note:tr('cities.right_between_london_amsterdam_paris')},
{id:'oos',name:'Oostkamp',x:0,y:0,land:'eu',reg:'EU',P:30,be:true,tape:true,ix:'',dc:'DC-Starfish Oostkamp',note:tr('cities.inland_from_ostend_where_the_cables')},
{id:'bet',name:'Bettembourg',x:0,y:0,land:'eu',reg:'EU',P:60,arpu:1.4,lux:true,ix:'LU-SICK',dc:'LuxDisconnect DC1.2',note:tr('cities.luxembourg_s_data_centers_are_not')},
{id:'mtl',name:'Montreal',ca:true,x:598,y:238,land:'am',reg:'AM',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:tr('cities.cheap_hydro_power_makes_it_a')},
{id:'kcy',name:'Kansas City',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Toto-IX',dc:'The Limestone Cave',note:tr('cities.the_geographic_middle_of_the_us')},
{id:'cal',name:'Calgary',x:0,y:0,land:'am',reg:'AM',P:150,ca:true,ix:'Stampede-IX',dc:'Bow & Arrow DC',note:tr('cities.the_prairie_gateway_between')},
{id:'van',name:'Vancouver',x:0,y:0,land:'am',reg:'AM',P:250,ca:true,ix:'Raincouver-IX',dc:'Colo-Logics VAN3',note:tr('cities.canada_s_pacific_door_it_rains')},
{id:'ott',name:'Ottawa',x:0,y:0,land:'am',reg:'AM',P:120,ca:true,blackout:true,ix:'Bytown-IX',dc:'Purely Colo (Mostly)',note:tr('cities.canada_s_capital_once_called_bytown')},
{id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',P:900,ix:'Any2-Anywhere',dc:'One Wilshire',note:tr('cities.pacific_cables_land_nearby_and')},
{id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',P:700,ix:'',dc:'Querétaro Campus',note:tr('cities.huge_mobile_market_most_of_its')},
{id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:tr('cities.free_cooling_and_geothermal_power')},
{id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',P:250,ix:'Craic-IX',dc:'Clonsilla Hyperscale Campus',note:tr('cities.every_hyperscaler_s_european_hq')},
{id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'},
{id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:tr('cities.landing_point_for_cables_from_the')},
{id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:tr('cities.fast_fiber_east_and_west_and')},
{id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',P:250,ix:'',dc:'Danube Docks DC'},
{id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',P:250,ix:'Rakija-IX',dc:'Vitosha DC',note:tr('cities.balkan_peering_hub_with_famously')},
{id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',P:400,uae:true,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:tr('cities.crossroads_for_cables_between_europe')},
{id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:tr('cities.sovereign_internet_rules_every_pop')},
{id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:tr('cities.far_from_everything_every_packet')},
{id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:200,ix:'Beard-IX',dc:'Very Remote DC',dc2:'Next-Door-DC P#',dc2N:2,note:tr('cities.the_most_isolated_big_city_on')},
{id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:tr('cities.270_million_people_on_17_000')},
{id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',P:600,ix:'',dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')},
{id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:tr('cities.startups_techno_and_a_surprising')},
{id:'ham',name:'Hamburg',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Moin-IX',dc:'Speicherstadt Colo',note:tr('cities.germany_s_port_city_everyone_says')},
{id:'dus',name:'Düsseldorf',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Altbier-IX',dc:'Königsallee Cage',note:tr('cities.the_rhine_ruhr_hub_more_carrier')},
{id:'muc',name:'Munich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Brezn-IX',dc:'Weißwurst Works',note:tr('cities.bavaria_s_capital_cars_insurers_and')},
{id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:tr('cities.banks_very_punctual_packets_and')},
{id:'nbo',name:'Nairobi',x:0,y:0,land:'af',reg:'AF',cc:'KE',P:350,ix:'Safari-IX',dc:'Silicon Savannah Campus',note:tr('cities.east_africa_s_hub_cables_land')},
{id:'cai',name:'Cairo',x:0,y:0,land:'af',land2:'eu',reg:'AF',cc:'EG',P:600,ix:'Pharaoh-IX',dc:'Pyramid-adjacent DC',note:tr('cities.almost_every_europe_asia_cable')},
{id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:tr('cities.cars_engineers_and_kehrwoche_every')},
{id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',P:300,ix:'NodNod',dc:'Nuclear Bunker DC'},
{id:'bcn',name:'Barcelona',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Catnip-IX',dc:'Poblenou DC',note:tr('cities.catalonia_s_own_exchange_small_and')},
{id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',P:600,ix:'Siesta-IX',dc:'Interaction MAD'},
{id:'lag',name:'Lagos',x:1010,y:565,land:'af',reg:'AF',cc:'NG',P:500,ix:'Jollof-IX',dc:'Rack-n-Roll Centre'},
{id:'jnb',name:'Johannesburg',x:1130,y:730,land:'af',reg:'AF',cc:'ZA',P:400,za:true,ix:'Braai-IX',dc:'Tera-Cotta Campus'},
{id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',P:1100,india:true,ix:'Mumb-IX',dc:'Goregaon Tech Park'},
{id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',P:450,ix:'Lah-IX',dc:'Equinox SG',note:tr('cities.asia_s_hub_expensive_humid_very')},
{id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',P:600,ix:'HK-Kicks',dc:'Mega-Eye Plus'},
{id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',P:900,kr:true,ix:'Kimch-IX',dc:'Gasan Digital Complex',note:tr('cities.some_of_the_fastest_home_broadband')},
{id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun DC',note:tr('cities.mainland_china_behind_the_great')},
{id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui Data Center',note:tr('cities.mainland_china_enormous_market')},
{id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',P:1400,ix:'JP-Naptime',dc:'Otemachi Tower'},
{id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:500,ix:'IX Straya',dc:'Next-Door-DC S#',dcN:3,dc2:'Equinox SY#',dc2N:7,note:tr('cities.the_harbour_the_bridge_and_most')},
{id:'for',name:'Fortaleza',x:0,y:0,land:'sa',reg:'SA',P:250,br:true,andes:'e',ix:'IX.brrr Fortaleza',ixCheap:0.3,dc:'Praia Landing Station',note:tr('cities.where_south_america_s_cables')},
{id:'rio',name:'Rio de Janeiro',x:0,y:0,land:'sa',reg:'SA',P:600,br:true,andes:'e',ix:'IX.brrr Rio',ixCheap:0.3,dc:'Copacabana Colo',note:tr('cities.beaches_cable_landings_and_a')},
{id:'bsb',name:'Brasília',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Brasília',ixCheap:0.3,dc:'Modernist Concrete Colo',note:tr('cities.brazil_s_planned_capital_shaped_like')},
{id:'bhz',name:'Belo Horizonte',x:0,y:0,land:'sa',reg:'SA',P:250,br:true,andes:'e',ix:'IX.brrr BH',ixCheap:0.3,dc:'Pão de Queijo Point',note:tr('cities.mountains_mines_and_more_bars_per')},
{id:'cwb',name:'Curitiba',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Curitiba',ixCheap:0.3,dc:'Pine Nut Park DC',note:tr('cities.brazil_s_coldest_big_city_and')},
{id:'poa',name:'Porto Alegre',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Porto Alegre',ixCheap:0.3,dc:'Chimarrão Colo',note:tr('cities.the_deep_south_halfway_to_buenos')},
{id:'aju',off:true,name:'Aracaju',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Aracaju',ixCheap:0.3,dc:'Crab Walk Colo'},
{id:'bel',name:'Belém',x:0,y:0,land:'sa',reg:'SA',P:100,br:true,andes:'e',rain:true,ix:'IX.brrr Belém',ixCheap:0.3,dc:'Açaí Bowl DC',note:tr('cities.gateway_to_the_amazon_at_the')},
{id:'bvb',name:'Boa Vista',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Boa Vista',ixCheap:0.3,dc:'Northern Lights Racks',note:tr('cities.brazil_s_northernmost_capital_the')},
{id:'cac',off:true,name:'Cascavel',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Cascavel',ixCheap:0.3,dc:'Soybean Silo DC'},
{id:'cpv',off:true,name:'Campina Grande',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Campina Grande',ixCheap:0.3,dc:'Forró Forum DC',note:tr('cities.throws_the_biggest_sao_joao_festival')},
{id:'cpq',name:'Campinas',x:0,y:0,land:'sa',reg:'SA',P:130,br:true,andes:'e',ix:'IX.brrr Campinas',ixCheap:0.3,dc:'Silicon Sugarcane Park',note:tr('cities.brazil_s_tech_hub_an_hour')},
{id:'cgr',name:'Campo Grande',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Campo Grande',ixCheap:0.3,dc:'Pantanal Edge Colo'},
{id:'cau',off:true,name:'Caruaru',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Caruaru',ixCheap:0.3,dc:'Clay Doll Datacenter'},
{id:'cgb',name:'Cuiabá',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Cuiabá',ixCheap:0.3,dc:'Forty Degrees DC',note:tr('cities.the_geographic_center_of_south')},
{id:'cxj',off:true,name:'Caxias do Sul',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr Caxias do Sul',ixCheap:0.3,dc:'Wine Cellar Racks',note:tr('cities.italian_immigrants_vineyards_and')},
{id:'fec',off:true,name:'Feira de Santana',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr Feira de Santana',ixCheap:0.3,dc:'Crossroads Colo'},
{id:'fln',off:true,name:'Florianópolis',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Florianópolis',ixCheap:0.3,dc:'Island Uplink DC',note:tr('cities.an_island_capital_of_beaches_and')},
{id:'igu',off:true,name:'Foz do Iguaçu',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Foz do Iguaçu',ixCheap:0.3,dc:'Triple Border Racks',note:tr('cities.where_brazil_argentina_and_paraguay')},
{id:'gyn',name:'Goiânia',x:0,y:0,land:'sa',reg:'SA',P:100,br:true,andes:'e',ix:'IX.brrr Goiânia',ixCheap:0.3,dc:'Pequi Peak DC',note:tr('cities.agribusiness_capital_and_home_of')},
{id:'jpa',off:true,name:'João Pessoa',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr João Pessoa',ixCheap:0.3,dc:'Sunrise Point DC',note:tr('cities.the_easternmost_city_of_the_americas')},
{id:'ljd',off:true,name:'Lajeado',x:0,y:0,land:'sa',reg:'SA',P:10,br:true,andes:'e',ix:'IX.brrr Lajeado',ixCheap:0.3,dc:'Valley Co-op Colo',note:tr('cities.a_small_town_with_its_own')},
{id:'ldb',name:'Londrina',x:0,y:0,land:'sa',reg:'SA',P:35,br:true,andes:'e',ix:'IX.brrr Londrina',ixCheap:0.3,dc:'Red Soil DC'},
{id:'mcp',name:'Macapá',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',rain:true,blackout:true,ix:'IX.brrr Macapá',ixCheap:0.3,dc:'Equator Line Colo',note:tr('cities.right_on_the_equator_at_the')},
{id:'mcz',off:true,name:'Maceió',x:0,y:0,land:'sa',reg:'SA',P:55,br:true,andes:'e',ix:'IX.brrr Maceió',ixCheap:0.3,dc:'Lagoon View Racks'},
{id:'mao',name:'Manaus',x:0,y:0,land:'sa',reg:'SA',P:90,br:true,andes:'e',rain:true,ix:'IX.brrr Manaus',ixCheap:0.3,dc:'Free Zone Colo',note:tr('cities.two_million_people_in_the_middle')},
{id:'mgf',off:true,name:'Maringá',x:0,y:0,land:'sa',reg:'SA',P:30,br:true,andes:'e',ix:'IX.brrr Maringá',ixCheap:0.3,dc:'Cathedral Cone DC'},
{id:'nat',name:'Natal',x:0,y:0,land:'sa',reg:'SA',P:60,br:true,andes:'e',ix:'IX.brrr Natal',ixCheap:0.3,dc:'Dune Buggy DC',note:tr('cities.dunes_buggies_and_the_corner_of')},
{id:'pmw',name:'Palmas',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Palmas',ixCheap:0.3,dc:'Planned Grid DC',note:tr('cities.brazil_s_youngest_state_capital')},
{id:'pvh',name:'Porto Velho',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',rain:true,ix:'IX.brrr Porto Velho',ixCheap:0.3,dc:'Madeira River Racks'},
{id:'rao',off:true,name:'Ribeirão Preto',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Ribeirão Preto',ixCheap:0.3,dc:'Sugarcane & Servers',note:tr('cities.brazil_s_agribusiness_capital')},
{id:'rec',name:'Recife',x:0,y:0,land:'sa',reg:'SA',P:160,br:true,andes:'e',ix:'IX.brrr Recife',ixCheap:0.3,dc:'Frevo Colo',note:tr('cities.the_venice_of_brazil_all_bridges')},
{id:'rbr',name:'Rio Branco',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Rio Branco',ixCheap:0.3,dc:'Acre-ly Real DC',note:tr('cities.the_capital_of_acre_a_state')},
{id:'ssa',name:'Salvador',x:0,y:0,land:'sa',reg:'SA',P:160,br:true,andes:'e',ix:'IX.brrr Salvador',ixCheap:0.3,dc:'Axé Uplink DC',note:tr('cities.brazil_s_first_capital_with_cables')},
{id:'ria',off:true,name:'Santa Maria',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Santa Maria',ixCheap:0.3,dc:'Gaúcho Plains Colo'},
{id:'sjp',off:true,name:'São José do Rio Preto',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr São José do Rio Preto',ixCheap:0.3,dc:'Rio Preto Racks'},
{id:'slz',name:'São Luís',x:0,y:0,land:'sa',reg:'SA',P:65,br:true,andes:'e',ix:'IX.brrr São Luís',ixCheap:0.3,dc:'Reggae Island DC',note:tr('cities.an_island_city_of_tiled_colonial')},
{id:'the',name:'Teresina',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Teresina',ixCheap:0.3,dc:'Sunbaked Server Hall',note:tr('cities.the_only_northeastern_capital_away')},
{id:'vix',name:'Vitória',x:0,y:0,land:'sa',reg:'SA',P:80,br:true,andes:'e',ix:'IX.brrr Vitória',ixCheap:0.3,dc:'Moqueca Colo',note:tr('cities.an_island_capital_with_a_big')},
{id:'mvd',name:'Montevideo',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'e',ix:'Chivito-IX',dc:'Rambla Racks',note:tr('cities.uruguay_fiber_to_almost_every_home')},
{id:'asu',name:'Asunción',x:0,y:0,land:'sa',reg:'SA',P:120,andes:'e',ix:'Chipa-IX',dc:'Hydro Surplus DC',note:tr('cities.paraguay_shares_two_giant_dams_with')},
{id:'cor',name:'Córdoba',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'e',arpu:0.7,ix:'Fernet-IX',dc:'Sierras Server Shed',note:tr('cities.argentina_s_second_city_universities')},
{id:'lpb',name:'La Paz',x:0,y:0,land:'sa',reg:'SA',P:80,andes:'m',ix:'Salteña-IX',dc:'Cable Car Colo',note:tr('cities.the_highest_seat_of_government_on')},
{id:'uio',name:'Quito',x:0,y:0,land:'sa',reg:'SA',P:100,andes:'m',ix:'Equator-IX',dc:'Middle of the World DC',note:tr('cities.a_capital_high_in_the_andes')},
{id:'mde',name:'Medellín',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'m',ix:'Paisa-IX',dc:'Eternal Spring DC',note:tr('cities.the_city_of_eternal_spring_with')},
{id:'ccs',name:'Caracas',x:0,y:0,land:'sa',reg:'SA',P:120,blackout:true,ix:'Cachapa-IX',dc:'Generator Included DC',note:tr('cities.a_capital_in_a_valley_under')},
{id:'gua',name:'Guatemala City',x:0,y:0,land:'am',reg:'AM',P:120,ix:'Quetzal-IX',dc:'Volcano View Colo',note:tr('cities.central_america_s_biggest_city')},
{id:'sjo',name:'San José',x:0,y:0,land:'am',reg:'AM',P:80,ix:'Pura Vida-IX',dc:'Cloud Forest DC',note:tr('cities.costa_rica_runs_almost_entirely_on')},
{id:'qro',name:'Querétaro',x:0,y:0,land:'am',reg:'AM',P:120,ix:'Gordita-IX',dc:'Bajío Bit Barn',note:tr('cities.mexico_s_data_center_boom_town')},
{id:'mty',name:'Monterrey',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Cabrito-IX',dc:'Saddle Mountain Colo',note:tr('cities.mexico_s_industrial_capital_a_few')},
{id:'gdl',name:'Guadalajara',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Tequila-IX',dc:'Mariachi Mainframes',note:tr('cities.mexico_s_silicon_valley_home_of')},
{id:'bue',name:'Buenos Aires',x:0,y:0,land:'sa',reg:'SA',P:500,andes:'e',arpu:0.7,ix:'Asado-IX',dc:'Puerto Madero DC',note:tr('cities.tango_steak_and_a_currency_that')},
{id:'scl',name:'Santiago',x:0,y:0,land:'sa',reg:'SA',P:350,andes:'w',ix:'Empanada-IX',dc:'Andes-view Bunker',note:tr('cities.the_pacific_gateway_the_andes_sit')},
{id:'lim',name:'Lima',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'w',ix:'Ceviche-IX',dc:'Fog-cooled DC',note:tr('cities.it_almost_never_rains_but_the')},
{id:'bog',name:'Bogotá',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'m',ix:'Arepa-IX',dc:'2,600 m Above Sea Level DC',note:tr('cities.high_up_in_the_andes_no')},
{id:'pan',name:'Panama City',x:0,y:0,land:'am',reg:'AM',P:80,ix:'Canal-IX',dc:'Isthmus Interconnect',note:tr('cities.every_cable_between_the_americas')},
{id:'del',name:'Delhi',x:0,y:0,land:'eu',reg:'AS',P:1600,arpu:0.4,india:true,ix:'Butter-Chicken-IX',dc:'Smog-filtered DC',note:tr('cities.an_enormous_very_online_city_a')},
{id:'maa',name:'Chennai',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.5,india:true,ix:'Dosa-IX',dc:'Cyclone-rated Landing Bay',note:tr('cities.india_s_east_coast_landing_hub')},
{id:'blr',name:'Bengaluru',x:0,y:0,land:'eu',reg:'AS',P:600,arpu:0.6,india:true,ix:'Filter-Kaapi-IX',dc:'Traffic-jam-adjacent Campus',note:tr('cities.india_s_tech_capital_packets_move')},
{id:'hyd',name:'Hyderabad',x:0,y:0,land:'eu',reg:'AS',P:400,arpu:0.5,india:true,ix:'Biryani-IX',dc:'Hyperscale Hills',note:tr('cities.every_hyperscaler_is_building_a')},
{id:'tpe',name:'Taipei',x:0,y:0,land:'tw',reg:'AS',P:450,ix:'Bubble-Tea-IX',dc:'Typhoon-proof Tower',note:tr('cities.makes_most_of_the_world_s')},
{id:'auh',name:'Abu Dhabi',x:0,y:0,land:'eu',reg:'AS',P:200,arpu:1.4,uae:true,ix:'',dc:'Oasis-cooled Campus',note:tr('cities.the_capital_sovereign_ai_money_and')},
{id:'fuj',name:'Fujairah',x:0,y:0,land:'eu',reg:'AS',P:20,uae:true,ix:'',dc:'Cable Landing Sandcastle',note:tr('cities.most_uae_cables_land_on_this')},
{id:'cpt',name:'Cape Town',x:0,y:0,land:'af',reg:'AF',cc:'ZA',P:250,za:true,ix:'Biltong-IX',dc:'Table Mountain Colo',note:tr('cities.where_the_atlantic_cables_to_africa')},
{id:'dkr',name:'Dakar',x:0,y:0,land:'af',reg:'AF',P:140,cc:'SN',ix:'Thieboudienne-IX',dc:'Teranga Racks',note:tr('cities.africa_s_westernmost_capital_where')},
{id:'abj',name:'Abidjan',x:0,y:0,land:'af',reg:'AF',P:200,cc:'CI',ix:'Attiéké-IX',dc:'Plateau Point DC',note:tr('cities.the_business_capital_of_french')},
{id:'acc',name:'Accra',x:0,y:0,land:'af',reg:'AF',P:170,cc:'GH',ix:'Kelewele-IX',dc:'Black Star Colo',note:tr('cities.ghana_s_capital_and_a_favourite')},
{id:'dla',name:'Douala',x:0,y:0,land:'af',reg:'AF',P:130,cc:'CM',ix:'Ndolé-IX',dc:'Wouri Riverside DC',note:tr('cities.cameroon_s_port_city_a_cable')},
{id:'fih',name:'Kinshasa',x:0,y:0,land:'af',reg:'AF',P:350,cc:'CD',blackout:true,ix:'Rumba-IX',dc:'Congo River Colo',note:tr('cities.one_of_africa_s_biggest_cities')},
{id:'lad',name:'Luanda',x:0,y:0,land:'af',reg:'AF',P:250,cc:'AO',ix:'Muamba-IX',dc:'Marginal View DC',note:tr('cities.angola_s_oil_capital_and_the')},
{id:'cas',name:'Casablanca',x:0,y:0,land:'af',reg:'AF',P:150,cc:'MA',ix:'Tagine-IX',dc:'Here’s Looking at You, Rack',note:tr('cities.morocco_s_business_capital_on_the')},
{id:'alg',name:'Algiers',x:0,y:0,land:'af',reg:'AF',P:130,cc:'DZ',ix:'Couscous-IX',dc:'Kasbah Colo',note:tr('cities.white_houses_climbing_up_from_the')},
{id:'tun',name:'Tunis',x:0,y:0,land:'af',reg:'AF',P:100,cc:'TN',ix:'Harissa-IX',dc:'Carthage Was Here DC',note:tr('cities.a_capital_next_to_the_ruins')},
{id:'jib',name:'Djibouti',x:0,y:0,land:'af',reg:'AF',P:40,cc:'DJ',ix:'Lake Assal-IX',dc:'Cable Landing Capital DC',note:tr('cities.a_tiny_country_at_the_mouth')},
{id:'add',name:'Addis Ababa',x:0,y:0,land:'af',reg:'AF',P:170,cc:'ET',ix:'Injera-IX',dc:'Highland Coffee DC',note:tr('cities.ethiopia_s_capital_at_2_400')},
{id:'mba',name:'Mombasa',x:0,y:0,land:'af',reg:'AF',P:60,cc:'KE',ix:'Pwani-IX',dc:'Old Town Landing Station',note:tr('cities.where_east_africa_s_cables_come')},
{id:'dar',name:'Dar es Salaam',x:0,y:0,land:'af',reg:'AF',P:220,cc:'TZ',ix:'Bongo-IX',dc:'Kariakoo Colo',note:tr('cities.tanzania_s_biggest_city_and_the')},
{id:'kla',name:'Kampala',x:0,y:0,land:'af',reg:'AF',P:130,cc:'UG',ix:'Matooke-IX',dc:'Seven Hills DC',note:tr('cities.a_city_on_seven_hills_by')},
{id:'kgl',name:'Kigali',x:0,y:0,land:'af',reg:'AF',P:60,cc:'RW',ix:'Umuganda-IX',dc:'Clean Streets Colo',note:tr('cities.probably_the_cleanest_capital_in')},
{id:'mpm',name:'Maputo',x:0,y:0,land:'af',reg:'AF',P:70,cc:'MZ',ix:'Matapa-IX',dc:'Polana Point DC',note:tr('cities.mozambique_s_capital_an_hour_from')},
{id:'dur',name:'Durban',x:0,y:0,land:'af',reg:'AF',P:130,cc:'ZA',za:true,ix:'Bunny Chow-IX',dc:'Golden Mile Colo',note:tr('cities.south_africa_s_east_coast_surf')},
{id:'wdh',name:'Windhoek',x:0,y:0,land:'af',reg:'AF',P:25,cc:'NA',ix:'Kapana-IX',dc:'Desert Breeze DC',note:tr('cities.a_small_capital_in_the_middle')},
{id:'lun',name:'Lusaka',x:0,y:0,land:'af',reg:'AF',P:100,cc:'ZM',blackout:true,ix:'Nshima-IX',dc:'Copperbelt Colo',note:tr('cities.zambia_runs_on_hydro_power_from')},
{id:'hre',name:'Harare',x:0,y:0,land:'af',reg:'AF',P:70,cc:'ZW',blackout:true,ix:'Sadza-IX',dc:'Jacaranda DC',note:tr('cities.purple_jacaranda_trees_and_long')},
{id:'gbe',name:'Gaborone',x:0,y:0,land:'af',reg:'AF',P:25,cc:'BW',ix:'Seswaa-IX',dc:'Diamond Dust DC',note:tr('cities.botswana_quiet_safe_and_rich_in')},
{id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',dc2:'Next-Door-DC M#',dc2N:3,note:tr('cities.four_seasons_in_one_day_and')},
{id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',dc2:'Next-Door-DC B#',dc2N:2,note:tr('cities.brisvegas_big_sky_a_thunderstorm_at')},
{id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')},
{id:'adl',name:'Adelaide',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:150,ix:'Vineyard-IX',dc:'OurDC',dc2:'Next-Door-DC A1',note:tr('cities.twenty_minutes_from_everything')},
{id:'cbr',capital:true,name:'Canberra',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:50,ix:'Capital-IX',dc:'Classified Data Cupboard',dc2:'Next-Door-DC C1',note:tr('cities.built_for_the_government_the_data')},
{id:'chc',name:'Christchurch',x:0,y:0,land:'nzs',reg:'OC',P:40,ix:'Garden-City-IX',dc:'Mainland Colo',note:tr('cities.the_garden_city_and_the_biggest')},
{id:'ivc',name:'Invercargill',x:0,y:0,land:'nzs',reg:'OC',P:10,ix:'',dc:'Sheargrid Makarewa',note:tr('cities.the_bottom_of_the_country_on')},
{id:'hba',name:'Hobart',x:0,y:0,land:'tas',reg:'OC',au:true,arpu:AU_ARPU,P:25,ix:'Cousin-IX',dc:'Firmest',note:tr('cities.the_bottom_of_the_map_cool')},
{id:'hnl',name:'Honolulu',x:0,y:0,land:'hi',reg:'OC',cc:'US',P:70,ix:'Poke-IX',dc:'Dr. Fortress of Solitude',note:tr('cities.halfway_between_california_and')},
{id:'gum',name:'Guam',x:0,y:0,land:'gu',reg:'OC',cc:'GU',P:15,blackout:true,ix:'Spam-IX',dc:'Typhoon-Proof Bunker',note:tr('cities.a_small_island_where_cables_from')},
{id:'ror',name:'Koror',x:0,y:0,land:'pw',reg:'OC',cc:'PW',P:3,ix:'',dc:'Jellyfish Lake Landing',note:tr('cities.palau_on_a_branch_cable_from')},
{id:'maj',name:'Majuro',x:0,y:0,land:'mh',reg:'OC',cc:'MH',P:3,ix:'',dc:'Two Metres Up Colo',note:tr('cities.the_capital_of_the_marshall_islands')},
{id:'pom',name:'Port Moresby',x:0,y:0,land:'pg',reg:'OC',cc:'PG',P:40,blackout:true,ix:'',dc:'Bird of Paradise DC',note:tr('cities.papua_new_guinea_s_capital_in')},
{id:'hir',name:'Honiara',x:0,y:0,land:'sb',reg:'OC',cc:'SB',P:8,blackout:true,ix:'Shell Money-IX',dc:'Guadalcanal Grotto',note:tr('cities.the_solomon_islands_capital_on')},
{id:'nou',name:'Nouméa',x:0,y:0,land:'nc',reg:'OC',cc:'NC',P:20,ix:'Bougna-IX',dc:'Lagoon Rack',note:tr('cities.new_caledonia_a_slice_of_france')},
{id:'suv',name:'Suva',x:0,y:0,land:'fj',reg:'OC',cc:'FJ',P:25,ix:'Kava-IX',dc:'Bula Bula Colo',note:tr('cities.fiji_s_capital_and_the_crossroads')},
{id:'tbu',name:'Nuku’alofa',x:0,y:0,land:'to',reg:'OC',cc:'TO',P:4,ix:'',dc:'Volcano View DC',note:tr('cities.tonga_hangs_on_one_cable_from')},
{id:'apw',name:'Apia',x:0,y:0,land:'ws',reg:'OC',cc:'WS',P:5,ix:'',dc:'Siva Shed',note:tr('cities.samoa_s_capital_with_cables_to')},
{id:'ppg',name:'Pago Pago',x:0,y:0,land:'as',reg:'OC',cc:'AS',P:4,ix:'',dc:'Rainmaker Rack',note:tr('cities.american_samoa_a_deep_harbour_tuna')},
{id:'ppt',name:'Papeete',x:0,y:0,land:'pf',reg:'OC',cc:'PF',P:18,ix:'',dc:'Overwater Bungalow DC',note:tr('cities.tahiti_in_french_polynesia_a_cable')},
{id:'hfx',name:'Halifax',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,P:45,ix:'Donair-IX',dc:'Bluenose Bunker',note:tr('cities.nova_scotia_s_capital_and_the')},
{id:'bda',name:'Bermuda',x:0,y:0,land:'bm',reg:'AM',cc:'BM',P:6,ix:'',dc:'Pink Sand Colo',note:tr('cities.a_thousand_kilometres_off_the')},
{id:'pdl',name:'Ponta Delgada',x:0,y:0,land:'az',reg:'EU',cc:'PT',P:8,ix:'',dc:'Caldeira Colo',note:tr('cities.the_azores_in_the_middle_of')},
{id:'tci',name:'Tenerife',x:0,y:0,land:'ic',reg:'EU',cc:'ES',P:25,ix:'',dc:'Mojo Picón DC',note:tr('cities.the_canary_islands_a_short_hop')},
{id:'rai',name:'Praia',x:0,y:0,land:'cv',reg:'AF',cc:'CV',P:5,ix:'Cachupa-IX',dc:'Morabeza Rack',note:tr('cities.cape_verde_s_capital_off_the')},
{id:'jam',name:'St Helena',x:0,y:0,land:'sh',reg:'AF',cc:'SH',P:1,blackout:true,ix:'',dc:'Napoleon’s Last Rack',note:tr('cities.one_of_the_most_remote_islands')},
{id:'osa',name:'Osaka',x:0,y:0,land:'jp',reg:'AS',P:700,ix:'Takoyaki-IX',dc:'Dojima DC',note:tr('cities.japan_s_second_hub_and_tokyo')},
{id:'kul',name:'Kuala Lumpur',x:0,y:0,land:'eu',reg:'AS',P:350,ix:'Satay-IX',dc:'Twin Towers Colo',note:tr('cities.cheaper_than_singapore_next_door_the')},
{id:'bkk',name:'Bangkok',x:0,y:0,land:'eu',reg:'AS',P:600,ix:'Tom-Yum-IX',dc:'Floating Market DC',note:tr('cities.big_busy_and_flooded_with_traffic')},
{id:'sgn',name:'Ho Chi Minh City',x:0,y:0,land:'eu',reg:'AS',P:500,vn:true,ix:'Pho-IX',dc:'Scooter-cooled DC',note:tr('cities.very_online_and_badly_served_by')},
{id:'khi',name:'Karachi',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.4,ix:'Chai-IX',dc:'Seaview Landing Station',note:tr('cities.pakistan_s_door_to_the_sea')},
{id:'dac',name:'Dhaka',x:0,y:0,land:'eu',reg:'AS',P:700,arpu:0.3,ix:'Rickshaw-IX',dc:'Monsoon-mapped DC',note:tr('cities.huge_dense_and_hungry_its')},
{id:'cbo',name:'Colombo',x:0,y:0,land:'lk',reg:'AS',P:120,ix:'Hopper-IX',dc:'Tea-cooled Landing Station',note:tr('cities.a_small_island_at_the_crossroads')},
{id:'waw',name:'Warsaw',x:0,y:0,land:'eu',reg:'EU',P:550,ix:'Pierogi-IX',dc:'Palace-of-Culture-adjacent DC',note:tr('cities.central_europe_s_rising_hub_more')},
{id:'prg',name:'Prague',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Pilsner-IX',dc:'Castle-view Colo',note:tr('cities.beer_is_cheaper_than_water_here')},
{id:'vie',name:'Vienna',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Schnitzel-IX',dc:'Waltz-cooled DC',note:tr('cities.the_old_gateway_to_eastern_europe')},
{id:'bud',name:'Budapest',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Goulash-IX',dc:'Thermal Bath DC',note:tr('cities.waste_heat_goes_straight_into_the')},
{id:'buh',name:'Bucharest',x:0,y:0,land:'eu',reg:'EU',P:400,ix:'Sarmale-IX',dc:'Parliament-sized DC',note:tr('cities.gigabit_home_broadband_for_the_price')},
{id:'tll',name:'Tallinn',x:0,y:0,land:'eu',reg:'EU',P:80,ix:'E-Stonia-IX',dc:'Medieval Wall DC',note:tr('cities.digital_everything_e_residency_for')},
{id:'ist',name:'Istanbul',x:0,y:0,land:'eu',reg:'EU',P:900,ix:'Baklava-IX',dc:'Bosphorus Bridge DC',note:tr('cities.one_foot_in_europe_one_in')},
{id:'kyv',name:'Kyiv',x:0,y:0,land:'eu',reg:'EU',P:500,blackout:true,ix:'Varenyky-IX',dc:'Generator-backed Bunker DC',note:tr('cities.ukrainian_network_engineers_kept_the')},
{id:'jed',name:'Jeddah',x:0,y:0,land:'eu',reg:'AS',P:300,saudi:true,gcc:true,ix:'',dc:'Red Sea Landing Palace',note:tr('cities.saudi_arabia_s_red_sea_cable')},
{id:'ruh',name:'Riyadh',x:0,y:0,land:'eu',reg:'AS',P:600,saudi:true,gcc:true,ix:'Kabsa-IX',dc:'Desert Megaproject DC',note:tr('cities.the_capital_building_ai_campuses_at')},
{id:'doh',name:'Doha',x:0,y:0,land:'eu',reg:'AS',P:150,arpu:1.5,qa:true,ix:'Pearl-IX',dc:'Air-cooled Stadium DC',note:tr('cities.small_rich_and_very_well_connected')},
{id:'mil',name:'Milan',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'MIX-and-Match',dc:'Caldera Park Campus',note:tr('cities.italy_s_digital_capital_fashion_week')},
{id:'rom',name:'Rome',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Carbonara-IX',dc:'Colosseum-adjacent Colo',note:tr('cities.all_roads_lead_to_rome_most')},
{id:'pmo',name:'Palermo',x:0,y:0,land:'eu',reg:'EU',P:60,ix:'Cannoli-IX',dc:'Sicilian Hub-a-Dub',note:tr('cities.a_small_city_on_a_big')},
{id:'lis',name:'Lisbon',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Pastel-de-Nata-IX',dc:'Seven Hills Colo',note:tr('cities.europe_s_new_atlantic_gateway_cables')},
{id:'ath',name:'Athens',x:0,y:0,land:'eu',reg:'EU',P:350,ix:'Souvlaki-IX',dc:'Acropolis-view DC',note:tr('cities.ancient_city_brand_new_cables_greece')},
{id:'atn',name:'Atlanta',x:0,y:0,land:'am',reg:'AM',P:450,ix:'Peach-IX',dc:'56 Marietta',note:tr('cities.the_southeast_s_carrier_hotel')},
{id:'den',name:'Denver',x:0,y:0,land:'am',reg:'AM',P:250,ix:'Mile-High-IX',dc:'Thin Air DC',note:tr('cities.a_mile_up_and_halfway_between')},
{id:'phx',name:'Phoenix',x:0,y:0,land:'am',reg:'AM',P:300,ix:'Cactus-IX',dc:'Dry Heat Campus',note:tr('cities.cheap_land_cheap_power_and_48')},
{id:'bos',name:'Boston',x:0,y:0,land:'am',reg:'AM',P:350,ix:'Chowder-IX',dc:'One Summer Street',note:tr('cities.universities_biotech_and_a_carrier')},
{id:'hou',name:'Houston',x:0,y:0,land:'am',reg:'AM',P:450,ix:'Rodeo-IX',dc:'Hurricane-hardened DC',note:tr('cities.oil_gas_and_hurricanes_the')},
{id:'slc',name:'Salt Lake City',x:0,y:0,land:'am',reg:'AM',P:150,ix:'Fry-Sauce-IX',dc:'Great Salt Lake DC',note:tr('cities.cheap_power_dry_air_and_a')},
{id:'man',name:'Manchester',x:0,y:0,land:'uk',reg:'EU',P:350,ix:'Rainy-City-IX',dc:'Old Cotton Mill Colo',note:tr('cities.the_north_s_hub_with_its')},
{id:'edi',name:'Edinburgh',x:0,y:0,land:'uk',reg:'EU',P:200,ix:'Haggis-IX',dc:'Castle Rock Colo',note:tr('cities.scotland_s_capital_north_sea_cables')},
{id:'bde',name:'Bude',x:0,y:0,land:'uk',reg:'EU',P:3,ix:'',dc:'Clifftop Landing Station',note:tr('cities.a_tiny_surfing_town_in_cornwall')},
{id:'svg',name:'Stavanger',x:0,y:0,land:'eu',reg:'EU',P:60,ix:'Brunost-IX',dc:'Inside-a-Mountain DC',note:tr('cities.norway_s_oil_capital_now_full')},
];
// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat.
const CITY_NUDGE={
aju:[-13.5,-2.7],
akl:[.6,.4],
alg:[0.9,0.9],
asu:[-1.2,-0.8],
auh:[-5,6],
bcn:[-6,-4],
bel:[0.4,0.4],
bru:[1,3],
cac:[2.4,-0.7],
cas:[0.6,0.6],
cau:[-10.2,2.4],
cph:[-.7,.3],
cpq:[-2.8,-5.2],
cpv:[-10.2,-5.1],
cxj:[5.4,-9.4],
dal:[0,-4],
dar:[0,12.6],
dur:[-0.2,0],
dxb:[9,-7],
fec:[-10.8,1.4],
fln:[0.8,4.4],
fuj:[8,15],
gdl:[-1.2,0.2],
gyn:[-4,2.6],
hel:[-.8,-.2],
hkg:[.8,0],
hou:[0,6],
igu:[-3.9,5.3],
ist:[.8,0],
jib:[0.1,0.2],
jpa:[-0.9,0.6],
khi:[-2,-6],
ldb:[6.2,0.1],
lis:[.8,0],
ljd:[-5.2,-7.7],
mba:[-0.8,0],
mcp:[-1.7,1.7],
mcz:[-7.2,8],
mde:[-1.7,-1.9],
mgf:[-5.8,-4.4],
mia:[-.6,.4],
mtl:[.8,0],
mvd:[2.2,-4.3],
nat:[-1.5,-3.3],
nyc:[.3,-.7],
oos:[-3,0],
osa:[-10,6],
ott:[-3,-3],
qro:[-1.9,-3.9],
rao:[3.6,-2.6],
rec:[-2.4,7.2],
ria:[-2.4,4.9],
sea:[1,4],
sin:[-1.3,-1.3],
sjp:[-3.5,0.4],
slz:[0.3,0.3],
ssa:[0.5,-0.2],
stg:[7,1],
tll:[-4,22],
van:[-3,-6],
vix:[-0.4,0.4],
zrh:[-3,3],
};
for(const c of CITIES){const q=CITY_LL[c.id];if(q){c.lon=q[0];c.lat=q[1];const pt=proj(q[0],q[1]),n=CITY_NUDGE[c.id]||[0,0];c.x=pt[0]+n[0];c.y=pt[1]+n[1];}}
const CITY=Object.fromEntries(CITIES.map(c=>[c.id,c])),CIDX=Object.fromEntries(CITIES.map((c,i)=>[c.id,i]));

View file

@ -0,0 +1,134 @@
const CABLES=[
{"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":tr('cables.hits_the_high_notes_across_the'),"pairs":[["ash","mad",[[-74,36.5],[-50,40],[-25,43],[-10,44]]]]},
{"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":tr('cables.hops_from_new_york_to_the'),"pairs":[["nyc","lon",[[-72,40],[-50,47],[-25,50],[-10,50.5]]],["nyc","mad",[[-72,39.8],[-50,42],[-25,43.2],[-10,43.8]]]]},
{"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":tr('cables.nobody_remembers_who_it_is_named'),"pairs":[["ash","par",[[-74,36.8],[-50,42],[-25,46],[-5,47.3]]]]},
{"id":"amitie","name":"Ami-Tea","price":0.9,"age":"new","blurb":tr('cables.a_friendly_cable_with_french_manners'),"pairs":[["nyc","lon",[[-70,41.5],[-50,46],[-25,49],[-8,50.3]]],["nyc","par",[[-70,41.3],[-50,45],[-25,47.5],[-5,47.6]]]]},
{"id":"hibx","name":"Hibernia Express-o","price":1.7,"age":"mid","blurb":tr('cables.the_straightest_line_across_the'),"pairs":[["nyc","lon",[[-68,42],[-55,46.5],[-30,52.5],[-12,52.5]]],["nyc","hfx",[[-70,41.6],[-66,43.3]]],["hfx","lon",[[-60,45.5],[-55,46.5],[-30,52.5],[-12,52.5]]]],"lat":0.9},
{"id":"tat","name":"TAT-14 Retirement Home","price":1.3,"age":"old","blurb":tr('cables.laid_last_century_cuts_often_costs'),"pairs":[["nyc","ams",[[-70,41],[-45,48],[-20,52],[0,54],[3,53.5]]]]},
{"id":"ella","name":"EllaLink-ing","price":1.0,"age":"new","blurb":tr('cables.brazil_straight_to_iberia_skipping'),"pairs":[["for","mad",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-10,37.5]]],["sao","mad",[[-44,-24.5],[-38,-14],[-34,-6],[-30,5],[-22,20],[-14,33],[-10,37.5]]],["for","lis",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-9.6,37.9]]],["for","rai",[[-37,-2.2],[-32,5],[-26,13]]],["rai","lis",[[-22,20],[-14,33],[-9.6,37.9]]]]},
{"id":"sacs","name":"SACS-y Cable","price":1.0,"age":"mid","blurb":tr('cables.south_atlantic_cool_and_confident'),"pairs":[["for","lag",[[-36,-3],[-20,0],[0,3]]],["sao","lag",[[-44,-24.5],[-35,-10],[-15,-3],[0,2],[3,5.5]]],["for","lad",[[-37,-2.5],[-20,-5],[0,-8],[12.6,-9]]]]},
{"id":"col3","name":"Columbus III-and-a-half","price":1.4,"age":"old","blurb":tr('cables.discovered_the_atlantic_again_old'),"pairs":[["mia","mad",[[-79,26],[-60,30],[-30,35],[-10,36.5]]],["mia","pdl",[[-79,26],[-60,30],[-35,36]]],["pdl","lis",[[-15,38.2]]]]},
{"id":"twoaf","name":"2Africa-n-Back","price":0.75,"age":"new","blurb":tr('cables.all_the_way_around_africa_and'),"pairs":[["lon","lag",[[-6,49],[-12,40],[-20,20],[-18,8],[-5,3],[3,5.5]]],["jnb","mrs",[[32,-30],[40,-20],[45,-5],[52,10],[45,12.3],[44,12.4],[41,15.1],[38,21.1],[35,26.1],[33,29.6],[32.4,31.3],[30,32.1],[20,34.1],[12,37.6],[6,42.5]]],["mrs","bom",[[6,42.5],[12,37.6],[20,34.1],[30,32.1],[32.4,31.3],[33,29.6],[35,26.1],[38,21.1],[41,15.1],[44,12.4],[52,13],[62,18],[70,19]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-4,4.8],[-0.2,5.1]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","lad",[[3.2,5.8],[6,3],[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.6,-9],[11.5,-15],[13.5,-22.7],[15,-30],[17.6,-34.4]]],["cpt","dur",[[17.6,-34.4],[22,-35.5],[28,-34],[32,-30.3]]],["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[40.6,-4.3],[45,2],[51,10.5],[45,12.3],[43.5,11.9]]],["jib","cai",[[43.5,11.9],[40.4,14.7],[37.4,20.7],[34.4,25.7],[32.4,29.2],[32.4,31.4]]],["lon","tci",[[-6,49],[-12,40],[-15.5,29.5]]],["tci","lag",[[-18,25],[-20,20],[-18,8],[-5,3],[3,5.5]]]]},
{"id":"equi","name":"Equi-yes","price":0.8,"age":"new","blurb":tr('cables.always_agrees_with_you_iberia_to'),"pairs":[["lag","cpt",[[4,3],[6,-5],[10,-20],[16,-33]]],["mad","lag",[[-10,38],[-15,28],[-18,15],[-14,5],[-2,3],[3,5.8]]],["lis","lag",[[-9.6,37.9],[-15,28],[-18,15],[-14,5],[-2,3],[3,5.8]]],["lag","wdh",[[3.2,5.8],[6,3],[9,3.6],[8,-2],[11.5,-6],[12.6,-9],[11.5,-15],[13.5,-22.7]]],["wdh","cpt",[[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lag","jam",[[4,3],[2,-5],[-3,-12]]],["jam","wdh",[[-2,-18],[8,-21.5],[13.5,-22.7]]]]},
{"id":"smw6","name":"SEE-ME-WAVE 6","price":0.95,"age":"new","blurb":tr('cables.sixth_in_a_long_running_series'),"pairs":[["mrs","bom",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,13.4],[62,18.4],[70,19.4]]],["bom","sin",[[72,17],[76,8],[80.5,5],[90,5],[96,5.5],[100,4],[103,1.5]]],["mrs","sin",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,12.8],[62,12.5],[75,6.8],[80.5,5.2],[92,5.8],[97,5.8],[100.5,4],[103,1.7]]]]},
{"id":"peace","name":"PEACE-out","price":0.85,"age":"new","blurb":tr('cables.marseille_to_singapore_then_it'),"pairs":[["mrs","sin",[[5.6,42.26],[11.6,37.36],[19.6,33.86],[29.6,31.860000000000003],[32.0,31.060000000000002],[32.6,29.360000000000003],[34.6,25.860000000000003],[37.6,20.860000000000003],[40.6,14.86],[43.6,12.16],[52,12.2],[62,11.8],[75,6.3],[80.5,4.6],[92,5.2],[97,5.3],[100.5,3.6],[103,1.4]]],["mba","cai",[[40.6,-4.3],[45,2],[51,10.5],[45,12.3],[43.5,11.9],[40.4,14.7],[37.4,20.7],[34.4,25.7],[32.4,29.2],[32.4,31.4]]]]},
{"id":"aae","name":"AAAAAE-1","price":1.0,"age":"mid","blurb":tr('cables.asia_africa_europe_and_one_more'),"pairs":[["khi","sin",[[66,22],[70,12],[78,5.5],[90,5.5],[97,6],[100,3.6],[102.6,2.1],[103.7,1.3]]],["mrs","hkg",[[6.8,42.98],[12.8,38.08],[20.8,34.58],[30.8,32.58],[33.199999999999996,31.78],[33.8,30.080000000000002],[35.8,26.580000000000002],[38.8,21.580000000000002],[41.8,15.58],[44.8,12.88],[52,11.8],[62,11.4],[75,6],[80.5,4.4],[92,5],[97,5],[100.5,3.3],[104.5,1.5],[107,5],[110,10],[113,18],[114.2,21.8]]],["sin","hkg",[[104.5,1.5],[108,6],[111,12],[114,20],[114.2,22]]],["jib","cai",[[43.5,11.9],[40.4,14.7],[37.4,20.7],[34.4,25.7],[32.4,29.2],[32.4,31.4]]]]},
{"id":"apg","name":"A Pretty Gateway","price":0.9,"age":"mid","blurb":tr('cables.the_pretty_way_around_east_asia'),"pairs":[["tpe","tok",[[123,25.5],[130,29.5],[137,33.5]]],["hkg","tpe",[[116.5,21.8],[119.5,22.8]]],["sin","hkg",[[105,2],[109,7],[112,13],[114.6,20],[114.4,22]]],["hkg","tok",[[116,21.5],[122,24],[126,28],[132,32],[137,33.8],[139.8,35]]],["hkg","icn",[[116,22],[122,26],[125,32],[126,35],[126.2,36.8]]],["tok","icn",[[136,33.8],[130,33.5],[128,34.5],[126.5,35.5]]],["tok","sha",[[135,33.5],[128,31.5],[122.5,31.2]]]]},
{"id":"jup","name":"Jupiterrible","price":0.9,"age":"new","blurb":tr('cables.named_after_a_planet_behaves_like'),"pairs":[["lax","osa",[[-121,33.3],[-145,31.5],[-175,31.5],[-200,32.5],[-222,33.8]]],["lax","tok",[[-121,33.5],[-145,32],[-175,32],[-200,33],[-218,34.5]]]]},
{"id":"fast","name":"FASTEST","price":0.85,"age":"mid","blurb":tr('cables.its_predecessor_was_faster_marketing'),"pairs":[["sea","tok",[[-125,46],[-150,45],[-180,42],[-205,38],[-218,35]]]]},
{"id":"ncp","name":"Crosspatch Pacific","price":1.0,"age":"mid","blurb":tr('cables.crosses_the_pacific_mildly_annoyed'),"pairs":[["sea","tpe",[[-125,46],[-155,45],[-185,38],[-212,28],[-235,25.6]]],["sea","icn",[[-125,46.5],[-155,46.5],[-185,42],[-212,33],[-229,33.8],[-232,36]]],["sea","sha",[[-125,46.2],[-155,45.5],[-185,40],[-212,31],[-236,30.5]]]]},
{"id":"plcn","name":"Pacific Lite","price":1.1,"age":"mid","blurb":tr('cables.lighter_on_paperwork_than_its'),"pairs":[["lax","tpe",[[-121,33],[-150,25],[-180,22],[-215,22],[-236,24]]],["lax","hkg",[[-121,33],[-150,25],[-180,22],[-215,21],[-240,21.5]]]]},
{"id":"scx","name":"Southern Cross-ed Fingers","price":1.2,"age":"old","blurb":tr('cables.old_pacific_workhorse_everyone_hopes'),"pairs":[["sjc","syd",[[-123,37],[-150,20],[-175,0],[-190,-20],[-200,-30],[-207,-33.5]]],["akl","syd",[[168,-37],[158,-35]]],["sjc","hnl",[[-123,36.5],[-140,28],[-156.2,21.5]]],["hnl","suv",[[-158.5,19.5],[-168,6],[-176,-8],[-181.2,-17.5]]],["suv","syd",[[177.5,-19],[166,-25.5],[156,-32],[152,-33.8]]],["akl","suv",[[175.2,-35.5],[176.5,-27],[178.2,-19]]]]},
{"id":"hwk","name":"Hawaiki-wiki","price":0.95,"age":"new","blurb":tr('cables.quick_pacific_crossing_with_a_stop'),"pairs":[["sea","syd",[[-125,45],[-150,20],[-170,-5],[-185,-25],[-200,-32],[-206,-33.8]]],["akl","sea",[[178,-34],[190,-20],[210,10],[230,40],[234.5,47]]],["sea","hnl",[[-125,45],[-145,31],[-157.8,21.8]]],["hnl","syd",[[-158.5,20],[-172,0],[-185,-25],[-200,-32],[-206,-33.8]]],["hnl","akl",[[-158.5,20],[-174,-5],[-182,-28],[-185.1,-36]]],["hnl","ppg",[[-158.6,20.5],[-166,2],[-170.5,-13.8]]]]},
{"id":"indigo","name":"Indi-Go-Down","price":0.9,"age":"new","blurb":tr('cables.singapore_to_sydney_via_perth_on'),"pairs":[["sin","syd",[[104.5,0],[107,-8],[113,-12],[112,-25],[114,-35],[130,-37],[145,-41],[152,-36]]],["sin","per",[[104.6,0],[107.2,-8],[113,-14],[112.5,-25],[115,-31.8]]]]},
{"id":"guam","name":"Guam-bling","price":1.1,"age":"mid","blurb":tr('cables.a_bet_on_a_tiny_island'),"pairs":[["tok","syd",[[142,33],[146,15],[152,0],[156,-20],[152.5,-33]]],["tok","gum",[[142,33],[146,20],[145.2,14]]],["gum","syd",[[145.5,12.5],[152,0],[156,-20],[152.5,-33]]]]},
{"id":"sushi","name":"Sushi Train Cable","price":1.15,"age":"old","blurb":tr('cables.sydney_to_tokyo_by_way_of'),"pairs":[["syd","tok",[[153,-33],[157,-20],[151,0],[145,14],[140.5,33]]]]},
{"id":"aloha","name":"Aloha Mate","price":1.05,"age":"mid","blurb":tr('cables.sydney_to_honolulu_and_not_a'),"pairs":[["hnl","syd",[[-158.5,20],[-168,4],[-180,-15],[-197,-30],[-205.5,-33.6]]]]},
{"id":"avo","name":"Cut Lunch Cable","price":0.9,"age":"new","fragile":true,"blurb":tr('cables.perth_to_singapore_and_jakarta'),"pairs":[["per","sin",[[114,-31.8],[110,-24],[106,-10],[105.5,-3],[104.4,1]]],["per","jkt",[[114,-31.8],[110,-24],[106.5,-10],[106.8,-6.3]]]]},
{"id":"ferry","name":"Ferry Express","price":1.0,"age":"mid","blurb":tr('cables.crosses_bass_strait_faster_than_the'),"pairs":[["mel","hba",[[145,-38.4],[146.3,-39.8],[147.9,-41.5],[147.6,-42.9]]]]},
{"id":"smap","name":"SMAP (Somewhere, Maybe Also Perth)","price":0.95,"age":"new","blurb":tr('cables.sydney_melbourne_adelaide_and_perth'),"pairs":[["syd","mel",[[151.6,-34.2],[150.5,-36.5],[150,-37.7],[147,-38.7],[145,-38.5]]],["mel","adl",[[144.5,-38.5],[141.5,-38.7],[139.7,-37.3],[138.3,-35.9],[138.4,-35.1]]],["adl","per",[[137.8,-35.9],[134,-34.6],[129,-33.2],[123,-34.9],[118,-35.7],[115,-34.7],[115.3,-32.5],[115.7,-32]]]]},
{"id":"ohman","name":"Oh-Man Australia Cable","price":1.0,"age":"new","blurb":tr('cables.perth_to_the_gulf_across_the'),"pairs":[["per","dxb",[[113,-31],[100,-25],[80,-10],[65,10],[59,20],[57,24.5]]]]},
{"id":"cook","name":"Cook Strait Talking","price":1.0,"age":"mid","blurb":tr('cables.down_the_west_coast_and_across'),"pairs":[["akl","chc",[[174.2,-37.3],[173.6,-38.6],[173.9,-39.7],[174.5,-40.6],[174.4,-41.4],[173.9,-42.1],[173.4,-43.0],[173.1,-43.6]]]]},
{"id":"ring","name":"Lord of the Tasman Rings","price":0.9,"age":"new","blurb":tr('cables.one_ring_to_bind_invercargill_to'),"pairs":[["ivc","syd",[[167.6,-46.9],[160,-42],[153,-35]]],["ivc","mel",[[167.6,-46.9],[156,-43.5],[146.2,-39.4]]],["ivc","akl",[[167.4,-46.5],[166.3,-45.4],[167.9,-43.8],[170.6,-42.3],[172.3,-40.6],[173.5,-38.8],[174.3,-37.3]]]]},
{"id":"tasman","name":"Tasman Global Excess","price":0.95,"age":"new","blurb":tr('cables.sydney_to_auckland_with_plenty_to'),"pairs":[["akl","syd",[[170,-36],[158,-34.5]]]]},
{"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":tr('cables.a_rainbow_bridge_from_singapore_to'),"pairs":[["sin","jkt",[[105,-1],[106,-4]]],["jkt","mnl",[[108,-5],[112,-3],[118,2],[122,6],[121,10],[120,13.5]]],["mnl","lax",[[123,15],[140,20],[180,25],[210,30],[235,33.5]]],["mnl","gum",[[123,15],[136,14.5],[144.3,13.6]]],["gum","lax",[[145.5,14.2],[180,22],[210,30],[235,33.5]]]]},
{"id":"sjcph","name":"Sushi-Jollibee Cable","price":0.9,"age":"mid","blurb":tr('cables.southeast_asia_to_japan_with_snacks'),"pairs":[["hkg","mnl",[[116,21],[119.5,16],[120.3,14.6]]],["mnl","sin",[[119,12],[115,8],[110,5],[105,2]]],["mnl","tok",[[122,19],[127,24],[133,30],[138.5,34.5]]]]},
{"id":"farice","name":"Far-Ice-1","price":1.2,"age":"old","blurb":tr('cables.iceland_s_lifeline_to_scotland'),"pairs":[["rek","lon",[[-20,63],[-10,61],[-4,59],[-1.5,57]]]]},
{"id":"danice","name":"Dance-Ice","price":1.0,"age":"mid","blurb":tr('cables.iceland_to_denmark_choreographed'),"pairs":[["rek","cph",[[-18,63],[-5,62],[5,59],[8.5,57.5],[11,57]]]]},
{"id":"gcon","name":"Greenland Connect-the-Dots","price":1.4,"age":"old","blurb":tr('cables.hops_via_greenland_polar_bears'),"pairs":[["rek","mtl",[[-26,63.5],[-42,60],[-55,53],[-60,48],[-66,47],[-70,46.5]]]]},
{"id":"iris","name":"IRIS Scan","price":0.9,"age":"new","blurb":tr('cables.iceland_to_ireland_brand_new_and'),"pairs":[["rek","dub",[[-22,63],[-15,58],[-10.5,54.5],[-9,53.3]]]]},
{"id":"aec","name":"AEConnect-the-Dots","price":0.85,"age":"new","blurb":tr('cables.new_york_to_ireland_the_tech'),"pairs":[["nyc","dub",[[-70,41],[-50,47],[-25,52],[-11,52.8]]]]},
{"id":"havf","name":"Havfun","price":0.8,"age":"new","blurb":tr('cables.danish_for_sea_fun_probably'),"pairs":[["nyc","cph",[[-70,41.5],[-50,49],[-25,55],[-10,58],[0,58],[7,57.5],[10,57.6]]],["dub","cph",[[-10,54.5],[-8,57],[-2,59],[6,58],[10,57.6]]]]},
{"id":"celtix","name":"Celtix Connected","price":0.7,"age":"mid","blurb":tr('cables.dublin_to_london_across_the_irish'),"pairs":[["dub","lon",[[-5,53.4]]]]},
{"id":"falcon","name":"Falcon Punch","price":0.9,"age":"mid","blurb":tr('cables.dubai_to_mumbai_hits_hard'),"pairs":[["cai","dxb",[[32.6,29.9],[34.4,27.2],[37.5,22.5],[41.5,15.5],[43.4,12.4],[48,12.6],[55,15.8],[59.4,21.8],[57,25.5]]],["fuj","bom",[[58,24.8],[63,22.3],[70,19.2]]],["dxb","bom",[[57,25.5],[60,23],[66,21],[71,19]]]]},
{"id":"eig","name":"Eye-Gee","price":1.0,"age":"mid","blurb":tr('cables.a_gateway_from_europe_to_india'),"pairs":[["dxb","mrs",[[57,25],[59,22],[55,16],[48,12.8],[43.2,11.92],[40.2,14.62],[37.2,20.62],[34.2,25.62],[32.2,29.12],[31.599999999999998,30.82],[29.2,31.62],[19.2,33.620000000000005],[11.2,37.120000000000005],[5.2,42.02]]]]},
{"id":"clion","name":"C-Lion King","price":1.0,"age":"new","blurb":tr('cables.helsinki_to_germany_under_the_baltic'),"pairs":[["hel","fra",[[24,59.8],[20,57.5],[15,55.2],[12.2,54.3]]]]},
{"id":"uly","df":true,"name":"Ulysseless","price":0.8,"age":"old","blurb":tr('cables.short_hop_across_the_north_sea'),"pairs":[["lon","ams",[[2,51.8]]]]},
{"id":"chn","df":true,"name":"Channel Hopper","price":0.7,"age":"mid","blurb":tr('cables.london_to_paris_under_the_channel'),"pairs":[["lon","par",[[1,50.5]]]]},
{"id":"medn","name":"Med-Nauti-lust","price":0.9,"age":"mid","blurb":tr('cables.across_the_mediterranean_egypt_to'),"pairs":[["ist","mrs",[[26.5,40],[25,37],[20,35.5],[12,38],[6.5,42.6]]],["cai","mrs",[[29.9,31.4],[28,32.5],[20,34.5],[12,38],[6.5,42.6]]]]},
{"id":"eassy","name":"EASSy Peasy","price":0.95,"age":"mid","blurb":tr('cables.east_africa_up_to_europe_via'),"pairs":[["nbo","mrs",[[39.7,-4],[42,-1],[45,2],[51,10.5],[45,12.3],[43.4,12.0],[40.4,14.7],[37.4,20.700000000000003],[34.4,25.700000000000003],[32.4,29.200000000000003],[31.799999999999997,30.900000000000002],[29.4,31.700000000000003],[19.4,33.7],[11.4,37.2],[5.4,42.1]]],["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[40.6,-4.3],[45,2],[51,10.5],[45,12.3],[43.5,11.9]]]]},
{"id":"teams","name":"TEAMS-work","price":0.9,"age":"mid","blurb":tr('cables.kenya_to_the_gulf_makes_the'),"pairs":[["nbo","dxb",[[39.7,-4],[44,0],[52,8],[58,18],[59,22.5],[57,25]]],["mba","fuj",[[40.6,-4.3],[44,0],[52,8],[58,18],[59,22.5],[57,25]]]]},
{"id":"monet","name":"Mo-Net-y","price":0.9,"age":"new","blurb":tr('cables.brazil_to_florida_the_invoice'),"pairs":[["sao","mia",[[-44,-25.5],[-36,-14],[-33,-4],[-45,4],[-62,16],[-76,25]]],["for","mia",[[-37,-2.2],[-45,4.5],[-62,16.5],[-76,25.3]]]]},
{"id":"seabras","name":"Sea-Bras","price":0.9,"age":"new","blurb":tr('cables.straight_from_sao_paulo_to_new'),"pairs":[["sao","nyc",[[-44,-25.5],[-34,-10],[-33,0],[-50,18],[-66,33],[-72,39.5]]]]},
{"id":"sam1","name":"SAM-1-and-Done","price":1.2,"age":"old","blurb":tr('cables.an_old_ring_around_the_whole'),"pairs":[["mia","for",[[-75,24],[-62,16],[-45,4],[-37,-2.5]]],["for","rio",[[-36,-4],[-34,-9],[-37,-16],[-41,-23.6]]],["for","ssa",[[-36,-4],[-34,-9],[-37,-13.5]]],["ssa","rio",[[-37.5,-14],[-38.5,-18],[-41,-23.6]]],["rio","sao",[[-44,-24.3]]],["sao","bue",[[-47,-27],[-52,-35],[-56,-36]]],["bue","scl",[[-56,-37.5],[-62,-45],[-65,-56],[-72,-56],[-77,-45],[-74,-34]]],["scl","lim",[[-73.5,-30],[-74,-20],[-78,-13]]],["lim","pan",[[-81,-6],[-82,0],[-80,7]]],["pan","mia",[[-79.5,10],[-77,15],[-74,19.5],[-75,23],[-79,25]]]]},
{"id":"curie","name":"Curie-osity","price":0.85,"age":"new","blurb":tr('cables.los_angeles_to_chile_with_a'),"pairs":[["lax","scl",[[-120,30],[-108,14],[-92,0],[-80,-20],[-73,-33]]],["lax","pan",[[-120,30],[-105,15],[-90,7],[-80,7.5]]]]},
{"id":"pccs","name":"Caribbean Cruise Control","price":1.0,"age":"mid","blurb":tr('cables.hops_the_caribbean_so_bogota_can'),"pairs":[["mia","bog",[[-80,24],[-77.5,19],[-76,12],[-75,10.5]]],["pan","bog",[[-79.6,9.6],[-77,9.9],[-75.5,10.5]]]]},
{"id":"tannat","name":"Tannat Wine Line","price":0.9,"age":"mid","blurb":tr('cables.named_after_a_wine_sao_paulo'),"pairs":[["sao","bue",[[-46,-26],[-50,-32],[-55,-35.5]]],["sao","mvd",[[-46,-26],[-50,-32],[-55,-35.3]]]]},
{"id":"humb","name":"Humboldt Penguin","price":1.3,"age":"new","blurb":tr('cables.the_first_cable_from_south_america'),"pairs":[["scl","syd",[[-75,-34],[-110,-38],[-150,-40],[-180,-38],[-200,-35],[-206,-34]]],["scl","ppt",[[-75,-34],[-100,-30],[-130,-22],[-149,-17.9]]],["ppt","syd",[[-150,-18.2],[-170,-28],[-185,-35],[-200,-35],[-206,-34]]]]},
{"id":"wacs","name":"WACS-a-Mole","price":1.1,"age":"mid","blurb":tr('cables.up_the_west_coast_of_africa'),"pairs":[["cpt","lag",[[16,-34],[10,-20],[6,-5],[4,3]]],["lag","lon",[[3,4],[-10,8],[-20,20],[-15,35],[-10,45],[-6,49.5]]],["abj","acc",[[-4,4.8],[-0.2,5.1]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","dla",[[3.2,5.8],[6,3],[9,3.6]]],["dla","lad",[[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","wdh",[[12.6,-9],[11.5,-15],[13.5,-22.7]]],["wdh","cpt",[[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lon","tci",[[-6,49.5],[-10,45],[-15,35],[-16.1,28.8]]],["tci","rai",[[-18,24],[-22,17]]],["rai","abj",[[-20,10],[-10,4.5],[-4,4.8]]]]},
{"id":"safe","name":"SAFE-ty Not Guaranteed","price":1.4,"age":"old","blurb":tr('cables.an_old_cable_from_cape_town'),"pairs":[["cpt","bom",[[22,-36],[45,-30],[57,-20],[65,0],[70,15]]]]},
{"id":"bbg","name":"Bay of Bengal Gate-Delay","price":0.95,"age":"mid","blurb":tr('cables.fujairah_to_mumbai_round_the_tip'),"pairs":[["fuj","bom",[[58,24.5],[63,22],[69.5,19.5]]],["bom","maa",[[72,15],[75,8],[78.5,6.6],[81.8,8],[81,12]]],["maa","sin",[[82,12],[90,8],[96.5,6],[100,3.5],[102.5,2],[103.6,1.25]]]]},
{"id":"i2i","name":"Eye-to-Eye","price":0.85,"age":"mid","blurb":tr('cables.chennai_to_singapore_looking_it'),"pairs":[["maa","sin",[[82,13],[91,9.5],[97,6.6],[100.2,3.8],[102.6,2.2],[103.7,1.3]]]]},
{"id":"tse","name":"Strait Outta Taipei","price":1.5,"age":"old","blurb":tr('cables.a_short_cable_across_a_very'),"pairs":[["tpe","sha",[[122.2,26.5],[122.6,29],[122.2,31]]]]},
{"id":"gbi","name":"Gulf Bridge Over Troubled Water","price":1.0,"age":"mid","blurb":tr('cables.leaves_the_gulf_from_fujairah_and'),"pairs":[["fuj","mrs",[[57.5,23.5],[59.5,21.5],[55,15.5],[48,12.6],[43.2,11.8],[40.2,14.5],[37.2,20.5],[34.2,25.5],[32.2,29],[31.6,30.7],[29.2,31.5],[19.2,33.5],[11.2,37],[5.2,42]]]]},
{"id":"aagony","name":"AAG-ony","price":1.1,"age":"old","blurb":tr('cables.an_asia_america_gateway_cable_that'),"pairs":[["sgn","hkg",[[109,12],[113,18],[114.2,21.5]]],["sgn","sin",[[106,7],[104.6,3]]]]},
{"id":"darwin","name":"Darwin Award Cable","price":1.0,"age":"new","blurb":tr('cables.darwin_to_singapore_via_jakarta'),"pairs":[["drw","jkt",[[129,-11.2],[122,-10],[114,-8.6],[108,-6.6]]],["drw","sin",[[129,-11.2],[120,-9],[114,-6],[108,-2],[105,0.6]]]]},
{"id":"jga","name":"J-G’day-A (Japan–Guam–Aussie)","price":0.9,"age":"new","blurb":tr('cables.brisbane_to_tokyo_with_a_beach'),"pairs":[["bne","tok",[[155,-25],[156,-5],[146,13],[141,30]]],["bne","gum",[[155,-25],[156,-5],[146,12.8]]],["gum","tok",[[145.3,14.5],[141,30]]]]},
{"id":"smw4","name":"SEE-ME-WAVE 4","price":1.2,"age":"old","blurb":tr('cables.the_previous_generation_still'),"pairs":[["khi","mrs",[[65,23.5],[60,22],[55,15.5],[48,12.6],[43.2,11.8],[40.2,14.5],[37.2,20.5],[34.2,25.5],[32.2,29],[31.6,30.7],[29.2,31.5],[19.2,33.5],[11.2,37],[5.2,42]]],["khi","bom",[[67,23],[70,20.5]]],["bom","cbo",[[72,15],[75,8],[78.5,6.3]]],["cbo","maa",[[80.6,8.6],[81,11.5]]],["maa","dac",[[82,14],[87,17.5],[91.5,21.2]]],["dac","sin",[[92,21],[93,17],[95,10],[97,6.4],[100,3.6],[102.6,2.1],[103.7,1.3]]]]},
{"id":"balt","name":"Baltic Anchor Magnet","price":0.8,"age":"mid","blurb":tr('cables.short_hops_under_the_baltic_sea'),"pairs":[["tll","hel",[[24.8,59.8]]],["tll","sto",[[22,59.3],[19.5,59.3]]]]},
{"id":"bsea","name":"Black Sea Shanty","price":1.0,"age":"mid","blurb":tr('cables.istanbul_to_bucharest_s_coast_across'),"pairs":[["ist","buh",[[29.5,42],[29.5,43.5],[28.8,44.2]]]]},
{"id":"concerto","name":"Concerto in Sea Minor","price":0.55,"age":"new","df":true,"blurb":tr('cables.north_sea_workhorse_from_london_to'),"pairs":[["lon","ams",[[1.6,51.72],[3.6,52.02]]]]},
{"id":"circe","name":"Circe du Soleil","price":0.6,"age":"mid","df":true,"blurb":tr('cables.another_london_amsterdam_route'),"pairs":[["lon","ams",[[1.8,52.18],[3.8,52.58]]]]},
{"id":"nshuttle","name":"North Sea Shuttle","price":0.5,"age":"new","df":true,"blurb":tr('cables.brand_new_cheap_and_it_lands'),"pairs":[["lon","ams",[[1.5,51.42],[3.9,51.88]]]]},
{"id":"imewe","name":"I-ME-WE-Us","price":1.05,"age":"mid","blurb":tr('cables.india_the_middle_east_and_western'),"pairs":[["cai","fuj",[[32.6,29.9],[34.4,27.2],[37.5,22.5],[41.5,15.5],[43.4,12.4],[48,12.6],[55,15.8],[59.4,21.8],[57.5,24.3]]],["cai","bom",[[32.6,29.9],[34.4,27.2],[37.5,22.5],[41.5,15.5],[43.4,12.4],[48,12.6],[60,15],[68,17.5]]]]},
{"id":"jedx","name":"Jeddah-i Express","price":0.95,"age":"new","blurb":tr('cables.new_cables_increasingly_land_in'),"pairs":[["jed","bom",[[38.6,22.5],[41.5,15.5],[43.4,12.4],[48,12.6],[60,15],[68,17.5]]],["jed","sin",[[38.6,22.5],[41.5,15.5],[43.4,12.4],[52,11],[70,6],[80,5.2],[92,5.5],[97,6],[100,3.6],[102.6,2.1],[103.7,1.3]]]]},
{"id":"rsea","name":"Red Sea Shortcut","price":0.9,"age":"mid","blurb":tr('cables.a_quick_hop_across_the_red'),"pairs":[["cai","jed",[[32.6,29.9],[34.6,27],[37.2,23.6]]]]},
{"id":"qgulf","name":"Doha Detour","price":1.0,"age":"mid","blurb":tr('cables.connects_doha_to_the_rest_of'),"pairs":[["doh","fuj",[[52.5,26.2],[55,26.4],[56.6,26],[56.9,25.3]]],["doh","bom",[[52.5,26.2],[55,26.4],[57,25.5],[60,23],[66,21],[71,19]]]]},
{"id":"nouk","name":"NO-UK-Way","price":0.6,"age":"new","df":true,"blurb":tr('cables.norway_to_the_uk_across_the'),"pairs":[["svg","edi",[[5.3,58.8],[2,57.5],[-1.5,56.2]]]]},
{"id":"celtn","name":"Celtic Norsemen","price":0.85,"age":"new","blurb":tr('cables.ireland_to_norway_the_long_way'),"pairs":[["dub","svg",[[-6,54],[-6.8,56.5],[-5.5,59.3],[-1.5,60.2],[3,59.5],[5.2,59]]]]},
{"id":"havh","name":"Havhingsten Hoofbeat","price":0.8,"age":"new","blurb":tr('cables.the_sea_stallion_blackpool_to'),"pairs":[["man","cph",[[-3.4,53.9],[-5,54.5],[-6.5,56.5],[-5,59],[-2,59.4],[2,58.5],[7,57.8],[8.2,57.2],[10.5,57.6],[11.5,56.5]]]]},
{"id":"shefa","name":"Shefa Sheep Line","price":1.1,"age":"mid","blurb":tr('cables.scotland_to_iceland_via_shetland_and'),"pairs":[["edi","rek",[[-2.5,56.2],[-1,58],[-1.3,60.2],[-6.8,62],[-14,63.4],[-20,63.6]]]]},
{"id":"apollo","name":"Apollo 13 (Houston, We Have Latency)","price":0.95,"age":"mid","blurb":tr('cables.new_york_to_the_cliffs_of'),"pairs":[["nyc","bde",[[-70,40],[-50,43],[-25,48.5],[-8,50.2],[-5,50.8]]]]},
{"id":"yellow","name":"Yellow Brick Road","price":0.9,"age":"mid","blurb":tr('cables.long_island_to_cornwall_follow_it'),"pairs":[["nyc","bde",[[-71,40.5],[-50,44.5],[-25,49.3],[-8,50.6],[-5,50.9]]]]},
{"id":"ace","name":"ACE of Spades","price":1.0,"age":"mid","blurb":tr('cables.africa_coast_to_europe_twenty_odd'),"pairs":[["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-4,4.8],[-0.2,5.1]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","lad",[[3.2,5.8],[6,3],[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.6,-9],[11.5,-15],[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lis","tci",[[-9.6,37.9],[-12,34],[-15.4,29.5]]],["tci","dkr",[[-17,26],[-18,21],[-18,14.7]]]]},
{"id":"sat3","name":"SAT-3-Legged Stool","price":1.25,"age":"old","blurb":tr('cables.west_africa_s_first_big_cable'),"pairs":[["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-4,4.8],[-0.2,5.1]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","dla",[[3.2,5.8],[6,3],[9,3.6]]],["dla","lad",[[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.6,-9],[11.5,-15],[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lis","tci",[[-9.6,37.9],[-12,34],[-15.4,29.5]]],["tci","dkr",[[-17,26],[-18,21],[-18,14.7]]]]},
{"id":"mone","name":"MainOne-Track Mind","price":1.0,"age":"mid","blurb":tr('cables.portugal_to_lagos_with_stops_in'),"pairs":[["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-4,4.8],[-0.2,5.1]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]]]},
{"id":"mtwa","name":"Mint Tea West Africa","price":1.05,"age":"new","blurb":tr('cables.casablanca_down_the_coast_to_abidjan'),"pairs":[["cas","dkr",[[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]]]},
{"id":"sail","name":"Set SAIL","price":1.0,"age":"new","blurb":tr('cables.straight_across_the_south_atlantic'),"pairs":[["for","dla",[[-37,-2.5],[-20,0],[0,2.5],[9,3.6]]]]},
{"id":"seacm","name":"Sea-Comedy Hour","price":0.95,"age":"mid","blurb":tr('cables.the_cable_that_brought_east_africa'),"pairs":[["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[40.6,-4.3],[45,2],[51,10.5],[45,12.3],[43.5,11.9]]],["jib","bom",[[43.5,11.9],[51,13],[62,18],[70,19]]]]},
{"id":"dare","name":"Dare-Devil-1","price":0.9,"age":"new","blurb":tr('cables.djibouti_down_to_durban_hugging_the'),"pairs":[["jib","mba",[[43.5,11.9],[45,12.3],[51,10.5],[45,2],[40.6,-4.3]]],["mba","dar",[[40.6,-4.3],[40.4,-7]]],["dar","mpm",[[40.4,-7],[41.5,-14],[38,-20],[34.5,-26]]],["mpm","dur",[[34.5,-26],[32,-30.3]]]]},
{"id":"glo1","name":"Glo-in-the-Dark","price":1.05,"age":"mid","blurb":tr('cables.cornwall_to_lagos_down_the_west'),"pairs":[["bde","lag",[[-5.2,50.6],[-11,45],[-15,30],[-19,15],[-12,4],[2,4.5],[3.4,6]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]]]},
{"id":"pasdc","name":"Pas de Câble","price":0.6,"age":"new","df":true,"blurb":tr('cables.another_hop_across_the_channel_with'),"pairs":[["lon","par",[[1.3,51.0],[1.7,50.7]]]]},
{"id":"tampn","name":"Oil Rig Wi-Fi","price":0.9,"age":"mid","blurb":tr('cables.stavanger_to_the_netherlands_via'),"pairs":[["svg","ams",[[5.3,58.6],[4.5,56],[4.2,53.5],[4.6,52.6]]]]},
{"id":"medusa","name":"Medusa Stare","price":0.85,"age":"new","blurb":tr('cables.lisbon_to_barcelona_and_marseille'),"pairs":[["lis","bcn",[[-9.6,37.9],[-8.9,36.6],[-5.6,35.9],[-2,36.4],[0.5,38.5],[2.6,41.1]]],["bcn","mrs",[[2.8,41.3],[3.8,42.4],[5,43]]],["lis","cas",[[-9.6,37.9],[-12,34],[-8.2,33.9]]],["mrs","alg",[[5,42.8],[4.5,40],[3,37.2]]],["alg","tun",[[3,37.2],[10.6,37.4]]]]},
{"id":"nuvem","name":"Nuvem-ber Rain","price":0.85,"age":"new","blurb":tr('cables.portugal_to_the_us_southeast_via'),"pairs":[["lis","atn",[[-9.6,37.9],[-30,35],[-64.8,32.3],[-78.9,33.7]]],["atn","bda",[[-78.9,33.7],[-72,33.2]]],["bda","lis",[[-50,34.5],[-30,35],[-9.6,37.9]]]]},
{"id":"blue","name":"Feeling Blue","price":0.85,"age":"new","blurb":tr('cables.genoa_to_sicily_and_on_to'),"pairs":[["mil","pmo",[[8.9,44.2],[9.4,42.5],[11.2,39.5],[12.9,38.4]]],["pmo","ath",[[13.6,38.3],[15.4,37.2],[19,36.8],[22.6,36.2],[23.6,37.6]]]]},
{"id":"cannoli","name":"Sicilian Spaghetti Junction","price":0.9,"age":"mid","blurb":tr('cables.palermo_to_marseille_and_alexandria'),"pairs":[["pmo","mrs",[[12.9,38.4],[9.5,40],[7.4,42.6],[5.4,43.1]]],["pmo","cai",[[13.6,37.8],[15.5,35.6],[22,33.4],[29.9,31.4]]]]},
{"id":"ouzo","name":"Ouzo Express","price":0.9,"age":"new","blurb":tr('cables.athens_to_alexandria_and_up_the'),"pairs":[["ath","cai",[[24,37.5],[25.2,35.5],[28,33],[29.9,31.4]]],["ath","ist",[[24.3,38.5],[25.6,39.9],[26.5,40.3],[28.2,40.8]]]]},
{"id":"tea","name":"Boston Tea Party Line","price":0.9,"age":"mid","blurb":tr('cables.boston_to_dublin_nobody_has_thrown'),"pairs":[["bos","dub",[[-69.5,42.2],[-60,44],[-40,50],[-15,52.4],[-8,53]]]]},
{"id":"clementine","name":"Clementine","price":0.6,"age":"new","df":true,"blurb":tr('cables.a_small_sweet_cable_from_broadstairs'),"pairs":[["lon","oos",[[1.44,51.36],[2.92,51.23]]]]},
{"id":"seaus","name":"SEA-US Later","price":1.0,"age":"mid","blurb":tr('cables.los_angeles_to_hawaii_guam_and'),"pairs":[["lax","hnl",[[-119,33.5],[-140,27],[-157.6,21.6]]],["hnl","gum",[[-158.3,21.2],[-180,18],[-200,15],[-214.6,13.5]]],["gum","mnl",[[144,13.7],[132,13.5],[124.5,13],[121.4,14.3]]],["gum","ror",[[144.5,13.1],[139,9.5],[134.8,7.5]]]]},
{"id":"aag","name":"Asia-America Gateaux","price":1.25,"age":"old","blurb":tr('cables.california_to_hong_kong_via_hawaii'),"pairs":[["sjc","hnl",[[-122.8,35],[-140,27.5],[-158.2,21.4]]],["hnl","gum",[[-158.4,21.5],[-180,19],[-200,16],[-214.4,13.7]]],["gum","hkg",[[144.5,14],[130,17.5],[121,20],[115,21.6],[114.3,22.2]]]]},
{"id":"echo","name":"Echo-Chamber","price":0.85,"age":"new","blurb":tr('cables.california_to_singapore_via_guam'),"pairs":[["sjc","gum",[[-125,38],[-150,30],[-180,21],[-214.8,14]]],["gum","sin",[[144.6,13],[133,6],[127,3],[118,2],[108,2],[104.5,1.4]]]]},
{"id":"hantru","name":"HANTRU-ly Yours","price":1.3,"age":"mid","blurb":tr('cables.guam_to_the_marshall_islands_with'),"pairs":[["gum","maj",[[145,13.3],[158,7],[167,8.5],[171.2,7.2]]]]},
{"id":"coral","name":"Coral Sea Shanty","price":1.0,"age":"new","blurb":tr('cables.sydney_to_papua_new_guinea_and'),"pairs":[["syd","pom",[[152,-33.5],[154.5,-25],[151,-15],[147.3,-10]]],["syd","hir",[[152,-33.5],[156.5,-25],[160.5,-14],[160,-9.6]]]]},
{"id":"gond","name":"Gondwanna-Be","price":1.1,"age":"mid","blurb":tr('cables.sydney_to_noumea_wishes_it_were'),"pairs":[["syd","nou",[[152,-33.5],[158,-28],[164,-23.5],[166.2,-22.5]]]]},
{"id":"tonga","name":"Tonga Twister","price":1.3,"age":"mid","blurb":tr('cables.fiji_to_tonga_the_only_way'),"pairs":[["suv","tbu",[[178.8,-18.5],[181.5,-20],[184.6,-21]]]]},
{"id":"tui","name":"Tui-Some-More","price":1.1,"age":"new","blurb":tr('cables.fiji_to_samoa_always_room_for'),"pairs":[["suv","apw",[[179,-18],[183,-15.5],[188,-13.95]]]]},
{"id":"ashc","name":"ASH-tray","price":1.4,"age":"old","blurb":tr('cables.american_samoa_to_hawaii_and_samoa'),"pairs":[["ppg","hnl",[[-170.5,-13.9],[-166,0],[-158.1,20.9]]],["ppg","apw",[[-170.9,-14.1],[-171.6,-13.9]]]]},
{"id":"hono","name":"Hono-tuna","price":1.2,"age":"mid","blurb":tr('cables.tahiti_to_hawaii_trolling_for'),"pairs":[["ppt","hnl",[[-149.7,-17.2],[-153,0],[-156.5,19.5],[-157.7,21.1]]]]},
{"id":"mana","name":"Mana-tea","price":1.1,"age":"new","blurb":tr('cables.samoa_to_tahiti_by_way_of'),"pairs":[["apw","ppt",[[-171.5,-14.2],[-165,-18],[-159.8,-21.2],[-152,-18.5],[-149.8,-17.6]]]]},
{"id":"scxn","name":"Southern Cross-ed Fingers NEXT","price":0.95,"age":"new","blurb":tr('cables.the_old_workhorse_s_younger_sibling'),"pairs":[["lax","suv",[[-119,33],[-140,15],[-165,-5],[-178,-15],[-181.2,-17.3]]],["suv","syd",[[177.8,-18.6],[166,-25],[156,-31.5],[152,-33.9]]]]},
{"id":"sol","name":"Sol Survivor","price":0.85,"age":"new","blurb":tr('cables.florida_to_northern_spain_via'),"pairs":[["mia","bda",[[-80,27],[-80.9,29.6],[-74,31.5]]],["bda","pdl",[[-50,35.5],[-35,37.5]]],["pdl","mad",[[-15,41.5],[-6,44],[-3.8,43.6]]]]},
{"id":"atl2","name":"Atlantis-2: The Sequel","price":1.4,"age":"old","blurb":tr('cables.argentina_to_portugal_via_brazil'),"pairs":[["bue","for",[[-56.5,-36.6],[-50,-32],[-42,-23.5],[-37,-12],[-34.5,-6]]],["for","rai",[[-36,-1.5],[-28,8],[-24,14]]],["rai","dkr",[[-20,14.7]]],["dkr","tci",[[-18,17],[-17.5,24],[-16.6,27.9]]],["tci","lis",[[-15.5,31],[-11,36.5],[-9.2,38.3]]]]},
{"id":"canl","name":"Canary in the Cable Mine","price":0.8,"age":"mid","blurb":tr('cables.tenerife_to_the_spanish_mainland_as'),"pairs":[["tci","mad",[[-14.5,30.5],[-9,35],[-6.1,36.3]]]]},
];
const CAB=Object.fromEntries(CABLES.map(c=>[c.id,c]));
const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=CITY[b];const near=(x,ref)=>x+W*Math.round((ref-x)/W);
const mp=mid.map(q=>proj(q[0],q[1]));const pts=[[near(A.x,mp[0][0]),A.y]].concat(mp,[[near(B.x,mp[mp.length-1][0]),B.y]]);
const ll=[[A.lon,A.lat]].concat(mid,[[B.lon,B.lat]]);let L=0;for(let i=1;i<ll.length;i++)L+=hav(ll[i-1][0],ll[i-1][1],ll[i][0],ll[i][1]);
return {cid:c.id,a,b,pts,km:Math.round(L)};}));
function cablesOk(a,b){const ban=S&&S.ev&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city);if(ban)return [];const rl=S&&S.scn&&S.scn.rules,bp=rl&&rl.banPairs,bc=rl&&rl.banCities;return bp||bc?cablesFor(a,b).filter(c=>!(bp&&(bp.includes(c.cid+':'+c.a+'-'+c.b)||bp.includes(c.cid+':'+c.b+'-'+c.a)))&&!(bc&&(bc.includes(c.a)||bc.includes(c.b)))):cablesFor(a,b);}
function cablesFor(a,b){return CABLE_PAIRS.filter(c=>(c.a===a&&c.b===b)||(c.a===b&&c.b===a));}
function cablePair(cid,a,b){const c=CABLE_PAIRS.find(x=>x.cid===cid&&((x.a===a&&x.b===b)||(x.a===b&&x.b===a)));if(!c)return null;return c.a===a?c:{...c,pts:c.pts.slice().reverse()};}
const ALLC=CITIES.filter(c=>!c.cn&&!c.ru&&!c.ixOnly).map(c=>c.id);
/* City density: a small city (P under 60) does not sit within 300 km of a bigger city in the same country, unless it
is a cable landing or a capital (tests/regions.test.js enforces it). Cities retired by that rule are marked off:
they stay in the data so old saves keep their POPs there, but new games never see them. */
const cityOn=id=>{const c=CITY[id];return !!c&&(!c.off||!!(S&&(S.pops[id]||S.ixp[id]!==undefined)));};
const OFFC=ALLC.filter(c=>!CITY[c].off);
const ruCity=c=>!!CITY[c].ru;
const cnCity=c=>!!CITY[c].cn;
const BIGC=['man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','ruh','jed','doh','kyv','mel','bne','osa','kul','bkk','sgn','khi','dac','waw','prg','vie','bud','buh','ist','rio','bue','scl','bog','lim','del','maa','blr','hyd','tpe','cpt','auh','ber','zrh','nbo','cai','jkt','mnl','per','akl','dub','lax','tor','mex','dxb','cph','icn','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mrs','mad','sto','bom','sin','hkg','tok','syd','jnb','lag'];
const MIDC=['man','bcn','mil','lis','atn','den','phx','bos','hou','mel','osa','kul','bkk','waw','vie','ist','rio','bue','scl','bog','del','maa','blr','tpe','auh','ber','zrh','jkt','mnl','dub','lax','tor','dxb','icn','sjc','ash','nyc','chi','dal','mia','lon','ams','fra','par','mad','sin','hkg','tok','syd','bom','sao'];

View file

@ -0,0 +1,110 @@
/* ================= NETWORKS ================= */
const NETS=[
{id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['syd','hfx','bda','hnl','bde','man','edi','svg','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist','kcy','cal','van','ott','bru','bet','ham','muc','cpq','gdl','mty','qro'],ix:[],blurb:tr('networks.grew_from_a_seedling_into_a')},
{id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['hnl','gum','man','mil','atn','den','bos','hou','phx','jkt','mnl','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd','tpe','del','maa','blr','hyd','osa','kul','bkk','sgn','kcy','dus'],ix:[],blurb:tr('networks.huge_in_asia_which_telecom_not')},
{id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')},
{id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['hfx','bde','man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv','kcy','van','ott','bru','oos','bet','ham','muc','dus','syd','per'],ix:[],blurb:tr('networks.cheapest_transit_on_the_map_famously')},
{id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['tci','gum','mil','pmo','lis','nbo','cai','jkt','dxb','nyc','ash','lon','fra','mrs','lag','jnb','bom','sin','hkg','tok','del','maa','blr','hyd','cpt','fuj','auh','tpe','khi','dac','cbo','kul','bkk','jed','ruh','doh','jib','dar','mba','dkr'],ix:[],blurb:tr('networks.waves_goodbye_to_latency_across_the')},
{id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')},
{id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih'],blurb:tr('networks.juicy_reach_into_europe_and_africa')},
{id:'sgt',name:'SingTell',asn:7474,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')},
{id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')},
{id:'ctc',name:'China Telecomet',asn:4314,type:'t2',pol:'restrictive',share:.02,price:22,premium:2.5,cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')},
{id:'cun',name:'China Unicorn',asn:4837,type:'t2',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:tr('networks.number_two_in_china_with_a')},
{id:'cmb',name:'China Moble',asn:9880,type:'eye',pol:'paid',freeLv:10,paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:tr('networks.the_largest_mobile_network_on_earth')},
{id:'cmc',name:'Comecast',asn:7227,type:'eye',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['atn','den','bos','hou','phx','slc','ash','nyc','chi','sjc','sea','mia'],ix:['atn','den','bos','ash','nyc','chi','sjc','sea'],blurb:tr('networks.huge_eyeball_network_come_for_the')},
{id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'eye',pol:'paid',freeLv:6,paidFee:9000,share:.03,col:'#E20074',pops:['fra','ams','lon','ham','muc','dus'],ix:[],blurb:tr('networks.pink_eyeball_giant_peering_is')},
{id:'nfx',name:'NetChill',asn:2906,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.15,cache:{name:'Open Couch',min:12},col:'#C8102E',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.streams_40_of_evening_traffic_hands')},
{id:'ggl',name:'Goggle',asn:15961,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.13,cache:{name:'Goggle Global Cache',min:15},col:'#3A7BEA',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.search_video_and_goggles_mostly')},
{id:'fbk',name:'Faceplant',asn:32943,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.08,cache:{name:'Faceplant Node Thingy',min:10},col:'#3B5BDB',auIx:['syd','mel'],pops:BIGC,ix:'ALL',blurb:tr('networks.social_media_everyone_keeps_falling')},
{id:'akm',name:'Akamaybe',asn:20490,type:'cdn',pol:'open',share:.07,cache:{name:'Akamaybe Box',min:6},col:'#0099CC',auIx:['syd','mel','bne','per','adl'],pops:ALLC,ix:'ALL',blurb:tr('networks.the_original_cdn_maybe_it_is')},
{id:'cfl',name:'Crowdflare',asn:13353,type:'cdn',pol:'open',share:.05,cache:{name:'Rackstar',min:10},col:'#F48120',auIx:['syd','mel','bne','per','adl','cbr','hba'],pops:BIGC.concat(['hnl','gum','nou','ppt','dus']),ix:'ALL',blurb:tr('networks.shields_half_the_web_from_crowds')},
{id:'amz',name:"Amazin' Web Services",asn:16590,type:'cdn',pol:'selective',minIx:8,minPni:30,share:.05,col:'#FF9900',auIx:['syd','mel','bne','per'],pops:MIDC.concat(['dus']),ix:'ALL',blurb:tr('networks.the_cloud_it_s_just_someone')},
{id:'msf',name:'Microsnoft',asn:8705,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.04,col:'#00A4EF',auIx:['syd','mel','bne','per'],pops:MIDC.concat(['dus']),ix:'ALL',blurb:tr('networks.updates_so_many_updates')},
{id:'bdc',name:'BiteDance',asn:39669,type:'cdn',pol:'open',share:.03,col:'#111111',auIx:[],pops:MIDC.concat(['pek','sha','dus']),ix:'ALL',blurb:tr('networks.short_videos_very_long_traffic')},
{id:'slw',name:'Slowly',asn:54311,type:'cdn',pol:'open',share:.02,col:'#E5383B',auIx:['syd','mel','bne','per','adl'],pops:MIDC,ix:'ALL',blurb:tr('networks.an_edge_cloud_that_is_despite')},
];
NETS.push(
{id:'tcs',name:'TenCents',asn:45900,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.02,cn:true,col:'#1AAD19',pops:['pek','sha','hkg','sin','tok','fra','sjc'],ix:['hkg','sin','tok','fra','sjc'],blurb:tr('networks.chat_games_and_payments_every')},
{id:'abc',name:'AliBubble Cloud',asn:37936,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.015,cn:true,col:'#FF6A00',pops:['pek','sha','hkg','sin','tok','fra','sjc','syd'],ix:['hkg','sin','tok','fra','sjc'],blurb:tr('networks.shopping_festivals_that_melt_traffic')},
{id:'byd',name:'Bye-du',asn:38635,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.01,cn:true,col:'#2932E1',pops:['pek','sha','hkg'],ix:['hkg'],blurb:tr('networks.search_maps_and_a_cheerful_goodbye')});
NETS.push(
{id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams'],ix:['mos','fra','ams'],blurb:tr('networks.the_national_carrier_every_punchline')},
{id:'ydx',name:'Yawndex',asn:13238,type:'cdn',pol:'open',share:.008,col:'#FC3F1D',pops:['mos','hel','fra','ams'],ix:['mos','hel','fra','ams'],blurb:tr('networks.search_taxis_and_maps_slightly')},
{id:'vkl',name:'VKontakt-lens',asn:47541,type:'cdn',pol:'open',share:.006,col:'#0077FF',pops:['mos','hel'],ix:['mos','hel'],blurb:tr('networks.social_network_with_perfect_vision')},
{id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',pol:'paid',freeLv:9,paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin','auh','fuj','doh'],ix:[],blurb:tr('networks.charges_a_lot_paid_peering_only')},
{id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',pol:'paid',freeLv:8,paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia','qro','mty','gdl'],ix:[],blurb:tr('networks.mexico_s_giant_paid_peering_only')},
{id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['hfx','tor','mtl','nyc','chi','ott','cal','van'],ix:['tor','mtl','ott'],blurb:tr('networks.polite_enormous_and_sorry_about_the')});
NETS.push(
{id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:tr('networks.indonesia_s_mobile_giant_every')},
{id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg'],blurb:tr('networks.philippine_giant_peering_requests')},
{id:'spk',name:'Spark-le',asn:4771,type:'eye',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')},
{id:'tsy',name:'Telstraya',asn:1221,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')});
NETS.push(
{id:'liq',name:'Liquid Lunch Networks',asn:30846,type:'t2',pol:'open',up:['tat','tly'],share:.006,price:6,col:'#00A0DF',pops:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],ix:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],blurb:tr('networks.cape_to_cairo_fiber_across_a')},
{id:'scm',name:'Sea-Comedy Networks',asn:37102,type:'t2',pol:'open',up:['ntt','tat'],share:.005,price:5,col:'#1C3F94',pops:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','kgl','jib','cai','mrs','bom','lon'],ix:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','jib','mrs'],blurb:tr('networks.owns_the_cable_that_brought_east')},
{id:'agc',name:'Angle-a Cables',asn:37470,type:'t2',pol:'open',up:['tly','cog'],share:.004,price:5,col:'#E30613',pops:['lad','fih','for','sao','mia','lon'],ix:['lad','for','sao','mia'],blurb:tr('networks.owns_the_cables_from_luanda_to')},
{id:'djt',name:'Djibouti Calling',asn:30992,type:'t2',pol:'selective',up:['tat','tly'],minIx:3,minPni:15,share:.003,price:8,col:'#0D7F3F',pops:['jib','add','mrs','bom','jed'],ix:['jib'],blurb:tr('networks.a_tiny_telco_in_a_country')},
{id:'mtx',name:'Empty-N',asn:29977,type:'eye',pol:'selective',up:['tat','lvl'],minIx:5,minPni:20,share:.008,col:'#FFCB05',pops:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],ix:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],blurb:tr('networks.africa_s_mobile_giant_in_a')},
{id:'art',name:'Air-Tell Africa',asn:36928,type:'eye',pol:'selective',up:['tat','tly'],minIx:4,minPni:18,share:.006,col:'#ED1C24',pops:['lag','kla','kgl','dar','lun','fih','nbo'],ix:['lag','kla','kgl','dar','lun','fih','nbo'],blurb:tr('networks.mobile_money_and_prepaid_data_in')},
{id:'eth',name:'Ethio-Tele-Calm',asn:24759,type:'eye',pol:'selective',up:['tat'],minIx:2,minPni:12,share:.005,col:'#8DC63F',pops:['add'],ix:['add'],blurb:tr('networks.ethiopia_s_state_telco_a_hundred')},
{id:'mrc',name:'Atlas Shrugged Telecom',asn:36905,type:'eye',pol:'selective',up:['lvl','tly'],minIx:3,minPni:15,share:.004,col:'#F28C00',pops:['cas','abj','dkr'],ix:['cas'],blurb:tr('networks.morocco_s_incumbent_with_sister')},
{id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')},
{id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:tr('networks.owns_the_land_crossing_every_red')});
NETS.push(
{id:'clr',name:'Clarovision',asn:28537,type:'t2',pol:'selective',minIx:10,minPni:30,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog','pan','mex','mia'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog'],blurb:tr('networks.the_big_regional_carrier_sees')},
{id:'viv',name:'Viva Vivo',asn:26959,type:'eye',pol:'selective',minIx:8,minPni:25,share:.01,col:'#660099',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.brazil_s_mobile_giant_very_much')},
{id:'oio',name:'Oi Oi',asn:7739,type:'eye',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')},
{id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')},
{id:'bsn',name:'Brisanada',asn:28127,type:'eye',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')},
{id:'mvs',name:'Moviestar',asn:12957,type:'t2',pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')},
{id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs'],ix:['pan','sjo','gua','bog'],blurb:tr('networks.cables_all_around_the_caribbean')},
{id:'ant',name:'Antelope',asn:6058,type:'eye',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')},
{id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')},
{id:'mlv',name:'Mercado Livre-ly',asn:52850,type:'cdn',pol:'open',share:.006,col:'#FFE600',pops:['sao','rio','bue','scl','bog','lim','mia'],ix:['sao','rio','bue','scl','bog','lim'],blurb:tr('networks.ships_parcels_and_packets_both')},
{id:'jio',name:'Jio-graphy',asn:55863,type:'eye',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:tr('networks.gave_a_billion_people_cheap_data')},
{id:'atl',name:'Airtel-tale',asn:9849,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:7,col:'#E40000',pops:['bom','del','maa','blr','hyd','sin','lon','dxb','dac','cbo'],ix:['bom','del','maa','blr'],blurb:tr('networks.india_s_other_giant_every_outage')},
{id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:tr('networks.taiwan_s_incumbent_stays_calm_while')},
{id:'duu',name:'Du-opoly',asn:15820,type:'eye',pol:'paid',freeLv:11,paidFee:6000,share:.004,col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')});
NETS.push(
{id:'kdi',name:'KD-DIY',asn:2561,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg'],ix:['tok','osa'],blurb:tr('networks.japanese_carrier_that_builds')},
{id:'opt',name:'Floptus',asn:4804,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')},
{id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')},
{id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')},
{id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')},
{id:'ddo',name:'Doodoo',asn:9443,type:'eye',pol:'open',up:['voc'],share:.0011,col:'#FFC20E',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.the_cheapest_plan_in_the_country')},
{id:'stb',name:'Musklink',asn:14593,type:'eye',pol:'selective',minIx:3,minPni:10,share:.001,col:'#1B1F24',pops:['syd','mel','bne','per','drw'],ix:['mel','bne','per','drw'],blurb:tr('networks.beams_the_outback_online_from_550')},
{id:'spl',name:'Speedyloop',asn:38195,type:'t2',pol:'open',up:['tly'],share:.001,price:6,col:'#FF5F00',pops:['syd','mel','bne','per','adl','sin','hkg','cbr','drw'],ix:['mel','bne','per','adl','hba','drw','sin','hkg'],blurb:tr('networks.speedy_by_name_owns_a_slice')},
{id:'blg',name:'Beshort',asn:135887,type:'eye',pol:'selective',minIx:8,minPni:25,up:['tsy'],share:.0005,col:'#FF5A00',pops:['syd','mel','bne'],ix:[],blurb:tr('networks.telstraya_s_budget_brand_cheaper')},
{id:'spn',name:'Spin2wintel',asn:18390,type:'eye',pol:'open',up:['voc'],share:.00015,col:'#0072CE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.cheap_broadband_with_the_sales_pitch')},
{id:'lpt',name:'Frogtel',asn:134090,type:'eye',pol:'open',share:.0001,col:'#7AC143',pops:['syd','mel','bne','adl','per','drw'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.small_fast_and_always_leaping_to')},
{id:'ext',name:'Lintel',asn:10143,type:'eye',pol:'open',up:['spl'],share:.0001,col:'#F26522',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.bought_by_speedyloop_and_still')},
{id:'tru',name:'Mostly-True Move',asn:7740,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#E4002B',pops:['bkk'],ix:['bkk'],blurb:tr('networks.thailand_s_mobile_giant_its_coverage')},
{id:'vtl',name:'Viet-tell',asn:7525,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:7,col:'#EE0033',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:tr('networks.vietnam_s_giant_will_tell_you')},
{id:'ptc',name:'PTC-hell',asn:17577,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:8,col:'#00843D',pops:['khi','dxb'],ix:['khi'],blurb:tr('networks.pakistan_s_incumbent_every_session')},
{id:'tmy',name:'Telekom Ma-lazy-sia',asn:4877,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:6,col:'#1F2A6B',pops:['kul','sin'],ix:['kul'],blurb:tr('networks.malaysia_s_incumbent_in_no_hurry')},
{id:'ttk',name:'Türk Tele-komik',asn:9211,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#1D3F8F',pops:['ath','ist','fra','sof','lon'],ix:['ist'],blurb:tr('networks.bridges_europe_and_asia_and')},
{id:'dgi',name:'Digi-tally Cheap',asn:8798,type:'eye',pol:'open',share:.006,col:'#2A5CAA',pops:['buh','bud','mad'],ix:['buh','bud','mad'],blurb:tr('networks.gigabit_to_every_flat_for_the')},
{id:'ups',name:'UPC-You-Later',asn:6380,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#D8001B',pops:['waw','prg','vie','bud','zrh','kyv'],ix:['waw','prg','vie','kyv'],blurb:tr('networks.cable_broadband_across_central')});
NETS.push(
{id:'tlu',name:'Tell Us',asn:852,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl','tly'],col:'#4B286D',pops:['van','cal','tor','mtl','ott','sea'],ix:['van','cal','tor'],blurb:tr('networks.western_canada_s_incumbent_tell_us')},
{id:'rgc',name:'Bodgers Communications',asn:812,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,up:['cog','ntt'],col:'#DA291C',pops:['tor','ott','mtl','van','cal'],ix:['tor','ott','van'],blurb:tr('networks.canada_s_cable_giant_held_together')});
NETS.push(
{id:'tny',name:'Telenyet',asn:6848,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl'],col:'#FFC421',pops:['bru','oos','ams','fra','lon'],ix:['bru'],blurb:tr('networks.half_of_the_flanders_duopoly_on')},
{id:'pxm',name:'Proxyminus',asn:5432,type:'eye',pol:'selective',minIx:15,minPni:40,share:.008,up:['bgs','lvl'],col:'#5C2D91',pops:['bru','oos','ams'],ix:['bru'],blurb:tr('networks.the_other_half_of_the_duopoly')},
{id:'bgs',name:'B.I.G.S.',asn:6774,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:5,up:['lvl'],col:'#7B2D8E',pops:['bru','bet','ams','fra','lon','par','mrs','nyc','sin'],ix:['bru','bet','ams','fra','lon','par'],blurb:tr('networks.proxyminus_s_wholesale_arm_present')},
{id:'cit',name:'Citrus Belgium',asn:47377,type:'eye',pol:'selective',minIx:10,minPni:30,share:.005,up:['lvl'],col:'#FF7900',pops:['bru','par'],ix:['bru'],blurb:tr('networks.tangerine_s_belgian_daughter_mobile')},
{id:'pst',name:'Poste Restante',asn:6663,type:'eye',pol:'selective',minIx:4,minPni:15,share:.001,up:['lvl','tly'],col:'#FFCC00',pops:['bet','fra','ams'],ix:['bet','fra'],blurb:tr('networks.luxembourg_s_post_office_which_also')},
{id:'cms',name:'CityMess',asn:199095,type:'eye',pol:'open',share:.002,up:['cog'],col:'#00B2A9',pops:['oos','bru'],ix:['bru'],blurb:tr('networks.private_5g_and_business_fiber_from')});
NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')});
NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',pol:'selective',minIx:10,minPni:30,share:.01,price:8,col:'#4F008C',pops:['ruh','jed','dxb','fra','lon','cai'],ix:['ruh'],blurb:tr('networks.the_kingdom_s_incumbent_once_you')},
{id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',pol:'paid',freeLv:11,paidFee:5000,share:.004,col:'#ED1C24',pops:['doh','dxb','jkt'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')});
NETS.push(
{id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',pol:'selective',minIx:8,minPni:25,share:.008,col:'#004691',pops:['mil','rom','pmo'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')},
{id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')},
{id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')},
{id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')},
{id:'nos',name:'NOS-y Neighbour',asn:2860,type:'eye',pol:'open',share:.003,col:'#111111',pops:['lis'],ix:['lis'],blurb:tr('networks.peers_with_anyone_and_wants_to')},
{id:'cos',name:'Cosmo-Note',asn:6799,type:'eye',pol:'selective',minIx:5,minPni:20,share:.004,col:'#7DC242',pops:['ath','sof'],ix:['ath'],blurb:tr('networks.greece_s_incumbent_takes_careful')},
{id:'spc',name:'Spectre-um Cable',asn:20115,type:'eye',pol:'selective',minIx:12,minPni:35,share:.02,col:'#0099D8',pops:['nyc','lax','dal','chi','atn','den','phx','slc','hou','bos','sjc'],ix:['nyc','lax','dal','chi','atn','den'],blurb:tr('networks.cable_broadband_for_half_of_america')},
{id:'vzn',name:'Very-Zone',asn:701,type:'eye',pol:'paid',paidFee:9000,share:.015,col:'#CD040B',pops:['nyc','ash','bos','dal','lax','chi','atn','mia'],ix:[],blurb:tr('networks.can_you_hear_me_now_only')});

View file

@ -0,0 +1,31 @@
/* Rival exchanges. Big metros rarely have just one IX: challengers undercut the incumbent and
share many members with it, but not all. The incumbent keeps the city id, challengers are 'city~n'. */
const XIX=[
{id:'jnb~2',c:'jnb',name:'JINXED-IX',cheap:.7,take:0.5,core:['drz','akm','cfl','tng'],blurb:tr('rival_exchanges.the_older_johannesburg_exchange_run')},
{id:'fra~2',c:'fra',name:'KleyWrecks',cheap:.5,take:0.5,core:['drz','akm','cfl','slw','bdc','ydx'],blurb:tr('rival_exchanges.a_smaller_commercial_exchange_down')},
{id:'fra~3',c:'fra',name:'Apfelwein-IX',cheap:0.3,take:0.3,blurb:tr('rival_exchanges.a_community_exchange_run_from_above')},
{id:'ams~2',c:'ams',name:'NL-Nyx',cheap:0.6,take:0.6,blurb:tr('rival_exchanges.one_fabric_across_the_whole_country')},
{id:'ams~3',c:'ams',name:'FRIES-IX',cheap:1,take:0.5,freeTo:1,core:['drz','akm','cfl','slw','msf'],blurb:tr('rival_exchanges.settlement_free_peering_with_frysian')},
{id:'lon~2',c:'lon',name:'LO-NAPS',cheap:.6,take:0.5,core:['drz','akm','cfl','slw','bdc','msf','fbk'],blurb:tr('rival_exchanges.member_owned_and_not_for_profit')},
{id:'par~2',c:'par',name:'Baguette-IX',cheap:0.55,take:0.5,blurb:tr('rival_exchanges.the_challenger_fresh_every_morning_a')},
{id:'mad~2',c:'mad',name:'Paella-NIX',cheap:.6,take:0.5,core:['drz','akm','cfl','tng','bdc','slw','msf'],blurb:tr('rival_exchanges.the_long_established_madrid_exchange')},
{id:'mil~2',c:'mil',name:'Aperitivo-IX',cheap:0.5,take:0.45,blurb:tr('rival_exchanges.opens_at_six_comes_with_free')},
{id:'ber~2',c:'ber',name:'Club-Mate-IX',cheap:0.35,take:0.4,blurb:tr('rival_exchanges.run_by_hackers_on_caffeine_the')},
{id:'waw~2',c:'waw',name:'Bigos-IX',cheap:0.45,take:0.5,blurb:tr('rival_exchanges.warsaw_has_more_exchanges_than')},
{id:'waw~3',c:'waw',name:'Zapiekanka-IX',cheap:0.3,take:0.35,blurb:tr('rival_exchanges.open_faced_cheap_and_available_at')},
{id:'prg~2',c:'prg',name:'Knedlík-IX',cheap:0.35,take:0.4,blurb:tr('rival_exchanges.dense_filling_and_very_cheap')},
{id:'buh~2',c:'buh',name:'Mici-IX',cheap:0.35,take:0.45,blurb:tr('rival_exchanges.grilled_ports_served_with_mustard')},
{id:'sto~2',c:'sto',name:'Fika-IX',cheap:0.5,take:0.5,blurb:tr('rival_exchanges.every_session_comes_with_a_coffee')},
{id:'kyv~2',c:'kyv',name:'Kyiv-Cake-IX',cheap:0.35,take:0.45,blurb:tr('rival_exchanges.layered_resilient_and_somehow_always')},
{id:'nyc~2',c:'nyc',name:'Bagel-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.a_community_exchange_in_a_hudson')},
{id:'chi~2',c:'chi',name:'Deep-Dish-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.takes_forever_to_set_up_but')},
{id:'sjc~2',c:'sjc',name:'Garage-IX',cheap:0.55,take:0.45,blurb:tr('rival_exchanges.started_in_somebody_s_garage_like')},
{id:'lax~2',c:'lax',name:'Smog-IX',cheap:0.6,take:0.45,blurb:tr('rival_exchanges.you_can_t_see_the_fabric')},
{id:'sin~2',c:'sin',name:'Kopi-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.strong_sweet_and_cheaper_than_the')},
{id:'hkg~2',c:'hkg',name:'Dim-Sum-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.lots_of_small_sessions_on_little')},
{id:'tok~2',c:'tok',name:'Bento-IX',cheap:0.65,take:0.5,core:['drz','akm','cfl','sgt','msf','amz'],blurb:tr('rival_exchanges.tokyo_has_more_exchanges_than_anyone')},
{id:'syd~2',c:'syd',name:'At-The-Edge IX',cheap:.7,take:0.5,core:['drz','nfx','ggl','fbk','akm','cfl','amz','msf','bdc','slw','abb','voc','stb','spl','lpt'],blurb:tr('rival_exchanges.the_challenger_to_ix_straya_pops')},
{id:'bom~2',c:'bom',name:'Vada-Pav-IX',cheap:0.45,take:0.45,blurb:tr('rival_exchanges.mumbai_s_street_food_exchange_fast')},
{id:'dxb~2',c:'dxb',name:'Shawarma-IX',cheap:0.6,take:0.4,blurb:tr('rival_exchanges.the_challenger_to_the_de_kicks')},
];
const XIXM=Object.fromEntries(XIX.map(x=>[x.id,x]));

View file

@ -0,0 +1,95 @@
/* The long tail: odd little networks with a sliver of traffic each, on one or two exchanges. */
const TAIL=[
['Grandma’s Basement Hosting','cdn',['fra'],tr('long_tail.three_servers_one_dehumidifier_and_a')],
['Hamster Wheel Networks','eye',['ams'],tr('long_tail.powered_by_renewable_rodents_uptime')],
['Fjordnet Kooperativ','eye',['osl'],tr('long_tail.a_fiber_co_op_for_one')],
['Kebab-Link','eye',['ber','fra'],tr('long_tail.an_isp_run_from_the_back')],
['Mesh Collective e.V.','eye',['ber','fra'],tr('long_tail.volunteers_with_rooftop_antennas_and')],
['Village Fibre Co-op','eye',['lon'],tr('long_tail.dug_the_trench_themselves_one_field')],
['Tiny Swiss Bank Shield','cdn',['zrh'],tr('long_tail.hosts_exactly_one_website_and_three')],
['Clockwork ISP','eye',['zrh'],tr('long_tail.packets_leave_on_time_to_the')],
['LAN-Party Federation','cdn',['ams','fra'],tr('long_tail.game_servers_energy_drinks_and_a')],
['Former Church Datacenter','cdn',['ams'],tr('long_tail.racks_in_the_nave_cooling_in')],
['WISP on a Silo','eye',['dal','chi'],tr('long_tail.wireless_internet_from_the_top_of')],
['Cornfield Broadband','eye',['chi'],tr('long_tail.rural_fiber_that_follows_the_tractor')],
['Moose Lake Telephone Co-op','eye',['tor','mtl'],tr('long_tail.has_served_the_lake_since_1912')],
['Surf Shop Networks','cdn',['lax'],tr('long_tail.hosting_for_surfboard_shops_closed')],
['Ski Lift Fiber','eye',['den','zrh'],tr('long_tail.fiber_strung_along_the_chairlifts')],
['Tumbleweed Telecom','eye',['phx','dal'],tr('long_tail.covers_a_lot_of_empty_ground')],
['Crypto Bro Colo','cdn',['ash','mia'],tr('long_tail.ten_thousand_gpus_and_a_podcast')],
['Ye Olde University Network','eye',['bos','lon'],tr('long_tail.has_had_a_8_since_before')],
['Mom & Pop Packet Shop','eye',['nyc'],tr('long_tail.family_run_since_dial_up_still')],
['Space Cowboy Broadband','eye',['hou','dal'],tr('long_tail.yee_haw_and_low_earth_orbit')],
['Fry Sauce Fibre','eye',['slc'],tr('long_tail.utah_s_dipping_sauce_of_an')],
['Sauna Uplink Oy','cdn',['hel','sto'],tr('long_tail.servers_cooled_by_the_lake_then')],
['Reindeer Relay','eye',['sto','osl','hel'],tr('long_tail.wireless_links_across_the_tundra')],
['Pierogi Hosting','cdn',['waw'],tr('long_tail.cheap_filling_hosting_ask_for_the')],
['Sunflower Uplink','eye',['kyv','waw'],tr('long_tail.kept_the_lights_on_in_its')],
['Tram Line Telecom','eye',['prg','vie'],tr('long_tail.fiber_laid_under_the_tram_tracks')],
['Paprika Peering','eye',['bud'],tr('long_tail.spicy_pricing_mild_latency')],
['Dracula Datacenter','cdn',['buh'],tr('long_tail.only_comes_online_at_night')],
['Bosphorus Ferry Net','eye',['ist'],tr('long_tail.wi_fi_on_every_ferry_backhaul')],
['Gondola Gigabit','eye',['mil','rom'],tr('long_tail.started_in_venice_upgraded_to_land')],
['Nonna’s Pasta Pipes','cdn',['rom','pmo'],tr('long_tail.hosting_for_every_family_restaurant')],
['Tram 28 Telecom','eye',['lis'],tr('long_tail.slow_on_the_hills_fast_on')],
['Olive Grove Online','eye',['ath'],tr('long_tail.rural_broadband_for_the_islands_one')],
['Siesta Server Hotel','cdn',['mad'],tr('long_tail.down_from_2_to_5_p')],
['Bouillabaisse Bits','cdn',['mrs','par'],tr('long_tail.a_rich_mix_of_everything_the')],
['Baguette Bandwidth Associés','eye',['par'],tr('long_tail.delivered_fresh_every_morning')],
['Pub Quiz Internet','eye',['dub','lon'],tr('long_tail.founded_after_a_pub_quiz_by')],
['Gaming Café Net','eye',['lag'],tr('long_tail.internet_cafe_turned_isp_the_gamers')],
['Matatu Mobile Mesh','eye',['nbo'],tr('long_tail.wi_fi_on_minibuses_and_the')],
['Load-Shedding Survivors','eye',['jnb','cpt'],tr('long_tail.has_more_batteries_than_customers')],
['Bollywood Buffer','cdn',['bom','del'],tr('long_tail.three_hour_films_zero_second_start')],
['Hawker Centre Hosting','cdn',['sin','kul'],tr('long_tail.cheap_fast_and_open_late')],
['Karaoke Box Networks','cdn',['tok','osa','icn'],tr('long_tail.lyrics_servers_low_latency_high')],
['Night Market Net','eye',['tpe','hkg'],tr('long_tail.comes_alive_after_dark')],
['Kangaroo Courier','eye',['syd','mel','bne'],tr('long_tail.packets_hop_sometimes_backwards')],
['Hobbit Hole Hosting','cdn',['akl'],tr('long_tail.cosy_racks_under_a_hill_second')],
['Capybara Connect','eye',['sao','poa','bue'],tr('long_tail.gets_along_with_every_other_network')],
['Llama Link','eye',['lim','scl','bog'],tr('long_tail.mountain_wireless_will_spit_at_bad')],
['Supercar Hosting','cdn',['dxb'],tr('long_tail.gold_plated_servers_valet_parking')],
['Tango Transit Co-op','eye',['bue','cor'],tr('long_tail.it_takes_two_to_peer')],
['Bánh Mì Broadband','eye',['sgn'],tr('long_tail.crispy_on_the_outside_cheap_on')],
['Jeepney Jumpnet','eye',['mnl'],tr('long_tail.colourful_crowded_and_gets_you_there')],
['Game Server Gremlins','cdn',['fra','ams','lon','nyc','sjc'],tr('long_tail.hosts_every_game_you_play_at'),0.003],
['Discord-ant Voice Relay','cdn',['ams','fra','ash'],tr('long_tail.voice_chat_for_millions_of_gamers'),0.003],
['Mastodon Instance Herd','cdn',['ber','ams','par'],tr('long_tail.a_thousand_tiny_social_networks_on')],
['Dutch Bike Fibre','eye',['ams'],tr('long_tail.fiber_laid_along_the_bike_lanes')],
['Chip Fab Cleanroom Net','cdn',['tpe','phx'],tr('long_tail.bunny_suits_mandatory_in_the_server')],
['Volunteer Fire Brigade Wi-Fi','eye',['vie','zrh'],tr('long_tail.runs_the_village_network_between')],
['Peach State Hosting','cdn',['atn'],tr('long_tail.sweet_fuzzy_and_surprisingly')],
['Chowder Hosting','cdn',['bos'],tr('long_tail.thick_comforting_and_very_new')],
];
function ixStatic(c){const o=[];if(CITY[c]&&CITY[c].ix)o.push(c);for(const x of XIX)if(x.c===c)o.push(x.id);return o;}
TAIL.forEach(([name,type,home,blurb,sh],i)=>{const h=hstr(name),cand=home.flatMap(ixStatic),ix=[];
if(cand.length){ix.push(cand[h%cand.length]);if(cand.length>1&&(h>>>8)%100<40){const o=cand[(h>>>12)%cand.length];if(!ix.includes(o))ix.push(o);}}
const sel=(h>>>4)%10>=8;
NETS.push({id:'tail'+i,name,asn:200000+(h%190000),type,tail:true,pol:sel?'selective':'open',...(sel?{minIx:1+(h>>>16)%3,minPni:6+(h>>>18)%8}:{}),share:sh||+(0.0006+((h>>>20)%15)*0.0001).toFixed(4),col:`hsl(${h%360} 55% 46%)`,pops:home.slice(),ix,blurb});});
NETS.push(
{id:'ktt',name:'Kay-Tea',asn:4766,type:'eye',pol:'paid',paidFee:5000,perG:90,kr:true,share:.012,col:'#E4002B',pops:['icn','hkg','tok','lax'],ix:[],blurb:tr('long_tail.korea_s_incumbent_sender_pays_every')},
{id:'skb',name:'SK Broadbandit',asn:9318,type:'eye',pol:'paid',paidFee:4000,perG:110,kr:true,share:.01,col:'#EA002C',pops:['icn','hkg','sjc'],ix:[],blurb:tr('long_tail.took_a_streaming_giant_to_court')},
{id:'lgu',name:'LG You-Pay-Plus',asn:3786,type:'eye',pol:'paid',paidFee:3000,perG:80,kr:true,share:.008,col:'#E6007E',pops:['icn','tok'],ix:[],blurb:tr('long_tail.the_plus_is_a_usage_fee')});
NETS.push(
{id:'btt',name:'Bee-Tee',asn:2856,type:'eye',pol:'selective',minIx:10,minPni:30,share:.012,col:'#5514B4',pops:['lon','man','edi','bde'],ix:['lon','man'],blurb:tr('long_tail.the_uk_s_incumbent_buzzes_politely')},
{id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',pol:'selective',minIx:6,minPni:25,share:.008,col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')},
{id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',pol:'selective',minIx:6,minPni:25,share:.007,col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')},
{id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#00A9E0',pops:['osl','svg','sto','cph'],ix:['osl','svg'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')});
NETS.push(
{id:'hwt',name:'Hawaiian Telecombo',asn:36149,type:'eye',pol:'selective',minIx:3,minPni:15,share:.004,up:['ntt','lvl'],col:'#5B2A86',pops:['hnl'],ix:['hnl'],blurb:tr('long_tail.hawaii_s_incumbent_every_plan_comes')},
{id:'gtg',name:'Grand Theft Teleguam',asn:9246,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tat'],col:'#0072CE',pops:['gum','ror','maj','hnl','tok'],ix:['gum','hnl'],blurb:tr('long_tail.guam_s_incumbent_and_the_way')},
{id:'dcp',name:'Docomoco Pacific',asn:3605,type:'eye',pol:'selective',minIx:2,minPni:10,share:.002,up:['ntt'],col:'#E4002B',pops:['gum','ror'],ix:['gum'],blurb:tr('long_tail.guam_s_mobile_network_rice_a')},
{id:'dsp',name:'Digi-Sell Pacific',asn:38442,type:'t2',pol:'open',share:.005,price:9,up:['ntt','tat'],col:'#E2001A',pops:['pom','suv','tbu','apw','syd'],ix:['suv'],blurb:tr('long_tail.phones_on_every_island_from_papua')},
{id:'fnt',name:'FINTEL-ligent',asn:9241,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tly'],col:'#00A3AD',pops:['suv','tbu','apw','ppg','syd','hnl'],ix:['suv'],blurb:tr('long_tail.fiji_s_international_gateway_very')},
{id:'pft',name:'Postes et Télé-Croissant',asn:56055,type:'t2',pol:'selective',minIx:3,minPni:15,share:.003,price:10,up:['tly','cog'],col:'#F7B500',pops:['nou','ppt','syd','lax'],ix:['nou'],blurb:tr('long_tail.runs_the_post_the_phones_and')},
{id:'tkp',name:'Telly-Kom PNG',asn:17828,type:'eye',pol:'selective',minIx:2,minPni:10,share:.003,up:['tat'],col:'#C8102E',pops:['pom'],ix:[],blurb:tr('long_tail.papua_new_guinea_s_state_telco')},
{id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_yours')},
{id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')},
{id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')},
{id:'pnc',name:'PNC-See',asn:9534,type:'eye',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')},
{id:'nta',name:'Never Too Atoll',asn:21581,type:'eye',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')});
NETS.push(
{id:'onc',name:'One Commotion',asn:3855,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')},
{id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')},
{id:'pss',name:'Pretty Sure South Atlantic',asn:210841,type:'t2',pol:'open',share:.0005,price:12,up:['tat'],col:'#7D2B8B',pops:['jam','cpt'],ix:[],blurb:tr('long_tail.the_telco_for_st_helena_ascension')},
{id:'bst',name:'Beastlink',asn:11260,type:'eye',pol:'selective',minIx:2,minPni:10,share:.002,up:['cog','lvl'],col:'#EE3124',pops:['hfx','tor'],ix:['hfx'],blurb:tr('long_tail.atlantic_canada_s_cable_company')});

View file

@ -0,0 +1,15 @@
const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id);
// The networks a PNI with each upstream reaches: the upstream itself plus everyone who buys transit from it.
const PNI_NETS={};for(const n of NETS)PNI_NETS[n.id]=[n.id].concat(NETS.filter(x=>x.up&&x.up.includes(n.id)).map(x=>x.id));
for(const X of XIX){X.members=NETS.filter(n=>Array.isArray(n.ix)&&n.ix.includes(X.id)||!n.tail&&(X.core?X.core.includes(n.id):(n.ix==='ALL'||Array.isArray(n.ix)&&n.ix.includes(X.c))&&hstr(n.id+'|'+X.id)%100<(n.ix==='ALL'?72:X.take*100))).map(n=>n.id);}
const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/t);}
// After Glitch leaves Korea, Seoul viewers watch half as much of it and the rest moves to everyone else.
const NSH_KRX={}; {const w=id=>NSH[id]*(id==='amz'?0.5:1),t=NETS.reduce((a,n)=>a+w(n.id),0); NETS.forEach(n=>NSH_KRX[n.id]=w(n.id)/t);}
const CN_W={ctc:.2,cun:.14,cmb:.08,tcs:.22,abc:.14,byd:.08,bdc:.08,akm:.02,msf:.02,amz:.01,drz:.01};
const RU_W={ydx:.24,vkl:.12,rtc:.14,ggl:.12,bdc:.08,akm:.05,cfl:.06,msf:.04,amz:.03,tly:.02,cog:.02,drz:.01};
const NSH_RU={}; {const t=Object.values(RU_W).reduce((a,b)=>a+b,0); for(const k in RU_W)NSH_RU[k]=RU_W[k]/t;}
const NSH_CN={}; {const t=Object.values(CN_W).reduce((a,b)=>a+b,0); for(const k in CN_W)NSH_CN[k]=CN_W[k]/t;}
const CN_BLOCKED=NETS.filter(n=>!CN_W[n.id]&&n.type==='cdn').map(n=>n.name);
const TYPE_L={t1:tr('common.tier_1'),t2:tr('common.tier_2'),cdn:tr('common.cdn_content'),eye:tr('common.eyeballs')};
const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).map(w=>w[0]).join('').slice(0,3).toUpperCase();

View file

@ -0,0 +1,63 @@
/* ================= BUSINESSES ================= */
const BIZ_T={
dia:{l:tr('common.enterprise_dia'),opts:[1,2,5,10],rate:600},
game:{l:tr('common.game_servers'),gaming:true,opts:[5,10,20,40],rate:120},
host:{l:tr('common.hosting'),opts:[10,20,40,80],rate:60},
isp:{l:tr('businesses.downstream_isp_buys_transit'),opts:[100,200,400,800],rate:15,lv:2},
l2vpn:{l:tr('common.l2vpn_circuit'),opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1},
fabip:{l:tr('businesses.customer_on_a_fabric_transit_over'),opts:[1,5,10,25],rate:110,nni:true,lv:2},
fabl2:{l:tr('businesses.fabric_circuit_to_one_of_your'),opts:[1,5,10],rate:0,l2:true,nni:true,km:0.8,lv:2},
stream:{l:tr('common.streaming_startup'),opts:[50,100,200],rate:80,lv:2},
edu:{l:tr('common.university_network'),opts:[20,50,100],rate:90,lv:2},
gpu:{l:tr('businesses.ai_gpu_data_center'),opts:[200,400,800],rate:70,lv:3,names:['Neural Noodles AI','GPUs R Us','Hallucination Labs','Transformers & Sons','Token Burners Inc.','Very Large Language Co.','Prompt Engineering Ltd','DeepThought Farms','Parameter Pastures','Gradient Descent Diner','Attention Is All We Need LLC','Overfit Analytics']},
onramp:{l:tr('businesses.cloud_on_ramp'),opts:[100,200,400],rate:0,l2:true,km:0.7,lv:3,names:["Amazin' Web Services on-ramp","Microsnoft Azzure on-ramp",'Goggle Cloud on-ramp','AliBubble Cloud on-ramp','Miracle Cloud on-ramp']},
ai:{l:tr('businesses.ai_training_interconnect'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.9,lv:4,names:['Skynot Compute','Galaxy Brain Training Run','Megawatt Minds','The Big Model Co.','Infinite Context Corp','Sentient Spreadsheet Inc.']},
hyper:{l:tr('common.hyperscaler_dci'),opts:[1600,3200,6400],rate:0,l2:true,div:true,km:0.5,lv:4,names:["Amazin' Web Services DCI","Microsnoft Azzure DCI",'Goggle Cloud DCI','Faceplant Infra DCI','AliBubble Cloud DCI']},
hft:{l:tr('businesses.high_frequency_trading_link'),opts:[1,5,10],rate:0,l2:true,lat:true,km:6,lv:2,names:['Flash Boys Capital','Nanosecond Nancy Trading','Speed of Light Securities','Arbitrage & Sons','Front-Run Fund','Microwave Tower Capital','Tick-Tock Quant','Low Latency Larry LLC']},
bulk:{l:tr('businesses.bulk_backup_transfer_latency_does'),opts:[100,200,400],rate:0,l2:true,scenic:true,km:0.1,lv:2,names:['Glacier Slow Storage','Tape Backup Tortoise','Scenic Route Archives','Cold Storage Cold Cuts','Sloth Sync','Eventually Consistent Inc.','Snail Mail Data Co.']},
event:{l:tr('common.event_network'),opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['Carnaval Parade','Diwali Streaming Night','The Big Football Final','NANOG 99','Burning Router Festival','Euro-Pop Song Contest','Formula Ping Grand Prix','The Big Game','Olympic Pings','A Pop Megastar Stadium Tour','LAN Party of the Century','The Keynote (One More Thing)','Gamer-Con Expo','Oktoberfest Livestream']},
sdwan:{l:tr('businesses.sd_wan_for_a_chain'),opts:[1,2,5,10],rate:0,l2:true,sdwan:true,km:0,lv:2,names:['Kebab Kingdom','Pretzel Palace','Burger Router Inc.','Café Latte-ncy','Hardware Hut Stores','Pharma-See Pharmacies','Bank of Tiny Branches','Supermarket Superhighway','Fitness Pings Gyms','Hotel Hops Group','Doughnut Data Diners']},
wwave:{l:tr('common.wholesale_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','G&T (Gin and Transit)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']},
dfpair:{l:tr('businesses.dark_fiber_pair_lease'),opts:[1],rate:0,fiber:true,lv:3,names:['A Hyperscaler Who Shall Not Be Named','Goggle Fiber Division','Faceplant Infra','Amazin’ Backbone Team','A Very Secretive Trading Firm']},
scrub:{l:tr('businesses.ddos_protection_dia'),opts:[1,5,10,20],rate:900},
aiwan:{l:tr('businesses.ai_wan_between_two_ai_factories'),opts:[3200,6400,12800],rate:0,l2:true,div:true,mega:true,km:0.45,lv:4,names:['Fairweather AI WAN','Planet-Scale Superfactory Link','Two Brains One Model Inc.','Distributed Godlike Compute','The Gigawatt Handshake']},
mtrain:{l:tr('businesses.multi_site_training_run'),opts:[1600,3200,6400],rate:0,l2:true,sdwan:true,mega:true,lv:4,names:['Gem-in-Eye Ultra Training Run','Frontier Model 9000','The Very Big Model','Checkpoint-Free Training Co.','Model Too Big For One Building']},
ingest:{l:tr('businesses.dataset_ingest_elephant_flow'),opts:[1600,3200,6400],rate:0,event:true,mega:true,lv:3,names:['Scrape-the-Whole-Web Ingest','Checkpoint Sync Storm','Video Dataset Firehose','Every Book Ever (allegedly licensed)','Synthetic Data Tsunami']},
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']},
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']},
mars:{l:tr('businesses.mars_mission_ground_station'),opts:[100,200,400],rate:0,l2:true,lat:true,km:4,lv:13,names:['Red Planet Relay','Ares Ground Segment','Olympus Mons Uplink','Mars or Bust Mission Control','Interplanetary Ping Society','Light-Minute Logistics','RFC 1149 Avian Carriers (Mars Division)']},
provedor:{l:tr('businesses.provedor_small_regional_isp'),opts:[5,10,20,40],rate:20,br:true,names:['Provedor Capivara Net','Fibra do Sertão','Rapidinho Telecom','Net Jabuticaba','Caipirinha Online','Wi-Fi do Zé','Pão de Queijo Fibra','Açaí Net','Tucano Telecom','Forró Fibra','Saci Net','Brigadeiro Banda Larga','Mandioca Online','Churrasco Connect']},
};
const LEVELS=[
{n:tr('common.local_isp'),q:tr('businesses.your_network_diagram_is_a_photo'),req:tr('common.start_here'),unlock:tr('businesses.enterprises_game_servers_hosting')},
{n:tr('common.regional_player'),q:tr('businesses.you_now_have_a_change_freeze'),req:tr('businesses.peak_200_gbps_and_3_pops'),unlock:tr('businesses.downstream_isps_streaming_startups')},
{n:tr('common.serious_backbone'),q:tr('businesses.it_s_not_dns_there_s'),req:tr('businesses.peak_1_tbps_and_6_pops'),unlock:tr('businesses.ai_gpu_data_centers_and_cloud')},
{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.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')},
{n:tr('businesses.internet_weather_system'),q:tr('businesses.when_your_bgp_sneezes_a_small'),req:tr('businesses.peak_33_tbps_and_60_pops'),unlock:tr('businesses.agi_labs_allegedly_wanting_ai_wans')},
{n:tr('businesses.too_big_to_route'),q:tr('businesses.your_last_fat_fingered_route_leak'),req:tr('businesses.peak_40_tbps_and_70_pops'),era:1.25,unlock:tr('businesses.the_ai_agent_era_eyeballs_want')},
{n:tr('common.the_internet'),q:tr('businesses.people_phone_you_to_ask_if'),req:tr('businesses.peak_50_tbps_and_80_pops'),unlock:tr('businesses.mars_mission_ground_stations_gear')},
];
// What each level asks for (peak Gbps, POPs, continents). Continents carry over to the levels above.
const LV_REQ=[null,{pk:200,pops:3},{pk:1000,pops:6},{pk:3000,pops:10,reg:3},{pk:6000,pops:15,reg:4},{pk:9000,pops:20},{pk:12000,pops:25,reg:5},{pk:16000,pops:32},{pk:21000,pops:40,reg:6},{pk:26000,pops:50},{pk:33000,pops:60},{pk:40000,pops:70},{pk:50000,pops:80}];
const lvReg=i=>Math.max(0,...LV_REQ.slice(1,i+1).map(q=>q.reg||0));
const lvl=()=>(S&&S.lvl)||1;
// Lower-case just the first word for mid-sentence use, so names like Tel-Mess or AGI keep their capitals.
const lc1=t=>/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t;
function custLevel(){const pops=Object.keys(S.pops).length,pk=S.stats.peak,rc=regionsCount();let lv=1;for(let i=1;i<LV_REQ.length;i++){const q=LV_REQ[i];if(pk>=q.pk&&pops>=q.pops&&rc>=lvReg(i))lv=i+1;else break;}return lv;}
// Traffic eras: some levels bring a new reason to watch more video, and every city's eyeballs grow toward more.
const eraMul=()=>LEVELS.slice(0,lvl()).reduce((a,L)=>a*(L.era||1),1);
const eyeP=c=>CITY[c].P*eraMul();
// New broadband starts small, but never above what the town can grow to (St Helena has 4,500 people).
const bbStart=c=>Math.min(eyeP(c),Math.max(8,CITY[c].P*0.03));
const BIZ_N=['Byte-Size Bakery','Hamster Wheel Power Co.','Llama Logistics','Cloud Nine Hosting','Rural Rabbit Broadband','Tiny Telco','Pixel Pirates Games','Moo-Moo Dairy Corp','Snack Overflow','Git Happens Ltd','Kernel Sanders Fried Code','Lag-Free Llamas','404 Bistro','Ping Pong Sports','Null Pointer Pets','Buffer Bloat Boats','Packet Pizza','Latency Lattes','Ctrl-Alt-Deli','Sudo Sandwiches','Cache Me Outside','Hertz So Good Radio','Jitterbug Dance Hall','Bit Barn Hosting','Fiber Optimists','The Daily Ping','Squirrel Mesh Wireless','Spam & Eggs Diner','Router Rooter Plumbing','Kilobyte Kebab','Gigglebit Studios','Uptime Funk Records','Ohm Sweet Ohm','Dial-Up Nostalgia Club','Two-Factor Tacos'];

View file

@ -0,0 +1,23 @@
/* ================= GOALS ================= */
const GOALS=[
{id:'bb',t:tr('goals.light_up_your_first_customers'),d:tr('goals.open_your_home_city_and_press'),r:5000,ok:()=>Object.values(S.pops).some(p=>p.bb)},
{id:'tr',t:tr('goals.reach_the_whole_internet'),d:tr('goals.your_eyeballs_want_everything_buy_ip'),r:5000,ok:()=>S.transit.length>0},
{id:'ix',t:tr('goals.join_an_internet_exchange'),d:tr('goals.get_a_port_at_an_ix'),r:7500,ok:()=>Object.keys(S.ixp).length>0},
{id:'p5',t:tr('goals.make_5_peering_friends'),d:tr('goals.on_the_peering_tab_request_sessions'),r:10000,ok:()=>R.sessions>=5},
{id:'ln',t:tr('goals.lay_your_first_fiber'),d:tr('goals.drag_from_your_pink_router_to'),r:10000,ok:()=>S.links.length>0},
{id:'bz',t:tr('goals.sign_a_business_customer'),d:tr('goals.businesses_show_up_with_a_bubble'),r:12500,ok:()=>S.biz.some(b=>!b.scripted)},
{id:'rd',t:tr('goals.survive_a_failure'),d:tr('goals.things_break_all_the_time_build'),r:12500,ok:()=>S.stats.survived>0},
{id:'ca',t:tr('goals.host_an_embedded_cache'),d:tr('goals.big_cdns_give_you_free_cache'),r:12500,ok:()=>S.caches.length>0},
{id:'pn',t:tr('goals.set_up_a_pni'),d:tr('goals.a_private_cross_connect_to_one'),r:15000,ok:()=>S.pni.some(pniOn)},
{id:'scrub',t:tr('goals.stand_up_ddos_defences'),d:tr('goals.build_a_scrubbing_center_from_a'),r:20000,ok:()=>hasScrub()},
{id:'c3',t:tr('common.go_global'),d:tr('goals.have_pops_on_3_continents_subsea'),r:50000,ok:()=>regionsCount()>=3},
{id:'t2',t:tr('goals.become_a_tier_2'),d:tr('goals.5_pops_ports_on_3_ixs'),r:50000,ok:()=>isTier2()},
{id:'tb',t:tr('goals.serve_1_tbps'),d:tr('goals.a_terabit_per_second_of_happy'),r:75000,ok:()=>R.served>=1000},
{id:'df',t:tr('goals.light_your_own_dark_fiber'),d:tr('goals.lease_or_dig_dark_fiber_put'),r:40000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)},
{id:'m2',t:tr('goals.be_in_two_buildings_at_once'),d:tr('goals.add_a_second_site_in_a'),r:30000,ok:()=>Object.values(S.pops).some(p=>p.site2)},
{id:'c5',t:tr('common.five_continents'),d:tr('goals.pops_in_five_of_the_six'),r:100000,ok:()=>regionsCount()>=5},
{id:'gi',t:tr('goals.sign_a_giant'),d:tr('goals.land_an_ai_wan_a_multi'),r:150000,ok:()=>S.biz.some(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega&&!BIZ_T[b.type].event)},
{id:'t10',t:tr('goals.serve_10_tbps'),d:tr('goals.ten_terabits_per_second_of_happy'),r:250000,ok:()=>R.served>=10000},
{id:'t1',t:tr('common.go_transit_free_tier_1'),d:tr('goals.peer_with_every_tier_1_over'),r:0,win:true,ok:()=>isTier1()},
];

5
src/game/50-state.js Normal file
View file

@ -0,0 +1,5 @@
/* ================= STATE ================= */
let S=null, R=emptyR();
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false};
let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++);
function emptyR(){return {nt:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{}};}

View file

@ -0,0 +1,109 @@
/* ================= BANKS & LOANS =================
Lenders make offers now and then (more often when you are broke). Each loan
is a fixed monthly payment that shows up in your costs; conditions are checked
daily and breaking one costs a penalty. */
const BANKS={
gs:{name:'Goldman Sacks',col:'#6F8FAF',min:'AA',apr:[.07,.11],amt:[4,9],term:[24,48],covs:['peer30','continents2','golf','yacht'],blurb:tr('banks.only_lends_to_people_who_do')},
db:{name:'Deutsche Bankrupt',col:'#0018A8',min:'A',apr:[.08,.13],amt:[3,7],term:[18,36],covs:['nocog','gen','fax'],blurb:tr('banks.very_solid_mostly')},
jpm:{name:'JP Morgain',col:'#5B4636',min:'A',apr:[.09,.14],amt:[3,6],term:[12,36],covs:['uptime','logo','nephew'],blurb:tr('banks.lends_you_money_and_also_a')},
cs:{name:'Credit Sweaty',col:'#7A9CC6',min:'BBB',apr:[.11,.17],amt:[2,5],term:[12,30],covs:['cash50','nochina'],blurb:tr('banks.nervous_but_enthusiastic')},
wf:{name:'Wells Far-Gone',col:'#D71E28',min:'BB',apr:[.12,.18],amt:[2,4],term:[12,24],covs:['nosub','logo','reach99'],blurb:tr('banks.opened_three_accounts_for_you_while')},
spk:{name:'Spätzle-Sparkasse',col:'#E30613',min:'B',apr:[.05,.08],amt:[1,3],term:[24,60],covs:['spaetzle','kehrwoche'],blurb:tr('banks.cheap_patient_and_very_particular')},
rev:{name:'Revoloot',col:'#191C1F',min:'B',apr:[.13,.2],amt:[1,3],term:[6,18],covs:['app'],blurb:tr('banks.instant_approval_instant_regret')},
gov:{name:'Ministry of Tubes',col:'#2E7D32',min:'CCC',apr:[.01,.02],amt:[1,2],term:[36,60],covs:['rural','forms'],blurb:tr('banks.cheap_state_money_for_connecting_the')},
crypto:{name:'Crypto Bros Capital',col:'#F7931A',min:'CCC',apr:[.15,.25],amt:[2,6],term:[6,18],covs:['hodl','tier3'],crypto:true,blurb:tr('banks.pays_out_in_tubecoin_value_may')},
vult:{name:'Venture Vultures',col:'#8E44AD',min:'CCC',amt:[6,12],share:[.1,.15],covs:['blitz'],equity:true,blurb:tr('banks.no_repayments_ever_just_a_slice')},
balloon:{name:'Ballooney Brothers',col:'#E91E63',min:'B',apr:[.1,.15],amt:[2,6],term:[12,24],covs:['oddpops'],model:'balloon',blurb:tr('banks.no_payments_at_all_until_the')},
storm:{name:'Stormy Weather Lending',col:'#546E7A',min:'BB',apr:[.04,.06],amt:[2,5],term:[12,36],covs:['nogen'],model:'storm',blurb:tr('banks.cheap_while_the_sun_shines_every')},
ppp:{name:'Peer Pressure Partners',col:'#00897B',min:'B',amt:[2,5],term:[24,36],covs:['nocache'],model:'transit',blurb:tr('banks.you_repay_with_30_of_your')},
astro:{name:'Horoscope Holdings',col:'#5E35B1',min:'CCC',apr:[.02,.3],amt:[1,4],term:[12,24],covs:['friday','nobude'],model:'astro',blurb:tr('banks.your_rate_is_set_by_the')},
pizza:{name:'Papa Pizza Capital',col:'#FF7043',min:'BB',apr:[.03,.05],amt:[1,3],term:[12,24],covs:['pizza'],blurb:tr('banks.the_cheapest_money_in_town_there')},
shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:tr('banks.always_open_ask_no_questions_do')},
};
const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA'];
const COVS={
peer30:{l:tr('banks.keep_your_peering_ratio_above_30'),ok:()=>(R.peerShare||0)>=0.3},
continents2:{l:tr('banks.keep_pops_on_at_least_2'),ok:()=>regionsCount()>=2},
golf:{l:tr('banks.your_ceo_plays_golf_with_our'),ok:()=>true},
nocog:{l:tr('banks.no_cogentle_transit_anywhere_our_ceo'),ok:()=>!S.transit.some(t=>t.net==='cog')},
gen:{l:tr('banks.every_pop_needs_a_backup_generator'),ok:()=>Object.values(S.pops).every(p=>p.gen)},
fax:{l:tr('banks.send_us_your_monthly_report_by'),ok:()=>true},
uptime:{l:tr('banks.deliver_at_least_95_of_what'),ok:()=>!R.demand||R.served/R.demand>=0.95},
logo:{l:tr('banks.our_logo_goes_on_every_router'),ok:()=>true},
cash50:{l:tr('banks.never_let_cash_drop_below_50k'),ok:()=>S.cash>=50000},
nochina:{l:tr('banks.stay_out_of_mainland_china'),ok:()=>!Object.keys(S.pops).some(cnCity)},
nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)},
spaetzle:{l:tr('banks.peer_at_the_spatzle_ix_in'),ok:()=>S.ixp.stg!==undefined},
kehrwoche:{l:tr('banks.do_the_kehrwoche_keep_your_noc'),ok:()=>!S.inc.some(i=>S.day-i.start>7)},
app:{l:tr('banks.download_our_app_and_enable_all'),ok:()=>true},
rural:{l:tr('banks.run_home_broadband_somewhere'),ok:()=>Object.keys(S.pops).some(c=>S.pops[c].bb&&['AS','AF','OC','SA'].includes(CITY[c].reg))},
forms:{l:tr('banks.fill_in_form_t_17b_in'),ok:()=>true},
hodl:{l:tr('banks.never_sell_your_tubecoin_diamond'),ok:()=>true},
oddpops:{l:tr('banks.always_run_an_odd_number_of'),ok:()=>Object.keys(S.pops).length%2===1},
nobude:{l:tr('banks.never_build_in_bude_the_loan'),ok:()=>!S.pops.bde},
nogen:{l:tr('banks.no_diesel_generators_anywhere_our'),ok:()=>!Object.values(S.pops).some(p=>p.gen)},
friday:{l:tr('banks.no_new_links_on_a_friday'),ok:l=>!S.links.some(x=>(x.day||0)>=l.start&&(x.day||0)%7===4)},
nocache:{l:tr('banks.no_goggle_cache_boxes_our_chairman'),ok:()=>!S.caches.some(c=>c.net==='ggl')},
reach99:{l:tr('banks.reach_99_of_the_internet_at'),ok:()=>(R.reach||0)>=0.99},
tier3:{l:tr('banks.stay_tier_3_number_go_up'),ok:()=>tierLabel()==='Tier 3'},
nephew:{l:tr('banks.give_our_ceo_s_nephew_a'),fee:3000,ok:()=>true},
yacht:{l:tr('banks.our_chairman_needs_a_yacht_for'),fee:8000,ok:()=>true},
pizza:{l:tr('banks.pizza_for_the_whole_noc_after'),each:400,ok:()=>true},
blitz:{l:tr('banks.open_a_new_pop_at_least'),ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90},
};
// Conditions read with their price filled in; some cost money every month, one costs money per incident.
const covLabel=c=>COVS[c]?COVS[c].l.replace('{price}',fmt$(COVS[c].fee||COVS[c].each||0)):c;
const loanFees=l=>(l.covs||[]).reduce((a,c)=>a+((COVS[c]&&COVS[c].fee)||0),0);
// Good terms are for good credit: every notch below AAA adds to the rate.
const RATE_PREM={AAA:0,AA:.005,A:.01,BBB:.02,BB:.04,B:.07,CCC:.12,C:.2};
// A loan worth more than this many months of revenue also wants a slice of revenue until it is repaid.
const BIG_LOAN=5;
const STAR_SIGNS=[N_('common.mercury'),N_('common.saturn'),N_('common.venus'),N_('banks.your_rising_sign'),N_('common.the_moon'),N_('banks.pluto_which_is_not_even_a')];
function niceAmt(v){const m=Math.pow(10,Math.floor(Math.log10(Math.max(1,v)))-1);return Math.max(50000,Math.round(v/m)*m);}
function rating(){if(!S)return 'BB';const rev=R.revMo||0,pay=(R.cost&&R.cost.loans)||0;let sc=2;
if(rev>100000)sc++;if(rev>500000)sc++;if(rev>2000000)sc++;if(R.revMo>R.costMo)sc++;else sc--;if(rev&&(R.revMo-R.costMo)/rev>=0.25)sc++;
if(S.cash<0)sc-=2;if(rev&&pay/rev>0.3)sc--;if(rev&&pay/rev>0.6)sc--;sc-=Math.min(3,S.loanStrikes||0);
return RATINGS[clamp(sc,0,RATINGS.length-1)];}
const rIdx=r=>RATINGS.indexOf(r);
function annuity(P,apr,n){const r=apr/12;return r?P*r/(1-Math.pow(1+r,-n)):P/n;}
function spawnLoanOffer(emergency){
const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k)));
let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk','astro','balloon'].includes(k)):keys.filter(k=>k!=='shark');if(!pool.length)pool=keys;if(!pool.length)return;
const k=pick(pool),B=BANKS[k],base=Math.max(60000,R.revMo||0),ra=(a)=>a[0]+Math.random()*(a[1]-a[0]);
const amount=niceAmt(base*ra(B.amt)*(emergency?0.6:1)),o={id:uid(),bank:k,amount,exp:S.day+(emergency?10:25),covs:B.covs.slice()};
if(B.equity){o.share=+ra(B.share).toFixed(3);}
else if(B.model==='transit'){o.model='transit';o.cut=0.3;o.term=Math.round(ra(B.term)/6)*6||6;o.owe=Math.round(amount*1.3);o.apr=0;o.pay=0;}
else{o.apr=+(ra(B.apr)+(RATE_PREM[rt]||0)).toFixed(3);o.term=Math.round(ra(B.term)/6)*6||6;o.pay=B.model==='balloon'?0:Math.round(annuity(amount,o.apr,o.term));if(B.model)o.model=B.model;}
if(!B.equity&&amount>BIG_LOAN*base)o.share=+Math.min(0.08,0.02+0.01*(amount/base-BIG_LOAN)).toFixed(3);
S.loanOffers.push(o);
toast(tr('banks.bank_would_like_to_lend_you',{bank:esc(B.name),amount:fmt$(amount)})+'<br>'+(emergency?tr('banks.they_heard_you_might_be_in'):tr('banks.terms_apply_several_terms')),emergency?'bad':'goal',[{l:tr('common.open_bank'),act:'bank',args:{}}]);
}
function loanTick(d){
// conditions: 15-day grace, then a penalty every 30 days while broken
for(const l of S.loans){const B=BANKS[l.bank];
const broken=l.covs.filter(c=>COVS[c]&&!COVS[c].ok(l));
if(d-l.start<15||!broken.length){l.breach=0;continue;}
l.breach=(l.breach||0)+1;
if(l.breach===1)toast(tr('banks.bank_is_unhappy_you_broke_a',{bank:esc(B.name),cond:esc(covLabel(broken[0]))}),'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]);
if(l.breach===10||(l.breach>10&&(l.breach-10)%30===0)){
if(B.equity){l.share=+(l.share+0.02).toFixed(3);toast(tr('banks.bank_are_circling_they_now_take',{bank:esc(B.name),pct:pct(l.share)}),'bad');}
else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(tr('banks.penalty_from_bank_fee_added_to',{bank:esc(B.name),fee:fmt$(fee),pay:fmt$(l.pay)}),'bad');}
sfx('err');}}
// monthly statement: payments already leave your cash daily as part of costs
for(const l of S.loans.slice()){const B0=BANKS[l.bank];if(B0.equity||(d-l.start)%30!==0||d===l.start)continue;
if(l.model==='transit')l.bal=Math.max(0,l.bal-Math.round(((R.cost&&R.cost.transit)||0)*(l.cut||0.3)));else l.bal=Math.max(0,l.bal*(1+l.apr/12)-l.pay);l.left--;
// A balloon, or what a transit-free network never paid, is due in one go at the end.
if(l.left<=0&&l.bal>=1&&(l.model==='balloon'||l.model==='transit')){S.cash-=Math.round(l.bal);toast(tr('banks.bank_the_balloon_popped_the',{bank:esc(B0.name),price:fmt$(l.bal)}),'bad');sfx('err');l.bal=0;}
if(l.left>0&&l.bal>=1){if(l.model==='storm'){l.apr=+((l.apr0||0)+0.02*S.inc.length).toFixed(3);l.pay=Math.round(annuity(l.bal,l.apr,l.left));}
else if(l.model==='astro'){const a=+(0.02+Math.random()*0.28).toFixed(3);if(Math.abs(a-l.apr)>=0.08)toast(tr('banks.bank_sign_is_in_retrograde_your',{bank:esc(B0.name),sign:tr(pick(STAR_SIGNS)),apr:(a*100).toFixed(1)}),a>l.apr?'bad':'good');l.apr=a;l.pay=Math.round(annuity(l.bal,l.apr,l.left));}}
if(l.left<=0||l.bal<1){S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');toast(tr('banks.loan_from_bank_paid_off_they',{bank:esc(BANKS[l.bank].name)}),'good');sfx('coin');}}
// the shark's collectors come by when you are broke
if(S.cash<0&&S.loans.some(l=>BANKS[l.bank].shark)&&Math.random()<0.03){const c=pick(Object.keys(S.pops));const p=S.pops[c];p.down=Math.max(p.down||0,d+1);const en=N_('banks.two_very_large_gentlemen_from_loan');addInc({type:'shutdown',ref:c,until:d+1,msg:tr(en,{city:CITY[c].name}),cost:0},en);toast(tr('banks.the_loan_shark_sent_a_reminder',{city:CITY[c].name}),'bad');sfx('alert');}
// offers: now and then, and much more often when you are in trouble
S.loanOffers=S.loanOffers.filter(o=>o.exp>d);
const broke=S.cash<0;
// With half a billion in the vault, loan offers are just noise (#52): banks stop calling, open offers lapse.
if(S.cash>=RICH_NO_LOANS){if(S.loanOffers.length||!S.richTold){S.loanOffers=[];if(!S.richTold&&S.mode!=='sandbox'){S.richTold=1;toast(tr('banks.the_banks_have_stopped_calling_you',{cash:fmt$(RICH_NO_LOANS)}),'good');}}return;}
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
}
const RICH_NO_LOANS=5e8;

View file

@ -0,0 +1,40 @@
/* Seeded games (scenarios, weekly challenge) draw every random number from S.rng, so the same seed
gives the same world. Free play keeps using the browser's Math.random. */
const _rand=Math.random;
Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();};
function isoWeek(dt){const d=new Date(Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate()));const n=d.getUTCDay()||7;d.setUTCDate(d.getUTCDate()+4-n);const y0=new Date(Date.UTC(d.getUTCFullYear(),0,1));return {y:d.getUTCFullYear(),w:Math.ceil(((d-y0)/864e5+1)/7)};}
const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g;
function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)<g)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l))continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// Looked up rather than read from the save, so it follows a language switch mid-scenario.
const scnName=()=>S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name;
const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size;
const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined).length;
const SCN=[
{id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_45_of_the_internet_and'),ok:()=>R.reach>=0.45&&R.served>=300},
{id:'redsea',n:tr('scenarios.red_sea_crisis'),city:'mrs',cash:2500000,days:540,rules:{banCities:['cai','jed'],banPairs:['eig:dxb-mrs','gbi:fuj-mrs','smw4:khi-mrs','smw6:mrs-bom','smw6:mrs-sin','peace:mrs-sin','aae:mrs-hkg','twoaf:mrs-bom','medn:cai-mrs','medn:ist-mrs','twoaf:jnb-mrs','eassy:nbo-mrs']},d:tr('scenarios.every_cable_through_the_red_sea'),goal:tr('scenarios.a_path_from_marseille_to_singapore'),ok:()=>pathExists('mrs','sin')&&(S.stats.asiaRun||0)>=RS_DAYS},
{id:'spat',n:tr('scenarios.the_cogentle_spat'),city:'nyc',cash:700000,days:540,rules:{spat:true},d:tr('scenarios.cogentle_and_goggle_are_not_speaking'),goal:tr('scenarios.99_reach_and_150_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=150},
{id:'carnaval',n:tr('common.carnaval'),city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),scripted:true,city:'rio',city2:null,reqs:[],name:'Carnaval Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:tr('scenarios.rio_from_scratch_carnaval_starts_in'),goal:tr('scenarios.deliver_carnaval_in_full'),ok:()=>(S.stats.evFull||0)>=1},
{id:'darien',n:tr('common.mind_the_gap'),city:'pan',cash:900000,days:730,rules:{},d:tr('scenarios.start_in_panama_city_nothing_crosses'),goal:tr('scenarios.pops_in_bogota_lima_santiago_and'),ok:()=>['bog','lim','scl','sao'].every(c=>S.pops[c])&&R.served>=150},
{id:'c2c',n:tr('scenarios.cape_to_cairo'),city:'cpt',cash:2000000,days:1095,rules:{},d:tr('scenarios.cape_town_build_a_network_across'),goal:tr('scenarios.a_path_from_cape_town_to'),ok:()=>pathExists('cpt','cai')&&S.pops.lag&&S.pops.nbo&&R.served>=150},
{id:'ixbr',n:tr('scenarios.order_and_progress'),city:'sao',cash:2500000,days:1095,rules:{},d:tr('scenarios.sao_paulo_brazil_is_a_continent'),goal:tr('scenarios.ports_on_15_ix_brrr_exchanges'),ok:()=>brIxN()>=15&&S.ixp.mao!==undefined&&R.served>=200},
{id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:365,rules:{},d:tr('scenarios.seoul_the_fastest_hungriest_eyeballs'),goal:tr('scenarios.99_reach_and_200_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=200},
{id:'flood',n:tr('common.flood_season'),city:'ams',cash:2000000,days:365,rules:{ddos:true},setup:()=>{S.lvl=Math.max(S.lvl||1,3);},d:tr('scenarios.amsterdam_hosting_capital_of_europe'),goal:tr('scenarios.hold_20_floods_5_of_them'),ok:()=>(S.stats.ddosOk||0)>=20&&(S.stats.ddosOkBig||0)>=5},
{id:'fttb',n:tr('scenarios.fibre_to_the_basement'),city:'syd',cash:1500000,days:730,rules:{levy:true},d:tr('scenarios.sydney_2013_the_toilet_paper_group'),goal:tr('scenarios.broadband_in_sydney_melbourne'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2},
{id:'baltic',n:tr('common.anchors_away'),city:'tll',cash:500000,days:540,rules:{anchors:3},d:tr('scenarios.tallinn_ships_drag_their_anchors'),goal:tr('scenarios.90_days_in_a_row_with'),ok:()=>(S.stats.clean||0)>=90},
{id:'pac',n:tr('common.stepping_stones'),city:'hnl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.honolulu_in_the_middle_of_the'),goal:tr('scenarios.a_path_from_los_angeles_to'),ok:()=>fastPath('lax','syd',1600)&&pathExists('lax','tok')&&R.served>=150},
{id:'atl',n:tr('scenarios.mid_atlantic_accent'),city:'pdl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.ponta_delgada_in_the_azores_halfway'),goal:tr('scenarios.1_6t_on_every_hop_from'),ok:()=>fastPath('mia','mad',1600)&&fastPath('lis','lag',1600)&&R.served>=100},
];
const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg'];
const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chaos',n:tr('scenarios.twice_the_failures')},{id:'poor',n:tr('scenarios.start_with_only_100k')},{id:'boom',n:tr('scenarios.eyeballs_grow_50_faster')},{id:'dk',n:tr('scenarios.every_ix_is_run_by_de')},{id:'sharks',n:tr('scenarios.shark_season_subsea_cuts_twice_as')}];
function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};}
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}newGame(nm,city);S.mode=o.mode||'normal';
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;S.nextFail=1e9;S.nextEvent=1e9;}
if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000);
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?tr('scenarios.sandbox_mode_a_billion_dollars_every'):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
renderAll();save();if(!S.scn&&S.mode!=='sandbox')tutorialStart();}

View file

@ -0,0 +1,15 @@
/* ---------- conference season ---------- */
const CONFS=[{n:'NANOG',c:'chi',m:1},{n:'APRICOT',c:'sin',m:1},{n:'Peering Days',c:'waw',m:2},{n:'DKNOG',c:'cph',m:2,j:N_('conferences.the_hallway_track_moved_to_a')},{n:'UKNOF',c:'lon',m:3},{n:'MENOG',c:'dxb',m:3},{n:'NZNOG',c:'akl',m:3},{n:'RIPE',c:'ams',m:4},{n:'NANOG',c:'sea',m:5},{n:'IX Forum',c:'tok',m:6},{n:'AfPIF',c:'nbo',m:7},{n:'AusNOG',c:'syd',m:8},{n:'NLNOG Day',c:'ams',m:8},{n:'LACNOG',c:'sao',m:9},{n:'NANOG',c:'ash',m:9},{n:'DENOG',c:'fra',m:10},{n:'RIPE',c:'ber',m:10},{n:'PTT Forum',c:'sao',m:11},{n:'PacNOG',c:'suv',m:11}];
const CONF_COST=8000,CONF_DAYS=45;
const confDay=(cf,y)=>y*360+cf.m*30+9;
function confKey(cf,y){return cf.n+'@'+cf.c+'@'+y;}
function upcomingConfs(within){const y0=Math.floor(S.day/360),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'}}]);}
for(const cf of upcomingConfs(0)){if(cf.day!==d||!S.confReg[cf.key])continue;const reg=CITY[cf.c].reg;S.conf={until:d+CONF_DAYS,reg,name:cf.n};S.stats.confs=(S.stats.confs||0)+1;
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])})+extra,'goal');sfx('coin');}}
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 `<h3 style="font-size:15px;margin:10px 0 4px">${tr('common.conferences')}</h3>${cb?`<div class="inc" style="background:#EAF7EE"><div class="nm">${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}</div><div class="meta">${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}</div></div>`:''}${up.map(cf=>{const reg=S.confReg&&S.confReg[cf.key];return `<div class="row"><div class="grow"><div class="nm">${esc(cf.n)} · ${esc(CITY[cf.c].name)}</div><div class="meta">${cf.day===S.day?tr('common.today'):tr('conferences.in_n_days',{n:cf.day-S.day})} · ${esc(REG[CITY[cf.c].reg])}</div></div>${reg?'<span class="tag st on">'+tr('common.registered')+'</span>':cf.day<=S.day?'<span class="tag st">'+tr('common.registration_closed')+'</span>':btn(tr('conferences.attend_cost',{cost:fmt$(CONF_COST)}),'confGo',{key:cf.key},'sm',S.cash<CONF_COST)}</div>`;}).join('')}`;}

View file

@ -0,0 +1,16 @@
/* ---------- guided first game ---------- */
const TUT=[
{t:tr('tutorial.your_router_is_live_press_launch'),sel:'[data-act="launchBB"]',ok:()=>S.pops[S.home]&&S.pops[S.home].bb},
{t:tr('tutorial.your_customers_want_the_whole'),sel:'[data-act="tab"][data-args*=\'"up"\'],[data-act="buyTransit"]',ok:()=>S.transit.length>0,skip:()=>!NETS.some(n=>sellsAt(n,S.home))},
{t:tr('tutorial.transit_costs_money_per_gigabit'),sel:'[data-act="tab"][data-args*=\'"peer"\'],[data-act="buyIx"],[data-act="rs"]',ok:()=>Object.keys(S.rs).length>0,skip:()=>!ixName(S.home)},
{t:tr('tutorial.start_the_clock_with_1_and'),sel:'#sp1',ok:()=>S.day>=5},
{t:tr('tutorial.grow_drag_from_your_pink_router'),sel:null,ok:()=>S.links.length>0},
{t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0},
];
function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();}
function renderCoach(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow'));
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;}
while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;}
if(S.tut>=TUT.length){S.tut=null;el.hidden=true;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');return;}
const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">${tr('tutorial.step_n_of_total',{n:S.tut+1,total:TUT.length})}</span>${esc(st.t)}</div>${btn(tr('common.skip_tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false;
if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}}

View file

@ -0,0 +1,43 @@
/* ---------- traceroute and looking glass ---------- */
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};}
function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[];
for(const x of S.caches)if(x.net===net&&popUp(x.city)&&!siteDown(x.city,'a'))out.push({k:'c',rank:0,city:x.city,pref:'normal',lab:tr('common.name_cache',{name:NET[net].cache.name}),used:R.useCache[x.id]||0,cap:CACHE_CAP});
for(const p of S.pni)if(p.net===net&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:1,city:p.city,pref:p.pref||'normal',lab:tr('common.pni_with_net',{net:NET[net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)});
for(const c in S.ixp)if(ixSessions(c).has(net)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:2,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});
for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&liveN(t.city,t.site,t.n)&&net!==leak&&!((ev.depeer>day||scnRule('spat'))&&t.net==='cog'&&net==='ggl'))out.push({k:'t',rank:3,city:t.city,pref:t.pref||'normal',lab:tr('traceroute.name_transit',{name:NET[t.net].name}),tnet:t.net,used:R.useT[t.id]||0,cap:liveCap(PORT[t.tier].g,t.city,t.site,t.n)});
return out;}
function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);};
hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name}));
const walk=path=>{for(const h of path){const l=h.l,lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}};
if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('traceroute.no_working_path_between_these_pops'));return {text:lines.join('\n'),why:tr('traceroute.no_path_every_route_between_these')};}walk(path);return {text:lines.join('\n'),why:S.te&&S.te.on?trn('traceroute.internal_path_over_n_link_chosen',path.length):trn('traceroute.internal_path_over_n_link_chosen_8620',path.length)};}
const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined);
lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`);
if(!ex.length){lines.push(' 2 * * *\n 3 * * * ← '+tr('traceroute.n_network_unreachable'));return {text:lines.join('\n'),why:tr('traceroute.nothing_on_your_network_reaches_net',{net:N.name,city:CITY[src].name}),asPath:null};}
ex.sort((a,b)=>(a.pref==='low'?4:a.rank)-(b.pref==='low'?4:b.rank)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]-P.dist[b.city]);
const e=ex.find(x=>x.used<x.cap*0.999)||ex[0];walk(P.path(e.city));
let asPath=[S.asn];
if(e.k==='t'){const T=NET[e.tnet];asPath.push(T.asn);hop(`be-${S.asn}.${e.city}.${slug(T.name)}.net`,`203.0.113.${hstr(e.city)%250}`,0.4,tr('traceroute.hand_off_to_net',{net:T.name}));
if(T.id!==N.id){const far=(N.pops&&N.pops.length?N.pops:[e.city]).reduce((a,c)=>kmBetween(e.city,c)<kmBetween(e.city,a)?c:a,(N.pops||[e.city])[0]);const km=CITY[far]?kmBetween(e.city,far):0;
hop(`ae-2.core.${far}.${slug(T.name)}.net`,`203.0.113.${(hstr(far)+7)%250}`,km*1.3/100+0.3,CITY[far]?tr('traceroute.net_carries_it_to_city',{net:T.name,city:CITY[far].name}):'');
hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,tr('traceroute.net_hands_it_to_to',{net:T.name,to:N.name}));}}
else if(e.k==='ix'){hop(`${slug(ixName(e.city))}.peering.${e.city}`,`185.0.${hstr(e.city)%250}.${hstr(N.id)%250}`,0.3,tr('traceroute.across_the_ix_switch',{ix:ixName(e.city)}));}
else if(e.k==='p'){hop(`pni-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('traceroute.private_cross_connect'));}
else{hop(`cache-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),4),0.1,tr('traceroute.embedded_cache_in_your_rack'));}
asPath.push(N.asn);if(e.k!=='c')hop(`www.${slug(N.name)}.example`,`198.51.100.${(hstr(N.id)+1)%250}`,0.5+(e.k==='t'?1:0.2),`${N.name}`);
const order={c:tr('traceroute.caches_beat_pnis'),p:tr('traceroute.pnis_beat_ix_peering'),ix:tr('traceroute.ix_peering_beats_transit'),t:tr('traceroute.transit_is_the_last_resort')}[e.k];
const cn=cnCity(src)!==!!N.cn?' '+tr('traceroute.crossing_the_great_firewall_here',{p:S.ev.gfw>S.day?35:20}):'';
return {text:lines.join('\n'),why:`${tr('traceroute.exit_exit_in_city',{exit:e.lab,city:CITY[e.city].name})} ${tr('traceroute.rule_and_closer_exits_win_ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('traceroute.this_one_is_set_to_mode',{mode:e.pref==='high'?tr('common.prefer'):tr('common.backup_only')}):''}.${e.used>=e.cap*0.999?' '+tr('traceroute.it_is_full_so_some_traffic'):''}${cn}`,asPath};}
function traceModal(src,to){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)});
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.looking_glass')}</div><h2 style="font-size:26px">${tr('common.traceroute')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="trsel"><label>${tr('common.from')} <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
<label>${tr('common.to')} <select id="trTo"><optgroup label="${tr('common.networks')}">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="${tr('common.your_pops')}">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn(tr('common.run'),'traceRun',{},'pink sm')}</div>
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta">${tr('traceroute.as_path_path',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}</p>`:''}<p class="note">${esc(r.why)}</p>
<div class="btns">${btn(tr('common.copy'),'traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}

View file

@ -0,0 +1,27 @@
/* ---------- share card ---------- */
// Straight link segments in map coordinates for flat maps. A link across the date line leaves one edge
// and comes back in at the other, so it becomes two segments, one per edge (#42).
function linkSegs(){const out=[];for(const l of S.links){const A=CITY[l.a],B=CITY[l.b];if(!A||!B)continue;const d=Math.abs(B.x-A.x)>W/2?(B.x<A.x?W:-W):0;
for(const o of d?[0,-d]:[0])out.push([A.x+o,A.y,B.x+d+o,B.y]);}return out;}
function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas');cv.width=Wc;cv.height=Hc;const g=cv.getContext&&cv.getContext('2d');if(!g)return null;
g.fillStyle='#57C4E5';g.fillRect(0,0,Wc,Hc);
// mini map
const mx=40,my=150,mw=700,mh=350,sx=mw/W,sy=mh/H;g.save();g.beginPath();g.rect(mx,my,mw,mh);g.clip();g.fillStyle='#3AA6CF';g.fillRect(mx,my,mw,mh);
g.fillStyle='#9BDA6C';g.strokeStyle='#1E2640';g.lineWidth=1.5;for(const pts of COAST){g.beginPath();pts.forEach((q,i)=>i?g.lineTo(mx+q[0]*sx,my+q[1]*sy):g.moveTo(mx+q[0]*sx,my+q[1]*sy));g.closePath();g.fill();g.stroke();}
g.strokeStyle='#FF4F9A';g.lineWidth=2.5;for(const [x1,y1,x2,y2] of linkSegs()){g.beginPath();g.moveTo(mx+x1*sx,my+y1*sy);g.lineTo(mx+x2*sx,my+y2*sy);g.stroke();}
for(const c in S.pops){const C=CITY[c];g.fillStyle='#FF4F9A';g.strokeStyle='#1E2640';g.lineWidth=2;g.beginPath();g.arc(mx+C.x*sx,my+C.y*sy,5,0,7);g.fill();g.stroke();}
g.restore();g.strokeStyle='#1E2640';g.lineWidth=5;g.strokeRect(mx,my,mw,mh);
// header
g.fillStyle='#1E2640';g.font='900 54px "Baloo 2", sans-serif';g.textBaseline='top';g.fillText(S.name,40,28);
g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${S.mode==='sandbox'?' · '+tr('common.sandbox'):''}`,42,92);
// stats
const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]).slice(0,8);
const rows=[[tr('common.peak_traffic'),fmtG(S.stats.peak||0)],[tr('common.peered'),pct(R.peerShare||0)],[tr('common.pops'),tr('share_card.n_in_r_regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('common.links'),String(S.links.length)],[tr('common.customers'),String(S.biz.length)],[tr('common.incidents_survived'),String(S.stats.survived||0)],[tr('common.shark_bites'),String(S.stats.sharks||0)],[tr('common.badges'),`${got.length}/${BADGES.length}`]];
if(S.scn)rows.unshift([scnName(),S.scn.done?(S.scn.id==='weekly'?tr('share_card.score_v',{v:fmtG(S.scn.score||S.stats.peak||0)}):tr('features.done_in_d_days',{d:S.scn.done})):S.scn.failed?tr('share_card.not_this_time'):tr('common.in_progress')]);
let y=150;for(const [k,v] of rows.slice(0,9)){g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=3;g.beginPath();g.roundRect?g.roundRect(770,y,390,42,12):g.rect(770,y,390,42);g.fill();g.stroke();g.fillStyle='#5A6280';g.font='800 18px Nunito, sans-serif';g.fillText(k,786,y+11);g.fillStyle='#1E2640';g.font='900 22px Nunito, sans-serif';const tw=g.measureText(v).width;g.fillText(v,1146-tw,y+9);y+=48;}
g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520));
g.fillStyle='#1E2640';g.font='900 30px "Baloo 2", sans-serif';g.fillText('seriesoftub.es',40,572);g.font='700 20px Nunito, sans-serif';g.fillText(tr('share_card.build_the_internet_one_tube_at'),300,580);
return cv;}
function shareModal(){const cv=shareCanvas();if(!cv){toast(tr('share_card.your_browser_cannot_draw_the_card'),'bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){}
UI.shareCv=cv;openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.share')}</div><h2 style="font-size:26px">${tr('share_card.your_network_card')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>${url?`<img src="${url}" alt="${tr('share_card.stats_card_for_name',{name:esc(S.name)})}" style="width:100%;border:3px solid var(--ink);border-radius:12px;margin-top:8px">`:''}<div class="btns" style="margin-top:10px">${navigator.share?btn(tr('common.share_2cd9'),'shareGo',{},'pink'):''}${btn(tr('common.download_png'),'shareDl',{},navigator.share?'':'pink')}</div><p class="note">${tr('share_card.post_it_wherever_your_peering')}</p>`);track('share_open');}
function shareFile(cb){const cv=UI.shareCv;if(!cv||!cv.toBlob){cb(null);return;}cv.toBlob(b=>cb(b?new File([b],`series-of-tubes-${slug(S.name)}.png`,{type:'image/png'}):null),'image/png');}

View file

@ -0,0 +1,12 @@
function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return;
if(sc.id==='weekly'){if(d>=sc.days){sc.done=d;const score=Math.round(S.stats.peak||0);sc.score=score;let best=null;try{const wk=JSON.parse(localStorage.getItem('sot-weekly')||'{}');best=wk[sc.key];if(!best||score>best){wk[sc.key]=score;localStorage.setItem('sot-weekly',JSON.stringify(wk));}}catch(e){}
const h=scnHof();h.weekly=h.weekly||{d:new Date().toISOString().slice(0,10)};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}
openModal(`<div class="eyebrow">${tr('features.weekly_challenge_key',{key:esc(sc.key)})}</div><h2 style="font-size:30px">${tr('scenario_progress.your_score_score',{score:fmtG(score)})}</h2><p class="tagline">${best&&best>score?tr('scenario_progress.peak_traffic_served_in_one_year',{best:fmtG(best)}):best?tr('scenario_progress.peak_traffic_served_in_one_year_c7e5'):tr('scenario_progress.peak_traffic_served_in_one_year_a67b')}</p><div class="btns">${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);track('weekly_done');}return;}
const def=SCN.find(x=>x.id===sc.id);if(!def)return;let ok=false;try{ok=def.ok();}catch(e){}
if(ok){sc.done=d;const h=scnHof();if(!h[sc.id]||h[sc.id].days>d)h[sc.id]={d:new Date().toISOString().slice(0,10),days:d};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}track('scenario_'+sc.id);
openModal(`<div class="eyebrow">${tr('common.scenario_complete')}</div><h2 style="font-size:30px">${tr('scenario_progress.name_done_in_d_days',{name:esc(def.n),d})}</h2><p class="tagline">${esc(def.goal)}. ${d<def.days/2?tr('scenario_progress.with_time_to_spare'):tr('scenario_progress.just_in_time')}</p><div class="btns">${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}${btn(tr('common.more_scenarios'),'scenarios',{},'ghost')}</div>`);sfx('coin');}
else if(d>=def.days){sc.failed=d;openModal(`<div class="eyebrow">${tr('common.scenario_over')}</div><h2 style="font-size:30px">${tr('common.time_s_up')}</h2><p class="tagline">${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(def.goal),d:def.days})}</p><div class="btns">${btn(tr('common.try_again'),'startScn',{id:def.id},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);}}
function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){}
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.scenarios')}</div><h2 style="font-size:28px">${tr('scenario_progress.pick_a_challenge')}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="${tr('common.close')}">×</button></div>
<div class="scn wk"><div class="grow"><div class="nm">${tr('features.weekly_challenge_key',{key:esc(wk.key)})}</div><div class="meta">${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}</div></div>${btn(tr('common.play'),'startWeekly',{},'pink')}</div>
${SCN.map(x=>`<div class="scn"><div class="grow"><div class="nm">${esc(x.n)} ${h[x.id]?`<span class="tag open">${tr('features.done_in_d_days',{d:h[x.id].days})}</span>`:''}</div><div class="meta">${esc(x.d)}</div><div class="meta">${tr('scenario_progress.goal_goal_time_d_days_start',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}</div></div>${btn(tr('common.play'),'startScn',{id:x.id},'')}</div>`).join('')}`);}

View file

@ -0,0 +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:2,auV:1,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:{},
done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}};
}

View file

@ -0,0 +1,24 @@
/* ================= HELPERS ================= */
const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';if(a>=1e6)return s+'$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';if(a>=1e3)return s+'$'+(a/1e3).toFixed(a>=1e5?0:1)+'k';return s+'$'+Math.round(a);};
const fmtG=g=>g>=1000?(g/1000).toFixed(g>=10000?1:2)+' Tbps':(g>=100?g.toFixed(0):g.toFixed(1))+' Gbps';
const pct=x=>Math.round(x*100)+'%';
// Reach never rounds up to 100%: Tier 1 needs more than 99.9%, and 99.6% must not look like a full house (#73).
const reachPct=x=>x>0.999?'100%':x>=0.99?(Math.floor(x*1000)/10).toFixed(1)+'%':pct(x);
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const pick=a=>a[Math.floor(Math.random()*a.length)];
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function dateStr(d){const y=1+Math.floor(d/360),m=Math.floor(d/30)%12,dd=d%30+1;return tr('helpers.y_y_mon_d',{y,mon:MONTHS[m],d:dd});}
function wrapDx(a,b){let dx=b-a;if(dx>W/2)dx-=W;if(dx<-W/2)dx+=W;return dx;}
function kmBetween(a,b){const A=CITY[a],B=CITY[b];return Math.max(20,Math.round(hav(A.lon,A.lat,B.lon,B.lat)));}
// Cities on a land bridge belong to two landmasses: Cairo reaches Asia overland across the Sinai, the way
// Istanbul does across the Bosporus (#47). Overland between continents still costs the intercontinental price.
const lands=C=>C.land2?[C.land,C.land2]:[C.land];
const isSub=(a,b)=>{const A=lands(CITY[a]),B=lands(CITY[b]);return !A.some(x=>B.includes(x));};
const popUp=c=>S.pops[c]&&!(S.pops[c].down>S.day);
const regionsCount=()=>new Set(Object.keys(S.pops).map(c=>CITY[c].reg)).size;
const ixCity=x=>String(x).split('~')[0];
function ixIdsIn(c){const o=ixStatic(c);if(S&&S.myIx&&S.myIx[c]&&!o.includes(c))o.unshift(c);return o;}
const hasIxAt=c=>ixIdsIn(c).some(x=>S.ixp[x]!==undefined);
function ixName(c){if(XIXM[c])return XIXM[c].name;return S.myIx[c]?S.myIx[c].name:CITY[c].ix;}
// IX.brrr Campinas already says where it is, so messages skip "in Campinas" (#134)
const ixNamesCity=c=>String(ixName(c)||'').toLowerCase().includes(CITY[ixCity(c)].name.toLowerCase());

View file

@ -0,0 +1,30 @@
/* Australian exchanges follow PeeringDB (every Australian exchange's member list, Oct 2026): networks that sit on
every IX elsewhere list the Australian cities they really peer in as auIx, and the big incumbents peer only privately. */
/* Transit in Australia is sold only by carriers with an Australian site and at least ten Australian networks buying
from them (RIPEstat, Oct 2026): Telstraya, Hocus Pocus, Speedyloop, SingTell, Drizzle Electric, Cogentle,
Not That Telecom and Level Tree (whose real-world network lists no sites in PeeringDB at all, but sells in Sydney). Others can sit in
an Australian city, like the Pacific carriers backhauling to Sydney, but reach Australian customers only from overseas. */
const AU_SELLERS=['tsy','voc','spl','sgt','drz','cog','ntt','lvl'],sellsAt=(n,c)=>!!n.price&&n.pops.includes(c)&&(!CITY[c].au||AU_SELLERS.includes(n.id));
const onIx=(n,c)=>CITY[c].au&&n.auIx?n.auIx.includes(c):n.ix==='ALL'||Array.isArray(n.ix)&&n.ix.includes(c);
function ixMembers(c){if(XIXM[c])return XIXM[c].members.slice();if(S.myIx[c])return S.myIx[c].members.slice();if(!CITY[c].ix)return [];return NETS.filter(n=>onIx(n,c)).map(n=>n.id);}
// 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;
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));}
function ixSessions(c){
const s=new Set(); if(S.ixp[c]===undefined)return s;
for(const id of ixMembers(c)){const n=NET[id];
if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id))&&!mpDown(id,c))s.add(id);
else if(S.rs[c]&&n.pol==='open'&&ppol()==='open')s.add(id);
else if(S.myIx[c]&&(n.pol==='open'||n.pol==='selective'))s.add(id);}
return s;
}
function t1Club(){
const miss=[];const pops=Object.keys(S.pops).length;
if(regionsCount()<3)miss.push(tr('exchanges.pops_on_3_continents'));
if(pops<10)miss.push(tr('exchanges.10_pops_n',{n:pops}));
if(R.served<1500)miss.push(tr('exchanges.serve_1_5_tbps_v',{v:fmtG(R.served)}));
if(R.sessions<20)miss.push(tr('exchanges.20_peering_sessions_n',{n:R.sessions}));
return {ok:!miss.length,missing:miss};
}

View file

@ -0,0 +1,19 @@
/* ---------- PNIs with the big networks: slow orders and no small ports ----------
Big content networks, Tier 1s and big eyeball networks usually deliver a PNI or an augment in about 30 days, but
15% of orders get lost in provisioning for 6 to 12 months. The content networks and Tier 1s start at 100G. Doitsche Telekomm sells PNIs down to 1G, and takes its time too. */
const pniBig=id=>{const n=NET[id];return n.type==='t1'||(n.type==='cdn'&&n.pol!=='open')||(n.type==='eye'&&n.share>=0.02);};
const pniMin=id=>{const n=NET[id];return n.type==='t1'||(n.type==='cdn'&&n.pol!=='open')?1:0;};
const pniG1=id=>id==='dtk';
// A beer with their peering coordinator at a conference halves the wait. It is how it really works.
const PNI_SLOW=0.15,pniLead=id=>{const n=pniBig(id)?(Math.random()<PNI_SLOW?180+Math.floor(Math.random()*186):30):14+Math.floor(Math.random()*29);return S.conf&&S.conf.until>S.day?Math.round(n/2):n;};
const pniG=p=>p.g1?1:PORT[p.tier].g,pniPN=p=>p.g1?'1G':PORT[p.tier].n,pniOn=p=>!(p.ready>S.day);
const pniEta=id=>pniBig(id)?tr('pnis.delivery_about_a_month_sometimes_6'):tr('pnis.delivery_2_to_6_weeks');
const PNI_G1_COST=1200,pniWhen=n=>n>=60?tr('pnis.their_team_quotes_m_months',{m:Math.round(n/30)}):tr('pnis.ready_in_about_n_days',{n});
function pniWait(p,c){return `<div class="kv"><span>${(p.n||1)>1?p.n+'×':''}${pniPN(p)} PNI</span><b>${tr('common.on_order')}</b></div><div class="meta">${tr('pnis.about_n_days_to_go_nothing',{n:Math.max(0,p.ready-S.day)})}</div><div class="btns">${btn(tr('common.chase_it'),'pniChase',{id:p.id},'ghost sm')}${btn(UI.confirm===p.id?tr('common.really_remove'):tr('pnis.cancel_the_order'),'cancelPni',{id:p.id},'ghost sm')}</div>`;}
function pniDay(d){for(const p of S.pni){const nm=esc(NET[p.net].name),city=esc(CITY[p.city].name);
if(p.ready===d)toast(tr('pnis.pni_with_net_is_up_in',{net:nm,city,dc:esc(siteName(p.city,'a'))}),'good');
if(p.up&&p.up.ready<=d){p.tier=p.up.tier;p.n=p.up.n;if(p.up.g1)p.g1=true;else delete p.g1;delete p.up;toast(tr('pnis.augment_with_net_delivered_in_city',{net:nm,city,port:((p.n||1)>1?p.n+'×':'')+pniPN(p)}),'good');}}}
// Microsnoft has no capacity on the US east coast. Not for a PNI, not at an exchange, not for anyone.
const US_EAST=['ash','nyc','bos','atn','mia'];
const MSF_NOPE=[N_('pnis.no_capacity_in_us_east_you'),N_('pnis.us_east_is_sold_out_until'),N_('pnis.their_peering_team_says_us_east'),N_('pnis.a_new_region_is_coming_online')];
const msfNope=(id,city)=>id==='msf'&&!!city&&US_EAST.includes(ixCity(city));

View file

@ -0,0 +1,83 @@
/* ---------- The peering inbox ----------
Every exchange port brings mail: peering requests from networks nobody has heard of, and sessions that drop
because someone's PeeringDB says 50 prefixes and they now send 400 (or a full table). Answer it, or hire an AI. */
const PPOL_N={open:N_('peering_inbox.open_to_all'),selective:N_('common.selective'),closed:N_('common.closed')},PPOL_D={open:N_('peering_inbox.everyone_who_asks_gets_a_session'),selective:N_('peering_inbox.fewer_requests_and_you_answer_them'),closed:N_('peering_inbox.nobody_asks_and_no_route_servers')};
const AI_MO=Math.round(20e6/12),INBOX_MAX=80,IBX_LEAKS=['nfx','ggl','fbk','amz','msf'];
const TINY=['Basement Broadband','Uncle Dave’s WISP','Fibre Fiesta','Raspberry Pi Transit','Vanity ASN Ltd','Moonshot Crypto Hosting','Minecraft Collective','Bob’s Bits','Homelab Heroes','Hackerspace Uplink','Tiny Tower Networks','Pigeon Post IP','Retro BBS Revival','Overkill Home Network','Two Guys and a Rack','Big Dreams Small Prefix','Mesh-y Business','Garden Shed Datacenter','Carrier-Grade NAT Fan Club','LIR in a Box','Yet Another VPN','Grandma’s Fibre Co-op','Seedbox Society','The /24 That Could'];
const REQ_SAY=[N_('peering_inbox.hi_we_would_like_to_peer'),N_('peering_inbox.dear_sir_or_madam_please_peer'),N_('peering_inbox.we_noticed_you_are_at_ix'),N_('peering_inbox.hello_please_find_attached_our'),N_('peering_inbox.peering_request_fifth_attempt_is'),N_('peering_inbox.hey_quick_one_can_you_peer'),N_('peering_inbox.greetings_we_are_a_fast_growing'),N_('peering_inbox.please_configure_sessions_with_us_at')];
const IBX_AI=[N_('peering_inbox.replied_to_a_peering_request_with'),N_('peering_inbox.signed_you_up_for_a_webinar'),N_('peering_inbox.opened_a_ticket_with_itself_to'),N_('peering_inbox.wrote_a_thousand_word_apology_to'),N_('peering_inbox.updated_your_peeringdb_record_your'),N_('peering_inbox.asked_netchill_s_peering_team_to')];
function ibx(){if(!S.inbox||typeof S.inbox!=='object')S.inbox={items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0};return S.inbox;}
// Reputation nudges selective networks by up to 10% either way: worth caring about, never a wall.
// Your peering policy. Open: everyone who asks gets a session and the route servers work. Selective: fewer requests,
// you answer them yourself, and no route servers, so you go and ask networks at each exchange. Closed: nobody asks,
// and customers hear that you are hard to reach.
const PPOL=['open','selective','closed'],ppol=()=>(S&&S.inbox&&PPOL.includes(S.inbox.pol))?S.inbox.pol:'open';
const repMul=()=>1-clamp((S.inbox&&S.inbox.rep)||0,-10,5)*0.01;
const repName=r=>r>=1?tr('common.responsive'):r>=-2?tr('common.average'):r>=-6?tr('peering_inbox.mostly_ignores_email'):tr('common.black_hole');
const ibxOpen=()=>S.inbox?S.inbox.items.length:0,ibxUrgent=()=>S.inbox?S.inbox.items.filter(x=>x.k==='mp').length:0;
const mpDown=(id,c)=>{const t=S.inbox&&S.inbox.down[id+'@'+c];return !!t&&t>S.day;};
const ibxWho=x=>x.net?NET[x.net].name:x.nm,ibxAsn=x=>x.net?NET[x.net].asn:x.asn;
function ibxLog(m,a){const I=ibx();I.log.unshift({d:S.day,m,a:a||{}});I.log.length=Math.min(I.log.length,40);}
function inboxDay(d){const I=ibx(),ixs=Object.keys(S.ixp);
// new peering requests: more exchange ports, more mail
if(ixs.length&&Math.random()<Math.min(0.9,0.15*ixs.length)*({open:1,selective:0.7,closed:0}[ppol()])){const c=pick(ixs),set=ixSessions(c);
const real=ixMembers(c).filter(id=>{const n=NET[id];return !set.has(id)&&n.type!=='t1'&&n.type!=='cdn'&&n.pol!=='paid'&&n.share<=0.006&&!I.items.some(x=>x.net===id&&x.ix===c);});
const it={id:++I.seq,k:'req',ix:c,day:d,stale:Math.random()<0.6,yrs:1+Math.floor(Math.random()*9),say:Math.floor(Math.random()*REQ_SAY.length)};
if(real.length&&Math.random()<0.4)it.net=pick(real);else{it.nm=pick(TINY);it.asn=Math.random()<0.05?64512+Math.floor(Math.random()*1000):200000+Math.floor(Math.random()*200000);}
I.items.push(it);if(ppol()==='open')ibxAnswer(it.id,'accept',true);}
if(ppol()==='closed')I.rep=Math.max(-6,I.rep-0.05);
// max-prefix: someone grew past what their PeeringDB says, or leaked a full table
const ses=Object.keys(S.peers).filter(k=>{const n=NET[k.split('@')[0]];return n&&n.type!=='cdn'&&n.type!=='t1'&&!mpDown(...k.split('@'));}).map(k=>({key:k,net:k.split('@')[0],ix:k.split('@')[1]}))
.concat(Object.keys(I.tiny).map(a=>({key:'t'+a,nm:I.tiny[a].nm,asn:+a,ix:I.tiny[a].ix,stale:I.tiny[a].stale})));
if(ses.length&&Math.random()<Math.min(0.15,0.004*ses.length)){const x=pick(ses);if(!I.items.some(y=>y.k==='mp'&&y.key===x.key)){
const lim=pick([10,20,50,100,200,500,1000]),leak=Math.random()<0.3,yrs=1+Math.floor(Math.random()*9);
I.items.push({id:++I.seq,k:'mp',key:x.key,net:x.net,nm:x.nm,asn:x.asn,ix:x.ix,day:d,lim,got:leak?940000+Math.floor(Math.random()*90000):Math.ceil(lim*(1.15+Math.random()*1.6)),leak,yrs});
// A session that blows its limit is down for at most a few weeks: the other side eventually notices too.
if(x.net){I.down[x.key]=d+20+Math.floor(Math.random()*20);toast(tr('peering_inbox.max_prefix_limit_hit_who_at',{who:esc(ibxWho(x)),ix:esc(ixName(x.ix))}),'bad',[{l:tr('common.inbox'),act:'inbox',args:{}}]);}}}
// unanswered mail: requests go stale and people start asking around about you
for(const x of I.items){if(x.k==='mp')I.rep-=0.05;else if(d-x.day===14)x.bump=1;}
// A max-prefix alert nobody answers resolves itself in the end: the other side raises it, or gives up.
I.items=I.items.filter(x=>x.k!=='mp'||(x.net?(I.down[x.key]||0)>d:d-x.day<=30));
const old=I.items.filter(x=>x.k==='req'&&d-x.day>30);if(old.length){I.rep-=0.25*old.length;I.items=I.items.filter(x=>!old.includes(x));
if(old.some(x=>x.net))toast(tr('peering_inbox.who_asked_a_mailing_list_whether',{who:esc(ibxWho(old.find(x=>x.net))),me:esc(S.name)}),'bad',[{l:tr('common.inbox'),act:'inbox',args:{}}]);}
while(I.items.length>INBOX_MAX){const i=I.items.findIndex(x=>x.k==='req');if(i<0)break;I.items.splice(i,1);I.rep-=0.5;}
I.rep=clamp(I.rep,-10,5);
if(I.bot)inboxBot();}
// Answer one item. a: accept | decline | raise | keep. Returns false when the item is gone.
function ibxAnswer(id,a,bot){const I=ibx(),i=I.items.findIndex(x=>x.id===id);if(i<0)return false;const x=I.items[i];I.items.splice(i,1);const who=ibxWho(x),ix=ixName(x.ix);
if(x.k==='req'){if(a==='accept'){if(x.net){if(S.ixp[x.ix]!==undefined)S.peers[x.net+'@'+x.ix]=true;}else if(Object.keys(I.tiny).length<200)I.tiny[x.asn]={nm:x.nm,ix:x.ix,stale:!!x.stale};I.rep+=0.3;}else I.rep+=0.2;}
else if(a==='raise'){delete I.down[x.key];if(x.leak){const n=pick(IBX_LEAKS);S.ev.leak={net:n,until:S.day+4};
addInc({type:'leak',ref:n,until:S.day+4,msg:tr('peering_inbox.who_at_ix_was_sending_a',{who,ix,net:NET[n].name}),cost:0});
if(!bot)toast(tr('peering_inbox.that_was_a_route_leak_who',{who:esc(who),n:x.got.toLocaleString()}),'bad');I.rep-=1;}
else{I.rep+=0.3;if(!bot)toast(tr('peering_inbox.session_with_who_is_back_up',{who:esc(who),n:Math.ceil(x.got*1.5).toLocaleString()}),'good');}}
else{const back=S.day+(x.leak?3:10)+Math.floor(Math.random()*(x.leak?8:21));if(x.net)I.down[x.key]=back;I.rep+=x.leak?0.3:0.1;
if(!bot)toast(x.leak?tr('peering_inbox.good_call_it_was_a_route',{who:esc(who)}):tr('peering_inbox.the_session_stays_down_who_will',{who:esc(who)}),x.leak?'good':'');}
I.rep=clamp(I.rep,-10,5);return true;}
// The AI agent clears the inbox every day. It is fast, polite and wrong about a third of the time.
function inboxBot(){const I=ibx();let acc=0,dec=0;
for(const x of I.items.slice()){const oops=Math.random()<0.3;
if(x.k==='req'){const want=!x.stale||!!x.net;const a=(want!==oops)?'accept':'decline';ibxAnswer(x.id,a,true);a==='accept'?acc++:dec++;if(oops&&a==='decline'&&x.net)ibxLog(N_('peering_inbox.declined_who_at_ix_not_a'),{who:ibxWho(x),ix:ixName(x.ix)});}
else{const a=(x.leak!==oops)?'keep':'raise';ibxAnswer(x.id,a,true);
if(a==='raise'&&x.leak)ibxLog(N_('peering_inbox.raised_the_max_prefix_limit_for'),{who:ibxWho(x),ix:ixName(x.ix),n:Math.ceil(x.got*1.5).toLocaleString()});
else if(a==='keep'&&!x.leak)ibxLog(N_('peering_inbox.kept_who_down_at_ix_for'),{who:ibxWho(x),ix:ixName(x.ix)});
else ibxLog(a==='raise'?N_('peering_inbox.raised_the_max_prefix_limit_for_7b4b'):N_('peering_inbox.kept_who_down_at_ix_it'),{who:ibxWho(x),ix:ixName(x.ix)});}}
if(acc||dec)ibxLog(N_('peering_inbox.answered_your_mail_a_accepted_d'),{a:acc,d:dec});
if(Math.random()<0.01){const ks=Object.keys(S.peers);if(ks.length){const k=pick(ks),[id,c]=k.split('@');delete S.peers[k];ibxLog(N_('peering_inbox.tidied_up_a_session_it_decided'),{who:NET[id].name,ix:ixName(c)});}}
if(Math.random()<0.08)ibxLog(pick(IBX_AI),{});}
function inboxModal(){const I=ibx(),items=I.items.slice().sort((a,b)=>(b.k==='mp')-(a.k==='mp')||b.day-a.day),reqs=items.filter(x=>x.k==='req').length,mps=items.length-reqs;
const age=x=>{const n=S.day-x.day;return n?trn('peering_inbox.n_day_ago',n):tr('common.today_4203');};
const pdb=x=>x.stale?trn('peering_inbox.peeringdb_last_updated_n_year_ago',x.yrs):tr('peering_inbox.peeringdb_updated_last_month');
const card=x=>x.k==='mp'?`<div class="ibx mp"><div class="nm">⚠️ ${tr('peering_inbox.max_prefix_limit_hit_who_at_5c56',{who:esc(ibxWho(x)),ix:esc(ixName(x.ix))})}</div>
<div class="meta">AS${ibxAsn(x)} · ${age(x)}</div><p class="note">${tr('peering_inbox.configured_lim_prefixes_received_got',{lim:x.lim.toLocaleString(),got:x.got.toLocaleString()})} ${trn('peering_inbox.their_peeringdb_says_lim_last',x.yrs,{lim:x.lim.toLocaleString()})}</p>
<div class="btns">${btn(tr('peering_inbox.raise_the_limit'),'inboxAct',{id:x.id,a:'raise'},'sm')}${btn(tr('peering_inbox.keep_it_down'),'inboxAct',{id:x.id,a:'keep'},'ghost sm')}</div></div>`
:`<div class="ibx"><div class="nm">${esc(ibxWho(x))} <span class="meta">AS${ibxAsn(x)}</span>${x.bump?` <span class="tag">${tr('common.bumped')}</span>`:''}</div><div class="meta">${esc(ixName(x.ix))} · ${age(x)} · ${pdb(x)}</div>
<p class="note">“${esc(tr(REQ_SAY[x.say]||REQ_SAY[0],{ix:ixName(x.ix)}))}”</p><div class="btns">${btn(tr('common.accept'),'inboxAct',{id:x.id,a:'accept'},'sm')}${btn(tr('common.decline'),'inboxAct',{id:x.id,a:'decline'},'ghost sm')}</div></div>`;
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.peering_inbox')}</div><h2 style="font-size:26px">📬 ${trn('peering_inbox.n_unanswered',items.length)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('peering_inbox.every_exchange_port_brings_mail')}</p>
<div class="kv"><span>${tr('common.your_reputation')}</span><b>${repName(I.rep)}</b></div>
<div class="kv"><span>${tr('common.peering_policy')}</span><b>${tr(PPOL_N[ppol()])}</b></div><div class="seg">${PPOL.map(p=>btn(tr(PPOL_N[p]),'inboxPol',{p},ppol()===p?'sm':'ghost sm')).join('')}</div><p class="meta">${tr(PPOL_D[ppol()])}</p>
<div class="ibx ai">${I.bot?`<div class="nm">🤖 ${tr('peering_inbox.large_peering_model_is_answering')}</div><div class="meta">${tr('peering_inbox.price_year_it_never_sleeps_never',{price:fmt$(20e6)})}</div>
${I.log.length?`<pre class="term">${I.log.slice(0,8).map(e=>esc(tr('peering_inbox.day_d',{d:e.d})+': '+tr(e.m,e.a))).join('\n')}</pre>`:''}<div class="btns">${btn(tr('peering_inbox.fire_the_ai'),'inboxBot',{on:0},'ghost sm')}</div>`
:`<div class="nm">🤖 ${tr('peering_inbox.large_peering_model')}</div><div class="meta">${tr('peering_inbox.an_ai_agent_that_answers_every',{price:fmt$(20e6)})}</div><div class="btns">${btn(tr('peering_inbox.hire_it_mo_mo',{mo:fmt$(AI_MO)}),'inboxBot',{on:1},'aibtn sm',S.cash<AI_MO)}</div>`}</div>
${reqs>1||mps>1?`<div class="btns">${reqs>1?btn(tr('peering_inbox.accept_all_requests'),'inboxAll',{a:'accept'},'sm')+btn(tr('peering_inbox.decline_all_requests'),'inboxAll',{a:'decline'},'ghost sm'):''}${mps>1?btn(tr('peering_inbox.raise_all_max_prefix_limits'),'inboxRaiseAll',{},'sm'):''}</div>`:''}
${items.length?items.slice(0,40).map(card).join(''):`<p class="empty">${Object.keys(S.ixp).length?tr('peering_inbox.inbox_zero_enjoy_it_while_it'):tr('peering_inbox.no_mail_yet_buy_an_ix')}</p>`}`);}

View file

@ -0,0 +1,32 @@
/* Big networks sometimes refuse to peer in a particular city, for a while. Each (network, city)
pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. */
const SNUB_WIN=150,SNUB_P=0.22;
const SNUB_IX=[tr('peering_policy.only_peers_over_pnis_in_this'),tr('peering_policy.their_ix_port_here_is_full'),tr('peering_policy.moved_everything_in_this_city_to'),tr('peering_policy.the_peering_coordinator_for_this'),tr('peering_policy.their_policy_here_says_ix_peering')];
const SNUB_ALL=[tr('peering_policy.not_accepting_new_peers_in_this'),tr('peering_policy.region_frozen_while_they_renegotiate'),tr('peering_policy.their_routers_in_this_city_are'),tr('peering_policy.already_reach_you_through_your'),tr('peering_policy.their_lawyers_are_reviewing_every'),tr('peering_policy.a_new_vp_wants_to_monetise')];
function hstr(t){let h=2166136261;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return h>>>0;}
function bigPeer(n){return !!n&&n.pol==='selective'&&n.share>=0.03;}
function snub(id,c){
const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c])return null;
const off=hstr(id+c)%SNUB_WIN,ep=Math.floor((S.day+off)/SNUB_WIN),h=hstr(S.asn+'|'+id+'|'+c+'|'+ep);
if(h%1000>=SNUB_P*1000)return null;
const all=(h>>>10)%5<2,list=all?SNUB_ALL:SNUB_IX;
return {all,why:list[(h>>>13)%list.length],until:(ep+1)*SNUB_WIN-off};
}
/* Remote peering: offered, but discouraged. A reseller marks up the port, oversubscribes it,
and many selective networks refuse members who are not physically in the building. */
const REMOTE_FEE=1.5,REMOTE_CAP=0.8;
const REMOTE_WARN=`<p class="note" style="color:var(--bad)">${tr('peering_policy.remote_peering_is_a_last_resort')}</p>`;
const REMOTE_WHY=[tr('peering_policy.policy_no_remote_peers_be_in'),tr('peering_policy.saw_your_session_come_in_over'),tr('peering_policy.only_peers_with_members_they_can'),tr('peering_policy.their_pearingdb_entry_says_remote'),tr('peering_policy.tried_a_remote_peer_once_it')];
function isRemote(c){return S.ixp[c]!==undefined&&!S.pops[ixCity(c)]&&!S.myIx[c];}
function noRemote(id){const n=NET[id];if(!n||n.pol!=='selective')return false;return hstr(id+'|remote')%100<(n.share>=0.03?60:30);}
/* Europe's peering market is crowded and competitive: ports are cheaper, and incumbents cut prices
when a challenger in the same metro gets too popular. DE-KICKS harmonises instead. */
const IX_REG={EU:0.8};
function ixMul(x){const X=XIXM[x],c=ixCity(x);return (X?X.cheap:(CITY[c].ixCheap||1))*(IX_REG[CITY[c].reg]||1)*(CITY[c].au?AU_IX:1)*((S&&S.ixCut&&S.ixCut[x])||1);}
function ixPortMo(c,tier){const X=XIXM[c];if(X&&tier<=(X.freeTo??-1))return 0;return Math.round(PORT[tier].ix*(S.pops[ixCity(c)]?1:REMOTE_FEE)*dkMult(c)*ixMul(c));}
function ixPriceWar(d){if(!S.ixp||Math.random()>=1/120)return;
const mine=Object.keys(S.ixp).filter(x=>{const c=ixCity(x);return CITY[c].reg==='EU'&&ixStatic(c).length>1;});if(!mine.length)return;
const x=pick(mine),c=ixCity(x),rival=pick(ixStatic(c).filter(y=>y!==x));
if(isDk(x)){toast(tr('peering_policy.rival_is_poaching_de_kicks_members',{rival:esc(ixName(rival)),city:esc(CITY[c].name)}),'bad');return;}
S.ixCut=S.ixCut||{};const cur=S.ixCut[x]||1;if(cur<=0.62)return;S.ixCut[x]=+Math.max(0.6,cur*0.9).toFixed(3);
toast(tr('peering_policy.price_war_in_city_ix_cut',{city:esc(CITY[c].name),ix:esc(ixName(x)),rival:esc(ixName(rival))}),'good');}

View file

@ -0,0 +1,30 @@
/* DE-KICKS Group: runs several big exchanges and really, really hates open pricing.
No price list, personalised quotes, haggling, yearly "harmonisation", auto-enrolled add-ons
you have to opt out of, and a retention offer when you try to leave. */
const DK_CITIES=['fra','mad','mrs','dxb','bom','nyc'];
const isDk=c=>(DK_CITIES.includes(c)||scnRule('dkAll'))&&!!CITY[c]&&!!CITY[c].ix&&!S.myIx[c];
const DK_ADDONS=[['Blackholing Plus™',tr('de_kicks.like_blackholing_but_with_a_plus')],['Route Server Gold',tr('de_kicks.the_same_route_server_in_a')],['Premium Port LEDs',tr('de_kicks.your_port_light_now_blinks_in')],['Strategic Peering Insights',tr('de_kicks.a_monthly_pdf_of_your_own')],['GlobePeer Ready™',tr('de_kicks.makes_your_port_ready_for_a')],['Cloud Exchange Readiness Fee',tr('de_kicks.a_fee_for_being_ready_for')],['Account Manager Lunch Fund',tr('de_kicks.your_account_manager_is_hungry')]];
const DK_STALL=[tr('de_kicks.your_account_manager_would_love_to'),tr('de_kicks.pricing_is_reviewed_by_the_global'),tr('de_kicks.they_sent_a_14_page_nda'),tr('de_kicks.your_account_manager_is_at_a')];
function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return S.dk.m[c]*(ret&&ret>S.day?0.6:1);}
function dkAddonMo(c){return S.dk&&S.dk.add[c]?S.dk.add[c].reduce((a,x)=>a+x.mo,0):0;}
function dkState(){S.dk=S.dk||{m:{},add:{},ret:{},retUsed:{},stall:0,q:null};return S.dk;}
function dkQuoteMult(){const pops=Object.keys(S.pops).length,big=Math.min(1.2,pops*0.04+(R.served||0)/20000);return +(0.95+Math.random()*0.45+big).toFixed(2);}
function dkQuoteModal(){const q=S.dk.q,c=q.city,mo=Math.round(PORT[q.tier].ix*(S.pops[c]?1:REMOTE_FEE)*q.m*ixMul(c));
openModal(`<div class="eyebrow">${tr('de_kicks.de_kicks_group_sales')}</div><h2 style="font-size:26px">${tr('de_kicks.your_personalised_port_quote_for_ix',{port:PORT[q.tier].n,ix:esc(ixName(c))})}</h2>
<p class="tagline">${tr('de_kicks.thanks_for_your_interest_we_don')}</p>
<div class="kv"><span>${tr('de_kicks.monthly_price_just_for_you')}</span><b>${tr('common.price_mo',{price:fmt$(mo)})}</b></div>
<div class="kv"><span>${tr('common.list_price')}</span><b>${tr('common.confidential')}</b></div>
<div class="kv"><span>${tr('de_kicks.what_others_pay')}</span><b>${tr('de_kicks.covered_by_nda')}</b></div>
<p class="note">${tr('de_kicks.quotes_go_up_with_how_big')} ${q.h>=3?tr('de_kicks.your_account_manager_has_stopped'):tr('de_kicks.haggles_left_n',{n:3-q.h})}</p>
<div class="btns">${btn(tr('de_kicks.sign_price_mo',{price:fmt$(mo)}),'dkAccept',{},'pink',S.cash<mo)}${btn(tr('common.haggle'),'dkHaggle',{},'',q.h>=3)}${btn(tr('common.walk_away'),'dkWalk',{},'ghost')}</div>`);}
function dkTick(d){if(!S.dk)return;const dk=S.dk;
for(const c in S.ixp){if(!isDk(c))continue;
if(dk.ret[c]&&dk.ret[c]===d){dk.m[c]=+(dk.m[c]*1.1).toFixed(3);toast(tr('de_kicks.your_ix_promo_ended_price_is',{ix:esc(ixName(c))}),'bad');}
if(dk.m[c]&&(d+hstr(c)%90)%365===0){const f=1.08+Math.random()*0.07;dk.m[c]=+(dk.m[c]*f).toFixed(3);toast(tr('de_kicks.de_kicks_has_harmonised_its_prices',{ix:esc(ixName(c)),p:Math.round((f-1)*100)}),'bad');}
const add=dk.add[c]=dk.add[c]||[];
if(add.length<3&&Math.random()<1/150){const a=DK_ADDONS.filter(x=>!add.some(y=>y.n===x[0]));if(a.length){const [n,blurb]=pick(a),mo=Math.round((300+Math.random()*1200)/50)*50;add.push({n,blurb,mo,day:d});
toast(tr('de_kicks.good_news_you_ve_been_enrolled',{addon:esc(n),blurb:esc(blurb),price:fmt$(mo),ix:esc(ixName(c))}),'bad');}}}
}
function elephant(){S.phpDone=true;S.ev.php=S.day+4;
toast(tr('de_kicks.breaking_cve_2026_31337_just_took'),'bad');sfx('alert');renderMega();}

View file

@ -0,0 +1,23 @@
/* Sold out: now and then a carrier has no spare capacity of a size on a route. Each route, size and 90-day window
gets a stable verdict from a hash, so asking again does not reroll it, and bigger waves sell out more often. */
const SOLD_WIN=90,SOLD_WHY=[N_('sold_out.a_hyperscaler_bought_every_wave_of'),N_('sold_out.the_carrier_is_out_of_spectrum'),N_('sold_out.the_transponders_for_this_route_are'),N_('sold_out.the_capacity_is_available_in_the'),N_('sold_out.their_capacity_planner_is_on_holiday'),N_('sold_out.the_upgrade_is_planned_for_q3')];
const soldP=tier=>Math.min(0.1,0.02+0.012*tier);
// Never in the first 90 days: a new network has enough on its plate. Never in the tutorial or a scenario's first quarter either.
function soldOut(a,b,tier,via){if(!S||S.day<SOLD_WIN||S.tut)return null;const k=(a<b?a+b:b+a)+'|'+(via||'')+'|'+tier,off=hstr(k)%SOLD_WIN,ep=Math.floor((S.day+off)/SOLD_WIN),h=hstr(S.asn+'|'+k+'|'+ep);
if(h%1000>=soldP(tier)*1000)return null;return {why:SOLD_WHY[(h>>>10)%SOLD_WHY.length],until:(ep+1)*SOLD_WIN-off};}
function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return sn.why+' '+trn('sold_out.they_will_reconsider_in_n_day',d);}
// Paid-peering giants drop the fee for networks too big to ignore (freeLv: the customer level that does it).
const paidFree=n=>!!(n&&n.freeLv&&lvl()>=n.freeLv);
function peerOk(id,via,city){
const n=NET[id],dem=R.demTo[id]||0;
const sn=snub(id,city);if(sn&&(via==='ix'||sn.all))return {ok:false,snub:true,why:snubWhy(sn)};
if(msfNope(id,city))return {ok:false,why:tr(MSF_NOPE[hstr(ixCity(city)+S.day)%MSF_NOPE.length])};
if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]};
if(n.pol==='open')return {ok:true};
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*repMul());return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};}
if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')};
if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')};
if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};}
if(via!=='pni')return {ok:false,why:tr('sold_out.tier_1s_never_peer_at_ixs')};
const c=t1Club();return c.ok?{ok:true}:{ok:false,why:tr('sold_out.not_big_enough_yet_list',{list:c.missing.join(', ')})};
}

View file

@ -0,0 +1,19 @@
// Everything that can fill up at a POP: transit ports, IX ports, PNIs, caches and the routers themselves.
const HOT=0.9,HOTL={t:'T',ix:'IX',p:'P',c:'C',r:'R'},HOTC={t:'#7B61FF',ix:'#FFD23F',p:'#2C7A7B',c:'#C8102E',r:'#FF4F9A'};
function hotPorts(){const out=[];if(!R||!S)return out;
for(const t of S.transit){if(t.down>S.day)continue;const cap=lagCap(PORT[t.tier].g,t.n),u=(R.useT[t.id]||0)/cap;if(u>=HOT)out.push({k:'t',city:t.city,lab:tr('hot_ports_and_rank.net_transit_lag',{net:NET[t.net].name,lag:lagName(t.tier,t.n)}),u,tip:tr('hot_ports_and_rank.add_a_lag_member_upgrade_the')});}
for(const c in S.ixp){const cap=ixCap(c);if(!cap)continue;const u=(R.useIx[c]||0)/cap;if(u>=HOT)out.push({k:'ix',city:ixCity(c),lab:tr('common.port_port',{port:ixName(c)}),u,tip:tr('hot_ports_and_rank.upgrade_the_ix_port_or_add')});}
for(const p of S.pni){if(!pniOn(p))continue;const cap=lagCap(pniG(p),p.n),u=(R.usePni[p.id]||0)/cap;if(u>=HOT)out.push({k:'p',city:p.city,lab:tr('common.pni_with_net',{net:NET[p.net].name}),u,tip:tr('hot_ports_and_rank.add_a_lag_member_or_upgrade')});}
const cc={};for(const x of S.caches){const k=x.city+'|'+x.net;(cc[k]=cc[k]||{city:x.city,net:x.net,used:0,cap:0});cc[k].used+=R.useCache[x.id]||0;cc[k].cap+=CACHE_CAP;}
for(const k in cc){const x=cc[k],u=x.used/x.cap;if(u>=HOT)out.push({k:'c',city:x.city,lab:x.cap>CACHE_CAP?tr('hot_ports_and_rank.name_caches',{name:NET[x.net].cache.name}):tr('common.name_cache',{name:NET[x.net].cache.name}),u,tip:tr('hot_ports_and_rank.ask_for_another_box_the_overflow')});}
for(const c in S.pops){const cap=R.nodeCap[c];if(!cap)continue;const u=(R.nodeLoad[c]||0)/cap;if(u>=HOT)out.push({k:'r',city:c,lab:tr('common.routers'),u,tip:tr('hot_ports_and_rank.upgrade_the_router_or_add_a')});}
return out.sort((a,b)=>b.u-a.u);}
function hotByCity(){const m={};for(const h of hotPorts())(m[h.city]=m[h.city]||{})[h.k]=Math.max((m[h.city]||{})[h.k]||0,h.u);return m;}
function isTier2(){return Object.keys(S.pops).length>=5&&Object.keys(S.ixp).length>=3&&R.sessions>=15;}
// Sparkly Seabone joined the Tier 1s in 1.12. Older saves keep the five they were playing for.
const t1Need=()=>NETS.filter(n=>n.type==='t1'&&(n.id!=='skl'||(S&&S.t1v>=2)));
function isTier1(){return t1Need().every(n=>S.pni.some(p=>p.net===n.id&&pniOn(p)))&&S.transit.length===0&&R.reach>0.999;}
// What you are now, not what you once were (#46): buying transit again or losing reach drops the label.
function tierLabel(){return S.won&&isTier1()?'Tier 1':isTier2()?'Tier 2':'Tier 3';}
function t1Why(){if(S.transit.length)return tr('hot_ports_and_rank.you_buy_transit_again');const miss=t1Need().filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p)));if(miss.length)return tr('hot_ports_and_rank.no_pni_with_list',{list:miss.map(n=>n.name).join(', ')});{const lost=NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);if(lost.length)return tr('hot_ports_and_rank.you_cannot_reach_list',{list:lost.slice(0,3).map(n=>n.name).join(', ')+(lost.length>3?' '+tr('hot_ports_and_rank.and_n_more',{n:lost.length-3}):'')});}return tr('hot_ports_and_rank.your_reach_is_p_not_100',{p:reachPct(R.reach)});}

View file

@ -0,0 +1,17 @@
/* ================= SIMULATION ================= */
// Binary-heap Dijkstra over city indices: adj[i] lists [neighbour, edge]. wf(edge) gives the weight, skip(v,edge) can
// rule edges out, and the search stops early once `stop` is settled. D is the distance to each city (Infinity: no
// path) and P the edge it was reached by. The heap lives in two typed arrays, and equal distances always settle in the
// same order, so routes do not flip between runs.
function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n).fill(Infinity),P=new Array(n),done=new Uint8Array(n);
let cap=64,hd=new Float64Array(cap),hu=new Int32Array(cap),m=0;
const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=a;hu=b;}
let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}};
D[src]=0;put(0,src);
while(m){const d=hd[0],u=hu[0];m--;
if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l<m&&hd[l]<hd[k])k=l;if(r<m&&hd[r]<hd[k])k=r;if(k===i)break;const td=hd[k],tu=hu[k];hd[k]=hd[i];hu[k]=hu[i];hd[i]=td;hu[i]=tu;i=k;}}
if(done[u]||d>D[u])continue;done[u]=1;if(u===stop)break;
for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<D[v]){D[v]=nd;P[v]=e;put(nd,v);}}}
return {D,P};}
// The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices.
function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};}

View file

@ -0,0 +1,129 @@
/* ---------- RouteScript: a tiny, safe rule language for the Auto-TE controller ----------
Player scripts are parsed into plain data and never executed, so a shared or imported
save can't run code. One rule per line, # for comments. */
const TE_KINDS={pni:'p',ix:'ix',transit:'t'};
const TE_EXAMPLE=`# RouteScript for your Auto-TE controller. One rule per line.
# Keep Cogentle at its 20 Gbps commit; overflow goes elsewhere
cap transit cogentle at 20 gbps
# Goggle should come over peering, not transit
avoid transit for goggle
# Move traffic before links are completely full
spill at 85%
# Local-pref: use the cheap upstream first, the pricey one last
# prefer transit cogentle
# avoid transit level tree
# AS-path prepending: ask the world to send less via one upstream (a hint, not an order)
# prepend transit drizzle electric 2
# Business customers first when links are congested; home users get what is left
# protect customers
# Maintenance window? Drain a POP's exits, or steer around a link
# drain paris
# avoid link frankfurt-amsterdam
# Under DDoS: drop the junk at the edge (takes some real traffic with it)
# blackhole ddos`;
function lev(a,b){const m=a.length,n=b.length,d=Array.from({length:m+1},(_,i)=>[i]);for(let j=1;j<=n;j++)d[0][j]=j;for(let i=1;i<=m;i++)for(let j=1;j<=n;j++)d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]===b[j-1]?0:1));return d[m][n];}
function teFind(word,list,label){const w=slug(word);if(!w)return {err:tr('routescript.missing_what',{what:label})};
for(const x of list)if(x.id===w||slug(x.name)===w)return {v:x.id};
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};
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;
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;}
if(m=line.match(/^(prefer|avoid)\s+transit\s+(?!for\s)(.+)$/)){const r=teFind(m[2],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.up[r.v]=m[1];out.n++;return;}
if(m=line.match(/^prepend\s+transit\s+(.+?)\s+(\d+)$/)){const v=+m[2];if(v<1||v>3){out.errors.push(tr('routescript.line_n_prepend_1_to_3',{n:L}));return;}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.prep[r.v]=v;out.n++;return;}
if(line==='protect customers'){out.protect=true;out.n++;return;}
if(m=line.match(/^drain\s+(.+)$/)){const r=teFind(m[1],CITIES,tr('common.city'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.drain.add(r.v);out.n++;return;}
if(m=line.match(/^avoid\s+link\s+(.+?)\s*(?:-|\bto\b|→)\s*(.+)$/)){const a=teFind(m[1],CITIES,tr('common.city')),b=teFind(m[2],CITIES,tr('common.city'));if(a.err||b.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:a.err||b.err}));return;}out.avoid.add(a.v<b.v?a.v+'|'+b.v:b.v+'|'+a.v);out.n++;return;}
if(line==='blackhole ddos'){out.blackhole=true;out.n++;return;}
out.errors.push(tr('routescript.line_n_i_don_t_understand',{n:L,text:raw.trim().slice(0,40)}));});
return out;}
// Share of an upstream's traffic that moves away for each prepend: prepending is a hint, not an order.
const PREPEND_F=[0,0.35,0.6,0.75];
function teOptimize(){const L=[tr('routescript.suggested_by_the_optimizer_from_live'),'spill at 85%'];
// Protecting customers costs a second routing pass: only worth it where IP customers would get unhappy (under 95% served).
if(S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95))L.push('protect customers');
const ups=[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p);
if(ups.length>1){L.push('prefer transit '+NET[ups[0].n].name.toLowerCase());L.push('avoid transit '+NET[ups[ups.length-1].n].name.toLowerCase());}
const tips=[];
for(const n of NETS){const g=(R.netEg[n.id]||{}).t||0;if(g<1)continue;// The exchange where it is a member and you have no port yet, in a city where you have a POP.
let at=null;for(const c of Object.keys(S.pops)){at=ixIdsIn(c).find(x=>S.ixp[x]===undefined&&ixMembers(x).includes(n.id));if(at)break;}
if(at){const v={net:n.name,g:fmtG(g),ix:ixName(at),city:CITY[ixCity(at)].name};tips.push([g,ixNamesCity(at)?tr('routescript.net_g_over_transit_but_it',v):tr('routescript.net_g_over_transit_but_it_e707',v)]);}}
for(const n of NETS){const g=(R.netEg[n.id]||{}).ix||0;if(g>=50&&!S.pni.some(p=>p.net===n.id))tips.push([g,tr('routescript.net_g_over_the_ix_a',{net:n.name,g:fmtG(g)})]);}
tips.sort((a,b)=>b[0]-a[0]).slice(0,5).forEach(x=>L.push(x[1]));
return L.join('\n');}
// Ready-made RouteScripts, filled in from the live network. Players load them from the help; the AI button picks them too.
const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p);
const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0;
const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95);
const TE_RECIPES=[
{id:'shield',n:N_('common.shields_up'),d:N_('routescript.for_a_ddos_drop_the_junk'),fit:()=>teAtk()?9:0.3,
src:()=>[tr('routescript.shields_up_for_the_length_of'),'blackhole ddos','protect customers','spill at 80%']},
{id:'care',n:N_('common.customer_care'),d:N_('routescript.business_customers_first_when_links'),fit:()=>teSad()?5:0.5,
src:()=>[tr('routescript.customer_care_the_people_who_pay'),'protect customers','spill at 75%']},
{id:'peer',n:N_('common.peering_first'),d:N_('routescript.big_networks_you_can_reach_over'),fit:()=>S.pni.length||Object.keys(S.ixp).length?3:0,
src:()=>{const L=[tr('routescript.peering_first_free_paths_before_paid'),'spill at 85%'],seen=new Set(),ix=new Set(),eg=n=>(R.netEg[n]||{}).t||0;
for(const p of S.pni)if(!seen.has(p.net)){seen.add(p.net);L.push('prefer pni for '+teNm(p.net));}
for(const c in S.ixp)for(const n of ixSessions(c))ix.add(n);
NETS.filter(n=>!seen.has(n.id)&&ix.has(n.id)&&eg(n.id)>=1).sort((a,b)=>eg(b.id)-eg(a.id)).slice(0,4).forEach(n=>L.push('prefer ix for '+teNm(n.id)));
if(L.length===2)L.push(tr('routescript.nothing_to_move_yet_get_an'));return L.slice(0,12);}},
{id:'pinch',n:N_('common.penny_pincher'),d:N_('routescript.cheapest_upstream_first_priciest'),fit:()=>teUps().length>1?2+(R.cost.transit||0)/1e5:0,
src:()=>{const u=teUps(),L=[tr('routescript.penny_pincher_cheapest_upstream'),'spill at 85%'];
if(u.length>1)L.push('prefer transit '+teNm(u[0].n),'avoid transit '+teNm(u[u.length-1].n));else L.push(tr('routescript.buy_transit_from_a_second_upstream'));return L;}},
{id:'diet',n:N_('common.prepend_diet'),d:N_('routescript.ask_the_rest_of_the_internet'),fit:()=>teUps().length>1?1.5:0,
src:()=>{const u=teUps();return [tr('routescript.prepend_diet_a_hint_to_the'),'spill at 85%',...(u.length>1?['prepend transit '+teNm(u[u.length-1].n)+' 2']:[tr('routescript.prepending_needs_two_upstreams_to')])];}},
{id:'maint',n:N_('common.maintenance_window'),d:N_('routescript.drain_a_pop_and_steer_around'),fit:()=>0.2,
src:()=>{const l=S.links.find(x=>!linkDown(x)),c=l?CITY[l.a].name.toLowerCase():'paris';return [tr('routescript.maintenance_window_change_the_names'),'drain '+c,...(l?['avoid link '+c+'-'+CITY[l.b].name.toLowerCase()]:[]),'spill at 80%'];}},
{id:'calm',n:N_('common.keep_calm'),d:N_('routescript.one_rule_move_traffic_before_links'),fit:()=>1,
src:()=>[tr('routescript.keep_calm_one_rule_hard_to'),'spill at 85%']}];
// The AI button: the two recipes that fit best, merged, with an AI's confidence on top.
const AI_NAMES=['Large Latency Model','Stochastic Parrot Pro','Co-Pilot Error','Autocomplete Ultra','Hallucinet 4o','Artificial Ignorance'];
const AI_SAY=[N_('routescript.great_question_here_is_a_production'),N_('routescript.as_a_large_language_model_i'),N_('routescript.i_have_optimised_your_network_you'),N_('routescript.done_i_vibe_checked_your_bgp'),N_('routescript.here_you_go_i_was_trained'),N_('routescript.i_asked_myself_to_review_my')];
function aiSlop(bad){const ai=pick(AI_NAMES),fits=TE_RECIPES.map(r=>({r,f:r.fit()})).filter(x=>x.f>0).sort((a,b)=>b.f-a.f).map(x=>x.r);
// It really does dry-run its three favourite ideas (and one merge) against live traffic, and keeps the best.
const merge=rs=>{const L=[],seen=new Set();for(const r of rs)for(const x of r.src()){const k=/^spill/.test(x)?'spill':x;if(!seen.has(k)){seen.add(k);L.push(x);}}return L;};
const cands=fits.slice(0,3).map(r=>merge([r])).concat([merge(fits.slice(0,2))]),val=x=>x.served*EYE_RATE-x.tc;
const keep=S.te&&S.te.script,on=S.te&&S.te.on;if(!S.te)S.te={on:false,day:S.day,tmp:1};let best=null,bv=-Infinity;
for(const L of cands){if(teParse(L.join('\n')).errors.length)continue;S.te.script=L.join('\n');S.te.on=true;compute();const v=val({served:R.served,tc:R.cost.transit||0});if(v>bv){bv=v;best=L;}}
if(S.te.tmp)delete S.te;else{S.te.script=keep;S.te.on=on;}compute();
const L=[tr('routescript.written_by_ai_prompt_make_my',{ai})].concat(best||merge([TE_RECIPES.find(r=>r.id==='calm')]));
// Very occasionally it is just as sure of itself and completely wrong. Nothing says so.
const u=teUps();if(bad&&u.length)L.splice(2,0,tr('routescript.a_cap_of_0_gbps_means'),...u.map(x=>'cap transit '+teNm(x.n)+' at 0 gbps'));
L.push(tr('common.confidence_100'));return {src:L.join('\n'),ai,say:pick(AI_SAY)};}
function teHelpModal(){const rule=(code,what)=>`<dt><code>${code}</code></dt><dd>${what}</dd>`;
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('routescript.auto_te_controller')}</div><h2 style="font-size:26px">${tr('routescript.how_routescript_works')}</h2></div><button class="x" data-act="teBack" aria-label="${tr('common.close')}">×</button></div>
<div class="tehelp"><p class="tagline">${tr('routescript.every_gigabit_leaving_your_network')}</p>
<h3>${tr('routescript.writing_a_script')}</h3><ul>
<li>${tr('routescript.one_rule_per_line_a_starts')}</li>
<li>${tr('routescript.networks_providers_and_cities_go_by')}</li>
<li>${tr('routescript.check_dry_run_replays_today_s')}</li>
<li>${tr('routescript.deploy_makes_it_live_for_the')}</li></ul>
<h3>${tr('common.rules')}</h3><dl>
${rule('spill at 85%',tr('routescript.move_traffic_to_the_next_exit'))}
${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'))}
${rule('prefer transit cogentle',tr('routescript.rank_your_upstreams_preferred_ones'))}
${rule('prepend transit drizzle electric 2',tr('routescript.as_path_prepending_1_to_3'))}
${rule('protect customers',tr('routescript.when_links_are_congested_business'))}
${rule('drain paris',tr('routescript.move_traffic_off_a_pop_s'))}
${rule('avoid link frankfurt-amsterdam',tr('routescript.steer_traffic_around_one_link_unless'))}
${rule('blackhole ddos',tr('routescript.during_an_attack_drop_the_flood'))}
</dl><h3>${tr('routescript.ready_made_scripts')}</h3><p class="meta">${tr('routescript.filled_in_from_your_network_as')}</p>
${TE_RECIPES.map(r=>`<div class="terec"><div><b>${tr(r.n)}</b><div class="meta">${tr(r.d)}</div></div>${btn(tr('common.load'),'teRecipe',{id:r.id},'sm')}</div>`).join('')}</div>
<div class="btns" style="margin-top:12px">${btn(tr('routescript.back_to_the_editor'),'teBack',{},'big')}</div>`);}
let TE_CACHE={src:null,p:null};
function teRules(){if(!S||!S.te||!S.te.on||!S.te.script)return null;if(TE_CACHE.src!==S.te.script)TE_CACHE={src:S.te.script,p:teParse(S.te.script)};return TE_CACHE.p.errors.length?null:TE_CACHE.p;}
function teModal(msg){const src=UI.teDraft!==undefined?UI.teDraft:(S.te.script||TE_EXAMPLE);
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('routescript.auto_te_controller')}</div><h2 style="font-size:26px">RouteScript</h2></div><button class="x" data-act="teClose" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('routescript.write_rules_check_them_against_live')}</p>
<textarea id="teSrc" class="tecode" spellcheck="false" autocapitalize="off" autocomplete="off" rows="12">${esc(src)}</textarea>
${msg||''}<div class="btns" style="margin-top:8px">${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')}</div><div class="btns" style="margin-top:6px">${btn('✨ '+tr('routescript.slop_it_with_ai'),'teSlop',{},'aibtn')}${btn(tr('routescript.help_and_ready_made_scripts'),'teHelp',{},'ghost sm')}</div>
<p class="meta" style="margin-top:8px"><b>${tr('common.rules_7b18')}</b> <code>spill at 80%</code> · <code>prefer pni|ix|transit for NETWORK</code> · <code>avoid pni|ix|transit for NETWORK</code> · <code>cap transit PROVIDER at 20 gbps</code> · <code>prefer|avoid transit PROVIDER</code> · <code>prepend transit PROVIDER 1-3</code> · <code>protect customers</code> · <code>drain CITY</code> · <code>avoid link CITY-CITY</code> · <code>blackhole ddos</code></p>
${S.te.script?`<p class="meta">${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')})}</p>`:''}`);}
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};
S.te.script=keep;S.te.on=on;compute();return {before,after};}

View file

@ -0,0 +1,271 @@
// tr() with one placeholder, remembered: compute() labels every port, PNI and cache on every run.
const LABS=new Map();function labOf(s,k,v){const key=s+'|'+v;let o=LABS.get(key);if(o===undefined)LABS.set(key,o=tr(s,{[k]:v}));return o;}
function compute(){
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={};
for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[],res:0,ld:0,tr:null,pl:0};adj[ai].push([bi,e]);adj[bi].push([ai,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f*(TRX&&TRX.avoid.has(key)?60:1));e.lat=Math.min(e.lat,linkLat(l));}
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by.
// ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it).
const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05;
for(const s of pops){const i=CIDX[s],r=dijkstra(adj,i,wW);SDi[i]=SPD[s]=r.D;SPi[i]=SPP[s]=r.P;ALONE[i]=1;for(let x=0;x<NC;x++)if(x!==i&&r.D[x]<1e-6)ALONE[i]=0;}
const E=[], ev=S.ev;
const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue;
// AS-path prepending (#96) moves part of the port to a last-resort exit of its own.
const cap=Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),pf=TRX&&TRX.prep[t.net]?PREPEND_F[TRX.prep[t.net]]:0;
const ex={k:'t',net:t.net,prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:labOf(N_('common.net_transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak};
E.push(ex);if(pf)E.push({...ex,cap:cap*pf,prep:true});}
// `nets`: every network ok() can say yes to, so it need not be asked about the other hundred.
for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!(S.myIx[c]?myIxLive(c):liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c])))continue;const set=ixSessions(c);R2.sessions+=set.size;
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('common.ix_peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n),nets:set});}
for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('common.pni_with_net'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,ok:n=>n===p.net||!!(NET[n].up&&NET[n].up.includes(p.net)),nets:PNI_NETS[p.net]});}
for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push({k:'c',pref:'normal',lab:labOf(N_('common.name_cache'),'name',NET[c.net].cache.name),id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net,nets:[c.net]});}
// After an update adds networks, a free courtesy route reaches the new ones you have no other way to (#46).
R2.graceNets=0;if(S.grace&&S.grace.until>day){const gs=new Set(S.grace.nets.filter(n=>NET[n]&&!E.some(e=>e.k!=='c'&&e.ok(n)))),hc=popUp(S.home)?S.home:pops.find(popUp);
R2.graceNets=gs.size;if(gs.size&&hc)E.push({k:'ix',pref:'normal',lab:tr('compute.courtesy_route_to_new_networks'),id:'~grace',city:hc,cap:1e9,used:0,rank:2,ok:n=>gs.has(n),nets:gs});}
{const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);}}
// ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank.
// okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)).
const okBy={};for(const id of NET_IDS)okBy[id]=[];
R2.ingressPorts={};const ekN={};for(const e of E){e.ek=e.k+':'+e.id;if(e.k!=='c'){const p=R2.ingressPorts[e.ek]||(R2.ingressPorts[e.ek]={k:e.k,id:e.id,city:e.city,lab:e.lab,cap:0,traffic:0});p.cap+=e.cap;}ekN[e.ek]=(ekN[e.ek]||0)+1;}
// dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last.
for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}}
for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id];}}
const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net));
const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1);
// Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index).
const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j],f={c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j};flows.push(f);return f;};
// Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give).
const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}}
// Traffic shares by network index, and their sums, for each share table (and with Russia's throttle).
const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),scrubRoom={},atkBy={},junkGroups=[],bhCities=new Set(ddosAll().filter(a=>a.bh).map(a=>a.city));R2.haul=[];R2.ddos=[];for(const a of ddosAll())for(const part of ddosSlices(a))(atkBy[part.city]||(atkBy[part.city]=[])).push(part);
for(const c of Object.keys(S.pops)){
const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz;
// Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not
// 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=[]);}
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;
R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d;
for(let j=0;j<NN;j++)DEMTO[j]=(DEMTO[j]||0)+d0*sa[j]*thr(NETS[j].id);
// A shaped attack: `rtbh` is the player pulling the plug on the victim IP (junk gone, customer dark too);
// `edge` is the crude RouteScript `blackhole ddos` filter (junk gone, 10% of real traffic with it). Flowspec
// (a standing licence) and a scrubbing center each knock the flood down before it reaches the sim.
const attacks=atkBy[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh);
let dd=0;
for(const atk of attacks){const m=ddosMitigation(atk,{},bhCities.has((atk.parent||atk).city),false);R2.ddos.push(m);dd+=m.leak;
const group={m,flows:[]};junkGroups.push(group);
if(atk.entries?.length){for(const q of m.ingress){const f=flow(c,ci,cn,0,q.g,false,true);f.pin=q.entry.k+':'+q.entry.id;group.flows.push({f,share:m.leak>0?q.g/m.leak:0});}}
else for(let j=0;j<NN;j++)group.flows.push({f:flow(c,ci,cn,j,m.leak*NSH[NETS[j].id],false,true),share:NSH[NETS[j].id]});}
if(!popUp(c)){for(const m of R2.ddos.filter(m=>m.attack.city===c))m.offline=true;continue;}
const bh=rtbh||edge;
if(edge)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d;
R2.cityBlocked=R2.cityBlocked||{};
const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr;
for(let j=0;j<NN;j++){const n=NETS[j],a=(loc&&!R2.reachable[n.id]?0:d0)*sa[j]*thr(n.id)*(rtbh?0:edge?0.9:1)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&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(c,ci,cn,j,x*0.85,true,false,bz);flow(c,ci,cn,j,x*0.15,false,false,bz);}
else flow(c,ci,cn,j,x,false,false,bz);}}
R2.bizDem[c]=biz*d/(d0||1);R2.bizSrv[c]=0;
}
if(Object.keys(S.pops).length)for(let j=0;j<NN;j++)R2.demTo[NETS[j].id]=DEMTO[j];
/* While routing, each edge keeps its own room (res) and load (ld). Routers only exist in POPs (HAS): their room,
load and served traffic are kept per city index. What crosses each edge (R.ef) is added up by egress, and in
arrays by network (then 'junk' and 'l2vpn') and by source city, each key in the order it first got traffic. */
const LATP=new Float64Array(NC),FARL=[],NRES=new Float64Array(NC),HAS=new Uint8Array(NC),NLOAD=new Float64Array(NC),NSEEN=new Uint8Array(NC),NORD=[],SRV=new Float64Array(NC);
for(const k in edges)edges[k].res=edges[k].cap;for(const c of pops){const i=CIDX[c];NRES[i]=nodeCap(c);HAS[i]=1;R2.nodeCap[c]=NRES[i];}
const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;};
const NKN=NN+2,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[];
const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),n:[],d:[]};EL.push(l);}t.g.set(eg,(t.g.get(eg)||0)+a);
let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;};
R2.l2route={};R2.l2split={};
/* Scenic routing (#28). "Busy" is judged without the customer's own traffic, or it flees its own load and
flips paths every day. Two paths that are about as quiet share the load, and yesterday's choice is kept
unless today's is clearly better. */
const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id);
// disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer.
const LA=[];for(const l of live){const ai=CIDX[l.a],bi=CIDX[l.b];(LA[ai]||(LA[ai]=[])).push([bi,l]);(LA[bi]||(LA[bi]=[])).push([ai,l]);}
const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfsI=(a,b,skip)=>{const prev=[],seen=new Uint8Array(NC),q=[a];seen[a]=1;
for(let h=0;h<q.length;){const u=q[h++];if(u===b)break;for(const [v,l] of LA[u]||[])if(!seen[v]&&!(skip&&skip.has(srlg(l)))){seen[v]=1;prev[v]=l;q.push(v);}}
if(!seen[b])return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=CIDX[l.a]===v?CIDX[l.b]:CIDX[l.a];}return path;};
const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));};
for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;}
const l2Routes=(A,B,b)=>{const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B];
if(m!=='scenic')return [{...walkI(m==='fast'?(fastSP[A]||(fastSP[A]=dijkstra(adj,Ai,wLat))).P:SPP[A],Ai,Bi),share:1}];
const ek='l2:'+b.id,own=e=>(R.efg&&R.efg[e.id]&&R.efg[e.id].get(ek))||0;
const wf=e=>e.w*(1+10*(e.cap?Math.max(0,e.pl-own(e))/e.cap:0));
const cost=r=>r.path.reduce((x,e)=>x+wf(e),0)*r.share;
const s1=dijkstra(adj,Ai,wf,null,Bi);if(s1.D[Bi]===Infinity)return [{...walkI(SPP[A],Ai,Bi),share:1}];
const p1=walkI(s1.P,Ai,Bi),c1=cost({path:p1.path,share:1}),used=new Set(p1.path.map(e=>e.id));let pick2=[{...p1,share:1}];
const s2=dijkstra(adj,Ai,wf,(v,e)=>used.has(e.id),Bi);
if(s2.D[Bi]!==Infinity){const p2=walkI(s2.P,Ai,Bi);if(cost({path:p2.path,share:1})<=c1*1.15)pick2=[{...p1,share:0.5},{...p2,share:0.5}];}
const key=b.id+'>'+A+'>'+B,old=R.l2route&&R.l2route[key];let out=pick2;
if(old&&old.every(r=>r.keys.every(k=>edges[k]))){const prev=old.map(r=>{const path=r.keys.map(k=>edges[k]);return {path,ni:r.ns.map(c=>CIDX[c]),share:r.share};});
if(prev.reduce((x,r)=>x+cost(r),0)<=pick2.reduce((x,r)=>x+cost(r),0)*1.1)out=prev;}
R2.l2route[key]=out.map(r=>({keys:r.path.map(e=>e.id),ns:cityIds(r.ni),share:r.share}));return out;};
for(const b of S.biz){if(!BIZ_T[b.type].l2)continue;
// An SD-WAN is hub-and-spoke: one circuit from the first site to each of the others.
const pairs=b.sites?b.sites.slice(1).map(x=>[b.sites[0],x]):[[b.city,b.city2]];let minF=1,maxLat=0,tot=0,noPath=false;
for(const [A,B] of pairs){let amt=0;
if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][CIDX[B]]<Infinity){
const ek='l2:'+b.id;R2.egDesc[ek]={lab:labOf(b.sites?N_('compute.sd_wan_for_name'):N_('compute.l2vpn_for_name'),'name',b.name),city:A,k:'l2'};
const routes=l2Routes(A,B,b);if(routes.length>1)R2.l2split[b.id]=routes.length;
for(const {path,ni,share} of routes){let a=b.bw*share;for(const l of path)a=Math.min(a,l.res);for(const i of ni)if(HAS[i])a=Math.min(a,NRES[i]);a=Math.max(0,a);amt+=a;maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05);
for(const i of ni)if(HAS[i])nodeTake(i,a);
for(const l of path){l.res-=a;l.ld+=a;carry(l,ek,NN+1,CIDX[B],a);}}}
else noPath=true;
minF=Math.min(minF,amt/b.bw);tot+=amt;}
R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;
// Same answer as diversePaths(), which would rebuild today's live links for every customer.
if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}}
/* A flood for a scrubbing center elsewhere rides the backbone there, with the victim's own traffic (#117).
What the links cannot carry is not scrubbed and lands on the city after all. */
const scrubNear=new Map();
for(const m of R2.ddos){const atk=m.attack,A=atk.city,Ai=CIDX[A];
m.sp=!m.offline&&m.leak>0?scrubPlan(atk,m.leak,scrubRoom,(x,want)=>{const B=x.city,Bi=CIDX[B];if(A===B)return want;let h=0,ms=null;
if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]<Infinity){const {path,ni}=walkI(SPP[A],Ai,Bi);let room=Infinity;for(const l of path)room=Math.min(room,l.res);for(const i of ni)if(HAS[i])room=Math.min(room,NRES[i]);
const v=R2.cityDem[A]*0.1*want/Math.max(m.leak,1)/atkBy[A].length,total=want+v,take=Math.max(0,Math.min(total,room));h=total>0?want*take/total:0;ms=path.reduce((n,e)=>n+e.lat,0)*2;
// Sources sharing a center need separate labels in link breakdowns and map highlights.
const ek='scrub:'+A+'>'+B;R2.egDesc[ek]={lab:labOf(N_('compute.attack_hauled_to_scrubbing_in_city'),'city',CITY[B].name),city:A,k:'l2'};
for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}}
R2.haul.push({city:A,to:B,tier:x.tier||0,a:want,h,ms,attack:atk.id});return h;}):null;
if(m.sp){m.leak=m.sp.leak;
// The card describes the victim's nearest center, separately from distributed ingress hauling above.
const c=(atk.parent||atk).city;let near=scrubNear.get(c);if(near===undefined){near=null;
for(const x of S.scrubs)if(popUp(x.city)&&SPD[c]&&SPD[c][CIDX[x.city]]<Infinity){const ms=c===x.city?0:walkI(SPP[c],CIDX[c],CIDX[x.city]).path.reduce((n,e)=>n+e.lat,0);if(!near||ms<near.ms)near={city:x.city,ms};}
scrubNear.set(c,near);}m.near=near;}}
for(const group of junkGroups)for(const q of group.flows)q.f.rem=group.m.offline?0:group.m.leak*q.share;
const TE=!!(S.te&&S.te.on),TR=teRules();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1;
const altPath=(src,dst,base)=>{const key=src*NC+dst,c0=teCache.get(key);
if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0;
const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst);
if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;}
const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;};
const ingressE={};for(const e of E)(ingressE[e.ek]||(ingressE[e.ek]=[])).push(e);
const base=e=>e.pref==='low'?4:e.rank;
// LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96).
const eff=(e,n)=>{let r=base(e);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;};
const RANKS=TR?[0,0.5,1,2,2.9,3,3.5,4,4.4,4.5,4.6]:[0,1,2,3,4];
// With `protect customers`, business flows take every rank first; home users get what is left.
const PASSES=TR&&TR.protect?[x=>x.bz,x=>!x.bz]:null;
// Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order.
// Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order.
const byRank={};for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e);(m[r]||(m[r]=[])).push(e);}
for(const r in m){const L=m[r];L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}}
// The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index.
let f=null,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[];
// An exit the flow can still try: not visited yet, not full when the flow started, and reachable from the POP.
const usable=e=>e.vis!==vis&&e.used<e.cap&&Dv[e.ci]<Infinity,byDist=(a,b)=>a.hp-b.hp||Dv[a.ci]-Dv[b.ci];
// Push up to `want` along one path to exit e; returns what fitted. Capacity only shrinks while routing, so a
// path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing
// (most tries are into paths that filled up earlier).
const push=(e,P,want,keep=0)=>{if(P.dead)return 0;const path=P.path,ni=P.ni;let amt=want;
for(const l of path){const r=l.res;if(r<=1e-6){P.dead=1;return 0;}amt=Math.min(amt,r-l.cap*keep);}
for(const i of ni)if(HAS[i]){const r=NRES[i];if(r<=1e-6){P.dead=1;return 0;}amt=Math.min(amt,r);}
if(amt<=1e-6)return 0;
for(const i of ni)if(HAS[i])nodeTake(i,amt);
const ek=e.ek,nr=f.nr,ci=f.ci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc;e.told=true;}
for(const l of path){l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);}
e.used+=amt;f.rem-=amt;
if(!f.junk){if(e.k!=='c')R2.ingressPorts[ek].traffic+=amt;let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn;
if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;
// Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then
// it gets worse, and past 50 ms broadband and internet services count as bad service (#…).
if(path.length){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms;
if(rtt>LAT_OK){LATP[f.ci]+=ok*latLoss(rtt);if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
return amt;
};
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
// with free capacity, as long as they are no more than twice as long.
const send=(e,want)=>{
let room=Math.min(want,f.rem,e.cap-e.used);if(room<=1e-6)return;
const P=PP[e.ci]||(PP[e.ci]=walkI(Pv,f.ci,e.ci));if(!P.dead)room-=push(e,P,room,TE&&SPILL<1?1-SPILL:0);
if(TE&&room>1e-6&&f.rem>1e-6&&e.used<e.cap&&e.city!==f.c)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(f.ci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
};
// 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).
// Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes).
const gone=e=>{if(TE)return false;const P=PP[e.ci];return !!P&&P.dead===1;};
const ROOM=[],sendGroup=(g,i0=0,i1=g.length)=>{for(let k=i0;k<i1;k++)g[k].vis=vis;
if(i1-i0>1){let tot=0;for(let k=i0;k<i1;k++){const e=g[k],r=Math.max(0,e.cap-e.used);ROOM[k-i0]=r;tot+=r;}const want=f.rem;if(tot>1e-6)for(let k=i0;k<i1;k++)if(!gone(g[k]))send(g[k],want*ROOM[k-i0]/tot);}
for(let k=i0;k<i1;k++){if(f.rem<=1e-6)break;if(!gone(g[k]))send(g[k],f.rem);}};
// Stable, in place: short lists by insertion (no garbage), long ones by the built-in sort. Both are stable with the
// same comparison, so the order is the same either way.
const sortD=a=>{const n=a.length;if(n>24){a.sort(byDist);return;}for(let i=1;i<n;i++){const x=a[i];let j=i-1;while(j>=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}};
for(const pass of PASSES||[null])for(const rank of RANKS){
if(TR?!E.length:!E.some(e=>base(e)===rank))continue;
// Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute().
for(let fi=0,FN=flows.length;fi<FN;fi++){f=flows[fi];
if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue;
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
if(f.pin){for(const e of ingressE[f.pin]||[])if(base(e)===rank&&e.used<e.cap&&Dv[e.ci]<Infinity)send(e,f.rem);continue;}
const lst=byRank[f.n][rank];if(!lst)continue;
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
exits gives. Exits only fill up once tried, so the usable ones stay the same until then. Nearly every flow
fits in its first group: find that one with a scan (nothing is visited yet), and sort only what is left
when it does not fit. Most often the group is the POP's own exits: with no preferred exit on the list
and no other city at distance 0, the usable ones here are exactly the first group, already in order. */
G.length=0;
if(!lst.hi&&ALONE[f.ci]){const here=lst.at.get(f.ci);if(here)for(const e of here)if(e.used<e.cap)G.push(e);}
if(!G.length){
// One scan: the best (preference, distance) so far and, in list order, the exits within 1e-6 of it. The best
// distance only goes down, so dropping the ones it leaves behind gives exactly the exits a second scan would.
// Exits that are full stay full for this pass: when a quarter of a list is, it is rewritten without them.
let bh=2,bd=Infinity,full=0;
for(let li=0,LN=lst.length;li<LN;li++){const e=lst[li];if(e.used>=e.cap){full++;continue;}const d=Dv[e.ci];if(d===Infinity)continue;const h=e.hp;
if(h<bh){bh=h;bd=d;G.length=0;G.push(e);}
else if(h===bh){if(d<bd){bd=d;let k=0;for(let gi=0;gi<G.length;gi++){const x=G[gi];if(Dv[x.ci]-d<1e-6)G[k++]=x;}G.length=k;G.push(e);}else if(d-bd<1e-6)G.push(e);}}
if(full*4>=lst.length&&full){let k=0;for(let li=0;li<lst.length;li++){const e=lst[li];if(e.used<e.cap)lst[k++]=e;}lst.length=k;}
if(bh>1)continue;
if(G.length>1)sortD(G);}
sendGroup(G,0,G.length);
if(f.rem<=1e-6)continue;
REST.length=0;for(let li=0;li<lst.length;li++)if(usable(lst[li]))REST.push(lst[li]);sortD(REST);
for(let i=0;i<REST.length&&f.rem>1e-6;){
let j=i+1;while(j<REST.length&&REST[j].hp===REST[i].hp&&Math.abs(Dv[REST[j].ci]-Dv[REST[i].ci])<1e-6)j++;
sendGroup(REST,i,j);i=j;
}
}
}
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i];
if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);}
// Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did.
{const G=new Map();for(let k=0;k<FARL.length;k+=3){const P=FARL[k],src=FARL[k+1],to=FARL[k+2],key=src*NC+to,o=G.get(key);if(o){o.g+=P.fg;o.ms=Math.max(o.ms,2*P.ms);}else G.set(key,{src,to,g:P.fg,ms:2*P.ms});}
for(const o of G.values()){const c=CITIES[o.src].id,cur=R2.latFar[c];if(!cur||o.g>cur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}}
// R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic
// routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same).
{const efg={};for(const l of EL){const t=l.tr,i=l.i;let rec=null;efg[l.id]=t.g;
Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of t.g)rec.eg[k]=v;
for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});}
Object.defineProperty(R2,'efg',{value:efg});}
for(const k in edges){const e=edges[k],ld=e.ld||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
R2.peerShare=R2.served>0?R2.peered/R2.served:0;
for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
// money
const C=R2.cost,V=R2.rev,pm=S.priceMul;
C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0);
C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0);
C.links=S.links.reduce((a,l)=>a+(l.mo||0),0);
C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0);
C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0);R2.p95[t.id]=q;return a+transitMo(t,q);},0);
C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0);
C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0);
C.caches=S.caches.length*CACHE_MO;
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0);
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.inbox&&S.inbox.bot?AI_MO:0);
V.eyeballs=0;V.business=0;V.ix=0;
C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c),v=R2.cityEye[c]*sf*EYE_RATE*(CITY[c].arpu||1);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}}
for(const b of S.biz){const sf=BIZ_T[b.type].fiber?(fiberOk(b)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}
for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE;
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix);
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
R2.revMo=V.eyeballs+V.business+V.ix;
R=R2;UI.hotMap=hotByCity();
}

View file

@ -0,0 +1,10 @@
function p95(t,cur){const h=(t.hist||[]).slice(-29).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'&&dfCap(l)<=0);}
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.
function transitMo(t,q){const n=t.n||1;return Math.max(q,PORT[t.tier].g*n*0.2)*NET[t.net].price*(t.premium&&t.city==='hkg'?NET[t.net].premium:1)*S.priceMul*regionMult(t.city)+PORT[t.tier].tmo*n+(t.clean?cleanMo(t):0);}
function pniMo(p,use){if(!pniOn(p))return 0;return (p.g1?Math.round(PORT[0].pni/2):PORT[p.tier].pni)*(p.n||1)+(NET[p.net].pol==='paid'&&!paidFree(NET[p.net])?NET[p.net].paidFee:0)+(NET[p.net].perG?Math.round(NET[p.net].perG*use):0);}
function ixMo(c){return S.myIx[c]?Math.round(myFab(c).mo*((S.ixSite||{})[c]==='ab'?1.5:1)):ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1)+dkAddonMo(c);}
function nniPort(c,prov){return (S.nni||[]).find(x=>x.city===c&&x.prov===prov);}
function repayCost(l,B){return B.equity?Math.round(l.amount*3):Math.round(Math.max(l.bal,B.crypto&&l.got?l.got:0)*1.02);}

View file

@ -0,0 +1,78 @@
const own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
const isCity=c=>typeof c==='string'&&own(CITY,c),isIx=x=>typeof x==='string'&&(own(CITY,x)||own(XIXM,x)),isNet=n=>typeof n==='string'&&own(NET,n);
const num=(v,d=0)=>{v=+v;return Number.isFinite(v)?v:d;},int=(v,lo,hi,d)=>{v=Math.round(num(v,d));return Math.min(hi,Math.max(lo,v));};
/* Saves come from localStorage or from imported files, so treat them as untrusted: fill in anything
missing, drop references to cities, networks or types that do not exist, and force numbers to be numbers. */
function sanitize(s){
const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};};
['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr);
['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach'].forEach(obj);
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0);
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0);
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';
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);
s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);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))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);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);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;});
for(const l of s.links)repairSubUpgradeDates(l,s.day);
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));
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));
// 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}: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)};
if(lk&&typeof lk==='object')o.lock={until:num(lk.until,0),mul:clamp(num(lk.mul,1),1,HW_CAP)};s.hw=o;}
{const I=s.inbox&&typeof s.inbox==='object'&&!Array.isArray(s.inbox)?s.inbox:{},o=v=>v&&typeof v==='object'&&!Array.isArray(v)?v:{},str=(v,n)=>String(v==null?'':v).slice(0,n);
const items=(Array.isArray(I.items)?I.items:[]).filter(x=>x&&typeof x==='object'&&(x.k==='req'||x.k==='mp')&&typeof x.ix==='string'&&isIx(x.ix)&&(x.net===undefined||isNet(x.net))&&(x.net!==undefined||typeof x.nm==='string')).slice(0,INBOX_MAX).map(x=>({id:int(x.id,0,1e9,0),k:x.k,ix:x.ix,net:x.net,nm:x.net?undefined:str(x.nm,40),asn:x.net?undefined:int(x.asn,1,4294967294,64512),day:num(x.day,0),stale:!!x.stale,yrs:int(x.yrs,1,30,1),say:int(x.say,0,REQ_SAY.length-1,0),bump:x.bump?1:undefined,key:x.k==='mp'?str(x.key,80):undefined,lim:x.k==='mp'?int(x.lim,1,1e7,100):undefined,got:x.k==='mp'?int(x.got,1,1e7,100):undefined,leak:x.k==='mp'?!!x.leak:undefined}));
const down={};for(const [k,v] of Object.entries(o(I.down)))if(typeof k==='string'&&k.length<80)down[k]=num(v,0);
const tiny={};for(const [k,v] of Object.entries(o(I.tiny)).slice(0,200))if(/^\d{1,10}$/.test(k)&&v&&typeof v==='object'&&isIx(v.ix))tiny[k]={nm:str(v.nm,40),ix:v.ix,stale:!!v.stale};
const log=(Array.isArray(I.log)?I.log:[]).filter(e=>e&&typeof e==='object'&&typeof e.m==='string').slice(0,40).map(e=>{const a={};for(const [k,v] of Object.entries(o(e.a)).slice(0,6))a[str(k,12)]=typeof v==='number'?v:str(v,60);return {d:num(e.d,0),m:str(e.m,200),a};});
s.inbox={items,down,tiny,rep:clamp(num(I.rep,0),-10,5),bot:!!I.bot,pol:PPOL.includes(I.pol)?I.pol:'open',log,seq:Math.max(int(I.seq,0,1e9,0),...items.map(x=>x.id))};}
{const sp={};if(s.spares&&typeof s.spares==='object')for(const k in s.spares)if(own(OPT,k)){const v=Math.floor(+s.spares[k]);if(v>0)sp[k]=Math.min(999,v);}s.spares=sp;}
s.caches=s.caches.filter(x=>x&&isCity(x.city)&&isNet(x.net)&&NET[x.net].cache).map(x=>(x.id=sid(x.id),x.site=x.site==='b'&&s.pops[x.city]&&s.pops[x.city].site2?'b':'a',x));
for(const c of Object.keys(s.ixp)){if(!isIx(c))delete s.ixp[c];else s.ixp[c]=tier(s.ixp[c]);}
for(const k of ['rs','ixn','ixPref','ixSite'])for(const c of Object.keys(s[k]))if(!isIx(c))delete s[k][c];if(s.ixCut&&typeof s.ixCut==='object'){for(const c of Object.keys(s.ixCut))if(!isIx(c))delete s.ixCut[c];else s.ixCut[c]=Math.min(1,Math.max(0.6,num(s.ixCut[c],1)));}else delete s.ixCut;
for(const c of Object.keys(s.ixn))s.ixn[c]=lag(s.ixn[c]);for(const c of Object.keys(s.ixSite))if(!['a','b','ab'].includes(s.ixSite[c]))s.ixSite[c]='a';
for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];}
for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);}
const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity));
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';return b;};
s.biz=s.biz.filter(okBiz).map(fixBiz);s.offers=s.offers.filter(okBiz).map(fixBiz);
s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(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));
s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank));
s.usedNames=s.usedNames.filter(x=>typeof x==='string');s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='inbox'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null;
return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};});
// One scrubbing center became a list (#117): older saves carry theirs over.
if(!Array.isArray(s.scrubs))s.scrubs=s.scrubAt&&isCity(s.scrubAt)?[{city:s.scrubAt,tier:s.scrubTier}]:[];delete s.scrubAt;delete s.scrubTier;
{const seen=new Set();s.scrubs=s.scrubs.filter(x=>x&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));}
s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always';
// Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it.
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null;
a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+7);
if(Array.isArray(a.entries)){a.entries=a.entries.filter(en=>en&&['t','ix','p'].includes(en.k)&&isCity(en.city)&&typeof en.id==='string'&&Number.isFinite(+en.share)&&+en.share>0).slice(0,3000).map(en=>({k:en.k,id:en.id.slice(0,40),city:en.city,lab:String(en.lab||'').slice(0,60),share:+en.share}));const sum=a.entries.reduce((n,en)=>n+en.share,0);if(Number.isFinite(sum)&&sum>0)for(const en of a.entries)en.share/=sum;else delete a.entries;}else delete a.entries;
a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[];
if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}return a;};
const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14);
if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1);
s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14);
s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews;
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):'';}}
return s;}
function migrate(s){sanitize(s);
// Older saves have one contract per broker sale: fold a carrier's alien waves on one fiber into one contract.
{const one=new Map();s.biz=s.biz.filter(b=>{if(b.type!=='wwave')return true;const k=b.link+'|'+b.name,a=one.get(k);if(!a){one.set(k,b);return true;}
a.slots=(a.slots||0)+(b.slots||0);a.rate=(a.rate||0)+(b.rate||0);a.since=Math.min(a.since??0,b.since??0);a.mood=Math.min(a.mood??100,b.mood??100);a.folded=true;return false;});
for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true;for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave';
for(const c in s.pops){const p=s.pops[c];if(p.rgen===undefined){let g=0;const need=(i,key)=>{const k=RG.findIndex(r=>r[key]>=i);if(k>g)g=k;};
for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT');
for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');if(s.ixp&&s.ixp[c]!==undefined)need(s.ixp[c],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=s.nni||[];s.cnLic=s.cnLic||{state:'none'};s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;}
{const all=NETS.map(n=>n.id),seen=Array.isArray(s.seen)?s.seen.filter(x=>typeof x==='string'):null,fresh=seen?all.filter(id=>!seen.includes(id)):all;
if(fresh.length&&(s.day||0)>0){const g=s.grace&&s.grace.until>s.day?s.grace:{nets:[]};s.grace={until:s.day+GRACE_DAYS,nets:[...new Set(g.nets.concat(fresh))],fresh:seen?fresh.length:0};}
s.seen=all;}
// Australian pricing and peering changed in place (#148): a save that was already there gets told once.
if(s.auV!==1){if((s.day||0)>0&&Object.keys(s.pops).some(c=>CITY[c].au))s.auNews=true;s.auV=1;}
if(s.grace&&(typeof s.grace!=='object'||!isFinite(s.grace.until)||!Array.isArray(s.grace.nets)))s.grace=null;if(s.grace)s.grace.nets=s.grace.nets.filter(isNet);
return s;}

View file

@ -0,0 +1,63 @@
const GRACE_DAYS=60;
const REQS={
lat:{only:true,l2:true,bonus:0,l:o=>tr('requirements.one_way_latency_within_max_ms',{max:o.latMax,best:(()=>{const v=R.l2lat[o.id]!==undefined?R.l2lat[o.id]:bestLat(o.city,o.city2);return isFinite(v)?v.toFixed(1)+' ms':tr('common.no_path')})()}),ok:b=>(R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2))<=b.latMax},
nni:{only:true,bonus:0,l:o=>tr('requirements.comes_in_over_fab_needs_your',{fab:FAB[o.prov]?FAB[o.prov].name:'?',city:CITY[o.city].name,bw:fmtG(o.bw)}),ok:b=>{const pt=nniPort(b.city,b.prov);return !!pt&&nniUsed(b.city,b.prov)<=NNI[pt.tier].g+1e-9;}},
diverse:{l:tr('requirements.two_paths_that_share_no_trench'),bonus:.25,l2:true,can:(b,s=S)=>diversityPossible(b.city,b.city2,s),ok:b=>R.div[b.id]!==undefined?!!R.div[b.id]:diversePaths(b.city,b.city2)},
sharks:{l:tr('requirements.afraid_of_sharks_needs_a_path'),bonus:.2,l2:true,ok:b=>terrestrialPath(b.city,b.city2),can:b=>!!b.city2&&!isSub(b.city,b.city2)},
nocog:{l:tr('requirements.refuses_cogentle_transit_anywhere_on'),bonus:.15,ok:()=>!S.transit.some(t=>t.net==='cog')},
ipv6:{l:tr('requirements.ipv6_or_bust_you_must_peer'),bonus:.1,ok:()=>Object.keys(S.ixp).some(c=>ixSessions(c).has('drz'))||S.pni.some(p=>p.net==='drz'&&pniOn(p))},
netchill:{l:tr('requirements.wants_netchill_on_net_a_cache'),bonus:.15,ok:()=>S.caches.some(c=>c.net==='nfx')||S.pni.some(p=>p.net==='nfx'&&pniOn(p))},
gen:{l:tr('requirements.backup_generator_in_every_city_they'),bonus:.15,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].gen)},
routers:{l:tr('requirements.insists_on_two_routers_in_their'),bonus:.15,ok:b=>((S.pops[b.city]&&S.pops[b.city].routers)||1)>=2},
local:{l:tr('requirements.local_breakout_transit_or_an_ix'),bonus:.2,ip:true,ok:b=>S.transit.some(t=>t.city===b.city)||hasIxAt(b.city)||(isTier1()&&S.pni.some(p=>p.city===b.city))},
metro:{l:tr('requirements.two_data_centers_in_every_metro'),bonus:.2,only:true,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].site2)},
twoup:{l:tr('requirements.wants_two_different_transit'),bonus:.15,ip:true,ok:()=>new Set(S.transit.map(t=>t.net)).size>=2||S.transit.length===0},
china:{l:tr('requirements.needs_low_loss_reach_into_china'),bonus:.3,ip:true,ok:()=>S.transit.some(t=>t.premium&&t.city==='hkg')||S.links.some(l=>l.premium)||S.pni.some(p=>NET[p.net].cn&&pniOn(p))},
scrubbed:{l:tr('requirements.will_only_sign_with_a_network'),bonus:.15,ok:()=>hasScrub()},
scrubnear:{l:tr('requirements.wants_a_scrubbing_center_on_its'),bonus:.15,ip:true,ok:b=>S.scrubs.some(x=>CITY[x.city].reg===CITY[b.city].reg)},
puns:{l:tr('requirements.their_ceo_hates_puns_please_do'),bonus:.05,ok:()=>true},
};
function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b));
// Some requirements only make sense for some customers: nobody can reach another continent without getting wet.
const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b);
function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(lab)}</div>`;}).join('');}
function diversePaths(a,b){
const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);
return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));}
function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));}
// Check buildable geography, not today's POPs, capacity or outages. Parallel land
// routes can use separate trenches; all segments of one cable share its risk.
let diversityMap=null;
function diversityPossible(a,b,state=S){
if(!CITY[a]||!CITY[b]||a===b)return false;
const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]);
if(!diversityMap||diversityMap.key!==key){
const links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id);
const add=(a,b,id)=>links.push({a,b,id});
for(let i=0;i<cities.length;i++)for(let j=i+1;j<cities.length;j++){
const a=cities[i],b=cities[j];
if(!isSub(a,b)){add(a,b,'land:'+a+':'+b+':1');add(a,b,'land:'+a+':'+b+':2');}
for(const c of cablesFor(a,b))if(!(rules.banPairs||[]).some(p=>p===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid);
if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b);
for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);
}
diversityMap={key,links,answers:{}};
}
const pair=[a,b].sort().join(':');
return diversityMap.answers[pair]??(diversityMap.answers[pair]=disjointRoutes(a,b,diversityMap.links));
}
function fiberOk(b){const l=S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day);}
function soldSlots(l){return S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);}
// Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build
// a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices.
const freeCh=l=>chMax(l)-(l.ch||[]).length-soldSlots(l),pairFree=l=>!!l.own&&S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length<2&&!S.biz.some(b=>b.type==='pairs'&&b.link===l.id);
const wwWhat=(l,n)=>trn('requirements.n_400g_alien_wave_on_your',n,{a:CITY[l.a].name,b:CITY[l.b].name});
function fiberOffer(t,l,nm,cut=1){
if(t==='wwave'){const slots=1+Math.floor(Math.random()*Math.min(4,freeCh(l)));
return {id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:wwWhat(l,slots),name:nm(),type:t,bw:1,rate:Math.round(waveMo(l.km,false,2)*0.55*slots*cut),reqs:[],exp:S.day+30};}
return {id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9*cut),reqs:[],exp:S.day+30};}

View file

@ -0,0 +1,45 @@
function bizSf(b){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):bizSfOf(R,b.city);}
// Protected business traffic has its own served share; without the rule it shares the city's.
function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules().protect&&d>1e-6?clamp(r.bizSrv[c]/d,0,1):sfOf(r,c);}
function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);}
function bHas(o){return bCities(o).every(c=>S.pops[c]);}
function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day<b.start+b.dur;}
function bRisk(b){return BIZ_T[b.type]?.gaming?`<div class="meta">⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}</div>`:'';}
function bTerms(o){const T=BIZ_T[o.type];
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)});
if(T.fiber)return esc(o.what)+' · '+tr('common.price_mo',{price:fmt$(o.rate)});
return fmtG(o.bw)+' · '+tr('common.price_mo',{price:fmt$(o.bw*o.rate)});}
// Events are paid once at the end, prorated by how much of the crowd you served.
function eventTick(b,d){if(!BIZ_T[b.type].event)return false;if(d<b.start)return true;
if(d<b.start+b.dur){b.srv=(b.srv||0)+sfOf(R,b.city);b.srvDays=(b.srvDays||0)+1;if(d===b.start)toast(tr('customers_and_events.name_starts_today_bw_of_extra',{name:esc(b.name),bw:fmtG(b.bw),city:CITY[b.city].name,d:b.dur}),'goal',[{l:tr('common.show_me'),act:'focusCity',args:{city:b.city}}]);return true;}
const avg=b.srvDays?b.srv/b.srvDays:0;if(avg>=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:'Colossal Ego 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'}];
function spawnMega(t,T,nm,mine){
const megaMine=MEGA.filter(m=>mine.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);
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);
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;
const sites=[hub.c];while(sites.length<Math.min(4,pool.length+1)&&pool.length)sites.push(pool.splice(Math.floor(Math.random()*pool.length),1)[0]);
const avg=sites.slice(1).reduce((x,c)=>x+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;}
if(t==='pairs'){const ls=S.links.filter(l=>l.kind==='df'&&l.own&&l.ready<=S.day&&!S.biz.some(b=>(b.type==='pairs'||b.type==='dfpair')&&b.link===l.id)&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls),n=100+50*Math.floor(Math.random()*7);
S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('customers_and_events.n_fiber_pairs_in_your_a',{n,a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*n*0.2),reqs:[],exp:S.day+30,mega:true});}
}
function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1;
const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);S.usedNames.push(n);return n;};
if(T.mega){spawnMega(t,T,nm,mine);return;}
if(T.event){const city=Math.random()<0.85&&mine.length?pick(mine):pick(OFFC);const bw=pick(T.opts.slice(0,Math.min(T.opts.length,lv+2)));const dur=3+Math.floor(Math.random()*5),start=S.day+12+Math.floor(Math.random()*14);
S.offers.push({id:uid(),city,city2:null,name:tr('customers_and_events.name_in_city',{name:nm(),city:CITY[city].name}),type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*70),exp:start-2});return;}
if(T.sdwan){const hub=pick(mine),n=3+Math.floor(Math.random()*4),pool=(Math.random()<0.85?mine:OFFC).filter(c=>c!==hub),sites=[hub];
while(sites.length<n&&pool.length)sites.push(pool.splice(Math.floor(Math.random()*pool.length),1)[0]);if(sites.length<3)return;
S.offers.push({id:uid(),city:hub,city2:null,sites,name:nm(),type:t,bw:pick(T.opts),rate:700*sites.length,reqs:[],exp:S.day+40});return;}
const ready=S.links.filter(l=>l.kind==='df'&&l.ready<=S.day);
if(t==='wwave'){const ls=ready.filter(l=>freeCh(l)>=1&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;S.offers.push(fiberOffer(t,pick(ls),nm));return;}
if(t==='dfpair'){const ls=ready.filter(l=>pairFree(l)&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;S.offers.push(fiberOffer(t,pick(ls),nm));}
}

View file

@ -0,0 +1,39 @@
function cnOk(){return S.cnLic&&S.cnLic.state==='ok';}
function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.au)return AU_TRANSIT;if(C.tape)return 1.5;return C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;}
const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae;
const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain);
const borderPair=(a,b)=>!!CITY[a].cc&&!!CITY[b].cc&&CITY[a].cc!==CITY[b].cc;
// Perth to the east coast: the sea route round the south coast is domestic (AU_WAVE.ew), and the Nullarbor
// fiber costs a little more again because the incumbents own it.
const NULLARBOR=1.7,nullPair=(a,b)=>!!CITY[a].au&&!!CITY[b].au&&(a==='per')!==(b==='per');
const andesPair=(a,b)=>!!CITY[a].andes&&!!CITY[b].andes&&CITY[a].andes!==CITY[b].andes;
/* Overland between continents (Europe to the Middle East and Asia) crosses a dozen borders and as many
carriers, each taking a cut: in real life it costs ten times the subsea route or more (#40). */
const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg;
function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);}
function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two');
const r=[];if(CITY[a].reg!==CITY[b].reg)r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');}
function linkLat(l){const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;}
/* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and
long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and
routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York).
Each route also gets its own market mood, and new leases get cheaper every year (~8%). */
const WAVE_LAND={EU:0.65,AM:1,SA:1.6,AS:1.4,OC:1.2,AF:2.2},WAVE_SUB={EU:0.8,AM:1,SA:2,AS:1.5,OC:1.5,AF:4.5};
const WAVE_NAME={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')};
function waveMarket(a,b,sub){const ra=CITY[a].reg,rb=CITY[b].reg,T=sub?WAVE_SUB:WAVE_LAND,au=sub?AU_WAVE.sub:AU_WAVE.land;
const fa=CITY[a].au?au:(T[ra]||1),fb=CITY[b].au?au:(T[rb]||1),reg=sub&&nullPair(a,b)?AU_WAVE.ew:sub?Math.max(fa,fb):(fa+fb)/2;
const key=a<b?a+b:b+a,mood=0.85+(hstr(key+'|mood')%31)/100;
const ero=Math.max(0.55,Math.pow(0.92,Math.floor((S?S.day:0)/360)));
return {m:reg*mood*ero,reg,mood,ero};}
function marketNote(a,b,sub){const k=waveMarket(a,b,sub),ra=CITY[a].reg,rb=CITY[b].reg;const where=ra===rb?WAVE_NAME[ra]:tr('geography_and_latency.a_to_b',{a:WAVE_NAME[ra],b:WAVE_NAME[rb]});
const lvl=k.reg<0.9?tr('geography_and_latency.cheap_lots_of_competing_fiber'):k.reg<=1.05?tr('common.about_average'):k.reg<2?tr('geography_and_latency.pricey_fewer_carriers'):tr('geography_and_latency.expensive_scarce_capacity');const since=k.ero<1?tr('geography_and_latency.and_prices_have_fallen_p_since',{p:Math.round((1-k.ero)*100)}):'';
return k.mood<0.97?tr('geography_and_latency.where_lvl_this_route_is_p',{where,lvl,p:Math.round((1-k.mood)*100),since}):k.mood>1.03?tr('geography_and_latency.where_lvl_this_route_is_p_0196',{where,lvl,p:Math.round((k.mood-1)*100),since}):tr('geography_and_latency.where_lvl_this_route_is_right',{where,lvl,since});}
function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let via=UI.via;
if(!cabs.find(c=>c.cid===via))via=sub?(cabs[0]?cabs[0].cid:null):(via==='land'||!via?'land':'land');
if(!via)return null;const bf=border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1;
if(via==='land')return {via,cabs,cab:null,km:kmBetween(a,b),sub:false,wm:mult*landMult(a,b)*waveMarket(a,b,false).m};
const c=cabs.find(x=>x.cid===via);return {via,cabs,cab:via,km:c.km,sub:true,wm:bf*CAB[via].price*waveMarket(a,b,true).m};}
function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`<p class="note">${landWhy(a,b)}</p>`:'';const wr=waveRoute(a,b,1,false);
const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} <small>${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}</small>`})));
return `<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}</p>`:''}`;}
function bestLat(a,b){const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}

View file

@ -0,0 +1,26 @@
const RT={normal:tr('common.follow_metrics'),fast:tr('common.lowest_latency'),scenic:tr('sites_and_service.scenic_quietest_links')};
function routeCtl(b){const lt=R.l2lat[b.id];return `<div class="btns"><span class="meta" style="align-self:center">${tr('common.route_4a2e')}</span>${Object.keys(RT).map(m=>btn(RT[m],'setRoute',{id:b.id,m},(b.route||'normal')===m?'pink sm':'ghost sm')).join('')}</div><div class="meta">${tr('sites_and_service.path_latency_lat',{lat:lt!==undefined&&isFinite(lt)?tr('common.ms_ms_one_way',{ms:lt.toFixed(1)}):tr('sites_and_service.no_path_right_now')})}${b.route==='scenic'&&R.l2split&&R.l2split[b.id]?' · '+tr('sites_and_service.split_over_two_equally_quiet_paths'):''}${b.latMax?' · '+tr('sites_and_service.budget_ms_ms',{ms:b.latMax}):''}</div>`;}
function nodeCap(c){const p=S.pops[c];if(!p)return Infinity;const eff=(p.routers||1)-(p.rdown>S.day?1:0);return RG[p.rgen||0].cap*Math.max(1,eff)*(p.hot>S.day?(p.site2?0.75:0.5):1)*(p.site2&&(siteDown(c,'a')||siteDown(c,'b'))?0.5:1);}
// With a second site, one building can be dark (or cut off by a ring cut) while the other carries on.
function siteDown(c,s){const p=S.pops[c];if(!p||!p.site2)return false;if(S.inc.some(i=>i.type==='site'&&i.ref===c&&i.site===s&&i.until>S.day))return true;return s==='b'&&p.ringcut>S.day;}
// Ports can live in site A, site B, or be split across both ('ab'): a LAG with members in each
// building, so one dark building only takes out its half.
function liveN(c,site,n){n=n||1;const p=S.pops[c];if(!p||!p.site2)return n;if(site==='ab'){const a=Math.ceil(n/2),b=n-a;return (siteDown(c,'a')?0:a)+(siteDown(c,'b')?0:b);}return siteDown(c,site==='b'?'b':'a')?0:n;}
// Your own IX is a switch, not a port: it lives in building A or B, or in both with a second switch (#36).
const myIxLive=c=>{const ct=ixCity(c),st=(S.ixSite||{})[c]||'a';return st==='ab'?!(siteDown(ct,'a')&&siteDown(ct,'b')):!siteDown(ct,st);};
const liveCap=(g,c,site,n)=>{const k=liveN(c,site,n);return k?lagCap(g,k):0;};
const onSite=(site,s)=>(site||'a')===s||site==='ab';
function siteCtl(k,id,c,cur){const p=S.pops[c];if(!p||!p.site2)return '';cur=cur||'a';const n=k==='t'?(S.transit.find(x=>x.id===id)||{}).n:k==='p'?(S.pni.find(x=>x.id===id)||{}).n:(S.ixn||{})[id];return `<div class="seg site"><span class="meta">${tr('common.site')}</span>${['a','b'].map(x=>btn(`${x.toUpperCase()} <small>${esc(siteName(c,x))}</small>`,'siteSet',{k,id,s:x},cur===x?'pink sm':'ghost sm')).join('')}${btn(k==='ix'&&S.myIx[id]?tr('sites_and_service.both_a_second_switch_price_mo',{price:fmt$(Math.round(myFab(id).mo/2))}):(n||1)<2?tr('sites_and_service.both_adds_a_lag_member'):tr('sites_and_service.both_split_the_lag'),'siteSet',{k,id,s:'ab'},cur==='ab'?'pink sm':'ghost sm')}</div>`;}
function portOk(c,i){const p=S.pops[c];return i<=RG[p?(p.rgen||0):0].maxP;}
function waveOk(a,b,i){return [a,b].every(c=>i<=RG[S.pops[c]?(S.pops[c].rgen||0):0].maxLT);}
function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?tr('sites_and_service.pn_routers',{pn:g.pn}):'?';}
function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1;
return `<div style="margin-top:6px">${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=M.lvl>lvl();
return `<div class="row"><span class="logo" style="--c:${M.badge?'#2C7A7B':'#FF4F9A'}">${M.badge||'R'+(M.cls+1)}</span><div class="grow"><div class="nm">${esc(M.n)} <span class="meta">${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}</span></div><div class="meta">${esc(M.blurb)}</div>${why?`<div class="why">${esc(why)}</div>`:''}</div>${btn(lk?tr('sites_and_service.level_n',{n:M.lvl}):tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',lk||!!why||S.cash<swapCost(c,i)||p.rupDay===S.day)}</div>`;}).join('')}</div>`;}
function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP<PORT.length-1?`<p class="note" style="margin-top:0">${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}</p>`:'';}
// Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice.
const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]);
function latNote(c){if(!latSlow(c))return '';const f=R.latFar[c];return `<div class="warn">🐢 ${tr('sites_and_service.p_of_city_s_traffic_is',{p:pct(Math.min(1,f.share)),city:esc(CITY[c].name),to:esc(CITY[f.to].name),ms:Math.round(f.ms)})}</div>`;}
const LAT_OK=20,LAT_BAD=50,latLoss=rtt=>rtt<=LAT_OK?0:rtt<=LAT_BAD?0.2*(rtt-LAT_OK)/(LAT_BAD-LAT_OK):0.5;
function sfOf(r,c){const d=r.cityDem[c]||0;return d<=1e-6?1:clamp(r.citySrv[c]/d,0,1)*((r.latF&&r.latF[c])??1);}

View file

@ -0,0 +1,106 @@
/* ---------- failures & events ---------- */
// A few badges read the incident text: callers whose message mentions a shark, anchor, crocodile or llama pass its English as en.
function addInc(o,en=o.msg||''){if(S.loans&&S.loans.some(l=>(l.covs||[]).includes('pizza'))){S.cash-=COVS.pizza.each;S.stats.pizza=(S.stats.pizza||0)+1;}o.id=uid();o.start=S.day;S.inc.push(o);S.stats.incidents++;S.stats.by=S.stats.by||{};S.stats.by[o.type]=(S.stats.by[o.type]||0)+1;if(/shark/i.test(en))S.stats.sharks=(S.stats.sharks||0)+1;const f=S.stats.f=S.stats.f||{};if(/anchor/i.test(en))f.anchor=1;if(/crocodile/i.test(en))f.croc=1;if(/beaver/i.test(en))f.beaver=1;if(/llama/i.test(en))f.llama=1;}
const HARMLESS=[
[tr('common.certificate_expired'),tr('incidents_and_ddos.the_tls_certificate_on_your_noc')],
[tr('incidents_and_ddos.it_was_dns'),tr('incidents_and_ddos.someone_deleted_the_dns_record_for')],
[tr('common.leap_second'),tr('incidents_and_ddos.a_leap_second_convinced_one_of')],
[tr('common.change_freeze'),tr('incidents_and_ddos.management_declared_a_change_freeze')],
[tr('incidents_and_ddos.ticket_of_the_week'),tr('incidents_and_ddos.a_customer_opened_a_p1_ticket')],
[tr('common.monitoring'),tr('incidents_and_ddos.your_monitoring_system_went_down_you')],
[tr('incidents_and_ddos.load_bearing_typo'),tr('incidents_and_ddos.someone_named_a_vlan_prodcution_it')],
[tr('common.ipv6_milestone'),tr('incidents_and_ddos.your_ipv6_traffic_grew_400_from')],
[tr('common.mystery_link'),tr('incidents_and_ddos.you_found_a_10g_link_in')],
[tr('common.spreadsheet_ipam'),tr('incidents_and_ddos.your_ip_address_spreadsheet_hit_1')],
[tr('common.goose_incident'),tr('incidents_and_ddos.a_goose_attacked_the_technician_on')],
[tr('common.latency_test'),tr('incidents_and_ddos.a_carrier_pigeon_beat_one_of')],
[tr('common.zombie_route'),tr('incidents_and_ddos.a_route_you_withdrew_in_year')],
[tr('common.auditor_visit'),tr('incidents_and_ddos.an_auditor_asked_for_a_network')],
[tr('incidents_and_ddos.open_to_work'),tr('incidents_and_ddos.your_peering_coordinator_updated')],
[tr('common.hold_music'),tr('incidents_and_ddos.your_upstream_support_line_plays_the')],
[tr('common.naming_committee'),tr('incidents_and_ddos.a_two_hour_meeting_about_router')],
[tr('common.vendor_tac'),tr('incidents_and_ddos.vendor_support_asked_you_to_try')],
];
function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S.day))o.push({k:'t',id:t.id,o:t,n:t.n,lab:tr('incidents_and_ddos.name_transit_lag_in_city',{name:NET[t.net].name,city:CITY[t.city].name})});
for(const p of S.pni)if((p.n||1)>=2)o.push({k:'p',id:p.id,o:p,n:p.n,lab:tr('incidents_and_ddos.pni_lag_with_name_in_city',{name:NET[p.net].name,city:CITY[p.city].name})});
for(const x in S.ixp){const n=(S.ixn||{})[x]||1;if(n>=2&&!S.myIx[x])o.push({k:'ix',id:x,n,lab:ixNamesCity(x)?tr('incidents_and_ddos.ix_lag',{ix:ixName(x)}):tr('incidents_and_ddos.ix_lag_in_city',{ix:ixName(x),city:CITY[ixCity(x)].name})});}return o;}
// Where the junk comes in: one of the city's live uplinks, or just "the edge" if it has none yet.
// The primary slot remains compatible with older saves; every system uses the full live set.
function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));}
const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id);
function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);}
function ddosExpire(){for(const a of ddosAll(S,false))if(a.until<=S.day||!S.pops[a.city]){ddosDone(a);ddosDrop(a);}}
function ddosEntries(){const ports=Object.values(R.ingressPorts||{}).filter(p=>p.cap>0),busy=ports.some(p=>p.traffic>1e-6),weight=p=>busy?p.traffic:p.cap,total=ports.reduce((n,p)=>n+weight(p),0);
return total>0?ports.filter(p=>weight(p)>0).map(p=>({k:p.k,id:p.id,city:p.city,lab:p.lab,share:weight(p)/total})):[];}
function ddosSlices(a){if(!a.entries?.length)return [a];const groups={};
for(const en of a.entries){const c=S.pops[en.city]?en.city:a.city;(groups[c]||(groups[c]=[])).push(en);}
return Object.entries(groups).map(([city,entries])=>({...a,parent:a,city,entries,gbps:a.gbps*entries.reduce((n,en)=>n+en.share,0)}));}
const ddosCities=a=>[...new Set([a.city,...(a.entries||[]).map(en=>en.city)])].filter(c=>S.pops[c]);
const ddosHasIx=a=>ddosCities(a).some(hasIxAt);
const ddosSf=a=>Math.min(1,...ddosCities(a).map(c=>sfOf(R,c)));
function ddosReport(a){const ms=(R.ddos||[]).filter(m=>m.attack===a||m.attack.parent===a);if(!ms.length)return ddosMitigation(a);
const parts={};for(const m of ms)for(const x of m.sp?.parts||[]){const q=parts[x.city]||(parts[x.city]={city:x.city,tier:x.tier,a:0,cleaned:0});q.a+=x.a;q.cleaned+=x.cleaned;}
return {attack:a,blackhole:ms.some(m=>m.blackhole),upstream:ms.some(m=>m.upstream),reaching:ms.reduce((n,m)=>n+m.reaching,0),flowspec:ms.reduce((n,m)=>n+m.flowspec,0),fsMissing:ms.some(m=>m.fsMissing),filtered:ms.reduce((n,m)=>n+m.filtered,0),sp:Object.keys(parts).length?{parts:Object.values(parts)}:null,near:ms.find(m=>m.near)?.near||null,leak:ms.reduce((n,m)=>n+m.leak,0)};}
function ddosEntry(c){const o=[];
for(const t of S.transit)if(t.city===c&&!(t.down>S.day))o.push({k:'t',id:t.id,lab:tr('common.net_transit',{net:NET[t.net].name})});
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined)o.push({k:'ix',id:x,lab:tr('common.ix_peering',{ix:ixName(x)})});
for(const p of S.pni)if(p.city===c)o.push({k:'p',id:p.id,lab:tr('common.pni_with_net',{net:NET[p.net].name})});
return o.length?pick(o):{k:'edge',lab:''};}
// Flowspec capability at each ingress POP: 0 none, 1 basic, 2 full.
const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;};
// Scrubbing removes attack traffic up to the center's capacity; overflow leaks. On-demand
// does nothing for the first couple of days while traffic is being diverted.
function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start??S.day))>=SCRUB_DELAY);}
// Several centers (#117): the flood goes to the nearest working one, and what it cannot take spills to the next.
// A center in another city only helps if the backbone can carry the flood there; routing works that out.
const scrubFar=c=>ddosAll().some(a=>ddosCities(a).includes(c))&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null;
function scrubPlan(atk,g=atk.gbps||0,room={},take=null){if(!scrubEngaged(atk))return null;const c=atk.city;const parts=[];
for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const cap=SCRUB_TIERS[x.tier||0].g,a=Math.min(g,room[x.city]??cap);if(a<=0)continue;const cleaned=take?take(x,a):a;room[x.city]=(room[x.city]??cap)-cleaned;parts.push({city:x.city,tier:x.tier||0,a,cleaned});g-=cleaned;}
return parts.length?{parts,leak:g}:null;}
// One accounting pipeline for routing and the NOC: upstream -> edge -> scrubbing -> leakage.
function ddosMitigation(a,room={},blackhole=a.bh,plan=true){const entries=a.entries?.length?a.entries:[{...(a.entry||{}),share:1}],total=entries.reduce((n,en)=>n+en.share,0),ingress=[];
let upstream=false,reaching=0,g=0,flowspec=0,fsMissing=false;
for(const en of entries){const t=en.k==='t'?S.transit.find(x=>x.id===en.id):null,p=en.k==='p'?S.pni.find(x=>x.id===en.id):null,clean=!!(t&&t.clean);
upstream=upstream||clean;let part=blackhole?0:a.gbps*en.share/total*(clean?0.1:1);reaching+=part;
if(DDOS_VEC[a.vec]?.fs){const cap=fsAt(S.pops[en.city]?en.city:a.city),before=part;part*=FS_RES[cap];flowspec+=before-part;if(cap===0&&before>0)fsMissing=true;}
if(a.ixbh&&hasIxAt(a.city))part*=0.5;
if(p&&p.sacrif)part=Math.min(part,liveCap(pniG(p),p.city,p.site,p.n)*0.9);
if(teRules()?.blackhole&&!blackhole)part=0;
g+=part;ingress.push({entry:en,g:part});}
const filtered=reaching-g,sp=plan&&g>0?scrubPlan(a,g,room):null;
return {attack:a,blackhole,upstream,reaching,flowspec,fsMissing,filtered,ingress,sp,leak:sp?sp.leak:g};}
// The NOC's live attack view: what is hitting you, what each tool would do about it right now, and the buttons.
function ddosPanel(){return S?ddosAll().filter(a=>S.pops[a.city]).map(ddosOne).join(''):'';}
function ddosOne(a){
const V=DDOS_VEC[a.vec]||{n:'?',fs:false},en=a.entry||{};
const sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null;
const m=ddosReport(a),sp=m.sp,hl=x=>{const qs=(R.haul||[]).filter(q=>q.to===x.city&&q.attack===a.id);return qs.length?{a:qs.reduce((n,q)=>n+q.a,0),h:qs.reduce((n,q)=>n+q.h,0)}:null;};
const landLine=m.blackhole?'~ '+tr('incidents_and_ddos.blackholed_the_junk_is_gone_and',{city:esc(CITY[a.city].name)})
:m.upstream?'✓ '+tr('incidents_and_ddos.after_upstream_scrubbing_g',{g:fmtG(m.reaching)}):'';
const fsLine=!V.fs?'— '+tr('incidents_and_ddos.flowspec_cannot_catch_vec',{vec:esc(V.n)})
:m.flowspec<=1e-6?'— '+tr('incidents_and_ddos.no_flowspec_filtering_ingress')
:m.fsMissing?'~ '+tr('incidents_and_ddos.flowspec_dropping_g_some_ingress',{g:fmtG(m.flowspec)})
:'✓ '+tr('incidents_and_ddos.flowspec_dropping_g',{g:fmtG(m.flowspec)});
const used=c=>(R.ddos||[m]).reduce((n,q)=>n+(q.sp?.parts||[]).filter(x=>x.city===c).reduce((t,x)=>t+x.cleaned,0),0);
const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=hl(x),total=used(x.city);
return (x.cleaned>1e-6?'✓ ':'~ ')+tr('incidents_and_ddos.scrubbing_in_city_used_capacity',{city:esc(CITY[x.city].name),used:fmtG(total),capacity:T.n})
+(total>x.cleaned+1e-6?' · '+tr('incidents_and_ddos.this_attack_g',{g:fmtG(x.cleaned)}):'')
+(q&&q.h<q.a-0.5?'<br>~ '+tr('incidents_and_ddos.your_backbone_can_only_haul_g',{g:fmtG(q.h),city:esc(CITY[x.city].name)}):'');};
const scrLine=!hasScrub()?'— '+tr('incidents_and_ddos.no_scrubbing_center')
:!scrubEngaged(a)?'… '+tr('incidents_and_ddos.on_demand_scrubbing_diverting_live',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start??S.day)))})
:!sp?'— '+(m.leak<=1e-6?tr('incidents_and_ddos.no_scrubbing_needed_after_edge'):tr('incidents_and_ddos.scrubbing_centers_unavailable_or_at'))
:sp.parts.map(scrOne).join('<br>');
const haulLine=m.near&&m.near.ms>0&&sp?.parts.some(x=>x.cleaned>1e-6)?'✓ '+tr('incidents_and_ddos.scrubbing_traffic_hauled_over_your',{city:esc(CITY[a.city].name),to:esc(CITY[m.near.city].name),ms:m.near.ms.toFixed(1)}):'';
const entryLine=sacP&&sacP.sacrif?'✓ '+tr('incidents_and_ddos.contained_on_your_sacrificial_net',{net:esc(NET[sacP.net].name)}):'';
let h=`<div class="inc" style="background:#FFE2E6;border:1px solid #FF8A9A">
<div class="nm">🚨 ${tr('incidents_and_ddos.live_attack_city',{city:esc(CITY[a.city].name)})}</div>
<div class="meta">${tr('incidents_and_ddos.size_vec_entry_n_d_left',{size:fmtG(a.gbps),vec:esc(V.n),entry:a.entry&&a.entry.lab?' · '+esc(a.entry.lab):'',n:a.until-S.day})}</div>
${landLine?`<div class="meta"><b>${landLine}</b></div>`:''}
${m.blackhole?'':`<div class="meta">${fsLine}</div>${entryLine?`<div class="meta">${entryLine}</div>`:''}
${m.filtered-m.flowspec>1e-6?`<div class="meta">✓ ${tr('incidents_and_ddos.edge_filters_dropping_g',{g:fmtG(m.filtered-m.flowspec)})}</div>`:''}
<div class="meta">${scrLine}</div>
${haulLine?`<div class="meta">${haulLine}</div>`:''}
<div class="meta">${m.leak>1e-6?'~ '+tr('incidents_and_ddos.g_is_leaking_through',{g:fmtG(m.leak)}):'✓ '+tr('incidents_and_ddos.attack_fully_mitigated')}</div>`}
<div class="btns">${m.blackhole?btn(tr('common.stop_blackholing'),'unrtbh',{id:a.id},'ghost sm'):btn(tr('incidents_and_ddos.blackhole_the_target_rtbh'),'rtbh',{id:a.id},'red sm')}${ddosHasIx(a)&&!m.blackhole?btn(a.ixbh?tr('incidents_and_ddos.ix_blackhole_on'):tr('incidents_and_ddos.ix_blackhole_half_honour_it'),'ixbh',{id:a.id},a.ixbh?'green sm':'sm'):''}${btn(tr('incidents_and_ddos.hackback_3000tm_20k'),'hackback',{id:a.id},'sm',S.cash<20000)}</div>
<p class="meta">${tr('incidents_and_ddos.rtbh_is_free_and_instant_but')}</p></div>`;
return h;}

View file

@ -0,0 +1,183 @@
function fireFailure(){
const opts=[];
const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);}
if(Object.keys(S.pops).length)opts.push(['crash',3],['power',2]);
if(Object.values(S.pops).some(p=>p.site2))opts.push(['ring',1.2]);
if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]);
if(Object.keys(S.ixp).length)opts.push(['ixloop',2]);
if(S.transit.length&&S.day>60)opts.push(['leak',2]);
// DDoS has its own schedule, so other incidents cannot bypass the weekly limit.
if(fabsUsed.length)opts.push(['fabric',1.5]);
const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l));if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]);
opts.push(['funny',4]);
if(!opts.length)return;
let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0];
for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}
if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(Object.keys(S.ixp).length)f.push('maxpfx');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);}
const before=R.served;
if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`<b>${m[0]}</b><br>${m[1]}`,'goal');sfx('alert');return;}
if(type==='ring'){const cs=Object.keys(S.pops).filter(c=>S.pops[c].site2),c=pick(cs),pp=S.pops[c],dur=2+Math.floor(Math.random()*3);pp.ringcut=S.day+dur;
addInc({type,ref:c,until:pp.ringcut,msg:pick([tr('failures.a_backhoe_cut_the_metro_ring',{city:CITY[c].name}),tr('failures.someone_pulled_the_wrong_cross',{city:CITY[c].name,siteB:siteName(c,'b'),siteA:siteName(c,'a')}),tr('failures.a_tram_line_construction_project_in',{city:CITY[c].name})]),cost:3000,fix:tr('failures.splice_it_tonight')});}
else if(type==='ac'){const c=pick(Object.keys(S.pops)),pp=S.pops[c];pp.hot=S.day+2;
addInc({type,ref:c,until:pp.hot,msg:CITY[c].lux&&Math.random()<0.7?tr('failures.a_forestry_strike_stopped_the_waste',{dc:siteName(c,'a'),city:CITY[c].name}):pick([tr('failures.the_a_c_at_dc_died',{dc:siteName(c,'a'),city:CITY[c].name}),tr('failures.someone_set_the_data_center',{city:CITY[c].name}),tr('failures.the_cooling_contractor_in_city',{city:CITY[c].name})]),cost:2000,fix:tr('failures.buy_40_desk_fans')});
}else if(type==='fatwave'||type==='label'){
const l=pick(live),dur=1+Math.floor(Math.random()*2),A=CITY[l.a].name,B=CITY[l.b].name,W=pick(WAVECO);l.cut=Math.max(l.cut||0,S.day+dur);
const msg=type==='label'?pick([tr('failures.someone_in_dc_labeled_every_patch',{dc:siteName(l.a,'a'),a:A,b:B}),tr('failures.a_remote_hands_tech_in_a',{a:A,b:B}),tr('failures.a_new_tech_in_a_tidied',{a:A,b:B})])
:l.kind==='df'?pick([tr('failures.the_landlord_in_a_re_routed',{a:A,b:B}),tr('failures.a_splicer_fusing_someone_else_s',{b:B})])
:pick([tr('failures.co_fat_fingered_a_cross_connect',{co:W,a:A,b:B}),tr('failures.co_did_quick_maintenance_on_the',{co:W,a:A,b:B}),tr('failures.co_scheduled_maintenance_in_utc_your',{co:W,a:A,b:B}),tr('failures.an_engineer_at_co_swapped_tx',{co:W,a:A,b:B}),tr('failures.co_decommissioned_your_a_b_wave',{co:W,a:A,b:B})]);
addInc({type,ref:l.id,until:l.cut,msg,cost:1500,fix:tr('failures.bribe_their_noc_with_donuts')});
}else if(type==='lacp'){
const g=pick(lagsN()),n=g.n,dur=1+Math.floor(Math.random()*3),v=Math.floor(Math.random()*4);
const f=v===0?Math.max(0.3,1.4/n):v===3?0:(n-1)/n,until=S.day+(v===3?1:dur),lab=g.lab;
if(g.k==='ix'){S.ev.ixlacp=S.ev.ixlacp||{};S.ev.ixlacp[g.id]={until,f};}else g.o.lacp={until,f};
const msg=[N_('failures.hash_polarisation_on_your_lab_nearly'),
N_('failures.lacp_fast_slow_timer_mismatch_on'),
N_('failures.one_member_of_your_lab_was'),
N_('failures.someone_set_min_links_on_your')][v];
addInc({type,ref:g.k+':'+g.id,until,msg:tr(msg,{lab}),cost:600,fix:tr('failures.fix_the_lacp_config')},msg);
}else if(type==='loss'){
const deep=l=>[l.a,l.b].every(c=>S.pops[c]&&/deep-buffer/.test(RG[S.pops[c].rgen||0].chip));
const l=pick(live),v=Math.floor(Math.random()*3);
if(v===1&&deep(l)){S.stats.incidents++;S.stats.survived++;toast(tr('failures.microbursts_on_a_b_your_deep',{a:CITY[l.a].name,b:CITY[l.b].name}),'goal');return;}
const f=[0.6,0.8,0.7][v],dur=2+Math.floor(Math.random()*3);l.loss={until:S.day+dur,f};
const msg=[N_('failures.a_dirty_connector_on_a_b'),
N_('failures.microbursts_on_a_b_overflow_shallow'),
N_('failures.crc_errors_on_a_b_a')][v];
addInc({type,ref:l.id,until:l.loss.until,msg:tr(msg,{a:CITY[l.a].name,b:CITY[l.b].name}),cost:900,fix:[tr('failures.clean_the_connector'),tr('failures.rate_limit_the_bursts'),tr('failures.swap_the_optic')][v]},msg);
}else if(type==='pmtud'){
const top=NETS.filter(n=>(R.demTo[n.id]||0)>0.5).sort((a,b)=>(R.demTo[b.id]||0)-(R.demTo[a.id]||0)).slice(0,8),n=pick(top.length?top:NETS),dur=2+Math.floor(Math.random()*3);
S.ev.pmtud={net:n.id,until:S.day+dur,f:0.6};
const msg=hasScrub()&&Math.random()<0.5?N_('failures.your_scrubbing_center_returns_clean')
:pick([N_('failures.someone_filtered_all_icmp_on_your'),
N_('failures.a_pppoe_hop_shaved_8_bytes')]);
addInc({type,ref:n.id,until:S.ev.pmtud.until,msg:tr(msg,{net:n.name}),cost:500,fix:tr('failures.clamp_the_mss_to_1360')},msg);
}else if(type==='mtu'){
const l=pick(live);l.deg=S.day+3;addInc({type,ref:l.id,until:l.deg,msg:tr('failures.mtu_mismatch_on_a_b_jumbo',{a:CITY[l.a].name,b:CITY[l.b].name}),cost:800,fix:tr('failures.set_mtu_9216_everywhere')});
}else if(type==='oops'||type==='cleaner'){
const c=pick(Object.keys(S.pops)),pp=S.pops[c],C=CITY[c].name;
if(type==='cleaner'&&pp.site2&&(pp.routers||1)<2){S.stats.survived++;addInc({type:'site',ref:c,site:'a',until:S.day+1,msg:tr('failures.the_cleaner_unplugged_everything_at',{siteA:siteName(c,'a')}),cost:0});toast(tr('failures.vacuum_incident_in_city_the_cleaner',{city:C,siteA:esc(siteName(c,'a')),siteB:esc(siteName(c,'b'))}),'good');sfx('alert');return;}
if(type==='cleaner'&&(pp.routers||1)>=2){S.stats.incidents++;S.stats.survived++;toast(tr('failures.vacuum_incident_in_city_the_cleaner_47e0',{city:C,dc:siteName(c,'a')}),'good');sfx('alert');return;}
pp.down=Math.max(pp.down||0,S.day+1);
const msg=type==='cleaner'?tr('failures.the_cleaner_at_dc_unplugged_your',{dc:siteName(c,'a')}):pick([tr('failures.your_on_call_engineer_typed_clear',{city:C}),tr('failures.an_intern_pushed_an_acl_in',{city:C}),tr('failures.someone_ran_reload_on_the_city',{city:C}),tr('failures.a_config_template_rendered_router_id',{city:C}),tr('failures.someone_committed_a_config_in_city',{city:C}),tr('failures.someone_deployed_to_city_on_a',{city:C}),tr('failures.a_cosmic_ray_flipped_a_bit',{city:C}),tr('failures.an_automation_script_in_city_ran',{city:C})]);
addInc({type,ref:c,until:pp.down,msg:msg+(type==='oops'&&(pp.routers||1)>=2?' '+tr('failures.automation_pushed_it_to_every_router'):''),cost:1500,fix:type==='oops'?tr('failures.roll_back_the_config'):tr('failures.hide_the_vacuum')});
}else if(type==='maxpfx'){
const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+1+Math.floor(Math.random()*2));
addInc({type,ref:c,until:S.ev.ixdown[c],msg:ixNamesCity(c)?tr('failures.a_member_at_ix_leaked_the',{ix:ixName(c)}):tr('failures.a_member_at_ix_leaked_the_5563',{ix:ixName(c),city:CITY[ixCity(c)].name}),cost:0});
}else if(type==='prepend'){
const t=pick(S.transit);t.down=Math.max(t.down||0,S.day+2);addInc({type,ref:t.id,until:t.down,msg:tr('failures.net_fat_fingered_a_route_map',{net:NET[t.net].name,n:30+Math.floor(Math.random()*60),city:CITY[t.city].name}),cost:0});
}else if(type==='rpki'){
S.ev.rpki={until:S.day+3,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.5)};addInc({type,ref:'rpki',until:S.day+3,msg:tr('failures.your_roa_expired_over_the_weekend'),cost:1000,fix:tr('failures.renew_the_roa')});
}else if(type==='amp'||type==='roadmff'){
const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur;
const msg=type==='roadmff'?tr('failures.you_fat_fingered_the_channel_plan',{a:A,b:B}):pick([tr('failures.an_in_line_amplifier_hut_between',{a:A,b:B}),tr('failures.someone_stole_the_copper_grounding',{a:A,b:B}),tr('failures.a_firmware_bug_in_the_sys',{sys:DF_SYS[l.sys].n,a:A}),tr('failures.lightning_hit_an_amp_site_on',{a:A,b:B})]);
addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' '+tr('failures.your_spares_kit_gets_it_back'):''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:tr('failures.truck_a_spare_amp_out')});
}else if(type==='optic'){
const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,o=pick(l.ch),dur=l.spares?1:4;l.chFail={n:1,o,until:S.day+dur};
addInc({type,ref:l.id,until:S.day+dur,msg:pick([tr('failures.a_optic_on_a_b_overheated',{optic:OPT[o].n,a:A,b:B}),tr('failures.the_laser_in_a_optic_on',{optic:OPT[o].n,a:A,b:B}),tr('failures.a_optic_on_a_b_started',{optic:OPT[o].n,a:A,b:B})])+(l.spares?' '+tr('failures.swapped_from_your_spares_kit_by'):''),cost:l.spares?0:OPT[o].cost,fix:tr('failures.buy_a_replacement')});
}else if(type==='cut'){
const mon=Math.floor((S.day%365)/30.42),monsoon=mon>=5&&mon<=8,tw=x=>x.sub&&(x.a==='tpe'||x.b==='tpe'||['clion','balt'].includes(x.cable)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india);
const l=pick(live.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1;
const en=l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]);
addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en);
}else if(type==='crash'||type==='power'){
const c=pick(Object.keys(S.pops).flatMap(x=>type==='power'&&(CITY[x].za||CITY[x].blackout)?[x,x,x]:type==='crash'&&RG[S.pops[x].rgen||0].flaky?[x,x,x]:[x])),pp=S.pops[c],slow=slowBoot(c),dur=(type==='crash'?2+Math.floor(Math.random()*2):3+Math.floor(Math.random()*3))*(type==='crash'&&S.ev.sanction>S.day?2:1)+(slow?2+Math.floor(Math.random()*3):0);
if(type==='crash'&&(pp.routers||1)>=2){pp.rdown=S.day+dur;S.stats.incidents++;S.stats.survived++;toast(tr('failures.router_crash_in_city_one_router',{city:CITY[c].name,slow:slow?' '+tr('failures.the_crashed_one_what',{what:esc(pick(SLOW_BOOT))}):'',d:dur}),'good');sfx('alert');return;}
if(type==='power'&&!pp.gen&&pp.site2){const sd=Math.random()<0.5?'a':'b';addInc({type:'site',ref:c,site:sd,until:S.day+dur,msg:(CITY[c].za?tr('failures.load_shedding_took_out_site_in',{site:siteName(c,sd),city:CITY[c].name,other:siteName(c,sd==='a'?'b':'a')}):tr('failures.a_power_cut_took_out_site',{site:siteName(c,sd),city:CITY[c].name,other:siteName(c,sd==='a'?'b':'a')})),cost:5000,fix:tr('incidents.rent_a_generator')});S.stats.survived++;return;}
if(type==='power'&&pp.gen&&CITY[c].blackout){S.stats.incidents++;S.stats.survived++;S.stats.shed=(S.stats.shed||0)+1;toast(tr('failures.blackout_in_city_the_grid_went',{city:CITY[c].name}),'good');sfx('alert');return;}
if(type==='power'&&pp.gen){S.stats.incidents++;S.stats.survived++;if(CITY[c].za)S.stats.shed=(S.stats.shed||0)+1;toast(CITY[c].za?tr('failures.load_shedding_in_city_stage_n',{city:CITY[c].name,n:2+Math.floor(Math.random()*5)}):tr('failures.power_cut_in_city_your_backup',{city:CITY[c].name}),'good');sfx('alert');return;}
pp.down=Math.max(pp.down||0,S.day+dur);
const auc=CITY[c].au&&Math.random()<0.5,msg=type==='power'&&c==='ivc'&&Math.random()<0.6?tr('failures.the_smelter_at_tiwai_point_pulled',{city:CITY[c].name}):type==='crash'&&auc&&!slow?pick([tr('failures.a_routine_overnight_upgrade_took',{city:CITY[c].name}),tr('failures.a_huntsman_spider_the_size_of',{city:CITY[c].name}),tr('failures.a_new_tech_in_city_used',{city:CITY[c].name}),tr('failures.a_visiting_engineer_from_london',{city:CITY[c].name})]):type==='power'&&auc&&!CITY[c].blackout?((S.day%365)/30.42>=11||(S.day%365)/30.42<2?tr('failures.a_45_c_heatwave_in_city',{city:CITY[c].name,dc:siteName(c,'a')}):(c==='bne'&&Math.random()<0.6?tr('failures.the_four_o_clock_storm_rolled',{dc:siteName(c,'a')}):tr('failures.a_possum_got_into_the_substation',{city:CITY[c].name,dc:siteName(c,'a')}))):type==='crash'?(slow?tr('failures.your_router_in_city_crashed_and',{city:CITY[c].name,what:pick(SLOW_BOOT),min:bootMin(c),n:2+Math.floor(Math.random()*5)}):pick([tr('failures.your_router_in_city_crashed_kernel',{city:CITY[c].name}),tr('failures.a_firmware_update_bricked_your',{city:CITY[c].name})])):CITY[c].blackout?tr('failures.a_blackout_hit_city_and_your',{city:CITY[c].name}):CITY[c].za?tr('failures.load_shedding_stage_n_in_city',{n:3+Math.floor(Math.random()*4),city:CITY[c].name}):tr('failures.power_outage_at_dc_in_city',{dc:siteName(c,'a'),city:CITY[c].name});
addInc({type,ref:c,until:S.pops[c].down,msg,slow:type==='crash'&&slow,cost:type==='crash'?2500:7000,fix:type==='crash'?(slow?tr('failures.turn_it_off_and_on_again'):tr('failures.turn_it_off_and_on_again_0872')):tr('incidents.rent_a_generator')});
}else if(type==='transit'){
const t=pick(S.transit.filter(t=>!(t.down>S.day)));t.down=S.day+3+Math.floor(Math.random()*3);
addInc({type,ref:t.id,until:t.down,msg:tr('failures.net_is_having_an_outage_in',{net:NET[t.net].name,city:CITY[t.city].name}),cost:0});
}else if(type==='ixloop'){
const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+2+Math.floor(Math.random()*2));
addInc({type,ref:c,until:S.ev.ixdown[c],msg:tr('failures.someone_plugged_a_loop_into_the',{ix:ixName(c)}),cost:0});
}else if(type==='leak'){
const n=pick(['nfx','ggl','fbk','amz','msf']);S.ev.leak={net:n,until:S.day+4};
addInc({type,ref:n,until:S.day+4,msg:tr('failures.bgp_route_leak_a_small_isp',{net:NET[n].name}),cost:0});
}else if(type==='fabric'){
const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3);
addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0});
}else if(type==='ddos'){ddosAttack();return;
}
compute();
const last=S.inc[S.inc.length-1];
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
sfx('alert');
}
const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);
const ddosVectors=()=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gamingCount()>0);
// Expected starts per week in normal play; the rolling 14-start limit is a separate ceiling.
// Spread gaming exposure over dozens of customers, including the first, rather than switching baselines.
const ddosRate=()=>0.5+6.5*(1-Math.exp(-gamingCount()/50*(1+Math.max(1,S.lvl||1)/LEVELS.length)));
const ddosPressure=()=>1-Math.exp(-(.01+Math.max(0,(S.lvl||1)-1)/12+gamingCount()/10+(scnRule('ddos')?.2+S.day/365:0)));
// Normalize the vector mix so smaller gaming-only floods do not lower the advertised overall mean.
function ddosSizeMean(){const stage=Math.max(1,S.lvl||1)/LEVELS.length,games=gamingCount(),fl=scnRule('ddos');
const base=Math.max(10,(R.demand||0)*4/3*stage,fl?1400:0);
if(fl)return base*(1+0.2*games/(games+10))*(1+S.day/365);
// Relative to no gaming: 3x at one customer, 8x at 50, approaching the existing 12x balance.
const mean=base*(games?1.2-0.9*Math.pow(4/9,(games-1)/49):0.1),vectors=ddosVectors(),weight=vectors.reduce((n,k)=>n+(DDOS_VEC[k].gaming?1/3:1),0)/vectors.length;
return mean/weight;}
// Normal rolls: 98% uniform 0.2–2, 2% uniform 8–12. Their mean is 1.278, so spikes do not inflate the balance.
const ddosSizeMax=()=>ddosSizeMean()*(scnRule('ddos')?1.5:12/1.278);
function ddosSize(vec){const fl=scnRule('ddos'),r=Math.random(),roll=fl?1/3+r*2/3:(r<.98?.2+1.8*r/.98:8+4*(r-.98)/.02)/12;
const raw=ddosSizeMax()*(DDOS_VEC[vec].gaming?1/3:1)*roll;
return fl?Math.max(2,Math.floor(raw)):Math.max(0.001,Math.floor(raw*1000)/1000);}
function ddosTick(){if(S.mode==='sandbox')return;if(scnRule('ddos')){let next=+S.scn.nextDdos||3,n=0;
while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next<S.day?S.day+floodGap():next;}
else if(S.day>40||gamingCount())for(let i=0;i<2;i++)if(Math.random()<ddosRate()/14)ddosAttack(false);}
// Size, duration and starts are randomized independently; overlapping floods never replace each other.
function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExpire();
S.ddosStarts=(S.ddosStarts||[]).filter(d=>d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return;S.ddosStarts.push(S.day);
const c=pick(Object.keys(S.pops)),vec=pick(ddosVectors()),V=DDOS_VEC[vec];
const gbps=ddosSize(vec);
const dur=1+Math.floor(Math.random()*(1+6*ddosPressure())),entry=ddosEntry(c);
const entries=ddosEntries(),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('common.distributed_ingress')}:entries[0]||entry,entries,bh:false,start:S.day};
if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a);
const soaked=(V.fs&&fsAt(c))||hasScrub();
const how=entries.length>1?tr('failures.across_n_transit_and_peering_ports',{n:entries.length}):entry&&entry.lab?tr('failures.in_via_e',{e:entry.lab}):'';
const msg=tr('failures.a_size_vec_attack_is_hitting',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('failures.your_mitigation_is_eating_most_of'):tr('failures.junk_traffic_is_eating_your_capacity'));
if(fl)a.who=pick(FLOOD_WHO);
addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('failures.attacker_who',{who:tr(a.who)}):msg,cost:0});
if(soaked){S.stats.survived++;S.stats.ddosHeld=(S.stats.ddosHeld||0)+1;if(gbps>=1000)S.stats.ddosMonster=(S.stats.ddosMonster||0)+1;}
if(recompute){compute();a.worst=ddosSf(a);}
toast(`<b>${incTitle('ddos')}: ${esc(CITY[c].name)}</b><br>${esc(msg)}${fl?`<br><i>${esc(tr('failures.attacker_who',{who:tr(a.who)}))}</i>`:''}`,soaked?'goal':'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c});
sfx('alert');}
// When an attack is over: was it held? Held means the city under attack got at least 97% of its traffic every day.
function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=ddosSf(a);const ok=(a.worst===undefined?1:a.worst)>=0.97;
if(ok){S.stats.ddosOk=(S.stats.ddosOk||0)+1;if(a.gbps>=1000)S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;}else S.stats.ddosLost=(S.stats.ddosLost||0)+1;
if(scnRule('ddos')){const who=tr(a.who||FLOOD_WHO[0]);toast(ok?tr('failures.flood_held_g_who_gave_up',{g:fmtG(a.gbps),who:who.charAt(0).toUpperCase()+who.slice(1)}):tr('failures.that_one_got_through_g_city',{g:fmtG(a.gbps),city:CITY[a.city]?CITY[a.city].name:tr('common.your_network'),p:pct(a.worst||0),who}),ok?'goal':'bad');}}
const floodGap=()=>Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+gamingCount()/10+Math.max(0,(S.lvl||1)-1)/12)));
const FLOOD_WHO=[N_('failures.a_botnet_of_40_000_smart'),N_('failures.every_unpatched_baby_monitor_in'),N_('failures.a_gaming_clan_that_lost_one'),N_('failures.a_fridge_that_achieved_sentience_and'),N_('failures.a_crypto_bro_shorting_your_stock'),N_('failures.a_teenager_with_a_stolen_credit'),N_('failures.a_rival_isp_s_stress_test'),N_('failures.ten_thousand_smart_light_bulbs'),N_('failures.a_printer_just_one_printer_nobody'),N_('failures.a_botnet_run_from_a_cloud'),N_('failures.somebody_who_did_not_like_your'),N_('failures.the_internet_connected_kettles_of_a')];
function incTitle(t){return {ring:tr('failures.metro_ring_cut'),site:tr('common.site_outage'),cut:tr('common.fiber_cut'),crash:tr('common.router_crash'),power:tr('common.power_outage'),transit:tr('common.upstream_outage'),ixloop:tr('common.ix_meltdown'),leak:tr('common.route_leak'),ddos:tr('common.ddos_attack'),fabric:tr('common.fabric_outage'),depeer:tr('common.peering_spat'),fatwave:tr('failures.fat_fingered_wave'),label:tr('failures.patch_panel_mishap'),mtu:tr('common.mtu_mismatch'),krroute:tr('failures.rerouted_via_hong_kong'),ctrlplane:tr('failures.control_plane_meltdown'),lacp:tr('common.lacp_trouble'),loss:tr('common.packet_loss'),pmtud:tr('failures.pmtud_black_hole'),oops:tr('common.oops'),cleaner:tr('common.vacuum_incident'),maxpfx:tr('failures.max_prefix_meltdown'),prepend:tr('common.prepend_ageddon'),rpki:tr('common.rpki_invalid'),amp:tr('common.amplifier_failure'),roadmff:tr('failures.fat_fingered_roadm'),optic:tr('common.dead_optic'),maint:tr('common.maintenance_window_3a92'),ac:tr('common.cooling_failure'),hijack:tr('common.bgp_hijack'),shutdown:tr('common.government_shutdown'),redsea:tr('failures.geopolitical_cable_cut')}[t]||tr('common.incident');}
const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic'];
function remainUntil(pred){let u=0;for(const x of S.inc)if(pred(x))u=Math.max(u,x.until);return u;}
// Remove an incident, then restore each affected thing to whatever other incidents still hold it down.
function clearInc(i){
S.inc=S.inc.filter(x=>x!==i);const T=i.type;
if(LINKCUT_TR.includes(T)||LINKCUT_ID.includes(T)){const ls=LINKCUT_TR.includes(T)?S.links.filter(l=>(l.trench||l.id)===i.ref):S.links.filter(l=>l.id===i.ref);
for(const l of ls)l.cut=remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id));}
else if(POPDOWN.includes(T)){if(S.pops[i.ref])S.pops[i.ref].down=remainUntil(x=>POPDOWN.includes(x.type)&&x.ref===i.ref);}
else if(IXDOWN.includes(T)){if(S.ev.ixdown)S.ev.ixdown[i.ref]=remainUntil(x=>IXDOWN.includes(x.type)&&x.ref===i.ref);}
else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);}
else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;}
else if(T==='leak'){S.ev.leak=null;}
else if(T==='ddos'){const a=ddosAll(S,false).find(a=>i.atk?a.id===i.atk:a.city===i.ref&&(a.start===undefined||a.start===i.start));if(a){ddosDone(a);ddosDrop(a);}}
else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);}
else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);}
else if(T==='loss'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='loss'&&x.ref===i.ref))l.loss=null;}
else if(T==='lacp'){if(!S.inc.some(x=>x.type==='lacp'&&x.ref===i.ref)){const [k,...r]=String(i.ref).split(':'),id=r.join(':');if(k==='ix'){if(S.ev.ixlacp)delete S.ev.ixlacp[id];}else{const o=(k==='t'?S.transit:S.pni).find(x=>x.id===id);if(o)o.lacp=null;}}}
else if(T==='ctrlplane'){for(const id of Array.isArray(i.links)?i.links:[]){const l=S.links.find(x=>x.id===id);if(l)l.cut=Math.max(remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id)||(x.type==='ctrlplane'&&Array.isArray(x.links)&&x.links.includes(l.id))),0);}}
else if(T==='pmtud'){if(!S.inc.some(x=>x.type==='pmtud'))S.ev.pmtud=null;}
else if(T==='ring'){if(S.pops[i.ref])S.pops[i.ref].ringcut=remainUntil(x=>x.type==='ring'&&x.ref===i.ref);}
else if(T==='ac'){if(S.pops[i.ref])S.pops[i.ref].hot=remainUntil(x=>x.type==='ac'&&x.ref===i.ref);}
else if(T==='amp'||T==='roadmff'){const l=S.links.find(x=>x.id===i.ref);if(l)l.eqDown=remainUntil(x=>(x.type==='amp'||x.type==='roadmff')&&x.ref===i.ref);}
else if(T==='optic'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='optic'&&x.ref===i.ref))l.chFail=null;}
}
function purgeInc(){S.inc=S.inc.filter(i=>{const T=i.type;if(LINKCUT_TR.includes(T))return S.links.some(l=>(l.trench||l.id)===i.ref);if(LINKCUT_ID.includes(T)||LINKEQ.includes(T))return S.links.some(l=>l.id===i.ref);if(TDOWN.includes(T))return S.transit.some(t=>t.id===i.ref);if(IXDOWN.includes(T))return S.ixp[i.ref]!==undefined;if(POPDOWN.includes(T)||T==='ac')return !!S.pops[i.ref];return true;});}

View file

@ -0,0 +1,55 @@
function fireEvent(){
const opts=['viral','price','grant'];
if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
if(S.day>HW_FREE&&!hwShock())opts.push('hwshock');
if(S.day>90&&S.links.filter(l=>l.kind==='wave'&&!l.sub).length>=3)opts.push('ctrlplane');
if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet');
if(S.pops.doh&&Object.keys(S.pops).some(c=>CITY[c].gcc||CITY[c].uae)&&!(S.ev.gulf>S.day))opts.push('gulf');
if(Object.keys(S.pops).some(c=>CITY[c].saudi))opts.push('mega');
if(['mnl','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon');
if(S.pops.icn&&!S.krExit)opts.push('krexit');if(S.pops.icn&&!(S.ev.krroute>S.day))opts.push('krroute');
if(Object.keys(S.pops).some(cnCity)||R.gfwCross>1)opts.push('golden','gfw');
if(S.transit.some(t=>t.net==='cog'))opts.push('depeer','depeer');
if(Object.keys(S.peers).some(k=>k.startsWith('drz@'))||Object.keys(S.rs).length)opts.push('cake');
const e=pick(opts);
if(e==='gulf'){const dur=60+Math.floor(Math.random()*60);S.ev.gulf=S.day+dur;toast(tr('events.the_neighbours_have_fallen_out_a',{n:dur}),'bad');sfx('alert');}
/* A wave supplier pushes one bad update to its optical control plane, and every wave it sells you in a
region goes dark for a day or two. Your own dark fiber, subsea waves and fabric circuits keep working. */
if(e==='ctrlplane'){const by={};for(const l of S.links)if(l.kind==='wave'&&!l.sub&&!(l.cut>S.day)){const r=CITY[l.a].reg;(by[r]=by[r]||[]).push(l);}
const reg=Object.keys(by).sort((a,b)=>by[b].length-by[a].length)[0];if(!reg)return;const hit=by[reg],until=S.day+2;
for(const l of hit)l.cut=Math.max(l.cut||0,until);
const RN={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')};
addInc({type:'ctrlplane',ref:'reg:'+reg,links:hit.map(l=>l.id),until,msg:tr('events.your_wave_supplier_pushed_one',{n:hit.length,reg:RN[reg]||reg}),cost:Math.round(hit.reduce((a,l)=>a+l.mo,0)*0.3),fix:tr('events.escalate_to_their_cto')},'ctrlplane');
toast(tr('events.optical_control_plane_meltdown_every',{reg:RN[reg]||reg}),'bad');sfx('alert');return;}
if(e==='krexit'){S.krExit=S.day+1;S.stats.incidents++;S.stats.survived++;
toast(tr('events.glitch_is_leaving_korea_the_game'),'bad');sfx('alert');return;}
if(e==='krroute'){S.ev.krroute=S.day+20;addInc({type:'krroute',ref:'icn',until:S.day+20,msg:tr('events.faceplant_got_tired_of_korean_usage'),cost:0},'krroute');
toast(tr('events.faceplant_rerouted_korea_via_hong'),'bad');sfx('alert');return;}
if(e==='mega'){const c=pick(Object.keys(S.pops).filter(x=>CITY[x].saudi)),bw=pick([800,1600,3200]),start=S.day+15;S.offers.push({id:uid(),city:c,city2:null,name:tr('events.a_futuristic_city_that_is_not',{city:CITY[c].name}),type:'event',bw,rate:0,reqs:[],start,dur:4,fee:bw*4*90,exp:start-2});toast(tr('events.a_gigaproject_wants_a_demo_bw',{bw:fmtG(bw),city:CITY[c].name}),'goal');}
if(e==='sanction'){S.ev.sanction=S.day+60;toast(tr('events.sanctions_the_republic_of'),'bad');sfx('alert');return;}
if(e==='hwshock'){hwShockStart();return;}
if(e==='tariff'){S.ev.tariff=S.day+90;toast(tr('events.trade_war_on_optics_two_governments'),'bad');sfx('alert');return;}
if(e==='hijack'){const nh=NETS.map(n=>n.id).filter(()=>Math.random()<0.6),old=S.ev.rpki&&S.ev.rpki.until>S.day?S.ev.rpki:null;S.ev.rpki=old?{until:Math.max(old.until,S.day+1),nets:[...new Set(old.nets.concat(nh))]}:{until:S.day+1,nets:nh};addInc({type:'hijack',ref:'rpki',until:S.day+1,msg:tr('events.a_state_owned_isp_accidentally'),cost:1500,fix:tr('events.call_everyone_you_know')});toast(tr('events.bgp_hijack_someone_else_is'),'bad');sfx('alert');return;}
if(e==='landban'){const lc=[...new Set(CABLE_PAIRS.flatMap(c=>[c.a,c.b]))];const c=pick(lc);S.ev.landban={city:c,until:S.day+45};toast(tr('events.landing_permit_dispute_in_city_two',{city:CITY[c].name}),'bad');return;}
if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;}
if(e==='typhoon'){const c=pick(['mnl','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]);
if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;}
p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');compute();return;}
if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');compute();return;}
if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.baltic_cable_damaged_a_cargo_ship'),'goal');return;}
const dur=15+Math.floor(Math.random()*15),en=N_('events.a_cargo_ship_dragged_its_anchor');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.cables_cut_in_the_red_sea'),'goal');return;}
const dur=20+Math.floor(Math.random()*15),en=N_('events.a_ship_drifting_without_power');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
if(e==='golden'){S.ev.golden=S.day+7;toast(tr('events.golden_week_demand_in_mainland_china'),'goal');return;}
if(e==='gfw'){S.ev.gfw=S.day+10;toast(tr('events.the_border_got_stricter_cross_border'),'bad');sfx('alert');return;}
if(e==='viral'){S.ev.viral=S.day+8;toast(tr('events.new_season_of_stranger_pings_just'),'goal');}
else if(e==='price'){S.priceMul*=0.92;toast(tr('events.transit_prices_fell_8_they_do'),'good');}
else if(e==='grant'){S.cash+=30000;toast(tr('events.rural_broadband_grant_30k_the'),'good');sfx('coin');}
else if(e==='depeer'){S.ev.depeer=S.day+20;addInc({type:'depeer',ref:'cog',until:S.day+20,msg:tr('events.cogentle_and_goggle_are_in_a'),cost:0});toast(tr('events.peering_spat_cogentle_de_peered'),'bad');sfx('alert');}
else if(e==='cake'){S.cash+=8000;toast(tr('events.drizzle_electric_sent_you_an_ipv6'),'good');sfx('coin');}
}

View file

@ -0,0 +1,110 @@
/* ---------- daily tick ---------- */
function dayTick(){
if(!S||S.lost)return;
S.day++;
const d=S.day;
dkTick(d);ixPriceWar(d);inboxDay(d);pniDay(d);
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
{const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;}
if(S.grace&&S.grace.until===d){toast(tr('day_tick.the_courtesy_route_has_ended_new'),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
for(const a of ddosAll(S,false))if(a.until>=d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,ddosSf(a));
ddosExpire();
ddosTick();
if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0;
if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0;
if(S.ev.php===d)toast(tr('day_tick.the_internet_is_back_half_of'),'good');
for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];S.stats.depeered=(S.stats.depeered||0)+1;
{const v={net:esc(NET[id].name),ix:esc(ixName(c)),city:esc(CITY[ixCity(c)].name),why:esc(sn.why)};toast(ixNamesCity(c)?tr('day_tick.net_de_peered_you_at_ix',v):tr('day_tick.net_de_peered_you_at_ix_caef',v),'bad');}}
if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast(tr('day_tick.license_granted_your_joint_venture'),'goal');sfx('coin');}
// resolve incidents
for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i);
toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);}
// eyeball growth / churn uses last computed service
for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c),P=eyeP(c);
if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);}
else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));}
compute();
for(const a of ddosAll())a.worst=Math.min(a.worst??1,ddosSf(a));
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
S.cash+=(R.revMo-R.costMo)/30;
S.stats.peak=Math.max(S.stats.peak,R.served);
S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift();
{const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`<br><i>${esc(LEVELS[lv-1].q)}</i>`,'goal');}S.lvl=top;sfx('coin');}}
for(const l of S.links){if(l.kind!=='df')continue;
if(l.ready===d){toast(`<b>${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}</b><br>${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);sfx('coin');}
if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('day_tick.construction_delay_n_days_why_a',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}}
// DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack).
for(const a of ddosAll()){
for(const b of S.biz)if(b.type==='scrub'&&ddosCities(a).includes(b.city)&&!(a.sla||[]).includes(b.id)&&(a.id||b.slaFor!==a.start)&&sfOf(R,b.city)<0.85){
(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
for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),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);
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
else if(S.day-(b.since||0)<15){}
else{b.mood-=(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));
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');}
else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause();
toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:'')+(paused?`<br><b>${tr('common.game_paused')}</b>`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');}
else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}}
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
if(cands.length){cands.sort((a,b)=>(a.pol==='open'?0:1)-(b.pol==='open'?0:1)||b.share-a.share);const n=Math.random()<.6?cands[0]:pick(cands);m.members.push(n.id);toast(tr('day_tick.net_joined_ix_another_member_paying',{net:esc(n.name),ix:esc(m.name),fee:fmt$(MYIX_FEE)}),'good');sfx('coin');}
m.next=d+8+Math.floor(Math.random()*10);}}
loanTick(d);
if(S.mode==='sandbox'&&S.cash<1e8)S.cash=1e9;
// offers
S.offers=S.offers.filter(o=>o.exp>d);
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1))spawnOffer();
// failures & events
let dirty=false;
if(d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1));}
if(d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);}
if(dirty)compute();
// payday floaters
if(d%30===0){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-(CITY[c].arpu||1));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
checkGoals();
scnTick(d);
confTick(d);
// money trouble
if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('day_tick.you_are_in_the_red_cancel'),'bad');}
else S.neg=0;
if(S.cash<-100000){S.lost=true;track('bankrupt');showLose();return;}
if(d%360===0&&[1,2,4].includes(d/360))track('game_year_'+(d/360+1),true);
if(d%10===0)save();
}
function spawnOffer(){
const mine=Object.keys(S.pops),lv=S.lvl||1;
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');
if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan');
if(S.links.some(l=>l.kind==='df'&&l.ready<=S.day))types.push('wwave','wwave');if(S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('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&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))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');
const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor');
const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');}
const t=pick(types),T=BIZ_T[t];
if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;}
if(T.nni){const city=pick(fabC),prov=pick(FABS.filter(f=>f.cities.includes(city))).id,bw=pick(T.opts),others=mine.filter(c=>c!==city),city2=T.l2&&others.length?pick(others):null;if(T.l2&&!city2)return;
const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('day_tick.name_via_fab',{name:base,fab:FAB[prov].name});S.usedNames.push(base);
const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
S.offers.push({id:uid(),city,city2,prov,name,type:t,bw,rate,reqs:['nni'],exp:S.day+40});return;}
let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(OFFC.concat(cnOk()?['pek','sha']:[])),city2=null;
if(T.l2){city=pick(mine);const pool=(Math.random()<(T.lv>=3?0.8:0.6)?mine:OFFC).filter(c=>c!==city);city2=pick(pool.length?pool:OFFC.filter(c=>c!==city));}
let bw=T.lv>=2?pick(T.opts):pick(T.opts.slice(0,mine.length>=4?4:3));
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));
let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999));
S.usedNames.push(name);
if(t==='provedor')city=pick(br);
if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));}
let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
if(CITY[city].au&&!T.l2&&!T.fiber&&!T.event){rate=Math.round(rate*AU_ARPU);bw=Math.min(bw,pick(T.opts.slice(0,2)));}
if(T.div&&!reqCan('diverse',{city,city2}))return;
const reqs=T.div?['diverse']:T.lat?['lat']:[];if((t==='hyper'||t==='ai'||t==='gpu')&&Math.random()<0.4)reqs.push('metro');const pool=Object.keys(REQS).filter(k=>!reqs.includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,{city,city2}));
if(Math.random()<(T.lv>=3?0.65:0.3))reqs.push(pick(pool));
if(T.lv>=3&&Math.random()<0.35){const more=pool.filter(k=>!reqs.includes(k));if(more.length)reqs.push(pick(more));}
const r2=Math.round(rate*(1+reqs.reduce((a,k)=>a+REQS[k].bonus,0)));
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax:T.lat?+(kmBetween(city,city2)/200*1.35).toFixed(1):null,exp:S.day+40});
}

View file

@ -0,0 +1,89 @@
/* Badges: achievements with rarities. Earned per game, and also remembered across games on this
device in a hall of fame, so there is always something grand to work towards. */
const RARITY={c:{n:tr('common.common'),col:'#16A866'},r:{n:tr('common.rare'),col:'#3A7BEA'},e:{n:tr('common.epic'),col:'#9D4EDD'},l:{n:tr('common.legendary'),col:'#FF8A3D'}};
const st=()=>S.stats||{};
const BADGES=[
{id:'hello',i:'👋',t:tr('common.hello_neighbour'),d:tr('badges.bring_up_your_first_peering_session'),r:'c',ok:()=>R.sessions>=1},
{id:'backhoe',i:'🚜',t:tr('badges.met_the_backhoe'),d:tr('badges.have_a_fiber_cut'),r:'c',ok:()=>(st().by||{}).cut>=1},
{id:'debt',i:'🏦',t:tr('badges.in_debt_we_trust'),d:tr('badges.take_out_a_loan'),r:'c',ok:()=>(st().loans||0)>=1||(S.loans||[]).length>0},
{id:'twins',i:'👯',t:tr('common.twins'),d:tr('badges.run_two_routers_in_one_pop'),r:'c',ok:()=>Object.values(S.pops).some(p=>(p.routers||1)>=2)},
{id:'shark',i:'🦈',t:tr('common.shark_week'),d:tr('badges.get_a_subsea_cable_bitten_by'),r:'r',ok:()=>(st().sharks||0)>=1},
{id:'ixc',i:'🔀',t:tr('common.ix_collector'),d:tr('badges.have_ports_on_10_internet_exchanges'),r:'r',ok:()=>Object.keys(S.ixp).length>=10},
{id:'haggle',i:'🤝',t:tr('badges.never_paid_list_price'),d:tr('badges.haggle_a_de_kicks_quote_down'),r:'r',ok:()=>!!st().haggleWin},
{id:'unsub',i:'📭',t:tr('common.unsubscribed'),d:tr('badges.opt_out_of_3_auto_enrolled'),r:'r',ok:()=>(st().optouts||0)>=3},
{id:'read',i:'💔',t:tr('badges.left_on_read'),d:tr('badges.get_de_peered_by_a_big'),r:'r',ok:()=>(st().depeered||0)>=1},
{id:'couch',i:'🛋️',t:tr('badges.peering_from_the_couch'),d:tr('badges.peer_at_an_ix_remotely'),r:'r',ok:()=>Object.keys(S.ixp).some(c=>isRemote(c)&&ixSessions(c).size>0)},
{id:'sender',i:'🇰🇷',t:tr('common.sender_pays'),d:tr('badges.paid_pnis_with_all_three_korean'),r:'e',ok:()=>['ktt','skb','lgu'].every(n=>S.pni.some(p=>p.net===n&&pniOn(p)))},
{id:'oink',i:'🐖',t:tr('common.pig_whisperer'),d:tr('badges.run_a_slow_booting_packetoinker'),r:'r',ok:()=>Object.keys(S.pops).some(c=>/Oinker/.test(RG[S.pops[c].rgen||0].chip)&&slowBoot(c))},
{id:'gap',i:'🌴',t:tr('common.mind_the_gap'),d:tr('badges.link_panama_city_and_bogota'),r:'r',ok:()=>S.links.some(l=>[l.a,l.b].includes('pan')&&[l.a,l.b].includes('bog'))},
{id:'andes',i:'🏔️',t:tr('badges.over_the_mountains'),d:tr('badges.build_fiber_across_the_andes'),r:'r',ok:()=>S.links.some(l=>!l.sub&&andesPair(l.a,l.b))},
{id:'duo',i:'🏜️',t:tr('common.duopoly_customer'),d:tr('badges.buy_a_wave_inside_the_uae'),r:'r',ok:()=>S.links.some(l=>uaePair(l.a,l.b))},
{id:'shed',i:'🔌',t:tr('common.stage_six'),d:tr('badges.ride_out_load_shedding_on_your'),r:'r',ok:()=>(st().shed||0)>=1},
{id:'metro3',i:'🏢',t:tr('badges.two_buildings_three_cities'),d:tr('badges.have_a_second_site_in_3'),r:'r',ok:()=>Object.values(S.pops).filter(p=>p.site2).length>=3},
{id:'penguin',i:'🐧',t:tr('common.lonely_penguin'),d:tr('badges.light_a_wave_on_the_humboldt'),r:'e',ok:()=>S.links.some(l=>l.cable==='humb')},
{id:'horn',i:'⛵',t:tr('badges.the_long_way_round'),d:tr('badges.run_a_link_round_cape_horn'),r:'e',ok:()=>S.links.some(l=>l.cable==='sam1'&&[l.a,l.b].includes('bue')&&[l.a,l.b].includes('scl'))},
{id:'six',i:'🌍',t:tr('common.six_continents'),d:tr('badges.pops_in_every_region_on_the'),r:'e',ok:()=>regionsCount()>=6},
{id:'giants',i:'🏭',t:tr('badges.friend_of_giants'),d:tr('badges.hold_deals_at_3_different_ai'),r:'e',ok:()=>new Set(S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega).flatMap(b=>bCities(b))).size>=3},
{id:'landlord',i:'🧵',t:tr('common.trench_landlord'),d:tr('badges.lease_hundreds_of_fiber_pairs_to'),r:'e',ok:()=>S.biz.some(b=>b.type==='pairs')},
{id:'t1',i:'👑',t:tr('common.tier_1'),d:tr('badges.go_transit_free'),r:'e',ok:()=>!!S.won},
{id:'bait',i:'🎣',t:tr('common.shark_bait'),d:tr('badges.get_bitten_by_sharks_3_times'),r:'l',ok:()=>(st().sharks||0)>=3},
{id:'nines',i:'💎',t:tr('common.five_nines'),d:tr('badges.serve_99_5_of_demand_every'),r:'l',ok:()=>(st().clean||0)>=365},
{id:'fifty',i:'🗺️',t:tr('badges.everywhere_at_once'),d:tr('badges.have_pops_in_50_cities'),r:'l',ok:()=>Object.keys(S.pops).length>=50},
{id:'unicorn',i:'🦄',t:tr('common.unicorn'),d:tr('badges.hold_a_billion_dollars_in_cash'),r:'l',ok:()=>S.cash>=1e9},
{id:'clean',i:'🧼',t:tr('badges.debt_free_tier_1'),d:tr('badges.win_without_ever_taking_a_loan'),r:'l',ok:()=>!!S.won&&!(st().loans||0)&&!(S.loans||[]).length},
{id:'speed',i:'⚡',t:tr('common.speedrun'),d:tr('badges.reach_tier_1_within_three_years'),r:'l',ok:()=>!!S.won&&S.day<=1095},
{id:'te',i:'🧭',t:tr('common.traffic_whisperer'),d:tr('badges.have_auto_te_move_100_gbps'),r:'r',ok:()=>(st().teMax||0)>=100},
{id:'street',i:'🚧',t:tr('common.same_street'),d:tr('badges.lose_a_metro_ring_to_one'),r:'r',ok:()=>(st().by||{}).ring>=1},
{id:'anchor',i:'⚓',t:tr('common.anchors_aweigh'),d:tr('badges.have_a_cable_cut_by_a'),r:'r',ok:()=>!!(st().f||{}).anchor},
{id:'retained',i:'🎁',t:tr('badges.customer_success_story'),d:tr('badges.take_a_de_kicks_retention_offer'),r:'r',ok:()=>!!st().retained},
{id:'brrr',i:'🇧🇷',t:tr('common.samba_peering'),d:tr('badges.ports_on_ix_brrr_in_sao'),r:'e',ok:()=>['sao','rio','for'].every(c=>S.ixp[c]!==undefined)},
{id:'bingo',i:'🎰',t:tr('badges.de_kicks_bingo'),d:tr('badges.ports_at_all_six_de_kicks'),r:'e',ok:()=>DK_CITIES.filter(c=>CITY[c]&&CITY[c].ix).every(c=>S.ixp[c]!==undefined)},
{id:'fire',i:'🌋',t:tr('badges.ring_of_fire'),d:tr('badges.pops_all_the_way_round_the'),r:'e',ok:()=>['lax','tok','tpe','mnl','jkt','syd','akl','scl'].every(c=>S.pops[c])},
{id:'curtain',i:'🎭',t:tr('badges.iron_curtain_call'),d:tr('badges.pops_in_warsaw_prague_vienna'),r:'e',ok:()=>['waw','prg','vie','bud','buh','sof','beg','tll'].every(c=>S.pops[c])},
{id:'islands',i:'🏝️',t:tr('common.island_hopper'),d:tr('badges.pops_in_reykjavik_dublin_london'),r:'e',ok:()=>['rek','dub','lon','cbo','tpe','mnl','tok','akl'].every(c=>S.pops[c])},
{id:'wall',i:'🧱',t:tr('badges.through_the_wall'),d:tr('badges.run_a_licensed_pop_in_mainland'),r:'e',ok:()=>cnOk()&&Object.keys(S.pops).some(cnCity)},
{id:'beaver',i:'🦫',t:tr('common.dam_it'),d:tr('badges.have_your_fiber_chewed_through_by'),r:'e',ok:()=>!!(st().f||{}).beaver},
{id:'croc',i:'🐊',t:tr('common.darwin_award'),d:tr('badges.have_your_fiber_bitten_by_a'),r:'l',ok:()=>!!(st().f||{}).croc},
{id:'unbreak',i:'🛡️',t:tr('common.unbreakable'),d:tr('badges.survive_100_incidents_without'),r:'l',ok:()=>(st().survived||0)>=100},
{id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13},
{id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))},
{id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&S.day<=730},
{id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'l',ok:()=>R.served>=100000},
{id:'petabit',i:'🪐',t:tr('badges.a_petabit_a_second'),d:tr('badges.serve_1_pbps_a_thousand_terabits'),r:'l',ok:()=>R.served>=1e6},
{id:'llama',i:'🦙',t:tr('common.llama_drama'),d:tr('badges.lose_fiber_to_a_llama_herd'),r:'l',secret:true,ok:()=>!!(st().f||{}).llama},
{id:'hallway',i:'🎤',t:tr('common.hallway_track'),d:tr('badges.attend_a_conference'),r:'r',ok:()=>(st().confs||0)>=1},
{id:'beer',i:'🍺',t:tr('badges.peering_over_beer'),d:tr('badges.set_up_a_pni_while_the'),r:'e',ok:()=>!!st().beerPni},
{id:'circuit',i:'✈️',t:tr('common.conference_circuit'),d:tr('badges.attend_six_conferences_in_one_game'),r:'l',ok:()=>(st().confs||0)>=6},
{id:'kiddie',i:'💻',t:tr('common.script_kiddie'),d:tr('badges.deploy_a_routescript_that_cuts_your'),r:'r',ok:()=>!!st().kiddie},
{id:'fat',i:'🫠',t:tr('common.fat_finger'),d:tr('badges.deploy_a_routescript_that_takes_down'),r:'r',ok:()=>!!st().fat},
{id:'scen1',i:'🎯',t:tr('common.scenario_solver'),d:tr('badges.complete_any_scenario'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')},
{id:'weekly',i:'📅',t:tr('common.weekly_regular'),d:tr('badges.finish_a_weekly_challenge'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id==='weekly')},
{id:'scen3',i:'🏅',t:tr('common.scenario_specialist'),d:tr('badges.complete_three_different_scenarios'),r:'e',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&Object.keys(scnHof()).filter(k=>k!=='weekly').length>=3},
{id:'scenall',i:'🏆',t:tr('common.scenario_grandmaster'),d:tr('badges.complete_every_scenario'),r:'l',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&SCN.every(x=>scnHof()[x.id])},
{id:'elephant',i:'🐘',t:tr('badges.i_survived_the_elephant'),d:tr('badges.live_through_the_day_half_the'),r:'l',secret:true,ok:()=>!!S.phpDone&&!(S.ev.php>S.day)},
{id:'vigil',i:'⚖️',t:tr('common.vigilante'),d:tr('badges.fire_the_hackback_3000tm_and_flatten'),r:'e',secret:true,ok:()=>(st().vigilante||0)>=1},
{id:'nullroute',i:'💥',t:tr('common.collateral_damage'),d:tr('badges.blackhole_one_of_your_own_cities'),r:'r',ok:()=>(st().rtbh||0)>=1},
{id:'toaster',i:'🍞',t:tr('common.toaster_wrangler'),d:tr('badges.weather_a_ddos_with_your_defences'),r:'c',ok:()=>(st().ddosHeld||0)>=1},
{id:'cleanpipe',i:'🚿',t:tr('common.clean_pipes'),d:tr('badges.turn_on_a_transit_clean_pipe'),r:'r',ok:()=>S.transit.some(t=>t.clean)},
{id:'lamb',i:'🐐',t:tr('common.sacrificial_lamb'),d:tr('badges.run_a_sacrificial_pni_choke_point'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)},
{id:'flood',i:'🌊',t:tr('badges.held_the_flood'),d:tr('badges.weather_a_multi_terabit_ddos'),r:'e',ok:()=>(st().ddosMonster||0)>=1},
{id:'skynot',i:'🤖',t:tr('common.skynot_smiles'),d:tr('badges.land_a_hackback_3000tm_that_actually'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1},
{id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length},
];
function hof(){try{return JSON.parse(localStorage.getItem('sot-badges')||'{}')||{};}catch(e){return {};}}
function checkBadges(){S.ach=S.ach||{};if(S.mode==='sandbox')return;let h=null;
for(const b of BADGES){if(S.ach[b.id]!==undefined)continue;let ok=false;try{ok=b.ok();}catch(e){}
if(!ok)continue;S.ach[b.id]=S.day;const R0=RARITY[b.r];
if(!h)h=hof();if(!h[b.id])h[b.id]={d:new Date().toISOString().slice(0,10),n:S.name};
toast(`<b>${b.i} ${tr('badges.badge_unlocked_name',{name:esc(b.t)})}</b><br><span style="color:${R0.col};font-weight:900">${R0.n}</span> · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id);}
if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}}
function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length;
return `<h3 style="font-size:15px;margin:14px 0 6px">${tr('common.badges')} <span class="meta">${tr('badges.got_total_this_game_ever_ever',{got,total:BADGES.length,ever:Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length})}</span></h3><div class="badges">${BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!h[b.id],R0=RARITY[b.r],hide=b.secret&&!on&&!ever;
return `<div class="bdg ${on?'on':ever?'ever':''}" style="--rc:${R0.col}" title="${esc(hide?tr('badges.a_secret_badge'):b.t+': '+b.d)}"><span class="bi">${hide?'❔':b.i}</span><span class="bt">${esc(hide?'???':b.t)}</span><span class="br">${R0.n}${ever&&!on?' · '+tr('common.earned_before'):''}</span>${hide?'':`<span class="bd">${esc(b.d)}</span>`}</div>`;}).join('')}</div>`;}
function checkGoals(){checkBadges();
for(const g of GOALS){if(S.done[g.id]!==undefined)continue;let ok=false;try{ok=g.ok();}catch(e){}
if(ok){S.done[g.id]=S.day;if(g.r&&S.mode!=='sandbox'){S.cash+=g.r;}
toast(`<b>${tr('badges.goal_complete_name',{name:esc(g.t)})}</b>${g.r?`<br>${tr('badges.reward_amt',{amt:fmt$(g.r)})}`:''}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');
track('goal_'+g.id);if(g.win&&!S.won){S.won=true;track('win_tier1');checkBadges();showWin();}}}
}

View file

@ -0,0 +1,49 @@
/* ================= ACTIONS ================= */
function spend(c){if(S.cash<c){toast(tr('interface.not_enough_cash_wait_for_revenue'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
const ACT={
speed:({v})=>{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();},
help:()=>showHelp(),
dash:()=>{if(!S)return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
dashClose:()=>{$('dash').hidden=true;},
dashTab:({k})=>{if(!DTABS.includes(k))return;UI.dtab=k;renderDash();const d=$('dash');if(d)d.scrollTop=0;},
dashSort:({k})=>{if(!['name','asn','type','traffic','cost','lost'].includes(k))return;if(UI.dashSort===k)UI.dashDir=-(UI.dashDir||-1);else{UI.dashSort=k;UI.dashDir=k==='name'||k==='type'||k==='asn'?1:-1;}renderDash();},
bank:()=>{if(!S)return;UI.confirm=null;$('dash').hidden=true;const b=$('bankBox');b.hidden=false;UI._bh=null;renderBank();},
bankClose:()=>{UI.confirm=null;$('bankBox').hidden=true;},
takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;S.stats.loans=(S.stats.loans||0)+1;const B=BANKS[o.bank];let got=o.amount,note='';
if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=' '+(f>=1?tr('interface.tubecoin_moved_up_p_on_the',{p:Math.round(Math.abs(f-1)*100)}):tr('interface.tubecoin_moved_down_p_on_the',{p:Math.round(Math.abs(f-1)*100)}));}
S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o);
S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}});
track('loan_taken');toast(`<b>${tr('interface.amt_from_bank_has_landed',{amt:fmt$(got),bank:esc(B.name)})}</b><br>${B.equity?tr('interface.they_now_own_p_of_your',{p:pct(o.share)}):loanSummary(o)}${note}`,'good');sfx('coin');after();renderBank();},
declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();renderHUD();save();},
repayLoan:({id})=>{const l=S.loans.find(x=>x.id===id);if(!l)return;const B=BANKS[l.bank];const cost=repayCost(l,B);
if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;if(!spend(cost)){renderBank();return;}S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');
toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();},
leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=lvl()>=3?'roadm':'lite';openLinkModal(a,b);},
dashLink:({id})=>{$('dash').hidden=true;selectLink(id);},
animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();},
soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();},
langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save();location.reload();},
mute:()=>{UI.muted=!UI.muted;try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();},
closePanel:()=>{UI.sel=null;UI.confirm=null;renderPanel();renderLeft();},
closeModal:()=>closeModal(),
tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();},
leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();},
netFocus:({id})=>{if(!NET[id])return;$('dash').hidden=true;UI.netFocus=id;UI.nf='all';UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;},
netFilter:({f})=>{UI.nf=f==='out'?'out':'all';UI.netFocus=null;$('dash').hidden=true;UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;},
meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}},
toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();},
phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();},
phonePlay:()=>{haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();},
phoneSpeed:()=>{haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();},
install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;}
openModal(pitchHtml(false));},
pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();},
logOpen:({id})=>{const e=(S.log||[]).find(x=>x.id===id),o=e&&e.o;if(!o)return;$('dash').hidden=true;closeModal();
if(o.a==='city'&&isCity(o.v)){ACT.focusCity({city:o.v});return;}
if(o.a==='link'){if(S.links.some(l=>l.id===o.v)){ACT.selLink({id:o.v});return;}toast(tr('interface.that_link_is_gone_it_was'),'');return;}
if(o.a==='cust'){if(S.biz.some(b=>b.id===o.v)){ACT.custGo({id:o.v});return;}toast(tr('interface.that_customer_is_gone_the_contract'),'');return;}
if(o.a==='bank'){ACT.bank({});return;}if(o.a==='inbox'){ACT.inbox({});return;}if(o.a==='tab'&&LOG_TABS.includes(o.v))ACT.leftTab({t:o.v});},
logAll:()=>{UI.logAll=!UI.logAll;renderLeft();},
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();},
selLink:({id})=>selectLink(id),
};

View file

@ -0,0 +1,26 @@
Object.assign(ACT,{
buildPop:({city})=>{if(S.pops[city]||!cityOn(city))return;const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();},
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();},
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});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;
// 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};toast(tr('pops_transit_ix.augment_ordered_with_net_eta',{net:esc(NET[p.net].name),eta:pniWhen(lead)}),'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();},
cancelTransit:({id,ok})=>{if(!ok&&UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.transit=S.transit.filter(t=>t.id!==id);UI.confirm=null;after();},
buyIx:({city,tier,signed})=>{tier=+tier;if(!PORT[tier]||!ixName(city)||(!S.pops[ixCity(city)]&&(!remoteCities().includes(ixCity(city))||tier>1))||(S.ixp[city]!==undefined&&tier<=S.ixp[city]))return;if(S.pops[ixCity(city)]&&!portOk(ixCity(city),tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}{const h0=S.ixp[city]!==undefined;if(!S.myIx[city]&&!portGate(ixCity(city),h0?(PORT_SLOT(tier)-PORT_SLOT(S.ixp[city]))*((S.ixn||{})[city]||1):PORT_SLOT(tier)))return;}
if(isDk(city)&&S.ixp[city]===undefined&&!signed){const dk=dkState();if(dk.stall>S.day){toast(tr('pops_transit_ix.de_kicks_sales_is_still_aligning',{n:dk.stall-S.day}),'bad');sfx('err');return;}dk.lastQ=dk.lastQ||{};const lq=dk.lastQ[city];dk.q={city,tier,m:lq&&lq.until>S.day?lq.m:dkQuoteMult(),h:lq&&lq.until>S.day?lq.h:0};dk.lastQ[city]={m:dk.q.m,h:dk.q.h,until:S.day+90};dkQuoteModal();return;}const had=S.ixp[city]!==undefined;if(!spend(ixPortMo(city,tier)*(had?((S.ixn||{})[city]||1):1)))return;S.ixp[city]=tier;if(!had)toast(S.pops[ixCity(city)]?tr('pops_transit_ix.port_up_at_ix_now_request',{ix:esc(ixName(city))}):tr('pops_transit_ix.remote_port_up_at_ix_it',{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});after();},
cancelIx:({city,sure,ok})=>{if(!ok&&UI.confirm!=='ix'+city){UI.confirm='ix'+city;renderPanel();return;}
if(isDk(city)&&!sure){const dk=dkState();if(!dk.retUsed[city]){openModal(`<div class="eyebrow">${tr('pops_transit_ix.de_kicks_group_customer_success')}</div><h2 style="font-size:26px">${tr('pops_transit_ix.wait_before_you_go')}</h2><p class="tagline">${tr('pops_transit_ix.we_value_our_partnership_too_much')}</p><div class="kv"><span>${tr('common.retention_offer')}</span><b>${tr('pops_transit_ix.40_off_for_6_months')}</b></div><p class="note">${tr('pops_transit_ix.after_that_the_normal_price_returns')}</p><div class="btns">${btn(tr('pops_transit_ix.stay_take_the_discount'),'dkStay',{city},'pink')}${btn(tr('common.leave_anyway'),'cancelIx',{city,sure:1},'ghost')}</div>`);return;}}
closeModal();if(S.dk){if(S.dk.m[city]){S.dk.lastQ=S.dk.lastQ||{};S.dk.lastQ[city]={m:S.dk.m[city],h:3,until:S.day+365};}delete S.dk.m[city];delete S.dk.add[city];delete S.dk.ret[city];}delete S.ixp[city];delete S.rs[city];if(S.ixn)delete S.ixn[city];for(const k in S.peers)if(k.endsWith('@'+city))delete S.peers[k];UI.confirm=null;after();},
rs:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;S.rs[city]=!S.rs[city];if(S.rs[city])toast(tr('pops_transit_ix.route_server_session_up_you_now'),'good');sfx('build');after();},
dkAccept:()=>{const dk=dkState(),q=dk.q;if(!q)return;dk.m[q.city]=q.m;dk.q=null;closeModal();ACT.buyIx({city:q.city,tier:q.tier,signed:true});if(S.ixp[q.city]===undefined)delete dk.m[q.city];else toast(tr('pops_transit_ix.signed_with_de_kicks_welcome_to'),'good');},
dkHaggle:()=>{const dk=dkState(),q=dk.q;if(!q||q.h>=3)return;q.h++;const r=Math.random();
if(r<0.45){S.stats.haggleWin=1;q.m=+(q.m*(0.75+Math.random()*0.15)).toFixed(2);dkQuoteModal();toast(tr('pops_transit_ix.just_this_once_your_account_manager'),'good');}
else if(r<0.75){q.m=+(q.m*1.1).toFixed(2);dkQuoteModal();toast(tr('pops_transit_ix.after_consulting_with_management_the'),'bad');}
else{dk.stall=S.day+5+Math.floor(Math.random()*6);dk.q=null;closeModal();toast(tr('pops_transit_ix.haggling_paused_why',{why:esc(pick(DK_STALL))}),'bad');}},
dkWalk:()=>{const dk=dkState(),q=dk.q;if(q){dk.lastQ=dk.lastQ||{};dk.lastQ[q.city]={m:q.m,h:q.h,until:S.day+90};if(q.h>0)dk.stall=Math.max(dk.stall||0,S.day+3);}dk.q=null;closeModal();toast(tr('pops_transit_ix.de_kicks_will_circle_back_expect'),'');},
dkOptOut:({city,n})=>{const dk=dkState(),k='dk'+city+n;if(UI.confirm!==k){UI.confirm=k;renderPanel();return;}dk.add[city]=(dk.add[city]||[]).filter(x=>x.n!==n);UI.confirm=null;S.stats.optouts=(S.stats.optouts||0)+1;toast(tr('pops_transit_ix.opted_out_of_name_it_took',{name:esc(n)}),'good');after();},
dkStay:({city})=>{S.stats.retained=1;const dk=dkState();dk.ret[city]=S.day+180;dk.retUsed[city]=true;UI.confirm=null;closeModal();toast(tr('pops_transit_ix.40_off_ix_for_6_months',{ix:esc(ixName(city))}),'good');after();},
});

View file

@ -0,0 +1,27 @@
Object.assign(ACT,{
teEdit:()=>{if(!S.te)return;UI.teDraft=undefined;teModal();},
teClose:()=>{const t=$('teSrc');if(t)UI.teDraft=t.value;closeModal();},
teOpt:()=>{UI.teDraft=teOptimize();teModal();},
teExample:()=>{UI.teDraft=TE_EXAMPLE;teModal();},
teSlop:()=>{const t0=performance.now(),a=aiSlop(Math.random()<0.02),secs=Math.max(0.1,(performance.now()-t0)/1000);UI.teDraft=UI.slop=a.src;teModal(`<p class="note aisay">🤖 <b>${esc(a.ai)}</b> <small>${tr('route_script_and_tools.thought_for_s_seconds',{s:secs.toFixed(1)})}</small><br>${tr(a.say)}</p>`);sfx('build');},
teHelp:()=>{const t=$('teSrc');if(t)UI.teDraft=t.value;teHelpModal();},
teBack:()=>teModal(),
teRecipe:({id})=>{const r=TE_RECIPES.find(x=>x.id===id);if(!r)return;UI.teDraft=r.src().join('\n');teModal(`<p class="note">${tr('route_script_and_tools.loaded_name_check_it_then_deploy',{name:tr(r.n)})}</p>`);},
teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`<p class="note">${tr('route_script_and_tools.script_removed_plain_auto_te_is')}</p>`);},
teCheck:()=>{const t=$('teSrc');const src=t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}</pre>`);},
teDeploy:()=>{const t=$('teSrc');const src=(t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}</pre>`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after();
const drop=r.before.served>1?1-r.after.served/r.before.served:0,saved=r.before.tc>0?1-r.after.tc/r.before.tc:0;
if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');}
else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');}
else{if(saved>0.1&&drop<0.01)S.stats.kiddie=1;toast(`<b>${tr('common.commit_complete')}</b><br>${saved>0.01?trn('route_script_and_tools.n_rule_live_transit_bill_down',p.n,{p:pct(saved)}):trn('route_script_and_tools.n_rule_live',p.n)}`,'good');sfx('build');}closeModal();UI.slop=undefined;checkGoals();},
buyTE:()=>{if(S.te)return;if(lvl()<3){toast(tr('route_script_and_tools.auto_te_unlocks_at_customer_level'),'bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day};toast(tr('route_script_and_tools.auto_te_is_live_the_controller'),'good');after();},
teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();},
trace:({city})=>traceModal(city),
traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);},
traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast(tr('route_script_and_tools.copied_paste_it_into_your_favourite'),'good');}catch(e){}},
share:()=>shareModal(),
shareDl:()=>shareFile(f=>{if(!f)return;const a=document.createElement('a');a.href=URL.createObjectURL(f);a.download=f.name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);track('share_download');}),
shareGo:()=>shareFile(f=>{const d={title:'Series of Tubes',text:tr('route_script_and_tools.name_as_asn_tier_peak_peak',{name:S.name,asn:S.asn,tier:tierLabel(),peak:fmtG(S.stats.peak||0)}),url:'https://seriesoftub.es/'};try{if(f&&navigator.canShare&&navigator.canShare({files:[f]}))d.files=[f];navigator.share(d).then(()=>track('share_done')).catch(()=>{});}catch(e){}}),
confGo:({key})=>{S.confReg=S.confReg||{};if(S.confReg[key])return;const cf=upcomingConfs(75).find(x=>x.key===key);if(!cf||cf.day<=S.day)return;if(!spend(CONF_COST))return;S.confReg[key]=true;toast(tr('route_script_and_tools.registered_flights_booked_badge'),'good');after();},
tutSkip:()=>{S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}renderCoach();},
});

View file

@ -0,0 +1,38 @@
Object.assign(ACT,{
addSite:({city})=>{const p=S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(tr('sites_peering_caches.second_site_live_in_city_b',{city:CITY[city].name,b:esc(siteName(city,'b')),a:esc(siteName(city,'a'))}),'good');sfx('build');after();},
rmSite:({city})=>{const p=S.pops[city];if(!p||!p.site2)return;if(UI.confirm!=='site'+city){UI.confirm='site'+city;renderPanel();return;}UI.confirm=null;p.site2=0;p.sdown=null;p.ringcut=0;for(const t of S.transit)if(t.city===city)t.site='a';for(const x of S.pni)if(x.city===city)x.site='a';for(const x of S.caches)if(x.city===city)x.site='a';if(S.ixSite)for(const x of ixIdsIn(city))delete S.ixSite[x];after();},
siteSet:({k,id,s})=>{if(!['a','b','ab'].includes(s))return;
const o=k==='t'?S.transit.find(x=>x.id===id):k==='p'?S.pni.find(x=>x.id===id):null;if(k!=='ix'&&!o)return;if(k==='ix'&&(!isIx(id)||S.ixp[id]===undefined||!S.pops[ixCity(id)]))return;
if(k==='ix'&&S.myIx[id]){S.ixSite=S.ixSite||{};S.ixSite[id]=s;after();return;}
const n=()=>k==='ix'?((S.ixn||{})[id]||1):(o.n||1);
if(s==='ab'&&n()<2){const before=n();if(k==='t')ACT.lagT({id,d:1});else if(k==='p')ACT.lagP({id,d:1});else ACT.lagIx({city:id,d:1});if(n()<2||n()===before)return;toast(tr('sites_peering_caches.second_lag_member_added_one_member'),'good');}
if(k==='ix'){S.ixSite=S.ixSite||{};S.ixSite[id]=s;}else o.site=s;after();},
peer:({city,net})=>{if(!isIx(city)||!isNet(net)||S.ixp[city]===undefined||!ixMembers(city).includes(net))return;const r=peerOk(net,'ix',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');return;}S.peers[net+'@'+city]=true;
toast(`<b>${tr('sites_peering_caches.net_accepted',{net:esc(NET[net].name)})}</b><br>${NET[net].pol==='selective'?tr('sites_peering_caches.they_checked_your_pearingdb_page_and'):tr('sites_peering_caches.bgp_session_established')}`,'good');sfx('build');after();},
unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();},
peerAll:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;const set=ixSessions(city);let n=0;for(const id of ixMembers(city))if(!set.has(id)&&peerOk(id,'ix',city).ok){S.peers[id+'@'+city]=true;n++;}if(!n)return;toast(trn('sites_peering_caches.n_new_session_at_ix_small',n,{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});sfx('build');after();},
tailTog:()=>{UI.tailOpen=!UI.tailOpen;renderLeft();},
pni:({city,net,tier})=>{tier=+tier;const g1=tier===-1;if(g1){if(!pniG1(net))return;tier=0;}if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(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 r=peerOk(net,'pni',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');after();return;}
if(!g1&&tier<pniMin(net)){toast(tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n}),'bad');sfx('err');return;}
const ex=S.pni.find(p=>p.city===city&&p.net===net);if(ex&&(g1||!pniOn(ex)||ex.up))return;if(ex&&!(ex.g1&&tier===0)&&tier<=ex.tier)return;
const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1);if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(cost))return;if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
// Nothing is instant: a cross-connect takes weeks, and the big networks quote months for a new PNI or an augment.
const lead=pniLead(net);if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
toast(tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}),'good');after();},
pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random();
if(r<0.15){if(p.up)p.up.ready=Math.max(S.day+1,p.up.ready-30);else p.ready=Math.max(S.day+1,p.ready-30);toast(tr('sites_peering_caches.your_account_manager_found_the_order'),'good');}
else toast(pick([tr('sites_peering_caches.it_is_with_the_provisioning_team'),tr('sites_peering_caches.we_are_waiting_on_the_colo'),tr('sites_peering_caches.your_ticket_was_merged_into_another'),tr('sites_peering_caches.could_you_resend_the_loa_you'),tr('sites_peering_caches.your_account_manager_is_on_paternity')]));after();},
inbox:()=>{inboxModal();},
inboxAct:({id,a})=>{if(!['accept','decline','raise','keep'].includes(a))return;ibxAnswer(+id,a);after();inboxModal();},
inboxPol:({p})=>{if(!PPOL.includes(p))return;ibx().pol=p;after();inboxModal();},
inboxRaiseAll:()=>{const I=ibx(),mp=I.items.filter(x=>x.k==='mp');if(!mp.length)return;const leaks=mp.filter(x=>x.leak).length;for(const x of mp)ibxAnswer(x.id,'raise',true);
toast(leaks?trn('sites_peering_caches.raised_n_max_prefix_limits_one',leaks,{n:mp.length,k:leaks}):tr('sites_peering_caches.raised_n_max_prefix_limits_all',{n:mp.length}),leaks?'bad':'good');after();inboxModal();},
inboxAll:({a})=>{if(a!=='accept'&&a!=='decline')return;const I=ibx();for(const x of I.items.filter(x=>x.k==='req'))ibxAnswer(x.id,a,true);after();inboxModal();},
inboxBot:({on})=>{const I=ibx();if(+on){if(I.bot||!spend(AI_MO))return;I.bot=true;ibxLog(N_('sites_peering_caches.hello_i_am_large_peering_model'),{});toast(tr('sites_peering_caches.large_peering_model_is_hired_your',{price:fmt$(20e6)}),'good');}else{I.bot=false;toast(tr('sites_peering_caches.the_ai_is_gone_it_left'));}after();inboxModal();},
cancelPni:({id,ok})=>{if(!ok&&UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.pni=S.pni.filter(p=>p.id!==id);UI.confirm=null;after();},
cache:({city,net})=>{const n=NET[net];if(!n||!n.cache||!S.pops[city])return;if((R.demTo[net]||0)<n.cache.min){toast(tr('sites_peering_caches.net_says_not_yet_send_them',{net:esc(n.name),min:n.cache.min}),'bad');sfx('err');return;}if(!portGate(city,1))return;
{const hv=S.caches.filter(x=>x.city===city&&x.net===net),nb=hv.filter(x=>x.site==='b').length;S.caches.push({id:uid(),city,net,site:S.pops[city].site2&&nb<hv.length-nb?'b':'a'});}toast(tr('sites_peering_caches.cache_installed_in_city_net_shipped',{cache:esc(n.cache.name),city:CITY[city].name,net:esc(n.name),mo:fmt$(CACHE_MO)}),'good');sfx('build');after();},
rmCache:({id})=>{S.caches=S.caches.filter(c=>c.id!==id);after();},
// Move one of a CDN's boxes to the other building (#69), so a dark building only takes out part of the cache.
cacheSite:({city,net,s})=>{if(s!=='a'&&s!=='b'||!S.pops[city]||!S.pops[city].site2)return;const x=S.caches.find(c=>c.city===city&&c.net===net&&(c.site==='b'?'b':'a')!==s);if(!x)return;x.site=s;sfx('click');after();},
});

View file

@ -0,0 +1,19 @@
Object.assign(ACT,{
advertise:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.ready>S.day)return;if(S.offers.some(o=>o.link===l.id))return;
const t=freeCh(l)>=1?'wwave':pairFree(l)?'dfpair':null;if(!t){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}
const T=BIZ_T[t],nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);S.usedNames.push(n);return n;};
// A capacity broker finds a buyer at once and keeps 10% of the monthly price.
const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();},
accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;}
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)<o.slots){toast(tr('customers.not_enough_free_channels_on_that'),'bad');return;}}
if(BIZ_T[o.type].event&&S.day>=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;}
// A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves,
// instead of a new customer for every few waves (a big fiber business otherwise fills the save with tiny contracts).
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
S.offers=S.offers.filter(x=>x!==o);S.biz.push({id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov});
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},
});

View file

@ -0,0 +1,33 @@
Object.assign(ACT,{
upLink:({id,tier})=>{tier=+tier;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='wave'||!LT[tier]||tier<=l.tier)return;{const w=subWaveWhy(tier,l.km,l.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}if(!waveOk(l.a,l.b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}const nm=Math.round(waveMo(l.km,l.sub,tier)*(l.mult||1));if(!spend(nm))return;l.mo=nm;l.tier=tier;after();},
decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();},
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');}}S.links=S.links.filter(l=>l.id!==id);UI.sel=null;UI.confirm=null;after();},
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;if(i.slow&&i.rushed)return;if(!spend(i.cost))return;
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
foundIx:({city})=>{if(!S.pops[city]||S.myIx[city]||CITY[city].ix||CITY[city].cn)return;if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p)return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if((cnCity(a)||cnCity(b))&&!cnOk())return;
if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}
const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;}
{const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b));
if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);closeModal();
if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';}
floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();},
buyNni:({city,prov,tier})=>{tier=+tier;if(!NNI[tier]||!isCity(city)||!own(FAB,prov)||!FAB[prov].cities.includes(city)||!S.pops[city])return;const ex=nniPort(city,prov);if(ex&&tier<=ex.tier)return;if(!ex&&!portGate(city,1))return;if(ex&&nniUsed(city,prov)>NNI[tier].g){toast(tr('links.too_many_circuits_for_a_smaller'),'bad');return;}if(!spend(NNI[tier].mo))return;if(ex)ex.tier=tier;else S.nni.push({id:uid(),city,prov,tier});toast(tr('links.fab_port_is_up_in_city',{fab:esc(FAB[prov].name),city:CITY[city].name}),'good');after();},
rmNni:({city,prov})=>{if(nniUsed(city,prov)>0){toast(tr('links.cancel_the_circuits_on_this_port'),'bad');sfx('err');return;}S.nni=S.nni.filter(x=>!(x.city===city&&x.prov===prov));after();},
openVxc:(a)=>openVxcModal(a),
buyVxc:({a,b,prov,t})=>{t=+t;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>NNI[pa.tier].g){toast(tr('links.not_enough_room_on_your_fabric'),'bad');sfx('err');return;}
if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>NNI[pb.tier].g){toast(tr('links.not_enough_room_on_your_fab',{fab:esc(FAB[prov].name),city:CITY[b].name}),'bad');sfx('err');return;}}
const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal();
toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();},
upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('links.fabric_port_in_city_is_full',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();},
cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();},
setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();},
setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();},
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},
});

View file

@ -0,0 +1,17 @@
Object.assign(ACT,{
custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();},
listMore:({k})=>{if(k!=='conn'&&k!=='cust')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;renderDash();},
custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';listReset('cust');renderDash();},
custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';listReset('cust');renderDash();},
custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;listReset('cust');if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();},
custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};listReset('cust');UI.dtab='cust';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});},
connF:({f,v})=>{const F=UI.cf=UI.cf||{};listReset('conn');if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();},
connCity:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.city=isCity(v)?v:'';renderDash();},
connNet:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.net=NET[v]?v:'';renderDash();},
connSort:({k})=>{if(!['k','city','name','use','mo'].includes(k))return;listReset('conn');if(UI.connSort===k)UI.connDir=-(UI.connDir||1);else{UI.connSort=k;UI.connDir=k==='use'||k==='mo'?-1:1;}renderDash();},
connFor:({net})=>{if(!NET[net])return;UI.cf={net};ACT.connOpen();},
connCancel:({k,id})=>{const r=conns().find(x=>x.k===k&&x.id===id);if(!r||r.mine)return;const key='cc:'+k+':'+id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null;
if(k==='t')ACT.cancelTransit({id,ok:1});else if(k==='p')ACT.cancelPni({id,ok:1});else if(k==='ix')ACT.cancelIx({city:id,ok:1});else if(k==='c')ACT.rmCache({id});else{const [city,prov]=id.split('|');ACT.rmNni({city,prov});}renderDash();},
connOpen:()=>{if(!S)return;UI.dtab='conn';listReset('conn');const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
});

View file

@ -0,0 +1,19 @@
Object.assign(ACT,{
applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast(tr('security_and_china.application_filed_your_local_partner'),'goal');after();},
togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.premium=!t.premium;sfx('click');after();},
buildScrub:({city,tier})=>{if(!S.pops[city]||S.scrubs.some(x=>x.city===city))return;const T=SCRUB_TIERS[tier||0];if(!T)return;if((lvl()||1)<T.lvl){toast(tr('security_and_china.tier_scrubbing_unlocks_at_customer',{tier:T.n,lv:T.lvl}),'bad');sfx('err');return;}if(!spend(T.cost))return;if(!hasScrub())S.scrubMode='always';S.scrubs.push({city,tier:tier||0});toast(tr('security_and_china.tier_scrubbing_center_online_in_city',{tier:T.n,city:CITY[city].name,g:fmtG(T.g)}),'good');after();},
scrubUp:({city,tier})=>{const x=S.scrubs.find(q=>q.city===city);tier=+tier;if(!x||!SCRUB_TIERS[tier]||tier<=(x.tier||0))return;const T=SCRUB_TIERS[tier];if((lvl()||1)<T.lvl){toast(tr('security_and_china.tier_scrubbing_unlocks_at_customer',{tier:T.n,lv:T.lvl}),'bad');sfx('err');return;}if(!spend(Math.round(T.cost*0.6)))return;x.tier=tier;toast(tr('security_and_china.scrubbing_upgraded_to_tier',{tier:T.n}),'good');after();},
scrubMode:()=>{if(!hasScrub())return;S.scrubMode=S.scrubMode==='ondemand'?'always':'ondemand';sfx('click');after();},
rmScrub:({city})=>{if(!S.scrubs.some(x=>x.city===city))return;if(UI.confirm!=='scrub:'+city){UI.confirm='scrub:'+city;renderAll();return;}S.scrubs=S.scrubs.filter(x=>x.city!==city);if(!hasScrub())S.scrubMode='always';UI.confirm=null;after();},
cleanPipe:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.clean=!t.clean;toast(t.clean?tr('security_and_china.clean_pipe_add_on_enabled_on',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('security_and_china.clean_pipe_add_on_removed_from',{net:NET[t.net].name}),t.clean?'good':'');after();},
sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();},
ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(!ddosHasIx(a)){toast(tr('security_and_china.no_ix_in_city_to_announce',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('security_and_china.ix_blackhole_announced_in_city_about',{city:ddosCities(a).filter(hasIxAt).map(c=>CITY[c].name).join(', ')}):tr('security_and_china.ix_blackhole_withdrawn'),a.ixbh?'good':'');sfx('alert');after();},
rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('security_and_china.rtbh_announced_you_blackholed_the',{city:CITY[a.city].name}),'bad');sfx('alert');after();},
unrtbh:({id}={})=>{const a=ddosFind(id);if(!a)return;for(const x of ddosAll())if(x.city===a.city)x.bh=false;toast(tr('security_and_china.blackhole_withdrawn_city_is',{city:CITY[a.city].name}),'');after();},
hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('security_and_china.nothing_to_hack_back_right_now'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1;
if(Math.random()<0.35){a.until=S.day;a.bh=false;S.stats.hackWin=(S.stats.hackWin||0)+1;toast(tr('security_and_china.hackback_3000tm_strikes_back_skynot',{city:CITY[a.city].name}),'goal');sfx('coin');}
else{const fine=15000+Math.floor(Math.random()*35000);S.cash-=fine;S.stats.vigilante=(S.stats.vigilante||0)+1;
toast(tr('security_and_china.hackback_3000tm_hit_the_wrong_target',{who:pick([tr('security_and_china.skynot_ai_flattened_a_grandma_s'),tr('security_and_china.you_counter_flooded_a_hospital_in'),tr('security_and_china.the_botnet_was_already_someone_else')]),fine:fmt$(fine)}),'bad');sfx('err');}
after();},
cnPrem:({v})=>{UI.cnPrem=!!+v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
});

View file

@ -0,0 +1,15 @@
Object.assign(ACT,{
via:({v})=>{UI.via=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}},
route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);},
addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0)))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();},
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(RG[g].lvl>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');
else if(rt===1){const sl=slowBoot(city),dd=sl?3:1;p.down=Math.max(p.down||0,S.day+dd);addInc({type:'maint',ref:city,until:S.day+dd,msg:sl?tr('routing_and_routers.swapping_the_only_router_in_city',{city:CITY[city].name,model:RG[g].n,how:pick(SLOW_BOOT),n:dd}):tr('routing_and_routers.swapping_the_only_router_in_city_d5b5',{city:CITY[city].name,model:RG[g].n}),cost:0});toast(`<b>${tr('routing_and_routers.maintenance_window_in_city',{city:CITY[city].name})}</b><br>${sl?tr('routing_and_routers.one_router_and_this_one_takes',{n:dd}):tr('routing_and_routers.one_router_means_downtime_during_the')}`,'bad');}
else toast(tr('routing_and_routers.rolling_upgrade_in_city_n_model',{city:CITY[city].name,n:rt,model:esc(RG[g].n)}),'good');
floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');after();},
});

View file

@ -0,0 +1,37 @@
Object.assign(ACT,{
dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
seaPackage:({k})=>{if(!own(SUB_UPGRADES,k))return;UI['sea'+k]=!UI['sea'+k];if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+SUB_UPGRADES[k].days;after();},
seaDesign:({v})=>{if(!own(SEA_DESIGNS,v))return;UI.seaDesign=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
ownCab:()=>{UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
dfSys:({v})=>{UI.dfSys=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
orderCable:()=>{const p=UI.pending;if(!p)return;const {a,b}=p;if(ownCabWhy(a,b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering},q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return;
if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};
const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,ship=pick(OWNCAB_SHIPS),id=uid(),days=q.days;
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});
const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;
S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id};
toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();},
orderDf:()=>{const p=UI.pending;if(!p)return;const {a,b}=p;if(!dfAllowed(a,b))return;const sc=isSub(a,b)?subDfCable(a,b):null,km=sc?sc.km:kmBetween(a,b);
const own=UI.dfSrc==='build'&&lvl()>=3&&!sc,sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite';if(lvl()<2)return;
const up=(own?dfBuildCost(km):0)+DF_SYS[sys].cost+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return;
if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};
const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid();
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):30),spares:false};
S.links.push(l);closeModal();UI.sel={type:'link',id};
toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();},
regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.sub||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return;
if(d<0&&(l.ch||[]).some(o=>!optMode(o,{km:l.km,regen:n}))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;}
if(d>0&&!spend(REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH)))return;l.regen=n;toast(d>0?tr('fiber_and_hardware.regen_site_n_is_up_optical',{n,a:CITY[l.a].name,b:CITY[l.b].name,km:spanKm(l).toLocaleString()}):tr('fiber_and_hardware.regen_site_removed'),'good');sfx('build');after();},
addCh:({id,o})=>{const l=S.links.find(x=>x.id===id),O=OPT[o];if(!l||!O||l.kind!=='df')return;const why=chWhy(l,o);if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:O.n,why:esc(why)}),'bad');sfx('err');return;}if(!portGate(l.a,1)||!portGate(l.b,1))return;const sp=spareN(o)>0;if(!spend(chCost(l,o)))return;if(sp)S.spares[o]--;(l.ch=l.ch||[]).push(o);floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,`+${O.n}`,'#FF4F9A');after();},
rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o])return;const i=(l.ch||[]).lastIndexOf(o);if(i<0)return;l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();},
hwLock:()=>{if(hwLock())return;const c=hwLockCost();if(!spend(c))return;S.hw=S.hw||{};S.hw.lock={until:S.day+HW_LOCK_DAYS,mul:hwTrend(S.day)};toast(tr('fiber_and_hardware.prices_locked_until_date_your_vendor',{date:dateStr(S.hw.lock.until)}),'good');after();},
buySpare:({o})=>{if(!OPT[o]||OPT[o].lvl>lvl()||spareN(o)>=64)return;if(!spend(optCost(o)))return;S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;sfx('build');after();},
sellSpare:({o})=>{if(!OPT[o]||spareN(o)<1)return;S.spares[o]--;const v=spareValue(o);S.cash+=v;toast(tr('fiber_and_hardware.sold_a_spare_optic_on_ebuy',{optic:OPT[o].n,price:fmt$(v),p:pct(SPARE_RESALE)}),'good');sfx('coin');after();},
addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l)<chMax(l)){toast(tr('fiber_and_hardware.fill_this_pair_first_light_all',{max:chMax(l)}),'bad');sfx('err');return;}if(!spend(pairCost(l)))return;l.pairs=n+1;toast(tr('fiber_and_hardware.fiber_pair_n_is_lit_a',{n:n+1,a:CITY[l.a].name,b:CITY[l.b].name,m:DF_SYS[l.sys].max}),'good');sfx('build');after();},
upSys:({id})=>{const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||DF_SYS[to].lvl>lvl())return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();},
spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();},
crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();},
addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();},
});

View file

@ -0,0 +1,37 @@
Object.assign(ACT,{
randomName:()=>{const input=$('nmIn');if(input)input.value=UI.nm=randomNetworkName(input.value);},
start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24);beginGame(nm,UI.startCity,{mode:UI.mode==='sandbox'?'sandbox':'normal'});},
modeSet:({m})=>{UI.mode=m;document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('pink',b.dataset.m===m));document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('ghost',b.dataset.m!==m));},
scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();},
startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_name',{name:esc(sc.n)})}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_scenario'),'startScn',{id,sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});},
startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_the_weekly_challenge')}</h2><p class="tagline">${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}</p><div class="btns">${btn(tr('game_and_settings.start_the_challenge'),'startWeekly',{sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});},
pickStart:({city})=>{UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city));},
cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();},
newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;UI.nm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();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();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
menu:()=>{if(!S||!UI.started){showTitle();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>${isPhone()?installRow():''}
<div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}
${btn(tr('game_and_settings.export_save_download_a_file'),'exportSave',{},'')}
${btn(tr('game_and_settings.import_a_save_from_a_file'),'importPick',{},'')}
${btn(tr('game_and_settings.share_your_network_image_card'),'share',{},'')}
${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')}
${btn(tr('common.how_to_play'),'help',{},'ghost')}
${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}
${btn(tr('common.settings'),'settings',{},'ghost')}
${btn(tr('common.start_a_new_network'),'resetAsk',{},'red')}
</div>${chatHtml()}`);},
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},
settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();},
prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();},
vpSet:({v})=>{vpOn(v==='on');refreshSettings();},
resetAsk:()=>openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_a_new_network')}</h2><p class="tagline">${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}</p><div class="btns">${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`),
whatsNewShow:()=>whatsNew(true,true),
updateNow:()=>{save();location.reload();},
updateLater:()=>{$('update').hidden=true;UI.updLater=Date.now();},
helpClose:()=>{if(UI.started)closeModal();else showTitle();},
});

Some files were not shown because too many files have changed in this diff Show more