-
Notifications
You must be signed in to change notification settings - Fork 109
/
index.ts
60 lines (60 loc) · 1.81 KB
/
index.ts
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
import fs from "node:fs";
import { createServer } from "node:http";
import type { Socket } from "node:net";
import path from "node:path";
import fastifyMiddie from "@fastify/middie";
import fastifyStatic from "@fastify/static";
// @ts-expect-error shut
import { server as wisp } from "@mercuryworkshop/wisp-js/server";
import { build } from "astro";
import Fastify from "fastify";
import inConfig from "./config";
const port = Number.parseInt(process.env.PORT as string) || inConfig.port || 8080;
const app = Fastify({
serverFactory: (handler) =>
createServer(handler).on("upgrade", (req, socket: Socket, head) =>
req.url?.startsWith("/f")
? wisp.routeRequest(req, socket, head)
: socket.destroy(),
),
});
if (!fs.existsSync("dist")) {
console.log("Interstellar's not built yet! Building now...");
await build({}).catch((err) => {
console.error(err);
process.exit(1);
});
}
await app.register(import("@fastify/compress"), {
encodings: ["br", "gzip", "deflate"],
});
if (inConfig.auth?.challenge) {
await app.register(import("@fastify/basic-auth"), {
authenticate: true,
validate(username, password, _req, _reply, done) {
for (const [user, pass] of Object.entries(inConfig.auth?.users || {})) {
if (username === user && password === pass) {
return done();
}
}
return done(new Error("Invalid credentials"));
},
});
await app.after();
app.addHook("onRequest", app.basicAuth);
}
// @ts-ignore
const { handler } = await import("./dist/server/entry.mjs");
await app
.register(fastifyStatic, {
root: path.join(import.meta.dirname, "dist", "client"),
})
.register(fastifyMiddie);
app.use(handler);
app.listen({ port }, (err, addr) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log("Listening on %s", addr);
});