Ship short ids instead of labels; checker, tests and docs for labels

The build swaps every label for a short id in the shipped page, the inlined
English and the translation files (scripts/lib/compile-labels.js). Labels
passed to N_() stay whole because saves keep them. Against 1.33: page +4%
gzipped (321 -> 335 KB), translations -40% (it.js 143 -> 85 KB); routing,
day, panels, dashboard, map and boot time unchanged.

- i18n-check rejects labels the build cannot see (outside tr/trn/N_)
- tests/pages.test.js plays the shipped page in English, Italian and French
- docs/adr/0003, add-strings skill, ARCHITECTURE, README, CONTRIBUTING,
  CLAUDE.md describe labels
This commit is contained in:
Frederic Jung 2026-10-27 11:27:11 +01:00
parent 9043af5ab0
commit 0057e74472
No known key found for this signature in database
14 changed files with 253 additions and 63 deletions

View file

@ -1,47 +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/`
(Italian `it.js`, Portuguese `pt.js`, French `fr.js`). The code is in `src/`.
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/<lang>.js` is one object, `"English":"Translation",` per line, **sorted by the English
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:
`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`).
## 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'
{
"it": { "New English text": "Nuovo testo italiano", "Text that was removed": null },
"pt": { "New English text": "Novo texto em português" },
"fr": { "New English text": "Nouveau texte en français" }
"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 adds or replaces, null removes
node scripts/i18n-add.js --rename "Old English" "New English" # English text changed: move the key everywhere
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/
```
If a dictionary got out of order anyway (a hand edit, a merge), `npm run i18n:fix` sorts it again;
`npm run i18n:check` fails until it is sorted.
- **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
@ -52,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

@ -37,6 +37,9 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j
## 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:

View file

@ -54,9 +54,10 @@ npm run perf -- --base-ref origin/main --browser # the same, also in real Chro
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 every translation (`site/i18n/*.js`) in the same change with `scripts/i18n-add.js`
(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.

View file

@ -41,8 +41,10 @@ Many people work on the game at once. A few habits keep your pull request from c
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.
- 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`?
@ -58,8 +60,9 @@ 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
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
@ -97,8 +100,9 @@ where your change and `main` touched the same lines.
## Translations
Every player-facing string goes through `tr()`, `trn()` or `N_()`. Dictionaries live
in `site/i18n/` (English text → translation, one entry per line, sorted). To add a language, copy
`it.js`, translate the values, register the language in the language list in `src/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

@ -61,10 +61,11 @@ npm run i18n:check # lists text missing from (or stale in) the translations
```
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, loaded only when the game runs in Italian
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)
@ -80,14 +81,13 @@ docs/ architecture and decisions (docs/adr/)
## Translations
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
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 in `src/index.html`). 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

View file

@ -7,7 +7,8 @@ the build joins them into **one self-contained `index.html`** (one inline `<styl
```
src/ the game page, in pieces
index.html shell: <head>, static markup, the language loader, two @include lines
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…)
@ -54,22 +55,24 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
| Path | What it is |
| --- | --- |
| `site/i18n/it.js`, `pt.js`, `fr.js` | Dictionaries: English text → translation, one entry per line, sorted; loaded only for that language |
| `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, `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`, `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 `port-branch.js`, which carries older branches over |
| `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, the only workflow that can |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002) |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) |
## Globals
@ -150,11 +153,17 @@ 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

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.33 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 1.33 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.33 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.

View file

@ -9,7 +9,7 @@
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { assemble, ROOT } = require('./lib/page');
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);
@ -23,7 +23,11 @@ if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, '
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/');
fs.writeFileSync(path.join(OUT, 'index.html'), assemble().html);
// 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);

View file

@ -29,6 +29,14 @@ function sourceLabels(html) {
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;
const markup = [];

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 };

View file

@ -3,8 +3,9 @@
// 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] assemble this checkout (stdout by default)
// node scripts/lib/page.js --ref origin/main -o FILE assemble the page as it is at a git ref
// 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.
@ -85,18 +86,25 @@ function assembleRef(ref, cwd = ROOT) {
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
}
// The assembled page written to a file, for tools that need a path (perf in a real browser, base vs head).
// 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, assemble().html);
fs.writeFileSync(file, shipped().html);
return file;
}
module.exports = { assemble, assembleRef, pageFile, locate, listFiles, ROOT };
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')) : assemble().html;
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

@ -30,7 +30,8 @@ function load(opts = {}) {
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(__dirname, '..', 'site', 'i18n', opts.lang + '.js'), 'utf8')); }
// (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.)
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 };

View file

@ -152,3 +152,11 @@ for (const lang of ['en', 'it', 'pt', 'fr']) {
assert.deepEqual(errors, []);
});
}
test('the translation check catches labels the build could not see, and English-keyed calls', () => {
const { sourceLabels } = require('../scripts/i18n-check');
const { problems, labels } = sourceLabels("<html><body><script>const x='pnis.foo_bar';tr('pnis.ok_label');N_('pnis.kept');trn('{n} POP','{n} POPs',n)</script></body></html>");
assert.ok(labels.has('pnis.ok_label') && labels.has('pnis.kept'));
assert.ok(problems.some((p) => p.includes('pnis.foo_bar') && p.includes('N_()')), 'a bare label');
assert.ok(problems.some((p) => p.includes('not a label')), 'English text where a label belongs');
});

View file

@ -70,3 +70,19 @@ test('pages: only the release workflow deploys, and only with the GitHub Pages a
assert.match(rel, /actions\/deploy-pages@/);
assert.match(rel, /path: \.\/_site/);
});
test('pages: the shipped page and dictionaries, with labels shrunk to ids, still say the right things', () => {
const { load } = require('./harness');
const file = path.join(OUT, 'index.html'), dir = path.join(OUT, 'i18n');
assert.doesNotMatch(read('index.html'), /tr\('pnis\.delivery/, 'labels are shrunk in the shipped page');
for (const [lang, word] of [['en', 'Customers'], ['it', 'Clienti'], ['fr', null]]) {
const { ev, errors } = load(lang === 'en' ? { file } : { file, lang, dir });
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});for(let i=0;i<40;i++)dayTick();ACT.leftTab({t:'noc'});renderAll()");
const text = ev("['hud','leftBody','panelBody','modalCard','toasts'].map(i=>document.getElementById(i)?.textContent||'').join(' ')");
if (word) assert.ok(text.includes(word), `${lang}: ${word}`);
assert.doesNotMatch(text, /\b[a-z_]+\.[a-z0-9_]{6,}\b/, `${lang}: no raw labels`);
assert.equal(ev("tr(FLOOD_WHO[0])"), ev("tr('failures.a_botnet_of_40_000_smart')"), `${lang}: labels kept for saves still translate`);
assert.notEqual(ev("tr(FLOOD_WHO[0])"), 'failures.a_botnet_of_40_000_smart');
assert.deepEqual(errors, []);
}
});