118 lines
3.6 KiB
TypeScript
118 lines
3.6 KiB
TypeScript
import { existsSync } from "node:fs";
|
|
import { dirname, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import Fastify from "fastify";
|
|
import cors from "@fastify/cors";
|
|
import cookie from "@fastify/cookie";
|
|
import fastifyStatic from "@fastify/static";
|
|
import websocket from "@fastify/websocket";
|
|
import { ZodError } from "zod";
|
|
import { config } from "./config.js";
|
|
import { openDb, ensureAdmin } from "./db.js";
|
|
import { hashPassword, registerAuthHook, registerAuthRoutes } from "./auth.js";
|
|
import { registerRoutes } from "./routes.js";
|
|
import { registerWs } from "./ws.js";
|
|
import { registerAdminRoutes } from "./admin.js";
|
|
|
|
/** A Fastify error carrying a status code and a serializable payload. */
|
|
export interface HttpError extends Error {
|
|
statusCode: number;
|
|
payload: object;
|
|
}
|
|
|
|
declare module "fastify" {
|
|
interface FastifyInstance {
|
|
/** Create a throwable HTTP error: `throw app.httpErrors.create(404, { error: "not_found" })`. */
|
|
httpErrors: { create(status: number, payload: object): HttpError };
|
|
}
|
|
}
|
|
|
|
function makeHttpError(status: number, payload: object): HttpError {
|
|
const e = new Error("http_error") as HttpError;
|
|
e.statusCode = status;
|
|
e.payload = payload;
|
|
return e;
|
|
}
|
|
|
|
export async function buildApp() {
|
|
const app = Fastify({ logger: true });
|
|
await app.register(cors, { origin: true, credentials: true });
|
|
await app.register(cookie);
|
|
await app.register(websocket);
|
|
|
|
const db = openDb();
|
|
app.decorate("db", db);
|
|
app.decorate("httpErrors", { create: makeHttpError });
|
|
await ensureAdmin(db, hashPassword);
|
|
|
|
// Serialize thrown errors into the API's `{ error: "code" }` shape.
|
|
app.setErrorHandler((err, _req, reply) => {
|
|
if (err instanceof ZodError) {
|
|
return reply.code(400).send({ error: "invalid_input", issues: err.issues });
|
|
}
|
|
const status = (err as HttpError).statusCode ?? 500;
|
|
const payload = (err as HttpError).payload ?? { error: "internal_error" };
|
|
return reply.code(status).send(payload);
|
|
});
|
|
|
|
app.get("/api/health", async () => {
|
|
let dbUp = false;
|
|
try {
|
|
dbUp = db.prepare("SELECT 1").get() != null;
|
|
} catch {
|
|
dbUp = false;
|
|
}
|
|
return { ok: dbUp, db: dbUp ? "up" : "down", version: config.version, uptime: process.uptime() };
|
|
});
|
|
|
|
registerAuthHook(app);
|
|
registerAuthRoutes(app);
|
|
registerRoutes(app);
|
|
registerAdminRoutes(app);
|
|
registerWs(app);
|
|
|
|
// Serve the built web app when apps/web/dist (or PUBSCRIPT_WEB_DIST) is present
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const webRoot =
|
|
process.env.PUBSCRIPT_WEB_DIST || resolve(here, "../../apps/web/dist");
|
|
if (existsSync(webRoot) && existsSync(resolve(webRoot, "index.html"))) {
|
|
await app.register(fastifyStatic, {
|
|
root: webRoot,
|
|
prefix: "/",
|
|
wildcard: false,
|
|
});
|
|
app.setNotFoundHandler((req, reply) => {
|
|
if (
|
|
req.method === "GET" &&
|
|
!req.url.startsWith("/api/") &&
|
|
!req.url.startsWith("/ws")
|
|
) {
|
|
return reply.sendFile("index.html");
|
|
}
|
|
return reply.code(404).send({ error: "not_found" });
|
|
});
|
|
}
|
|
|
|
return app;
|
|
}
|
|
|
|
export async function start() {
|
|
const app = await buildApp();
|
|
await app.listen({ port: config.port, host: "0.0.0.0" });
|
|
return app;
|
|
}
|
|
|
|
// Auto-boot only when this file is the CLI entry point (pnpm dev / start),
|
|
// not when imported by tests (vitest) — otherwise start() would try to bind
|
|
// the port and tear the test process down.
|
|
const invokedDirectly =
|
|
process.argv[1] !== undefined &&
|
|
fileURLToPath(import.meta.url) === process.argv[1];
|
|
|
|
if (invokedDirectly) {
|
|
start().catch((err) => {
|
|
console.error("Failed to start server:", err);
|
|
process.exit(1);
|
|
});
|
|
}
|