Split the game page into partials under src/, assembled into one index.html at build
site/index.html (900 KB of HTML, CSS and JS in one file) becomes src/: a shell (src/index.html), styles/ and game/, concatenated in path order by scripts/lib/page.js. The assembled page is byte-identical to the old file, so load time and in-game performance are unchanged. - scripts/build.js replaces build.sh (same env vars, same output) - npm run dev: a zero-dependency dev server that assembles on every request - tests assemble the page in memory; npm test runs every tests/*.test.js - perf-bench takes --base-ref to build a git ref's page - scripts/legacy/split-index-html.js is the splitter, kept for older branches
This commit is contained in:
parent
295e68cc46
commit
67a40942b4
113 changed files with 5584 additions and 5195 deletions
52
scripts/build.js
Normal file
52
scripts/build.js
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
#!/usr/bin/env node
|
||||
// Builds the deployable site into _site/ (or $OUT) for GitHub Pages: copies the static files in site/,
|
||||
// assembles the game page from src/ into one index.html, and stamps the version (from package.json) and
|
||||
// the build date into the files that carry them. The output is plain static files and nothing else,
|
||||
// because GitHub Pages is where the game lives (docs/adr/0001-github-pages-only.md).
|
||||
//
|
||||
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment
|
||||
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
|
||||
const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version;
|
||||
const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10);
|
||||
const OUT = path.resolve(ROOT, process.env.OUT || '_site');
|
||||
const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
|
||||
|
||||
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
|
||||
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
|
||||
|
||||
fs.rmSync(OUT, { recursive: true, force: true });
|
||||
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
|
||||
if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/');
|
||||
fs.writeFileSync(path.join(OUT, 'index.html'), assemble().html);
|
||||
|
||||
for (const f of ['index.html', 'sitemap.xml', 'llms.txt', 'sw.js']) {
|
||||
const p = path.join(OUT, f);
|
||||
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replaceAll('__VERSION__', VERSION).replaceAll('__BUILD_DATE__', BUILD_DATE));
|
||||
}
|
||||
|
||||
// Release notes for this version, baked into the page ("What's new") and published as version.json so
|
||||
// open games can spot a newer release.
|
||||
const notes = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION], { encoding: 'utf8' });
|
||||
if (process.env.REQUIRE_NOTES === '1' && notes === '[]') die(`CHANGELOG.md has no '## [${VERSION}]' section with bullets (still under [Unreleased]?)`);
|
||||
const page = path.join(OUT, 'index.html'), PH = '/*__RELEASE_NOTES__*/[]', html = fs.readFileSync(page, 'utf8');
|
||||
if (!html.includes(PH)) die('release-notes placeholder missing from the page');
|
||||
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
|
||||
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')));
|
||||
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes) }, null, 2) + '\n');
|
||||
|
||||
// Nothing may ship half-stamped.
|
||||
const left = [];
|
||||
const scan = (dir) => { for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) scan(p);
|
||||
else if (/__VERSION__|__BUILD_DATE__/.test(fs.readFileSync(p, 'latin1'))) left.push(path.relative(OUT, p));
|
||||
} };
|
||||
scan(OUT);
|
||||
if (left.length) die(`unreplaced placeholders left in ${left.join(', ')}`);
|
||||
console.log(`Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${path.relative(ROOT, OUT) || OUT}/`);
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Builds the deployable site into _site/ (or $OUT): copies site/ and stamps the
|
||||
# version (from package.json) and the build date into the pages that carry them.
|
||||
# Set REQUIRE_NOTES=1 to fail when CHANGELOG.md has no bullets for this version.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
VERSION="${VERSION:-$(node -p "require('./package.json').version")}"
|
||||
BUILD_DATE="${BUILD_DATE:-$(date -u +%Y-%m-%d)}"
|
||||
OUT="${OUT:-_site}"
|
||||
|
||||
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "error: VERSION '$VERSION' is not a semantic version" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -rf "$OUT"
|
||||
cp -R site "$OUT"
|
||||
for f in "$OUT/index.html" "$OUT/sitemap.xml" "$OUT/llms.txt" "$OUT/sw.js"; do
|
||||
sed -i.bak -e "s/__VERSION__/${VERSION}/g" -e "s/__BUILD_DATE__/${BUILD_DATE}/g" "$f"
|
||||
rm -f "$f.bak"
|
||||
done
|
||||
|
||||
# Release notes for this version, baked into the page ("What's new") and
|
||||
# published as version.json so open games can spot a newer release.
|
||||
NOTES="$(node scripts/release-notes.js "$VERSION")"
|
||||
if [ "${REQUIRE_NOTES:-}" = "1" ] && [ "$NOTES" = "[]" ]; then
|
||||
echo "error: CHANGELOG.md has no '## [$VERSION]' section with bullets (still under [Unreleased]?)" >&2
|
||||
exit 1
|
||||
fi
|
||||
node -e '
|
||||
const fs=require("fs"),[,out,v,d,notes]=process.argv;
|
||||
const f=out+"/index.html",ph="/*__RELEASE_NOTES__*/[]",html=fs.readFileSync(f,"utf8");
|
||||
if(!html.includes(ph)){console.error("error: release-notes placeholder missing from index.html");process.exit(1);}
|
||||
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
|
||||
fs.writeFileSync(f,html.replace(ph,()=>notes.replace(/</g,"\\u003c")));
|
||||
fs.writeFileSync(out+"/version.json",JSON.stringify({version:v,date:d,notes:JSON.parse(notes)},null,2)+"\n");
|
||||
' "$OUT" "$VERSION" "$BUILD_DATE" "$NOTES"
|
||||
|
||||
if grep -rl "__VERSION__\|__BUILD_DATE__" "$OUT" >/dev/null; then
|
||||
echo "error: unreplaced placeholders left in $OUT" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${OUT}/"
|
||||
59
scripts/dev.js
Normal file
59
scripts/dev.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
#!/usr/bin/env node
|
||||
// Development server: http://localhost:8080 (PORT=… to change). The page is assembled from src/ on every
|
||||
// request, static files come straight from site/, and the browser reloads itself when you save a file.
|
||||
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has.
|
||||
// No dependencies: plain node:http. For the production build as GitHub Pages will serve it: npm run serve.
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
|
||||
const PORT = +process.env.PORT || 8080;
|
||||
const SITE = path.join(ROOT, 'site');
|
||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
|
||||
'.webmanifest': 'application/manifest+json' };
|
||||
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
|
||||
const clients = new Set();
|
||||
|
||||
function page() {
|
||||
const { html, map } = assemble();
|
||||
// Errors report a line of the assembled page; the console also says which file under src/ that is.
|
||||
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${JSON.stringify(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
|
||||
return html.replace('</body>', `${hint}${RELOAD}</body>`);
|
||||
}
|
||||
|
||||
http.createServer((req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
if (url.pathname === '/__dev') {
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
||||
res.write(': hi\n\n');
|
||||
clients.add(res);
|
||||
req.on('close', () => clients.delete(res));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (url.pathname === '/' || url.pathname === '/index.html') {
|
||||
res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' });
|
||||
return res.end(page());
|
||||
}
|
||||
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
|
||||
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
|
||||
res.writeHead(404, { 'content-type': TYPES['.html'] });
|
||||
return res.end(fs.readFileSync(path.join(SITE, '404.html')));
|
||||
}
|
||||
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
|
||||
fs.createReadStream(file).pipe(res);
|
||||
} catch (e) {
|
||||
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
res.end(String(e && e.stack || e));
|
||||
}
|
||||
}).listen(PORT, () => console.log(`Series of Tubes (dev): http://localhost:${PORT}/ — edits in src/ and site/ reload the page`));
|
||||
|
||||
let timer = null;
|
||||
for (const dir of ['src', 'site']) {
|
||||
fs.watch(path.join(ROOT, dir), { recursive: true }, () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => { for (const c of clients) c.write('data: reload\n\n'); }, 100);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
#!/usr/bin/env node
|
||||
// Checks a translation against the English text in site/index.html: every tr()/trn()/N_() literal and
|
||||
// Checks a translation against the English text in the game page (assembled from src/): every tr()/trn()/N_() literal and
|
||||
// every data-i18n text, aria-label and title in the static markup should have an entry, no stale entry
|
||||
// should linger, and each translation must keep the {placeholders} and HTML tags of its English key.
|
||||
// Usage: node scripts/i18n-check.js [lang ...] [--summary FILE] (default: every site/i18n/*.js)
|
||||
|
|
@ -10,6 +10,7 @@ const path = require('node:path');
|
|||
const vm = require('node:vm');
|
||||
|
||||
const SITE = path.join(__dirname, '..', 'site');
|
||||
const page = () => require('./lib/page').assemble().html;
|
||||
const LIT = String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`;
|
||||
const CALL = new RegExp(String.raw`(?<![\w$.])(tr|trn|N_)\(\s*(${LIT})(?:\s*,\s*(${LIT}))?`, 'g');
|
||||
const CTX = vm.createContext({});
|
||||
|
|
@ -58,11 +59,11 @@ module.exports = { loadDict, brokenEntries };
|
|||
|
||||
// A language file only works if the game offers it and the offline cache keeps it.
|
||||
function registration(lang) {
|
||||
const html = fs.readFileSync(path.join(SITE, 'index.html'), 'utf8');
|
||||
const html = page();
|
||||
const sw = fs.readFileSync(path.join(SITE, 'sw.js'), 'utf8');
|
||||
const out = [];
|
||||
const m = html.match(/SOT_LANGS=\{([^}]*)\}/);
|
||||
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in site/index.html)');
|
||||
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)');
|
||||
if (!sw.includes(`/i18n/${lang}.js`)) out.push('not cached for offline play (CORE in site/sw.js)');
|
||||
return out;
|
||||
}
|
||||
|
|
@ -71,7 +72,7 @@ if (require.main === module) {
|
|||
const args = process.argv.slice(2);
|
||||
const si = args.indexOf('--summary');
|
||||
const summary = si >= 0 ? args.splice(si, 2)[1] : null; // append a Markdown table here (CI: $GITHUB_STEP_SUMMARY)
|
||||
const keys = sourceKeys(fs.readFileSync(path.join(SITE, 'index.html'), 'utf8'));
|
||||
const keys = sourceKeys(page());
|
||||
const files = (args.length ? args.map((l) => `${l}.js`) : fs.readdirSync(path.join(SITE, 'i18n')))
|
||||
.map((f) => path.join(SITE, 'i18n', f));
|
||||
let bad = false;
|
||||
|
|
|
|||
184
scripts/legacy/split-index-html.js
Normal file
184
scripts/legacy/split-index-html.js
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
#!/usr/bin/env node
|
||||
// Splits a pre-split site/index.html (one file: HTML, CSS and JS) into the src/ layout.
|
||||
//
|
||||
// This is how src/ was made, and it stays around for work that was started before the split: a branch
|
||||
// or pull request that still edits site/index.html. scripts/legacy/port-branch.js uses it to carry those
|
||||
// edits over to src/ (see CONTRIBUTING.md, "Your branch still edits site/index.html?").
|
||||
//
|
||||
// node scripts/legacy/split-index-html.js INDEX_HTML OUT_DIR writes OUT_DIR/index.html and partials
|
||||
//
|
||||
// The cut points are found by content, not line numbers, so the same rules split any version from around
|
||||
// the split (1.33.x). Comments directly above a cut point travel with the code below them.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
// [partial, first line of it]. Each regex must match a line that comes after the previous cut.
|
||||
const CSS = [
|
||||
['styles/00-base.css', /^\/\* Layout: full-bleed/],
|
||||
['styles/10-hud.css', /^\/\* HUD \*\/$/],
|
||||
['styles/20-drawers.css', /^\/\* drawers \*\/$/],
|
||||
['styles/30-toasts.css', /^\/\* toasts \*\/$/],
|
||||
['styles/40-modal.css', /^\/\* modal \*\/$/],
|
||||
['styles/50-tablet.css', /^\/\* Tablets in landscape/],
|
||||
['styles/60-phone.css', /^\/\* =+ PHONES/],
|
||||
];
|
||||
|
||||
const JS = [
|
||||
['game/00-core/10-language.js', /^\/\* =+ LANGUAGE/],
|
||||
['game/00-core/20-analytics.js', /^\/\* =+ ANALYTICS/],
|
||||
['game/10-catalog/10-economy.js', /^\/\* =+ CONSTANTS/],
|
||||
['game/10-catalog/20-routers.js', /^const RG=\[/],
|
||||
['game/10-catalog/30-supply-chain.js', /^\/\* -+ Supply chain/],
|
||||
['game/10-catalog/40-ports.js', /^\/\* Ports are finite/],
|
||||
['game/10-catalog/50-dark-fiber.js', /^\/\/ dark fiber & optical gear/],
|
||||
['game/10-catalog/60-reach-and-subsea.js', /^\/\* Reach \(#17/],
|
||||
['game/20-world/10-projection.js', /^\/\* =+ WORLD/],
|
||||
['game/20-world/20-landmasses.js', /^const LANDS_LL=/],
|
||||
['game/20-world/30-coastline.js', /^\/\/ Drawn coastline/],
|
||||
['game/20-world/40-city-coords.js', /^const CITY_LL=/],
|
||||
['game/20-world/50-cities.js', /^const CITIES=\[/],
|
||||
['game/20-world/60-cables.js', /^const CABLES=\[/],
|
||||
['game/30-networks/10-networks.js', /^\/\* =+ NETWORKS/],
|
||||
['game/30-networks/20-rival-exchanges.js', /^\/\* Rival exchanges/],
|
||||
['game/30-networks/30-long-tail.js', /^\/\* The long tail/],
|
||||
['game/30-networks/40-traffic-shares.js', /^const NET=Object\.fromEntries/],
|
||||
['game/40-progress/10-businesses.js', /^\/\* =+ BUSINESSES/],
|
||||
['game/40-progress/20-goals.js', /^\/\* =+ GOALS/],
|
||||
['game/50-state.js', /^\/\* =+ STATE/],
|
||||
['game/60-features/10-banks.js', /^\/\* =+ BANKS & LOANS/],
|
||||
['game/60-features/20-scenarios.js', /^\/\* Seeded games/],
|
||||
['game/60-features/30-conferences.js', /^\/\* -+ conference season/],
|
||||
['game/60-features/40-tutorial.js', /^\/\* -+ guided first game/],
|
||||
['game/60-features/50-traceroute.js', /^\/\* -+ traceroute and looking glass/],
|
||||
['game/60-features/60-share-card.js', /^\/\* -+ share card/],
|
||||
['game/60-features/70-scenario-progress.js', /^function scnTick\(/],
|
||||
['game/60-features/80-new-game.js', /^function newGame\(/],
|
||||
['game/70-rules/10-helpers.js', /^\/\* =+ HELPERS/],
|
||||
['game/70-rules/20-exchanges.js', /^\/\* Australian exchanges follow/],
|
||||
['game/70-rules/30-pnis.js', /^\/\* -+ PNIs with the big networks/],
|
||||
['game/70-rules/40-peering-inbox.js', /^\/\* -+ The peering inbox/],
|
||||
['game/70-rules/50-peering-policy.js', /^\/\* Big networks sometimes refuse/],
|
||||
['game/70-rules/60-de-kicks.js', /^\/\* DE-KICKS Group/],
|
||||
['game/70-rules/70-sold-out.js', /^\/\* Sold out:/],
|
||||
['game/70-rules/80-hot-ports-and-rank.js', /^const HOT=/],
|
||||
['game/80-simulation/10-dijkstra.js', /^\/\* =+ SIMULATION/],
|
||||
['game/80-simulation/20-routescript.js', /^\/\* -+ RouteScript/],
|
||||
['game/80-simulation/30-compute.js', /^const LABS=new Map/],
|
||||
['game/80-simulation/40-billing.js', /^function p95\(/],
|
||||
['game/80-simulation/50-sanitize.js', /^const own=/],
|
||||
['game/80-simulation/60-requirements.js', /^const GRACE_DAYS=/],
|
||||
['game/80-simulation/70-customers-and-events.js', /^function bizSf\(/],
|
||||
['game/80-simulation/80-geography-and-latency.js', /^function cnOk\(/],
|
||||
['game/80-simulation/90-sites-and-service.js', /^const RT=\{/],
|
||||
['game/85-incidents/10-incidents-and-ddos.js', /^\/\* -+ failures & events/],
|
||||
['game/85-incidents/20-failures.js', /^function fireFailure\(/],
|
||||
['game/85-incidents/30-events.js', /^function fireEvent\(/],
|
||||
['game/88-days/10-day-tick.js', /^\/\* -+ daily tick/],
|
||||
['game/88-days/20-badges.js', /^const RARITY=/],
|
||||
['game/90-actions/00-actions.js', /^\/\* =+ ACTIONS/],
|
||||
['game/90-actions/90-action-helpers.js', /^function landTrenches\(/],
|
||||
['game/91-save.js', /^\/\* =+ SAVE/],
|
||||
['game/92-audio.js', /^\/\* =+ AUDIO/],
|
||||
['game/93-ui/10-dom.js', /^\/\* =+ DOM RENDER/],
|
||||
['game/93-ui/20-phone.js', /^\/\* =+ PHONE =/],
|
||||
['game/93-ui/30-install.js', /^\/\* =+ INSTALL/],
|
||||
['game/93-ui/40-hud-and-panels.js', /^function fitHud\(/],
|
||||
['game/93-ui/50-city-panel.js', /^function cityPanel\(/],
|
||||
['game/93-ui/60-decommission.js', /^\/\* Decommissioning POPs/],
|
||||
['game/93-ui/70-link-panels.js', /^const portMo=/],
|
||||
['game/94-dashboard/10-progress.js', /^\/\* -+ scenario and level progress/],
|
||||
['game/94-dashboard/20-meet-a-network.js', /^\/\* -+ where to meet a network/],
|
||||
['game/94-dashboard/30-customers.js', /^\/\* -+ customers overview/],
|
||||
['game/94-dashboard/40-connections.js', /^\/\* -+ connections overview/],
|
||||
['game/94-dashboard/50-lease-swaps.js', /^\/\* Leased lines you could swap/],
|
||||
['game/94-dashboard/60-dashboard.js', /^function dashTabs\(/],
|
||||
['game/94-dashboard/70-bank.js', /^function loanSummary\(/],
|
||||
['game/94-dashboard/80-hint.js', /^function renderHint\(/],
|
||||
['game/95-modals/10-toasts.js', /^\/\* -+ toasts & modals/],
|
||||
['game/95-modals/20-notifications.js', /^\/\* -+ notifications:/],
|
||||
['game/95-modals/30-modal-and-names.js', /^function openModal\(/],
|
||||
['game/95-modals/40-title.js', /^function showTitle\(/],
|
||||
['game/95-modals/50-release-notes.js', /^\/\* In-app notes stay short/],
|
||||
['game/95-modals/60-help.js', /^function showHelp\(/],
|
||||
['game/95-modals/70-link-modal.js', /^function openLinkModal\(/],
|
||||
['game/95-modals/80-own-cable.js', /^\/\* Your own subsea cable/],
|
||||
['game/95-modals/90-fiber-modals.js', /^function dfModalBody\(/],
|
||||
['game/96-map/10-canvas.js', /^\/\* =+ CANVAS/],
|
||||
['game/96-map/20-land-and-clouds.js', /^function rng\(seed\)/],
|
||||
['game/96-map/30-settings.js', /^function i18nDom\(/],
|
||||
['game/96-map/40-level-of-detail.js', /^\/\* Level of detail/],
|
||||
['game/96-map/50-link-geometry.js', /^\/\* Parallel waves on the same cable/],
|
||||
['game/96-map/60-draw.js', /^function draw\(now\)/],
|
||||
['game/96-map/70-world-layer.js', /^\/\* The land is never drawn/],
|
||||
['game/96-map/80-cities.js', /^const LBLW=/],
|
||||
['game/96-map/90-input.js', /^\/\* -+ hit tests & input/],
|
||||
['game/96-map/95-clicks.js', /^\/\* -+ click delegation/],
|
||||
['game/99-loop.js', /^\/\* =+ LOOP/],
|
||||
];
|
||||
|
||||
// Moves a cut up over the comment directly above it, so a comment stays with the code it describes.
|
||||
function liftOverComments(lines, i, floor) {
|
||||
for (;;) {
|
||||
const prev = lines[i - 1];
|
||||
if (i - 1 <= floor || prev === undefined) return i;
|
||||
if (/^\/\//.test(prev)) { i--; continue; }
|
||||
if (/\*\/\s*$/.test(prev)) {
|
||||
// A block comment ending just above: find the "/*" line it starts on, with no other "*/" in between.
|
||||
let j = i - 1;
|
||||
while (j > floor && !/^\/\*/.test(lines[j])) j--;
|
||||
if (j > floor && !lines.slice(j, i - 1).some((l) => l.includes('*/'))) { i = j; continue; }
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
// Cuts lines[from, to) into [file, text] pairs by the spec.
|
||||
function cut(lines, from, to, spec, what) {
|
||||
const starts = [];
|
||||
let at = from;
|
||||
for (const [file, re] of spec) {
|
||||
let i = at;
|
||||
while (i < to && !re.test(lines[i])) i++;
|
||||
if (i >= to) throw new Error(`${what}: no line matches ${re} (for ${file}) after line ${at + 1}`);
|
||||
const s = starts.length ? liftOverComments(lines, i, starts[starts.length - 1]) : from;
|
||||
starts.push(s);
|
||||
at = i + 1;
|
||||
}
|
||||
if (starts[0] !== from) throw new Error(`${what}: unexpected text before ${spec[0][0]}`);
|
||||
return spec.map(([file], k) => [file, lines.slice(starts[k], k + 1 < starts.length ? starts[k + 1] : to).map((l) => l + '\n').join('')]);
|
||||
}
|
||||
|
||||
function split(html) {
|
||||
if (html.includes('\r')) html = html.replace(/\r\n/g, '\n');
|
||||
const lines = html.split('\n');
|
||||
const find = (re, from = 0) => { const i = lines.findIndex((l, k) => k >= from && re.test(l)); if (i < 0) throw new Error(`no line matches ${re}`); return i; };
|
||||
const styleOpen = find(/^<style>$/), styleClose = find(/^<\/style>$/, styleOpen);
|
||||
// The game script is the last inline <script>, opened with 'use strict'.
|
||||
const gameOpen = find(/^'use strict';$/), gameClose = find(/^<\/script>$/, gameOpen);
|
||||
const files = [
|
||||
...cut(lines, styleOpen + 1, styleClose, CSS, 'styles'),
|
||||
...cut(lines, gameOpen + 1, gameClose, JS, 'game'),
|
||||
];
|
||||
const shell = [
|
||||
...lines.slice(0, styleOpen + 1), '<!-- @include styles -->',
|
||||
...lines.slice(styleClose, gameOpen + 1), '<!-- @include game -->',
|
||||
...lines.slice(gameClose),
|
||||
].join('\n');
|
||||
return [['index.html', shell], ...files];
|
||||
}
|
||||
|
||||
module.exports = { split };
|
||||
|
||||
if (require.main === module) {
|
||||
const [input, out] = process.argv.slice(2);
|
||||
if (!input || !out) { console.error('usage: split-index-html.js INDEX_HTML OUT_DIR'); process.exit(2); }
|
||||
const parts = split(fs.readFileSync(input, 'utf8'));
|
||||
// The post-split tidying (see transforms.js) is part of the layout, so ported work lines up with src/.
|
||||
const { transform } = require('./transforms');
|
||||
for (const [file, text] of transform(parts)) {
|
||||
const p = path.join(out, file);
|
||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
||||
fs.writeFileSync(p, text);
|
||||
}
|
||||
console.log(`Split ${input} into ${parts.length} files under ${out}/`);
|
||||
}
|
||||
2
scripts/legacy/transforms.js
Normal file
2
scripts/legacy/transforms.js
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// Tidying applied after the split (filled in by the next commit).
|
||||
module.exports = { transform: (parts) => parts };
|
||||
103
scripts/lib/page.js
Normal file
103
scripts/lib/page.js
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// Assembles the game page from src/: src/index.html is the shell, and every line that is exactly
|
||||
// `<!-- @include DIR -->` is replaced by the files under src/DIR, concatenated in path order.
|
||||
// The result is the same single, self-contained index.html the game has always shipped: one request,
|
||||
// no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/.
|
||||
//
|
||||
// node scripts/lib/page.js [-o FILE] 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
|
||||
//
|
||||
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
|
||||
// the split (when the page was site/index.html) are read as they are.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const INCLUDE = /^<!-- @include ([\w./-]+) -->$/;
|
||||
|
||||
// Every file under dir, as paths relative to dir with '/' separators, in a stable order
|
||||
// (plain code-unit comparison, so the order never depends on the machine's locale).
|
||||
function listFiles(dir, rel = '') {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
if (e.name.startsWith('.')) continue;
|
||||
const r = rel ? rel + '/' + e.name : e.name;
|
||||
if (e.isDirectory()) out.push(...listFiles(dir, r));
|
||||
else out.push(r);
|
||||
}
|
||||
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
}
|
||||
|
||||
// The partials that make up one include, in order: [{file, text}].
|
||||
function partials(src, dir) {
|
||||
const base = path.join(src, dir);
|
||||
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
|
||||
return listFiles(base).map((r) => {
|
||||
const file = path.join(base, r);
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
|
||||
if (text && !text.endsWith('\n')) throw new Error(`${path.relative(ROOT, file)}: must end with a newline`);
|
||||
if (/^<\/(script|style)/im.test(text)) throw new Error(`${path.relative(ROOT, file)}: must not close its <script>/<style>`);
|
||||
return { file: dir + '/' + r, text };
|
||||
});
|
||||
}
|
||||
|
||||
// The assembled page as a string, plus a map of which output line came from which source file.
|
||||
function assemble({ src = path.join(ROOT, 'src') } = {}) {
|
||||
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
|
||||
const out = [], map = [];
|
||||
let line = 1;
|
||||
const lines = shell.split('\n');
|
||||
lines.forEach((l, i) => {
|
||||
const m = INCLUDE.exec(l);
|
||||
if (!m) {
|
||||
out.push(l + (i < lines.length - 1 ? '\n' : ''));
|
||||
line++;
|
||||
return;
|
||||
}
|
||||
for (const p of partials(src, m[1])) {
|
||||
const n = p.text.split('\n').length - 1;
|
||||
map.push({ file: p.file, from: line, to: line + n - 1 });
|
||||
out.push(p.text);
|
||||
line += n;
|
||||
}
|
||||
});
|
||||
return { html: out.join(''), map };
|
||||
}
|
||||
|
||||
// Which source file (and line in it) an assembled-page line comes from: for stack traces and errors.
|
||||
function locate(map, line) {
|
||||
const m = map.find((x) => line >= x.from && line <= x.to);
|
||||
return m ? { file: m.file, line: line - m.from + 1 } : { file: 'index.html (shell)', line };
|
||||
}
|
||||
|
||||
// The page at a git ref: that commit's src/ through its own assembler, or site/index.html before the split.
|
||||
function assembleRef(ref, cwd = ROOT) {
|
||||
const git = (...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28 });
|
||||
const has = (p) => { try { git('cat-file', '-e', `${ref}:${p}`); return true; } catch { return false; } };
|
||||
if (!has('src/index.html')) return git('show', `${ref}:site/index.html`);
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-ref-'));
|
||||
try {
|
||||
const tar = execFileSync('git', ['archive', '--format=tar', ref, 'src', 'scripts'], { cwd, maxBuffer: 1 << 28 });
|
||||
execFileSync('tar', ['-x', '-C', tmp], { input: tar });
|
||||
return execFileSync(process.execPath, [path.join(tmp, 'scripts', 'lib', 'page.js')], { cwd: tmp, encoding: 'utf8', maxBuffer: 1 << 28 });
|
||||
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
// The assembled 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);
|
||||
return file;
|
||||
}
|
||||
|
||||
module.exports = { assemble, assembleRef, 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 out = opt('-o');
|
||||
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
|
||||
else process.stdout.write(html);
|
||||
}
|
||||
|
|
@ -2,7 +2,8 @@
|
|||
// Performance benchmark on a very large network (tests/fixtures/big-network.json).
|
||||
//
|
||||
// node scripts/perf-bench.js time this checkout
|
||||
// node scripts/perf-bench.js --base OLD.html compare OLD.html (e.g. main) with this checkout
|
||||
// node scripts/perf-bench.js --base-ref origin/main compare main with this checkout (builds main's page)
|
||||
// node scripts/perf-bench.js --base OLD.html compare a built page (e.g. a release's) with this checkout
|
||||
// node scripts/perf-bench.js --base OLD.html --md out.md --summary "$GITHUB_STEP_SUMMARY"
|
||||
// node scripts/perf-bench.js --save my-export.json --base OLD.html a player's save (plain or exported from the menu)
|
||||
// node scripts/perf-bench.js --base OLD.html --browser also in real Chromium, as a desktop and as a phone
|
||||
|
|
@ -19,8 +20,14 @@ const { load } = require('../tests/harness');
|
|||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const HEAD = opt('--head', path.join(ROOT, 'site', 'index.html'));
|
||||
const BASE = opt('--base', null);
|
||||
const page = require('./lib/page');
|
||||
// Pages as files: the browser run opens them from disk.
|
||||
const HEAD = opt('--head', null) || page.pageFile();
|
||||
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
|
||||
const f = path.join(require('node:os').tmpdir(), `tubes-base-${process.pid}.html`);
|
||||
fs.writeFileSync(f, page.assembleRef(opt('--base-ref', null)));
|
||||
return f;
|
||||
})());
|
||||
const RUNS = +opt('--runs', 15);
|
||||
// A plain save, or a file from the in-game "Export save", which wraps it as {app, version, exported, S}.
|
||||
const RAW = JSON.parse(fs.readFileSync(opt('--save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')), 'utf8'));
|
||||
|
|
|
|||
16
scripts/test.js
Normal file
16
scripts/test.js
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/usr/bin/env node
|
||||
// Runs every tests/*.test.js, one file at a time. New test files are picked up on their own, so adding
|
||||
// one never touches package.json (and never conflicts with someone else adding theirs).
|
||||
//
|
||||
// npm test everything
|
||||
// npm test -- tests/peering.test.js just these files (other arguments go to node --test)
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
|
||||
const dir = path.join(__dirname, '..', 'tests');
|
||||
const args = process.argv.slice(2);
|
||||
const files = args.some((a) => a.endsWith('.test.js')) ? [] :
|
||||
fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => path.join('tests', f));
|
||||
const r = spawnSync(process.execPath, ['--test', '--test-concurrency=1', ...args, ...files], { stdio: 'inherit', cwd: path.join(__dirname, '..') });
|
||||
process.exit(r.status ?? 1);
|
||||
Loading…
Add table
Add a link
Reference in a new issue