-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathvite.config.ts
More file actions
368 lines (352 loc) · 12.9 KB
/
Copy pathvite.config.ts
File metadata and controls
368 lines (352 loc) · 12.9 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
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 {
type AssetManifest,
buildAssetUrl,
rewriteAssetsForCdn,
} from "./src/core/AssetUrls";
import {
buildPublicAssetManifest,
copyRootPublicFiles,
createHashedPublicAssetFiles,
getProprietaryDir,
getResourcesDir,
writePublicAssetManifest,
} 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);
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";
const devNumWorkers = parseInt(env.NUM_WORKERS ?? "2", 10);
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"),
numWorkers: JSON.stringify(parseInt(env.NUM_WORKERS ?? "2", 10)),
turnstileSiteKey: JSON.stringify(
env.TURNSTILE_SITE_KEY ?? "1x00000000000000000000AA",
),
jwtAudience: JSON.stringify(env.DOMAIN ?? "localhost"),
instanceId: JSON.stringify(env.INSTANCE_ID ?? "DEV_ID"),
manifestHref: buildAssetUrl("manifest.json", assetManifest, cdnBase),
faviconHref: buildAssetUrl("images/Favicon.svg", assetManifest, cdnBase),
gameplayScreenshotUrl: buildAssetUrl(
"images/GameplayScreenshot.png",
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(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/* to "/" so Vite serves the index.html.
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\/[^/]+/.test(req.url)) {
return "/";
}
return undefined;
};
return {
test: {
globals: true,
environment: "jsdom",
setupFiles: "./tests/setup.ts",
},
root: "./",
base: "/",
publicDir: isProduction ? false : "resources",
resolve: {
tsconfigPaths: true,
alias: {
resources: path.resolve(__dirname, "resources"),
},
},
plugins: [
...(!isProduction
? [
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),
"process.env.WEBSOCKET_URL": JSON.stringify(
isProduction ? "" : "localhost:3000",
),
"process.env.GAME_ENV": JSON.stringify(isProduction ? "prod" : "dev"),
"process.env.STRIPE_PUBLISHABLE_KEY": JSON.stringify(
env.STRIPE_PUBLISHABLE_KEY,
),
// 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: {
manualChunks: (id) => {
const vendorModules = ["howler", "zod"];
if (vendorModules.some((module) => id.includes(module))) {
return "vendor";
}
},
},
},
},
server: {
port: 9000,
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,
},
},
},
};
});