Serve languages and artwork separately with compressed viewer releases
This commit is contained in:
parent
2be9a6b9c7
commit
36442ddd18
11 changed files with 228 additions and 73 deletions
|
|
@ -32,3 +32,5 @@ Read [the beta report](docs/BETA-REPORT.md) before public release: the supplied
|
|||
Guided lessons are available locally at `/?lesson=planning`, `/?lesson=fishing` and `/?lesson=islands`. Add `?players=2&new`, `?water&new` or `?hotseat&new` for practice variants. Practice progress stays in this browser. The viewer defaults to English; French can be selected in Help or in the BGS game preferences.
|
||||
|
||||
Release: `pnpm build && pnpm test && pnpm test:browser`, then `node scripts/publish-beta.mjs`. The publisher reads the admin token from `~/.bgs`, keeps the version in beta and ensures the game is listed. It refuses to overwrite a public version. `node test/simulations.mjs` runs the longer complete-game sweep.
|
||||
|
||||
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).
|
||||
|
|
|
|||
11
docs/viewer-publishing.md
Normal file
11
docs/viewer-publishing.md
Normal 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.
|
||||
|
|
@ -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"],
|
||||
|
|
@ -22,10 +22,46 @@ for (const [entry, format] of [
|
|||
outfile: entry.endsWith("preview.js")
|
||||
? "dist/preview.js"
|
||||
: "dist/viewer.js",
|
||||
loader: { ".webp": "dataurl" },
|
||||
define: {
|
||||
__BGS_LOCALE_BASE__: "__bgsVanuatuLocaleBase",
|
||||
__BGS_ASSET_BASE__: "__bgsVanuatuAssetBase",
|
||||
},
|
||||
banner: {
|
||||
js:
|
||||
"var __bgsVanuatuAssetBase = " +
|
||||
(format === "iife"
|
||||
? 'new URL("./", document.currentScript?.src || document.baseURI).href; var __bgsVanuatuLocaleBase = new URL("locales/", __bgsVanuatuAssetBase).href;'
|
||||
: 'new URL("./", import.meta.url).href; var __bgsVanuatuLocaleBase = new URL("locales/", __bgsVanuatuAssetBase).href;'),
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
name: "relative-artwork",
|
||||
setup(build) {
|
||||
build.onLoad({ filter: /\.webp$/ }, (args) => {
|
||||
if (args.suffix === "?bgs-file") return;
|
||||
return {
|
||||
contents: `import file from ${JSON.stringify(args.path + "?bgs-file")}; export default new URL(file, __BGS_ASSET_BASE__).href;`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
assetNames: "assets/[name]-[hash]",
|
||||
loader: { ".webp": "file" },
|
||||
minify: true,
|
||||
});
|
||||
await writeFile(
|
||||
"dist/index.html",
|
||||
'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vanuatu · Local practice</title><link rel="stylesheet" href="preview.css"><body><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") {
|
||||
const catalog = JSON.parse(
|
||||
await readFile("viewer/localization/" + file, "utf8"),
|
||||
);
|
||||
await writeFile("dist/locales/" + file, JSON.stringify(catalog));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { uploadViewerFiles } from "./viewer-files.mjs";
|
||||
import { chapterMetadata } from "../viewer/tutorials.js";
|
||||
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";
|
||||
const token = (await readFile(`${homedir()}/.bgs`, "utf8")).trim();
|
||||
const base = "https://admin.boardgamers.space/api/admin/gameinfo/vanuatu";
|
||||
|
|
@ -99,25 +99,15 @@ const engine = await api(
|
|||
await readFile(`.local/release/boardgamers-vanuatu-${pkg.version}.tgz`),
|
||||
"application/octet-stream",
|
||||
);
|
||||
const js = await readFile("dist/viewer.js"),
|
||||
css = await readFile("dist/viewer.css");
|
||||
const hash = createHash("sha256")
|
||||
.update(js)
|
||||
.update(css)
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
const viewer = await api(
|
||||
`/1/viewer/file?filename=viewer.js&bundle=${hash}`,
|
||||
"POST",
|
||||
js,
|
||||
"application/octet-stream",
|
||||
);
|
||||
const style = await api(
|
||||
`/1/viewer/file?filename=viewer.css&bundle=${hash}`,
|
||||
"POST",
|
||||
css,
|
||||
"application/octet-stream",
|
||||
const files = await uploadViewerFiles(
|
||||
"dist",
|
||||
"viewer.js",
|
||||
["viewer.css"],
|
||||
(query, bytes) =>
|
||||
api("/1/viewer/file?" + query, "POST", bytes, "application/octet-stream"),
|
||||
);
|
||||
const viewer = { url: files.url },
|
||||
style = { url: files.stylesheets[0] };
|
||||
const { unlisted: _unlisted, ...previous } = existing ?? {};
|
||||
await api("/1", "PUT", {
|
||||
...previous,
|
||||
|
|
@ -126,6 +116,7 @@ await api("/1", "PUT", {
|
|||
viewer: {
|
||||
...defaults.viewer,
|
||||
url: viewer.url,
|
||||
scriptBytes: files.scriptBytes,
|
||||
dependencies: { scripts: [], stylesheets: [style.url] },
|
||||
},
|
||||
});
|
||||
|
|
|
|||
56
scripts/viewer-files.mjs
Normal file
56
scripts/viewer-files.mjs
Normal 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)),
|
||||
};
|
||||
}
|
||||
|
|
@ -232,6 +232,11 @@ assert.equal(
|
|||
);
|
||||
await page.locator("[data-help]").first().click();
|
||||
await page.locator("[data-language]").selectOption("fr");
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("[data-back] span")?.textContent ===
|
||||
"Retour au plateau",
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator("[data-back] span").textContent(),
|
||||
"Retour au plateau",
|
||||
|
|
@ -244,6 +249,10 @@ assert.equal(
|
|||
);
|
||||
await page.locator("[data-help]").first().click();
|
||||
await page.locator("[data-language]").selectOption("en");
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("[data-back] span")?.textContent === "Back to board",
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator("[data-back] span").textContent(),
|
||||
"Back to board",
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ s.events = [
|
|||
{ type: "round", round: 2, first: 1 },
|
||||
].map((e, i) => ({ round: 1, step: i + 1, ...e }));
|
||||
const server = createServer(async (req, res) => {
|
||||
const name = req.url === "/viewer.css" ? "viewer.css" : "viewer.js";
|
||||
const name = req.url.slice(1);
|
||||
if (req.url === "/")
|
||||
res.end(
|
||||
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/viewer.css"><div id="app"></div><script src="/viewer.js"></script>',
|
||||
|
|
@ -75,11 +75,20 @@ const server = createServer(async (req, res) => {
|
|||
else {
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
name.endsWith("css") ? "text/css" : "text/javascript",
|
||||
name.endsWith(".json")
|
||||
? "application/json"
|
||||
: name.endsWith(".webp")
|
||||
? "image/webp"
|
||||
: name.endsWith("css")
|
||||
? "text/css"
|
||||
: "text/javascript",
|
||||
);
|
||||
const url = name.endsWith("css")
|
||||
? process.env.JOURNAL_CSS_URL
|
||||
: process.env.JOURNAL_JS_URL;
|
||||
const url =
|
||||
name === "viewer.css"
|
||||
? process.env.JOURNAL_CSS_URL
|
||||
: process.env.JOURNAL_JS_URL
|
||||
? new URL(name, process.env.JOURNAL_JS_URL).href
|
||||
: undefined;
|
||||
if (url) {
|
||||
const response = await fetch(url);
|
||||
assert.ok(response.ok);
|
||||
|
|
|
|||
|
|
@ -55,7 +55,8 @@ registerViewer(
|
|||
}
|
||||
return {
|
||||
chat,
|
||||
onState(state) {
|
||||
async onState(state) {
|
||||
await localization.ready;
|
||||
localization.setState(state);
|
||||
live = state;
|
||||
if (!replaying) {
|
||||
|
|
@ -73,8 +74,8 @@ registerViewer(
|
|||
onPlayer(p) {
|
||||
ui.setPlayer(p.index);
|
||||
},
|
||||
onPreferences(p) {
|
||||
localization.setLocale(p.locale ?? p.language);
|
||||
async onPreferences(p) {
|
||||
if (!(await localization.setLocale(p.locale ?? p.language))) return;
|
||||
ui.setPreferences(p);
|
||||
},
|
||||
onAvatars(avatars) {
|
||||
|
|
|
|||
3
viewer/localization/index.d.ts
vendored
3
viewer/localization/index.d.ts
vendored
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -1,40 +1,48 @@
|
|||
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 "./rtl.css";
|
||||
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)) {
|
||||
|
|
@ -43,16 +51,46 @@ export function translateText(text, locale = "en") {
|
|||
return translators.get(locale).translate(text);
|
||||
}
|
||||
export function mountLocalization(target, locale) {
|
||||
return mount(
|
||||
target,
|
||||
catalogs,
|
||||
locale ?? target.ownerDocument.documentElement.lang ?? "en",
|
||||
);
|
||||
const localization = mount(target, catalogs, "en");
|
||||
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 () => {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ const localization = mountLocalization(
|
|||
document.body,
|
||||
params.get("locale") ?? "en",
|
||||
);
|
||||
await localization.ready;
|
||||
if (params.has("lesson")) {
|
||||
const names = chapterMetadata.map((chapter) => chapter.id);
|
||||
const chapter = params.get("lesson");
|
||||
|
|
@ -61,10 +62,10 @@ if (params.has("lesson")) {
|
|||
show();
|
||||
scheduleBots();
|
||||
},
|
||||
onPreference: (name, value) => {
|
||||
onPreference: async (name, value) => {
|
||||
preferences[name] = value;
|
||||
localStorage.setItem("vanuatu-preferences", JSON.stringify(preferences));
|
||||
localization.setLocale(preferences.language);
|
||||
await localization.setLocale(preferences.language);
|
||||
ui.setPreferences(preferences);
|
||||
},
|
||||
});
|
||||
|
|
@ -73,7 +74,7 @@ if (params.has("lesson")) {
|
|||
preferences = JSON.parse(localStorage.getItem("vanuatu-preferences")) ?? {};
|
||||
} catch {}
|
||||
if (params.has("locale")) preferences.language = params.get("locale");
|
||||
localization.setLocale(preferences.language ?? "en");
|
||||
await localization.setLocale(preferences.language ?? "en");
|
||||
ui.setPreferences(preferences);
|
||||
function save() {
|
||||
try {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue