Docs and guard rails: GitHub Pages only, where code goes, updated skills

- docs/adr/0001: GitHub Pages is the only host, not open for renegotiation
- docs/adr/0002: source in many files, shipped as one page assembled at build
- tests/pages.test.js: builds stay static files Pages can serve, all local
  references resolve, only release.yml deploys and only via the Pages actions
- tests/build.test.js: partial naming and layout rules
- new skills: github-pages, edit-the-game; add-strings, performance, release
  and write-tests updated for src/, sorted dictionaries and --base-ref
- CLAUDE.md, ARCHITECTURE.md, CONTRIBUTING.md (incl. porting older branches),
  README.md and the PR template describe the new layout
This commit is contained in:
Frederic Jung 2026-10-27 10:15:12 +01:00
parent 052fdd713f
commit 05ff4ea7ad
No known key found for this signature in database
15 changed files with 530 additions and 101 deletions

View file

@ -7,7 +7,7 @@ description: Add or change player-facing text in Series of Tubes and keep every
The English text is the translation key. Every string a player can see must go 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/` through the translation helpers and have an entry in every dictionary in `site/i18n/`
(currently `it.js`, Italian). (Italian `it.js`, Portuguese `pt.js`, French `fr.js`). The code is in `src/`.
## In the code ## In the code
@ -23,21 +23,25 @@ through the translation helpers and have an entry in every dictionary in `site/i
## In the dictionary ## In the dictionary
`site/i18n/it.js` is one object, `"English": "Italiano",` per line, ending with `};`. `site/i18n/<lang>.js` is one object, `"English":"Translation",` per line, **sorted by the English
Append new entries before the closing `};`. A small script avoids quoting mistakes: text**. Sorted files mean two pull requests that add strings touch different lines instead of both
appending at the end. Don't edit the lines by hand; use the script, which quotes correctly, keeps the
order and works on every dictionary at once:
```python ```bash
import json cat > /tmp/strings.json <<'JSON'
it = {"New English text": "Nuovo testo italiano"} {
q = 'site/i18n/it.js'; t = open(q).read().rstrip() "it": { "New English text": "Nuovo testo italiano", "Text that was removed": null },
assert t.endswith('};') "pt": { "New English text": "Novo texto em português" },
t = t[:-2] + ''.join(json.dumps(k, ensure_ascii=False) + ':' + json.dumps(v, ensure_ascii=False) + ',\n' "fr": { "New English text": "Nouveau texte en français" }
for k, v in it.items() if json.dumps(k, ensure_ascii=False) + ':' not in t) + '};\n' }
open(q, 'w').write(t) JSON
node scripts/i18n-add.js /tmp/strings.json # a string adds or replaces, null removes
node scripts/i18n-add.js --rename "Old English" "New English" # English text changed: move the key everywhere
``` ```
When you **change** English text, rename the key in every dictionary too; when you If a dictionary got out of order anyway (a hand edit, a merge), `npm run i18n:fix` sorts it again;
remove text, delete its entry. `npm run i18n:check` fails until it is sorted.
## Italian style ## Italian style

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 # 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 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 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. 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 ## Measure
```bash ```bash
git show origin/main:site/index.html > /tmp/base.html npm run perf -- --base-ref origin/main # headless only, a few minutes
npm run perf -- --base /tmp/base.html # headless only, a few minutes npm run perf -- --base-ref origin/main --browser # plus real Chromium, desktop and phone (what CI runs)
npm run perf -- --base /tmp/base.html --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, `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 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: 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: save and a file from the in-game menu's Export save work:
```bash ```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 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 - **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 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. 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. rows that moved, in your summary. Say plainly when something got slower.
- **Before a release**: compare the release against the previous tag - **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 ## 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 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 `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 that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds
to GitHub Pages (https://seriesoftub.es). `_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 ## 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` - `package-lock.json` → top-level `"version"` and `packages[""].version`
4. `npm test` once more. 4. `npm test` once more.
Then compare performance with the previous release and mention anything notable to Frederic: 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: 5. Commit on `main` as Frederic, with no attribution trailers:
```bash ```bash
git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \ 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 # Writing tests
Tests use `node:test` and `tests/harness.js`, which loads `site/index.html` in jsdom Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/`
with the animation loop off, a seeded `Math.random` and a recording fake canvas. (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()`. Code runs inside the page through `ev()`.
## Pattern ## Pattern
@ -29,8 +29,11 @@ test('what the player should see happen', () => {
Pick the suite by topic: `game` (core loop), `build`, `persist` (save/import/migrate), Pick the suite by topic: `game` (core loop), `build`, `persist` (save/import/migrate),
`services` (customers), `peering`, `issues` (GitHub issue regressions, name them `services` (customers), `peering`, `issues` (GitHub issue regressions, name them
`#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`. A new file must be `#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`, `pages` (hosting).
added to the `test` script in `package.json`. 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 ## Rules
@ -40,7 +43,7 @@ added to the `test` script in `package.json`.
```js ```js
ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()"); 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()`. - **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`.
- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through - **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through
`parseSave()`/`migrate()`, and test that an *old* save without the new field still loads. `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

@ -1,30 +1,43 @@
# Series of Tubes: notes for Claude # Series of Tubes: notes for Claude
A free cartoon browser game about how the internet works, live at 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` https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with no framework.
(HTML, CSS and JS in one file, no framework, no build step for development). 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: Read these before larger changes:
- `docs/ARCHITECTURE.md`: how the code is laid out and how a day of simulation runs. - `docs/ARCHITECTURE.md`: where the code is, and how a day of simulation runs.
- `.claude/skills/`: step-by-step procedures (release, translations, tests). - `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 ## Commands
```bash ```bash
npm ci # once: installs jsdom for the tests npm ci # once: installs jsdom for the tests
npm test # node:test + jsdom, all suites, must stay green npm run dev # play while developing: http://localhost:8080, reloads on save
node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" npm test # node:test + jsdom, every tests/*.test.js, must stay green
npm run build # builds _site/ (stamps version, bakes release notes) node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries)
npm run serve # build and serve locally node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`)
npm run perf -- --base /tmp/base.html # big-network benchmark vs another version (see `performance`) npm run build # builds _site/ for GitHub Pages (assembles src/, stamps version, bakes release notes)
npm run perf -- --base /tmp/base.html --browser # the same, also in real Chromium (desktop and phone) 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 ## 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 - **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` `Frederic Jung <frederic@jc-ix.net>`. Never add `Co-Authored-By`, `Claude-Session`
or any other attribution trailers. or any other attribution trailers.
@ -42,25 +55,33 @@ To play during development, open `site/index.html` directly or run `npm run serv
- **Easter eggs stay secret.** Never mention hidden jokes or easter eggs (for example - **Easter eggs stay secret.** Never mention hidden jokes or easter eggs (for example
whatever `elephant()` does) in commit messages, release notes or the CHANGELOG. whatever `elephant()` does) in commit messages, release notes or the CHANGELOG.
- **Every player-facing string is translated.** Wrap it in `tr()`, `trn()` or `N_()` - **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`). and add 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 - **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 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. and bottom sheets. Check `isPhone()` layouts, not just desktop.
- **Saves are sacred.** Old saves must keep loading. Any new state field gets a default - **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. 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 - **Performance is always demonstrated.** Every change to `src/` or `site/` is measured on the big-network
fixture against `main` (`npm run perf -- --base /tmp/base.html`, see the `performance` skill), 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 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. CI. Anything slower needs a reason or a fix.
- **Tests come with features.** Add or extend a test in `tests/` for every feature or - **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, - **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 ## Style of the code
- Dense, single-file JavaScript. Match the surrounding style: short helper names, - Dense JavaScript in small topic files under `src/game/` (see `edit-the-game`): a new feature gets
arrow functions, template-literal HTML, no new dependencies. 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, - 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 re-render, save). Buttons are `btn(label, actName, args, cls, disabled)`, which
dispatch to `ACT[actName](args)` through `data-act`/`data-args`. dispatch to `ACT[actName](args)` through `data-act`/`data-args`.

View file

@ -18,19 +18,49 @@ Not sure yet whether something is a bug or an idea worth an issue? Ask in the
## Development ## Development
The game is one static page, `site/index.html`, with no framework and no build step The game is one static page with no framework, hosted on GitHub Pages. Its source is split into
while developing. 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 ```bash
npm ci # installs jsdom for the tests 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 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.
- Add translations with `node scripts/i18n-add.js` rather than by hand: it keeps the dictionaries
sorted, so your new strings don't land on the same lines as everyone else's.
- 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.33 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, merges
each piece into `src/`, and applies your dictionary changes entry by entry. It only reports conflicts
where your change and `main` touched the same lines.
## Pull requests ## Pull requests
@ -42,11 +72,14 @@ A tour of the code is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
must not depend on luck. must not depend on luck.
- Add a bullet for players under `## [Unreleased]` in `CHANGELOG.md`, in plain English. - Add a bullet for players under `## [Unreleased]` in `CHANGELOG.md`, in plain English.
Releases are cut by the maintainer. 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: 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). (add `--browser` to also time it in Chromium as a desktop and a phone, like CI does).
Anything marked slower needs an explanation. 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 - Old saves must keep loading. New state needs a default for new games and a check in
`sanitize()`. `sanitize()`.
- Check your change on a phone-sized screen (about 360 px wide). Most players are on - Check your change on a phone-sized screen (about 360 px wide). Most players are on
@ -64,8 +97,8 @@ A tour of the code is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
## Translations ## Translations
Every player-facing string goes through `tr()`, `trn()` or `N_()`. Dictionaries live 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 in `site/i18n/` (English text → translation, one entry per line, sorted). To add a language, copy
the values, register the language in the language list in `site/index.html`, and run `it.js`, translate the values, 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`. `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 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 ## 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 ```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. Progress is saved in your browser's local storage.
@ -51,32 +52,39 @@ and remembers the one you pick under Settings or on the title screen.
```sh ```sh
npm ci 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 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 npm run i18n:check # lists text missing from (or stale in) the translations
``` ```
``` ```
site/ everything that is deployed src/ the game page, in pieces (joined into one index.html at build)
index.html the whole game (HTML, CSS and JS in one file) index.html the shell: <head>, static markup, @include lines
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, loaded only when the game runs in Italian i18n/it.js Italian translation, loaded only when the game runs in Italian
i18n/pt.js Portuguese (Brazil) translation, loaded only when the game runs in Portuguese 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 i18n/fr.js French translation, loaded only when the game runs in French
images/og-image.png social preview (1200×630) images/og-image.png social preview (1200×630)
favicon.*, icon-* favicons, app icons, manifest favicon.*, icon-* favicons, app icons, manifest
sw.js service worker (offline play)
robots.txt, sitemap.xml, llms.txt, 404.html, CNAME 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 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 ## Translations
English is the source text. Player-facing strings in `index.html` go through English is the source text. Player-facing strings in `src/` go through
`tr('Unlocks at level {n}.', {n})` (or `trn(one, other, n)` for plurals); static markup `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 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 `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 `SOT_LANGS` (the language loader in `src/index.html`). Missing entries fall back to
English, so new English text never breaks the game; `npm run i18n:check` lists what 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}` needs translating, and the tests make sure every translation keeps its `{placeholders}`
and HTML tags. and HTML tags.

View file

@ -1,50 +1,75 @@
# Architecture # Architecture
Everything that runs in the browser lives in `site/index.html`. It is large (several Series of Tubes is a static web game hosted on **GitHub Pages, and only there**
thousand lines), so find things by the section banners rather than by line number: ([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 src/ the game page, in pieces
/* ================= LANGUAGE ================= */ tr(), trn(), N_(), dictionary loading index.html shell: <head>, static markup, the language loader, two @include lines
/* ================= ANALYTICS ================= */ privacy-friendly event counter styles/NN-*.css → pasted into the page's <style>, in path order
/* ================= CONSTANTS ================= */ prices, ports (PORT), routers (RG), optics game/NN-area/NN-*.js → pasted into the page's <script>, in path order
/* ================= WORLD ================= */ CITIES, CABLES, display nudges site/ static files copied to the build as they are (dictionaries, icons, sw.js…)
/* ================= NETWORKS ================= */ NETS (other ASes), traffic shares (NSH) scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted
/* ================= BUSINESSES ================= */ BIZ_T customer types, LEVELS + LV_REQ (13 levels, traffic eras) scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
/* ================= 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()
``` ```
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 | | Path | What it is |
| --- | --- | | --- | --- |
| `site/i18n/it.js` | Italian dictionary: English text → Italian, loaded when the language is `it` | | `site/i18n/it.js`, `pt.js`, `fr.js` | Dictionaries: English text → translation, one entry per line, sorted; loaded only for that language |
| `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` |
| `site/sw.js` | Service worker: network-first for pages, stale-while-revalidate for assets. Cache name is stamped with the version | | `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 | | `site/site.webmanifest`, icons, `404.html`, `CNAME`, `robots.txt`, `sitemap.xml`, `llms.txt` | PWA and GitHub Pages files, copied as they are |
| `scripts/build.sh` | Copies `site/` to `_site/`, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` | | `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) |
| `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/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/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` | Compares every `tr`/`trn`/`N_` literal and `data-i18n` text with each dictionary | | `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
| `tests/harness.js` | Loads the page in jsdom with a seeded `Math.random` and a fake canvas | | `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html`, 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/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/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) |
## Globals ## Globals
@ -133,7 +158,8 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood.
## Tests ## 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 ```js
const { load } = require('./harness'); 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.33 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

