feat: First iteration, multi themes, I18N

This commit is contained in:
gauvainboiche
2026-10-08 11:58:18 +02:00
parent 9240fa3c3c
commit aa9721ac2a
53 changed files with 3363 additions and 1 deletions
+76
View File
@@ -0,0 +1,76 @@
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
// Content packs are discovered from the filesystem, so adding a theme or a
// language is just dropping files in a folder: no code change, no rebuild list.
const THEME_ID = /^[a-z0-9][a-z0-9-]*$/;
const LOCALE_CODE = /^[a-z]{2,3}(-[A-Za-z0-9]+)*$/;
async function readJson(file) {
return JSON.parse(await readFile(file, 'utf8'));
}
async function listLocaleCodes(dir) {
let names;
try {
names = await readdir(dir);
} catch {
return [];
}
return names
.filter((n) => n.endsWith('.json'))
.map((n) => n.slice(0, -'.json'.length))
.filter((code) => LOCALE_CODE.test(code))
.sort();
}
/** GET /api/themes -> [{ id, order, assets, locales }] */
async function listThemes(publicDir) {
const root = path.join(publicDir, 'themes');
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
const themes = [];
for (const entry of entries) {
if (!entry.isDirectory() || !THEME_ID.test(entry.name)) continue;
const dir = path.join(root, entry.name);
try {
const manifest = await readJson(path.join(dir, 'theme.json'));
themes.push({
id: entry.name,
order: Number.isFinite(manifest.order) ? manifest.order : 100,
assets: manifest.assets && typeof manifest.assets === 'object' ? manifest.assets : {},
locales: await listLocaleCodes(path.join(dir, 'locales')),
});
} catch {
// Skip folders without a valid theme.json rather than failing the whole list.
}
}
return themes.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
}
/** GET /api/locales -> [{ code, name }] */
async function listLocales(publicDir) {
const dir = path.join(publicDir, 'locales');
const out = [];
for (const code of await listLocaleCodes(dir)) {
try {
const file = await readJson(path.join(dir, `${code}.json`));
out.push({ code, name: file?.meta?.name ?? code });
} catch {
// Ignore malformed locale files.
}
}
return out;
}
/** Returns a JSON payload for known /api routes, or undefined for unknown ones. */
export async function handleApi(publicDir, pathname) {
switch (pathname) {
case '/api/themes':
return listThemes(publicDir);
case '/api/locales':
return listLocales(publicDir);
default:
return undefined;
}
}
+53
View File
@@ -0,0 +1,53 @@
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { handleApi } from './api.js';
import { SECURITY_HEADERS } from './security.js';
import { createStaticHandler } from './static.js';
const PORT = Number(process.env.PORT) || 8080;
const HOST = process.env.HOST || '0.0.0.0';
const PUBLIC_DIR = fileURLToPath(new URL('../public/', import.meta.url));
const serveStatic = createStaticHandler(PUBLIC_DIR);
const server = http.createServer(async (req, res) => {
try {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405, { ...SECURITY_HEADERS, Allow: 'GET, HEAD' });
return res.end();
}
const { pathname } = new URL(req.url, 'http://localhost');
if (pathname === '/healthz') {
res.writeHead(200, { ...SECURITY_HEADERS, 'Content-Type': 'text/plain' });
return res.end('ok');
}
if (pathname.startsWith('/api/')) {
const payload = await handleApi(PUBLIC_DIR, pathname);
if (payload === undefined) {
res.writeHead(404, { ...SECURITY_HEADERS, 'Content-Type': 'application/json' });
return res.end('{"error":"not_found"}');
}
res.writeHead(200, {
...SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
});
return res.end(req.method === 'HEAD' ? undefined : JSON.stringify(payload));
}
return await serveStatic(req, res, pathname, SECURITY_HEADERS);
} catch (err) {
console.error(err);
if (!res.headersSent) res.writeHead(500, SECURITY_HEADERS);
res.end();
}
});
server.listen(PORT, HOST, () => console.log(`Idle Clicker listening on http://${HOST}:${PORT}`));
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => server.close(() => process.exit(0)));
}
+23
View File
@@ -0,0 +1,23 @@
// Response headers applied to every response (static files and API).
// The frontend ships no inline script/style, so the CSP can stay strict.
const CSP = [
"default-src 'none'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"font-src 'self'",
"connect-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join('; ');
export const SECURITY_HEADERS = Object.freeze({
'Content-Security-Policy': CSP,
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'no-referrer',
'Cross-Origin-Opener-Policy': 'same-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=()',
});
+71
View File
@@ -0,0 +1,71 @@
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import path from 'node:path';
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
/**
* Resolve a URL pathname to a file inside `root`, or null if it escapes it.
* Exported for tests.
*/
export function resolveSafe(root, pathname) {
let decoded;
try {
decoded = decodeURIComponent(pathname);
} catch {
return null;
}
if (decoded.includes('\0')) return null;
const target = path.resolve(root, '.' + path.posix.normalize('/' + decoded));
return target === root || target.startsWith(root + path.sep) ? target : null;
}
/** Serve files from `root`. Revalidates with ETag so edits show up on refresh. */
export function createStaticHandler(root) {
const base = path.resolve(root);
return async function serve(req, res, pathname, headers) {
let file = resolveSafe(base, pathname === '/' ? '/index.html' : pathname);
if (!file) return send(res, 400, headers, 'Bad request');
let info;
try {
info = await stat(file);
if (info.isDirectory()) {
file = path.join(file, 'index.html');
info = await stat(file);
}
} catch {
return send(res, 404, headers, 'Not found');
}
const etag = `W/"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`;
const type = MIME[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
const out = { ...headers, 'Content-Type': type, 'Cache-Control': 'no-cache', ETag: etag };
if (req.headers['if-none-match'] === etag) {
res.writeHead(304, out);
return res.end();
}
res.writeHead(200, { ...out, 'Content-Length': info.size });
if (req.method === 'HEAD') return res.end();
createReadStream(file).on('error', () => res.destroy()).pipe(res);
};
}
function send(res, status, headers, text) {
res.writeHead(status, { ...headers, 'Content-Type': 'text/plain; charset=utf-8' });
res.end(text);
}