Split viewer translations and fonts into separately cached files

This commit is contained in:
coyotte508 2026-09-30 00:31:23 +02:00
commit 0e9d3cc8ac
13 changed files with 244 additions and 75 deletions

View file

@ -25,7 +25,7 @@ The environment-card manifest in `engine/catalog.js` uses the owner's confirmed
Five and six players use the complete 39-card standard gene pool from the [publisher's Freshly Spiced rules and reference sheets](http://doris-frank.de/download/Ursuppe_Frisch_Abgeschmeckt.pdf). Streamline and Struggle for Survival have mutation sensitivity 5; Frugality costs 5 BP. Amoebas eat four different foreign colours, receive 11 BP in phase 4, and are limited to numbers 1–6. Starting scores are chosen from 1–6, even with five players. Population scores for 0–6 amoebas are 0, 0, 1, 2, 3, 4, 5; gene scoring is unchanged. These rules apply automatically by player count. The other base rules continue to apply, including the first starting amoeba's injury and Tentacle's four-player capacity of three cubes (the translated reference does not state a separate 5–6-player capacity).
The optional extra genes are from **Primordial Soup: Freshly Spiced** (*Ursuppe: Frisch abgeschmeckt*). All 26 effects are implemented. Enable the boolean `newGenes` option (default false), or check **New genes** before starting a practice game. Direct preview: `/?players=6&newGenes=1`. The catalogue lives in `engine/new-genes.js`, with a seeded shuffle, hidden deck and public market. The recommended initial pair is Social Gene and Population Explosion. Two more cards become available each round in phase 3 immediately after the score leader finishes buying, before the next player's purchases. Previously revealed cards remain available. The option is independent of player count; it does not use the platform's expansions array. The viewer supports gene exchanges, healing, remote food selection, excretion destinations, toxins and private forecasts. Forecasts are stripped separately for each recipient and never written to the public journal. Source errata: [publisher's corrections](http://doris-frank.de/Ursuppe.html#ERRATA).
The optional extra genes are from **Primordial Soup: Freshly Spiced** (_Ursuppe: Frisch abgeschmeckt_). All 26 effects are implemented. Enable the boolean `newGenes` option (default false), or check **New genes** before starting a practice game. Direct preview: `/?players=6&newGenes=1`. The catalogue lives in `engine/new-genes.js`, with a seeded shuffle, hidden deck and public market. The recommended initial pair is Social Gene and Population Explosion. Two more cards become available each round in phase 3 immediately after the score leader finishes buying, before the next player's purchases. Previously revealed cards remain available. The option is independent of player count; it does not use the platform's expansions array. The viewer supports gene exchanges, healing, remote food selection, excretion destinations, toxins and private forecasts. Forecasts are stripped separately for each recipient and never written to the public journal. Source errata: [publisher's corrections](http://doris-frank.de/Ursuppe.html#ERRATA).
Implementation conventions for interactions not detailed by the translated reference: Social Gene collects at the start of phase 6, using the scores before movement; Flexible also discounts transfers and the positive price difference of an exchange; Highly Adaptable still requires and consumes an earlier-round prerequisite for an advanced gene. Healing II follows the reference’s explicit immediate death of the injury recipient, even if otherwise healthy. Ordinary injuries (including toxins and More than a Mouthful) wait for phase 5; lethal Bang chain reactions resolve immediately in descending score and amoeba-number order. Suction II takes at most two cubes from a single adjacent space, including diagonals. Rebound can cross one obstacle to a valid space, without wrapping around the board.
@ -46,3 +46,5 @@ Movement II has larger, split fins with visible fin rays, distinguishing it from
Bundled fonts retain their OFL notices in `viewer/assets/`.
The display font is a renamed OFL derivative of Lilita One with corrected glyph bounds. Rebuild it with `uv run --with fonttools --with brotli scripts/build-display-font.py`.
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).

11
docs/viewer-publishing.md Normal file
View file

@ -0,0 +1,11 @@
# Publishing the viewer
Upload `dist/viewer.js`, `dist/viewer.css`, `dist/locales/` and `dist/assets/`. Leave out `engine.js`, the preview app and HTML.
All files in a release must share one BGS `bundle` directory, with their relative paths preserved. Upload everything before saving the new entry URL. A main-JS-only upload will break language or asset loading. Keep engines and test data out of the viewer upload.
BGS compresses JS, CSS, JSON and WASM automatically during upload. Send the original bytes; do not create `.gz` files. Keep sourcemaps local unless you deliberately want to publish them. Set `viewer.scriptBytes` to the original entry size so BGS can show download progress.
The BGS admin's **Upload folder** control handles multi-file builds. For scripted releases, use BGS's `scripts/publish-viewer.mjs` with `--dir`, `--entry` and `--style`; it verifies every uploaded file, records the previous viewer, and activates only with `--apply --activate`. The full command and API contract are in the [BGS viewer documentation](https://docs.boardgamers.space/guide/viewer-api#publishing-a-viewer-with-multiple-files).
English needs no language download; other languages load when selected. Test a cold load and a language change after publishing. Also check the browser Network panel for missing relative assets.

View file

@ -1,5 +1,5 @@
import { build } from "esbuild";
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, writeFile, readdir, readFile } from "node:fs/promises";
await mkdir("dist", { recursive: true });
await build({
entryPoints: ["engine/index.js"],
@ -14,22 +14,44 @@ await build({
bundle: true,
platform: "browser",
format: "iife",
define: { __BGS_LOCALE_BASE__: "__bgsSoupLocaleBase" },
banner: {
js: 'var __bgsSoupLocaleBase = new URL("locales/", document.currentScript?.src || document.baseURI).href;',
},
target: "es2022",
outfile: "dist/viewer.js",
loader: { ".ttf": "dataurl", ".woff2": "dataurl" },
assetNames: "assets/[name]-[hash]",
loader: { ".ttf": "file", ".woff2": "file" },
minify: true,
});
await build({
entryPoints: ["viewer/preview.js"],
define: { __BGS_LOCALE_BASE__: "__bgsSoupLocaleBase" },
banner: {
js: 'var __bgsSoupLocaleBase = new URL("locales/", import.meta.url).href;',
},
bundle: true,
platform: "browser",
format: "esm",
target: "es2022",
outfile: "dist/preview.js",
loader: { ".ttf": "dataurl", ".woff2": "dataurl" },
assetNames: "assets/[name]-[hash]",
loader: { ".ttf": "file", ".woff2": "file" },
minify: false,
});
await writeFile(
"dist/index.html",
'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Primordial Soup</title><link rel="stylesheet" href="preview.css"></head><body><div id="preview-nav"></div><div id="game"></div><script type="module" src="preview.js"></script></body></html>',
);
await mkdir("dist/locales", { recursive: true });
for (const file of await readdir("viewer/localization")) {
if (file.endsWith(".json") && file !== "en.json") {
await writeFile(
"dist/locales/" + file,
JSON.stringify(
JSON.parse(await readFile("viewer/localization/" + file, "utf8")),
),
);
}
}

View file

@ -1,7 +1,7 @@
import { uploadViewerFiles } from "./viewer-files.mjs";
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import assert from "node:assert/strict";
import { NEW_GENES_OPTION } from "../engine/new-genes.js";
import { chapterMetadata } from "../viewer/tutorials.js";
@ -50,25 +50,14 @@ const tarball = await readFile(
`.local/release/boardgamers-primordial-soup-${pkg.version}.tgz`,
);
const uploaded = await api("/1/engine", "POST", tarball, true);
const js = await readFile("dist/viewer.js"),
css = await readFile("dist/viewer.css");
const bundle = createHash("sha256")
.update(js)
.update(css)
.digest("hex")
.slice(0, 16);
const viewer = await api(
`/1/viewer/file?filename=viewer.js&bundle=${bundle}`,
"POST",
js,
true,
);
const style = await api(
`/1/viewer/file?filename=viewer.css&bundle=${bundle}`,
"POST",
css,
true,
const files = await uploadViewerFiles(
"dist",
"viewer.js",
["viewer.css"],
(query, bytes) => api("/1/viewer/file?" + query, "POST", bytes, true),
);
const viewer = { url: files.url },
style = { url: files.stylesheets[0] };
const current = await api("/1");
await api("/1", "PUT", {
...current,
@ -87,6 +76,7 @@ await api("/1", "PUT", {
viewer: {
...current.viewer,
url: viewer.url,
scriptBytes: files.scriptBytes,
topLevelVariable: "primordialSoup",
fullScreen: true,
fullScreenMobile: true,

56
scripts/viewer-files.mjs Normal file
View file

@ -0,0 +1,56 @@
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { createHash } from "node:crypto";
import assert from "node:assert/strict";
export async function uploadViewerFiles(directory, entry, styles, upload) {
const files = [];
async function walk(directory, prefix = "") {
for (const item of await readdir(directory, { withFileTypes: true })) {
const name = prefix + item.name;
assert(!item.isSymbolicLink(), `Symlink in viewer build: ${name}`);
if (item.isDirectory())
await walk(join(directory, item.name), name + "/");
else if (
/\.(js|css|json|wasm|svg|png|jpe?g|webp|avif|gif|woff2?|ttf|mp3|ogg|wav)$/.test(
name,
) &&
!/^(engine|preview)\.(js|css)$/.test(name)
) {
files.push({ name, bytes: await readFile(join(directory, item.name)) });
}
}
}
await walk(directory);
files.sort((a, b) => a.name.localeCompare(b.name));
for (const name of [entry, ...styles])
assert(
files.some((file) => file.name === name),
`Missing viewer asset: ${name}`,
);
const hash = createHash("sha256");
for (const file of files)
hash.update(file.name).update("\0").update(file.bytes).update("\0");
const bundle = "assets-" + hash.digest("hex").slice(0, 20);
const urls = new Map();
for (const file of files) {
const saved = await upload(
`filename=${encodeURIComponent(file.name)}&bundle=${bundle}`,
file.bytes,
);
const response = await fetch(saved.url, {
signal: AbortSignal.timeout(60000),
});
assert(response.ok, `Viewer asset unavailable: ${file.name}`);
assert(
Buffer.from(await response.arrayBuffer()).equals(file.bytes),
`Viewer asset mismatch: ${file.name}`,
);
urls.set(file.name, saved.url);
}
return {
url: urls.get(entry),
scriptBytes: files.find((file) => file.name === entry).bytes.length,
stylesheets: styles.map((name) => urls.get(name)),
};
}

View file

@ -1,3 +1,5 @@
import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
import { checkHostPresentation } from "./host-presentation-smoke.mjs";
import { prepared } from "../viewer/tutorials.js";
import assert from "node:assert/strict";
@ -29,10 +31,8 @@ try {
game === "fuji"
? root + "/packages/viewer/dist/fuji-viewer"
: root + "/dist/viewer";
await page.addStyleTag({ path: prefix + ".css" });
await page.addScriptTag({
path: prefix + (game === "fuji" ? ".iife.js" : ".js"),
});
await page.addStyleTag({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/viewer.js" });
await page.evaluate(
({ state, game }) => {
window.e = (game === "fuji" ? fuji : primordialSoup).launch("#app");

33
test/asset-server.mjs Normal file
View file

@ -0,0 +1,33 @@
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { resolve, extname, sep } from "node:path";
export async function serveAssets(directory) {
const root = resolve(directory);
const server = createServer(async (req, res) => {
try {
const path = resolve(
root,
"." + new URL(req.url, "http://localhost").pathname,
);
if (!path.startsWith(root + sep)) throw Error("Invalid asset path");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Content-Type",
{
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".webp": "image/webp",
".jpg": "image/jpeg",
".wasm": "application/wasm",
}[extname(path)] || "application/octet-stream",
);
res.end(await readFile(path));
} catch {
res.writeHead(404).end();
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
server.unref();
return `http://127.0.0.1:${server.address().port}`;
}

View file

@ -1,3 +1,5 @@
import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { fileURLToPath } from "node:url";
@ -16,8 +18,8 @@ try {
await page.setContent(
'<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="app"></div></body></html>',
);
await page.addStyleTag({ path: root + "dist/viewer.css" });
await page.addScriptTag({ path: root + "dist/viewer.js" });
await page.addStyleTag({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/viewer.js" });
let s = prepared({
genes: ["flexible", "adaptable"],
phase: 2,
@ -165,6 +167,10 @@ try {
.isVisible(),
);
await page.evaluate(() => e.emit("preferences", { locale: "fr" }));
await filter
.locator("span")
.getByText("Achetables", { exact: true })
.waitFor();
assert.equal(await filter.locator("span").textContent(), "Achetables");
await filter.click();
assert.equal(await filter.getAttribute("aria-pressed"), "false");

View file

@ -1,3 +1,5 @@
import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { fileURLToPath } from "node:url";
@ -20,15 +22,16 @@ async function hostedViewer(preferences, localValue) {
body: '<!doctype html><div id="app"></div>',
}),
);
await page.goto("http://127.0.0.1:5221/__preferences-test");
await page.goto(assetBase + "/__preferences-test");
if (localValue !== undefined)
await page.evaluate(
({ localKey, localValue }) =>
localStorage.setItem(localKey, String(localValue)),
{ localKey, localValue },
);
await page.addStyleTag({ path: root + "dist/viewer.css" });
await page.addScriptTag({ path: root + "dist/viewer.js" });
await page.addStyleTag({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/viewer.js" });
assert.deepEqual(errors, [], "Viewer failed before launch");
await page.evaluate((preferences) => {
window.emitter = primordialSoup.launch("#app");
window.savedPreferences = preferences;

View file

@ -1,3 +1,5 @@
import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { fileURLToPath } from "node:url";
@ -16,8 +18,8 @@ try {
await page.setContent(
'<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div>',
);
await page.addStyleTag({ path: root + "dist/viewer.css" });
await page.addScriptTag({ path: root + "dist/viewer.js" });
await page.addStyleTag({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/viewer.js" });
await page.evaluate(() => {
window.e = primordialSoup.launch("#app");
window.moves = [];

View file

@ -96,15 +96,16 @@ registerViewer(
".pond-tools, .board-actions",
);
},
onPreferences(preferences) {
localization.setLocale(preferences.locale);
async onPreferences(preferences) {
if (!(await localization.setLocale(preferences.locale))) return;
ui.setAnalysisMode(preferences.analysis === true);
ui.setColorBlind(preferences[COLOR_BLIND_PREFERENCE.name] === true);
},
onPlayer(player) {
ui.setPlayer(player.index);
},
onState(state) {
async onState(state) {
await localization.ready;
localization.setState(state);
ui.render(state);
if (pending) {

View file

@ -2,7 +2,8 @@ import type { TutorialMount } from "@boardgamers/protocol/tutorial";
export interface Localization {
readonly locale: string;
translate(text: string): string;
setLocale(locale: unknown): void;
readonly ready: Promise<boolean>;
setLocale(locale: unknown): Promise<boolean>;
setState(state: unknown): void;
setNames(names: unknown[]): void;
refresh(): void;

View file

@ -1,41 +1,49 @@
import { renderRichText } from "../rich-text.js";
import { renderJournalSentence } from "../journal.js";
import catalog0 from "./en.json";
import catalog1 from "./de.json";
import catalog2 from "./fr.json";
import catalog3 from "./pl.json";
import catalog4 from "./ro.json";
import catalog5 from "./el.json";
import catalog6 from "./hi.json";
import catalog7 from "./ru.json";
import catalog8 from "./da.json";
import catalog9 from "./pt-BR.json";
import catalog10 from "./ko.json";
import catalog11 from "./zh-TW.json";
import catalog12 from "./vi.json";
import catalog13 from "./it.json";
import catalog14 from "./nl.json";
import catalog15 from "./fa.json";
import { mountLocalization as mount, createTranslator } from "./runtime.js";
import {
mountLocalization as mount,
createTranslator,
resolveLocale,
} from "./runtime.js";
export { languages, resolveLocale } from "./runtime.js";
export const catalogs = {
en: catalog0,
de: catalog1,
fr: catalog2,
pl: catalog3,
ro: catalog4,
el: catalog5,
hi: catalog6,
ru: catalog7,
da: catalog8,
"pt-BR": catalog9,
ko: catalog10,
"zh-TW": catalog11,
vi: catalog12,
it: catalog13,
nl: catalog14,
fa: catalog15,
};
const catalogBase = __BGS_LOCALE_BASE__;
async function fetchCatalog(locale) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 20000);
try {
const response = await fetch(new URL(`${locale}.json`, catalogBase), {
signal: controller.signal,
});
if (!response.ok)
throw new Error(`Language ${locale}: HTTP ${response.status}`);
return { default: await response.json() };
} finally {
clearTimeout(timeout);
}
}
export const catalogs = { en: {} };
const pending = new Map();
export function loadLocale(value) {
const locale = resolveLocale(value);
if (catalogs[locale]) return Promise.resolve(locale);
if (!pending.has(locale)) {
pending.set(
locale,
fetchCatalog(locale)
.then((module) => {
catalogs[locale] = module.default;
translators.delete(locale);
return locale;
})
.catch((error) => {
pending.delete(locale);
throw error;
}),
);
}
return pending.get(locale);
}
const translators = new Map();
export function translateText(text, locale = "en") {
if (!translators.has(locale)) {
@ -44,10 +52,10 @@ export function translateText(text, locale = "en") {
return translators.get(locale).translate(text);
}
export function mountLocalization(target, locale) {
return mount(
const localization = mount(
target,
catalogs,
locale ?? target.ownerDocument.documentElement.lang ?? "en",
"en",
(source, translate, node) =>
node.hasAttribute("data-journal-players")
? renderJournalSentence(
@ -57,11 +65,45 @@ export function mountLocalization(target, locale) {
)
: renderRichText(source, translate),
);
let revision = 0;
let ready = Promise.resolve(true);
function setLocale(value) {
const attempt = ++revision;
ready = loadLocale(value)
.then((loaded) => {
if (attempt !== revision) return false;
localization.setLocale(loaded);
return true;
})
.catch((error) => {
console.warn("Could not load game language", error);
if (attempt !== revision) return false;
localization.setLocale("en");
return true;
});
return ready;
}
setLocale(locale ?? target.ownerDocument.documentElement.lang ?? "en");
return {
...localization,
setLocale,
get locale() {
return localization.locale;
},
get ready() {
return ready;
},
destroy() {
revision++;
localization.destroy();
},
};
}
export function localizeTutorial(mountTutorial) {
return async (target, options) => {
const localization = mountLocalization(target, options.locale);
try {
await localization.ready;
const dispose = await mountTutorial(target, options);
localization.refresh();
return () => {