forked from mdn/fred
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
359 lines (320 loc) · 9.07 KB
/
Copy pathserver.js
File metadata and controls
359 lines (320 loc) · 9.07 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
import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { Worker } from "node:worker_threads";
import cookieParser from "cookie-parser";
import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
import openEditor from "open-editor";
import { FRED_BUILD_ROOT } from "./build/env.js";
import {
OPEN_BROWSER_ON_START,
PLAYGROUND_PORT,
PORT,
WRITER_MODE,
} from "./components/env/index.js";
import { handleRunner } from "./vendor/yari/libs/play/index.js";
import "source-map-support/register.js";
/**
* @import { Request, Response } from "express";
* @import { Stats } from "@rspack/core";
*/
let devMode = true;
/** @type {import("./build/render.js").render | undefined} */
let prodRender;
if (process.env.NODE_ENV === "production") {
devMode = false;
try {
const { render } = await import("./build/render.js");
prodRender = render;
} catch (error) {
throw typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === "ERR_MODULE_NOT_FOUND"
? new Error(
`can't find ${FRED_BUILD_ROOT}/ssr/index.js: did you forget to \`npm run build\`?`,
)
: error;
}
}
/**
* @param {Request} req
* @param {Response} res
* @param {import("@rari").BuiltPage} page
*/
async function serverRenderMiddleware(req, res, page) {
try {
let html;
/** @type {import("@fred").PartialContext} */
const context = {
localServer: true,
...page,
};
if (prodRender) {
// implies devMode === false
html = await prodRender(context);
} else {
/** @type {Stats} */
const stats = res.locals.webpack.devMiddleware.stats;
const compilationStats = stats.toJson().children;
if (!compilationStats) {
throw new Error("cannot parse the rspack config, did you modify it?");
}
html = await new Promise((resolve, reject) => {
// use worker so we have a fresh esm cache each page load
const worker = new Worker(
new URL("build/server-worker.js", import.meta.url),
{
/** @type {import("./build/types.js").WorkerData} */
workerData: {
reqPath: req.path,
context,
compilationStats,
},
},
);
worker.on("message", ({ html, error }) => {
error ? reject(error) : resolve(html);
});
});
}
res.writeHead(res.statusCode, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
console.error("SSR render error:", error);
res.writeHead(500).end();
}
}
/**
* @param {import("http").IncomingMessage} stream
* @returns {Promise<Buffer>}
*/
const streamToBuffer = (stream) =>
new Promise((resolve, reject) => {
/** @type {Buffer[]} */
const chunks = [];
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", reject);
});
export async function startServer() {
let app = express();
if (devMode) {
const { rspack } = await import("@rspack/core");
const { default: rspackConfig } = await import("./rspack.config.js");
const { default: webpackDevMiddleware } =
await import("webpack-dev-middleware");
const { default: webpackHotMiddleware } =
await import("webpack-hot-middleware");
const rspackCompiler = rspack(rspackConfig);
app.use(
// @ts-expect-error
webpackDevMiddleware(rspackCompiler, {
serverSideRender: true,
writeToDisk: true,
}),
);
// @ts-expect-error
app.use(webpackHotMiddleware(rspackCompiler));
} else {
const { default: compression } = await import("compression");
app.use(compression());
}
app.use("/", express.static(FRED_BUILD_ROOT));
app.get("/", async (_req, res, _next) => {
res.writeHead(302, {
Location: "/en-US/",
});
res.end();
});
const RUMBA_URL = process.env.RUMBA_URL;
app.all(
["/api/*_", "/users/*_"],
RUMBA_URL
? createProxyMiddleware({
target: RUMBA_URL,
changeOrigin: true,
proxyTimeout: 20_000,
timeout: 20_000,
headers: {
Connection: "keep-alive",
},
})
: (_req, res) => {
res.writeHead(502).end();
},
);
const CF_URL = process.env.CF_URL;
app.all(
["/pong/*_", "/pimg/*_"],
CF_URL
? createProxyMiddleware({
target: CF_URL,
changeOrigin: true,
proxyTimeout: 20_000,
timeout: 20_000,
headers: {
Connection: "keep-alive",
},
})
: (_req, res) => {
res.writeHead(502).end();
},
);
if (WRITER_MODE) {
app.get("/_open", async (req, _res) => {
const { filepath } = req.query;
const { CONTENT_ROOT, CONTENT_TRANSLATED_ROOT } = process.env;
if (typeof filepath === "string") {
const absolutePath = path.resolve(
(filepath.startsWith("en-us")
? CONTENT_ROOT
: CONTENT_TRANSLATED_ROOT) || "",
filepath,
);
openEditor([absolutePath]);
}
});
}
const RARI_URL = process.env.RARI_URL || "http://localhost:8083";
app.use(
createProxyMiddleware({
target: RARI_URL,
changeOrigin: true,
proxyTimeout: 20_000,
timeout: 20_000,
headers: {
Connection: "keep-alive",
},
selfHandleResponse: true,
on: {
proxyRes: async (proxyRes, req, res) => {
const contentType = proxyRes.headers["content-type"] || "";
const statusCode = proxyRes.statusCode || 500;
if (req.path === "/sandbox") {
return serverRenderMiddleware(req, res, {
// @ts-expect-error
renderer: "Sandbox",
pageTitle: "Fred sandbox",
});
}
if (
(!contentType || contentType.includes("text/plain")) &&
statusCode === 404
) {
// render 404 page
res.statusCode = 404;
const locale = req.url?.match(/[^/]+/)?.[0] ?? "en-us";
const notFoundRes = await fetch(
`http://localhost:8083/${locale}/404/index.json`,
);
const json = await notFoundRes.json();
return serverRenderMiddleware(req, res, json);
}
if (
!contentType.includes("application/json") ||
req.path.endsWith(".json")
) {
// stream assets
res.writeHead(statusCode, proxyRes.headers);
proxyRes.pipe(res);
return;
}
const buffer = await streamToBuffer(proxyRes);
const json = JSON.parse(buffer.toString("utf8"));
if ("renderer" in json) {
return serverRenderMiddleware(req, res, json);
}
res.writeHead(statusCode, proxyRes.headers);
res.end(buffer);
},
},
}),
);
let play = express();
play.use(cookieParser());
play.get(["/*_/runner.html", "/runner.html"], (req, res) => {
handleRunner(req, res);
});
play.get(
"/shared-assets/*_",
createProxyMiddleware({
target: "https://mdn.github.io/shared-assets/",
pathRewrite: {
"^/shared-assets/": "/",
},
changeOrigin: true,
autoRewrite: true,
xfwd: true,
}),
);
// live sample assets
play.use(
createProxyMiddleware({
target: RARI_URL,
changeOrigin: true,
proxyTimeout: 20_000,
timeout: 20_000,
headers: {
Connection: "keep-alive",
},
}),
);
let http2 = false;
if (process.env.HTTPS === "true") {
http2 = true;
// @ts-expect-error
const { default: spdy } = await import("spdy");
app = spdy.createServer(
{
key: await readFile(
process.env.HTTPS_CERT_FILE || "build/localhost-privkey.pem",
),
cert: await readFile(
process.env.HTTPS_KEY_FILE || "build/localhost-cert.pem",
),
},
app,
);
play = spdy.createServer(
{
key: await readFile(
process.env.HTTPS_CERT_FILE || "build/localhost-privkey.pem",
),
cert: await readFile(
process.env.HTTPS_KEY_FILE || "build/localhost-cert.pem",
),
},
play,
);
}
const httpServer = app.listen(PORT, () => {
const scheme = http2 ? "https" : "http";
const url = `${scheme}://localhost:${PORT}`;
console.log(`Server started at ${url}`);
// Auto open browser
if (OPEN_BROWSER_ON_START) {
const platform = process.platform;
const command =
platform === "win32"
? "start"
: platform === "darwin"
? "open"
: "xdg-open";
spawn(command, [url]);
}
});
const playServer = play.listen(PLAYGROUND_PORT, () => {
console.log(`Playground backend started on port ${PLAYGROUND_PORT}`);
});
return {
close: async () => {
httpServer.close();
playServer.close();
},
};
}
await startServer();