@ -40,3 +40,16 @@ test('a release build refuses to ship without release notes', () => {
assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } })); assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } }));
assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected'); assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected');
}); });
test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at-build.md)', () => {
const { listFiles, assemble } = require('../scripts/lib/page');
const src = path.join(root, 'src');
for (const f of listFiles(src)) {
if (f === 'index.html') continue;
assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|game\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/ or game/`);
}
const { html, map } = assemble();
assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})');
assert.equal((html.match(/<script>/g) || []).length, 2, 'the language loader and the game: one inline game script');
assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial');
});

72
tests/pages.test.js Normal file
View file

@ -0,0 +1,72 @@
// The game is hosted on GitHub Pages and only there (docs/adr/0001-github-pages-only.md). These tests make
// sure every build stays something Pages serves as it is: plain static files, all from one origin.
const test = require('node:test');
const assert = require('node:assert/strict');
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 OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-pages-'));
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.2.3', BUILD_DATE: '2026-10-27' } });
const files = (dir, rel = '') => fs.readdirSync(path.join(dir, rel), { withFileTypes: true }).flatMap((e) => {
const r = path.posix.join(rel, e.name);
return e.isDirectory() ? files(dir, r) : [{ r, e }];
});
const built = files(OUT);
const read = (f) => fs.readFileSync(path.join(OUT, f), 'utf8');
// Files that only mean something to other hosts or to a server. On Pages they would be served as plain
// files (or ignored), so their presence means someone is designing for a different host.
const FOREIGN = /(^|\/)(_redirects|_headers|\.htaccess|netlify\.toml|vercel\.json|wrangler\.toml|firebase\.json|staticwebapp\.config\.json|now\.json|app\.yaml|Procfile|Dockerfile|nginx\.conf|server\.js|package\.json)$|\.(php|py|rb|cgi)$/;
test('pages: the build is plain static files within GitHub Pages limits', () => {
let total = 0;
for (const { r, e } of built) {
assert.ok(e.isFile(), `${r} is a regular file (no symlinks)`);
assert.doesNotMatch(r, FOREIGN, `${r} is server or other-host configuration`);
const size = fs.statSync(path.join(OUT, r)).size;
assert.ok(size < 100e6, `${r} is under the 100 MB file limit`);
total += size;
}
assert.ok(total < 1e9, 'the site is under the 1 GB limit');
for (const f of ['index.html', '404.html', 'CNAME', 'version.json', 'sw.js']) assert.ok(fs.existsSync(path.join(OUT, f)), `${f} is shipped`);
assert.equal(read('CNAME').trim(), 'seriesoftub.es');
});
test('pages: the repository has no hosting configuration for anywhere else', () => {
for (const f of fs.readdirSync(root)) assert.doesNotMatch(f, /^(netlify\.toml|vercel\.json|wrangler\.toml|firebase\.json|staticwebapp\.config\.json|now\.json|app\.yaml|Procfile|Dockerfile|_redirects|_headers)$/, `${f} configures another host`);
});
test('pages: every local file the site refers to is in the build', () => {
const html = read('index.html');
const refs = new Set();
for (const m of html.matchAll(/\b(?:src|href)="([^"]+)"/g)) refs.add(m[1]);
for (const m of read('sw.js').matchAll(/'(\/[^']*)'/g)) refs.add(m[1]);
for (const i of JSON.parse(read('site.webmanifest')).icons || []) refs.add(i.src);
const local = [...refs].filter((u) => !/^(https?:|data:|mailto:|#|\$\{|javascript:)/.test(u) && !u.includes('${') && !u.includes("'+"));
assert.ok(local.length >= 5, 'found the local references');
for (const u of local) {
const p = u.split(/[?#]/)[0].replace(/^\//, '') || 'index.html';
assert.ok(fs.existsSync(path.join(OUT, p)), `${u} resolves inside the build`);
}
// Same origin for code: the only scripts from elsewhere are the analytics counter, and no stylesheets
// but the web fonts (see the ADR).
for (const m of html.matchAll(/<script[^>]*\bsrc="(https?:[^"]+)"/g)) assert.fail(`page loads a script from ${m[1]}`);
for (const m of html.matchAll(/<link[^>]*rel="stylesheet"[^>]*href="(https?:[^"]+)"/g)) assert.match(m[1], /^https:\/\/fonts\.googleapis\.com\//);
});
test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => {
const dir = path.join(root, '.github', 'workflows');
for (const f of fs.readdirSync(dir)) {
const y = fs.readFileSync(path.join(dir, f), 'utf8');
assert.doesNotMatch(y, /netlify|vercel|wrangler|cloudflare\/pages-action|firebase deploy|surge\.sh|peaceiris\/actions-gh-pages|aws s3 sync|rsync /i, `${f} deploys somewhere other than GitHub Pages`);
if (f !== 'release.yml') assert.doesNotMatch(y, /pages:\s*write|deploy-pages/, `${f} must not deploy`);
}
const rel = fs.readFileSync(path.join(dir, 'release.yml'), 'utf8');
assert.match(rel, /actions\/upload-pages-artifact@/);
assert.match(rel, /actions\/deploy-pages@/);
assert.match(rel, /path: \.\/_site/);
});