Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
594 lines (574 loc) · 22.1 KB
/
Copy pathvite.config.ts
File metadata and controls
594 lines (574 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import {
type AssetManifest,
buildAssetUrl,
} from "@openfront/shared/AssetPaths";
import { rewriteAssetsForCdn } from "@openfront/shared/AssetUrls";
import tailwindcss from "@tailwindcss/vite";
import fs from "fs";
import http from "http";
import { lookup as lookupMime } from "mrmime";
import path from "path";
import { fileURLToPath } from "url";
import { defineConfig, loadEnv, type Plugin } from "vite";
import { createHtmlPlugin } from "vite-plugin-html";
import { configDefaults } from "vitest/config";
import {
buildPublicAssetManifest,
copyRootPublicFiles,
createHashedPublicAssetFiles,
getProprietaryDir,
getPublicDir,
getResourcesDir,
writePublicAssetManifest,
writeRootFilesIndex,
} from "./src/server/PublicAssetManifest";
// Vite already handles these, but its good practice to define them explicitly
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const clientForksTests = [
"tests/client/ApexNavigation.test.ts",
"tests/client/Auth.desktopLogin.test.ts",
"tests/client/Auth.steamOpenId.test.ts",
"tests/client/ClientEnvStatic.test.ts",
"tests/client/ClientGameRunnerMessages.test.ts",
"tests/client/CosmeticPackPurchase.test.ts",
"tests/client/CosmeticPurchaseDebt.test.ts",
"tests/client/CreatorCodePanel.test.ts",
"tests/client/HashedEmail.test.ts",
"tests/client/InlineCheckout.test.ts",
"tests/client/MainInitialize.test.ts",
"tests/client/Matchmaking.test.ts",
"tests/client/Platform.test.ts",
"tests/client/ServerList.test.ts",
"tests/client/ShareLinks.test.ts",
"tests/client/TransportConnectionRefused.test.ts",
"tests/client/TransportPoolRedirect.test.ts",
"tests/client/TransportReconnect.test.ts",
"tests/client/UsernameBareClaim.test.ts",
"tests/client/UsernameClaimPrefill.test.ts",
"tests/client/graphics/layers/WinModal.test.ts",
"tests/client/poki/PokiSDK.test.ts",
];
// Percent of en.json's strings each language file translates, keyed by
// language code. The modal can't measure this itself: it only fetches the
// language the player picks.
function langCoverage(langDir: string): Record<string, number> {
const flatten = (
obj: object,
prefix = "",
out = new Map<string, unknown>(),
) => {
for (const [key, value] of Object.entries(obj)) {
const full = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === "object")
flatten(value, full, out);
else out.set(full, value);
}
return out;
};
const read = (file: string) =>
flatten(JSON.parse(fs.readFileSync(path.join(langDir, file), "utf8")));
const englishKeys = [...read("en.json").keys()];
const coverage: Record<string, number> = {};
for (const file of fs.readdirSync(langDir)) {
if (
!file.endsWith(".json") ||
file === "en.json" ||
file === "metadata.json"
)
continue;
const lang = read(file);
const translated = englishKeys.filter((key) => {
const value = lang.get(key);
return typeof value === "string" && value !== "";
}).length;
coverage[file.slice(0, -".json".length)] = Math.floor(
(100 * translated) / englishKeys.length,
);
}
return coverage;
}
// Dev-only: resources/public/ is served at the site root, as the build copies
// it into static/. Vite's publicDir (resources/) would put it under /public/.
function serveRootPublicDir(publicDir: string): Plugin {
return {
name: "serve-root-public-dir",
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (!req.url) return next();
let rel = decodeURIComponent(
new URL(req.url, "http://x").pathname,
).replace(/^\/+/, "");
if (rel.split(/[\\/]/).some((part) => part === "." || part === ".."))
return next();
if (rel === "" || rel.endsWith("/")) rel += "index.html";
const filePath = path.join(publicDir, rel);
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
return next();
const mime = lookupMime(filePath);
if (mime) res.setHeader("Content-Type", mime);
res.setHeader("Cache-Control", "no-store");
fs.createReadStream(filePath).pipe(res);
});
},
};
}
function serveProprietaryDir(
proprietaryDir: string,
resourcesDir: string,
): Plugin {
return {
name: "serve-proprietary-dir",
configureServer(server) {
// Must run before Vite's htmlFallback; skip when resources/ has the file
// so publicDir keeps precedence.
server.middlewares.use((req, res, next) => {
if (!req.url) return next();
const rel = decodeURIComponent(
new URL(req.url, "http://x").pathname,
).replace(/^\//, "");
if (rel.includes("..")) return next();
if (fs.existsSync(path.join(resourcesDir, rel))) return next();
const filePath = path.join(proprietaryDir, rel);
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
return next();
const mime = lookupMime(filePath);
if (mime) res.setHeader("Content-Type", mime);
res.setHeader("Cache-Control", "no-store");
fs.createReadStream(filePath).pipe(res);
});
},
};
}
// Dev-only stand-in for nginx's `location = /link` blocks (see nginx.conf).
//
// The desktop app's account-linking gate prints a short URL for the player to
// type by hand when it cannot open their browser for them. In production
// nginx 302s /link to /#steam-link, the client route that shows the code-entry
// form. Without this middleware the dev server falls through to Vite's SPA
// fallback and serves the home page instead -- a 200, so it does not look
// broken, but the printed URL silently would not work locally.
//
// A redirect rather than serving index.html directly, so dev matches
// production exactly and the desktop's siteUrlForAudience can emit one URL
// shape for every environment.
function steamLinkAliasRedirect(): Plugin {
return {
name: "steam-link-alias-redirect",
configureServer(server) {
// Matches on `originalUrl`, not `url`, and that is load-bearing.
//
// Whatever the documented middleware ordering, the measured behaviour
// in this config is that by the time this handler runs `req.url` has
// already been rewritten to "/index.html", while `originalUrl` still
// holds what the browser asked for. Logging both showed a request to
// /link arriving here as url="/index.html", originalUrl="/link".
// Which middleware performs that rewrite was not established, so this
// deliberately does not claim one.
//
// The practical warning: switching this to `req.url` type-checks,
// lints, runs, and silently never matches -- the dev server just keeps
// serving the home page with a 200. Re-verify against a running server
// if you change it, and use a control path (e.g. /linkxyz) to prove a
// 200 is not coming from the SPA fallback.
server.middlewares.use((req, res, next) => {
const requested = (req as { originalUrl?: string }).originalUrl;
if (!requested) return next();
// Decode before comparing, because nginx resolves percent-encoded
// bytes before exact `location =` matching but URL.pathname does
// not: "/link%2F" reaches production as /link/ and redirects, and
// would otherwise fall straight through here. The whole point of
// this plugin is that dev and production agree.
let pathname: string;
try {
pathname = decodeURIComponent(
new URL(requested, "http://x").pathname,
);
} catch {
// Malformed percent-encoding -- not our route; let Vite answer.
return next();
}
// Exact matches only, mirroring nginx's `location =`. A prefix match
// would swallow any future /link/* route.
if (pathname !== "/link" && pathname !== "/link/") return next();
res.writeHead(302, { Location: "/#steam-link" });
res.end();
});
},
};
}
// Dev-only stand-in for the nginx random-worker routing (the openfront_workers
// upstream). Forwards these prefix-less POSTs to a randomly chosen worker port
// so the worker can mint a self-owned id. Runs as direct middleware (before
// vite's /api proxy).
const RANDOM_WORKER_PATHS = ["/api/create_game", "/api/adminbot/create_game"];
function randomWorkerCreateProxy(numWorkers: number): Plugin {
return {
name: "random-worker-create-proxy",
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.method !== "POST") return next();
const path = (req.url ?? "").split("?")[0];
if (!RANDOM_WORKER_PATHS.includes(path)) return next();
const port = 3001 + Math.floor(Math.random() * numWorkers);
const proxyReq = http.request(
{
host: "localhost",
port,
path,
method: "POST",
headers: req.headers,
},
(proxyRes) => {
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
proxyRes.pipe(res);
},
);
proxyReq.on("error", (err) => {
res.statusCode = 502;
res.end(`create proxy error: ${err.message}`);
});
req.pipe(proxyReq);
});
},
};
}
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
const isProduction = mode === "production";
// Dev identity: the same INSTANCE_LETTER / NUM_WORKERS defaults the dev
// server boots with (ServerEnv), so the dev-served index.html carries the
// one-entry map production RenderHtml injects. The proxy below needs the
// worker count to know how many /wN paths to forward.
const devInstanceLetter = env.INSTANCE_LETTER || "a";
// Strict decimal first: Number() alone would take "1e3" or " 2".
const devNumWorkers = /^[1-9][0-9]*$/.test(env.NUM_WORKERS || "2")
? Number(env.NUM_WORKERS || 2)
: NaN;
// The same checks ServerEnv applies: the letter leads every game id, and
// the count feeds a modulo, so a bad value here is a wNaN worker path.
if (!/^[a-z]$/.test(devInstanceLetter)) {
throw new Error(
`INSTANCE_LETTER must be one lowercase letter, got ${JSON.stringify(devInstanceLetter)}`,
);
}
if (!Number.isInteger(devNumWorkers) || devNumWorkers < 1) {
throw new Error(
`NUM_WORKERS must be a positive integer, got ${JSON.stringify(env.NUM_WORKERS)}`,
);
}
const devClusterJson = JSON.stringify({
[devInstanceLetter]: { host: "localhost", numWorkers: devNumWorkers },
});
const resourcesDir = getResourcesDir(__dirname);
const proprietaryDir = getProprietaryDir(__dirname);
const sourceDirs = [resourcesDir, proprietaryDir];
const assetManifest: AssetManifest = isProduction
? buildPublicAssetManifest(sourceDirs)
: {};
const cdnBase = env.CDN_BASE ?? "";
const htmlAssetData = {
assetManifest: JSON.stringify(assetManifest),
cdnBase: JSON.stringify(cdnBase),
gameEnv: JSON.stringify(env.GAME_ENV ?? "dev"),
cluster: devClusterJson,
instanceLetter: JSON.stringify(devInstanceLetter),
turnstileSiteKey: JSON.stringify(
env.TURNSTILE_SITE_KEY ?? "1x00000000000000000000AA",
),
jwtAudience: JSON.stringify(env.DOMAIN ?? "localhost"),
// Dev only: set FARO_COLLECTOR_URL in .env to point a local client at a
// collector; unset drops the guarded line, exactly as in production.
faroCollectorUrl: env.FARO_COLLECTOR_URL
? JSON.stringify(env.FARO_COLLECTOR_URL)
: undefined,
instanceId: JSON.stringify(env.INSTANCE_ID ?? "DEV_ID"),
manifestHref: buildAssetUrl("manifest.json", assetManifest, cdnBase),
faviconHref: buildAssetUrl("images/Favicon.svg", assetManifest, cdnBase),
appleTouchIconHref: buildAssetUrl(
"icons/icon512_maskable.png",
assetManifest,
cdnBase,
),
gameplayScreenshotUrl: buildAssetUrl(
"images/KeyArt.jpg",
assetManifest,
cdnBase,
),
backgroundImageUrl: buildAssetUrl(
"images/background.webp",
assetManifest,
cdnBase,
),
desktopLogoImageUrl: buildAssetUrl(
"images/OpenFront.png",
assetManifest,
cdnBase,
),
mobileLogoImageUrl: buildAssetUrl("images/OF.png", assetManifest, cdnBase),
};
// Vite's HTML transform replaces the source <script src="/src/client/Main.ts">
// with the hashed bundle URL and injects <link rel="modulepreload"> /
// <link rel="stylesheet"> tags. rewriteAssetsForCdn rewrites those refs to
// an EJS placeholder so RenderHtml.ts can prefix them with CDN_BASE at
// request time.
const injectCdnBaseTemplate = (): Plugin => ({
name: "inject-cdn-base-template",
apply: "build" as const,
enforce: "post",
transformIndexHtml: rewriteAssetsForCdn,
});
let viteBundleFiles: string[] = [];
const syncHashedPublicAssets = (): Plugin => ({
name: "sync-hashed-public-assets",
apply: "build" as const,
writeBundle(_options, bundle) {
viteBundleFiles = Object.keys(bundle);
},
closeBundle() {
const outDir = path.join(__dirname, "static");
copyRootPublicFiles(getPublicDir(resourcesDir), outDir);
writeRootFilesIndex(getPublicDir(resourcesDir), outDir);
// Run the source→hashed copy first; createHashedPublicAssetFiles iterates
// assetManifest and expects every key to resolve to a file in resources/
// or proprietary/. Vite's bundle output (assets/...) doesn't, so it's
// merged in after.
createHashedPublicAssetFiles(sourceDirs, outDir, assetManifest);
// Track Vite's own bundle output (vendor chunks, JS, CSS, workers under
// static/assets/) in the manifest so the deploy-time R2 upload covers
// them alongside the hashed source assets. Skip non-assets/ emits like
// index.html — those are served by the app, not from R2.
for (const fileName of viteBundleFiles) {
if (!fileName.startsWith("assets/")) continue;
assetManifest[fileName] = `/${fileName}`;
}
writePublicAssetManifest(outDir, assetManifest);
},
});
// In dev, redirect visits to /w*/game/* and /w*/player/* to "/" so Vite
// serves the index.html. Only the /w<n> proxies below call this: a bare
// /player/<id> isn't proxied, so Vite's SPA fallback serves it the
// index.html already, as the master's fallback does in production.
const devGameHtmlBypass = (req?: {
url?: string;
method?: string;
headers?: { accept?: string | string[] };
}) => {
if (req?.method !== "GET") return undefined;
const accept = req.headers?.accept;
const acceptValue = Array.isArray(accept)
? accept.join(",")
: (accept ?? "");
if (!acceptValue.includes("text/html")) return undefined;
if (!req.url) return undefined;
if (/^\/w\d+\/(?:game|player)\/[^/]+/.test(req.url)) {
return "/";
}
return undefined;
};
return {
test: {
globals: true,
setupFiles: "./tests/setup.ts",
// Node 25 turned Web Storage on by default, where `localStorage` is a
// built-in global that evaluates to undefined unless --localstorage-file
// is passed. It shadows the jsdom localStorage vitest installs, so every
// test touching UserSettings dies on "Cannot read properties of
// undefined (reading 'getItem')". Turn Node's own Web Storage off in the
// test workers so jsdom always provides it. No-op on Node 24, which keeps
// Web Storage behind a flag.
execArgv: ["--no-experimental-webstorage"],
// Git worktrees live inside the repo, so their tests match the default
// glob and run against that worktree's own (often stale) source and
// node_modules. Anyone with a worktree checked out sees failures that
// have nothing to do with their branch.
// Spread the defaults rather than restating them: setting `exclude`
// replaces vitest's built-in list, and hand-copying a subset silently
// drops the dot-directory pattern (.git, .cache, .output, ...) --
// reintroducing the same stray-file problem this is here to fix.
exclude: [
...configDefaults.exclude,
"**/.worktrees/**",
"**/.claude/worktrees/**",
],
// Starting jsdom costs every file ~0.5s, more than many of them spend
// running tests, so only the client tests get it. A test elsewhere that
// needs a DOM opts in with a `// @vitest-environment jsdom` first line.
// vmThreads keeps jsdom loaded across files instead of importing it again
// in a fresh process for each one. Its window is the real jsdom window,
// though, whose location, top and window can't be redefined and whose
// crypto has no subtle, so tests that need those stay on the default pool.
projects: [
{
extends: true,
test: {
name: "client",
environment: "jsdom",
pool: "vmThreads",
include: ["tests/client/**/*.test.ts"],
exclude: clientForksTests,
},
},
{
extends: true,
test: {
name: "client-forks",
environment: "jsdom",
include: clientForksTests,
},
},
{
extends: true,
test: {
name: "node",
environment: "node",
exclude: ["tests/client/**", "tests/perf/**"],
},
},
{
extends: true,
test: {
name: "perf",
environment: "node",
include: ["tests/perf/**/*.test.ts"],
},
},
],
},
root: "./",
base: "/",
publicDir: isProduction ? false : "resources",
// Vite's JS preload helper (`__vitePreload`, used by dynamic import())
// resolves a chunk's dependency list against `base`, so with base "/" the
// helper chunks behind e.g. the lazy Faro import were requested from the
// page origin, where nothing serves /assets/ (openfront.io answered 503,
// and the import() rejected, so telemetry never started). Emitting those
// references relative makes the helper resolve them against
// import.meta.url, i.e. wherever the importing chunk itself was loaded
// from -- the CDN in production, same-origin in dev -- without baking
// CDN_BASE into the bundle (the Docker build does not have it). HTML keeps
// Vite's /assets/ refs so rewriteAssetsForCdn can turn them into the
// request-time EJS placeholder.
experimental: {
renderBuiltUrl(_filename, { hostType }) {
if (hostType === "js") return { relative: true };
return undefined;
},
},
resolve: {
tsconfigPaths: true,
alias: {
resources: path.resolve(__dirname, "resources"),
},
},
plugins: [
...(!isProduction
? [
serveRootPublicDir(getPublicDir(resourcesDir)),
serveProprietaryDir(proprietaryDir, resourcesDir),
randomWorkerCreateProxy(devNumWorkers),
steamLinkAliasRedirect(),
]
: []),
...(isProduction
? []
: [
createHtmlPlugin({
minify: false,
entry: "/src/client/Main.ts",
template: "index.html",
inject: {
data: {
gitCommit: JSON.stringify("DEV"),
...htmlAssetData,
},
},
}),
]),
...(isProduction
? [injectCdnBaseTemplate(), syncHashedPublicAssets()]
: []),
tailwindcss(),
],
define: {
__ASSET_MANIFEST__: JSON.stringify(assetManifest),
__LANG_COVERAGE__: JSON.stringify(
langCoverage(path.join(resourcesDir, "lang")),
),
"process.env.WEBSOCKET_URL": JSON.stringify(
isProduction ? "" : "localhost:3000",
),
"process.env.GAME_ENV": JSON.stringify(isProduction ? "prod" : "dev"),
// Force empty under vitest (mode "test") so the getApiBase localhost-
// fallback test is deterministic regardless of any API_DOMAIN in the
// host shell / CI environment.
"process.env.API_DOMAIN": JSON.stringify(
mode === "test" ? "" : (env.API_DOMAIN ?? ""),
),
// Add other process.env variables if needed, OR migrate code to import.meta.env
},
build: {
outDir: "static", // Webpack outputs to 'static', assuming we want to keep this.
emptyOutDir: true,
assetsDir: "assets", // Sub-directory for assets
rollupOptions: {
output: {
codeSplitting: {
groups: [
{
name: "vendor",
test: (id) =>
["howler", "zod"].some((module) => id.includes(module)),
priority: 2,
},
// Everything the page needs at startup stays in the entry
// chunk. Without this, a module shared by the entry and the
// lazily loaded screens (Lit, translateText, the cosmetics
// catalog, ...) can be split into chunks of its own, each one
// more request before the page can start, for no saving: the
// entry needs them all anyway.
{ name: "index", tags: ["$initial"], priority: 1 },
],
},
},
},
},
server: {
port: 9000,
strictPort: true,
host: process.env.VITE_HOST === "lan",
// Automatically open the browser when the server starts
open: process.env.SKIP_BROWSER_OPEN !== "true",
proxy: {
"/lobbies": {
target: "ws://localhost:3000",
ws: true,
changeOrigin: true,
},
// Worker proxies
"/w0": {
target: "ws://localhost:3001",
ws: true,
secure: false,
changeOrigin: true,
bypass: (req) => devGameHtmlBypass(req),
rewrite: (path) => path.replace(/^\/w0/, ""),
},
"/w1": {
target: "ws://localhost:3002",
ws: true,
secure: false,
changeOrigin: true,
bypass: (req) => devGameHtmlBypass(req),
rewrite: (path) => path.replace(/^\/w1/, ""),
},
// API proxies
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
secure: false,
},
},
},
};
});