File size: 2,147 Bytes
6c75f16
 
ec01417
6c75f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97069a3
 
 
 
 
 
 
 
6c75f16
97069a3
 
 
 
 
6c75f16
 
97069a3
6c75f16
 
 
97069a3
 
 
 
 
 
 
 
6c75f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { join } from "path";

const publicDir = join(process.cwd(), "dist", "public");

export async function router(req: Request): Promise<Response> {
  const url = new URL(req.url);
  const pathname = url.pathname;

  if (pathname === "/health") {
    return new Response(JSON.stringify({ status: "ok" }), {
      headers: { "Content-Type": "application/json" },
    });
  }

  if (pathname.startsWith("/api/")) {
    return handleApiRequest(pathname);
  }

  return serveStatic(pathname);
}

async function handleApiRequest(pathname: string): Promise<Response> {
  if (pathname.startsWith("/api/session/")) {
    const sessionId = pathname.split("/").pop();
    return new Response(JSON.stringify({ sessionId, valid: true }), {
      headers: { "Content-Type": "application/json" },
    });
  }

  return new Response(JSON.stringify({ error: "Not found" }), {
    status: 404,
    headers: { "Content-Type": "application/json" },
  });
}

async function serveStatic(pathname: string): Promise<Response> {
  if (pathname === "/") {
    const indexPath = join(publicDir, "index.html");
    const file = Bun.file(indexPath);
    return new Response(file, {
      headers: { "Content-Type": "text/html" },
    });
  }

  const fullPath = join(publicDir, pathname);
  const file = Bun.file(fullPath);
  const exists = await file.exists();
  
  if (exists) {
    return new Response(file, {
      headers: {
        "Content-Type": getContentType(pathname),
      },
    });
  }

  const indexPath = join(publicDir, "index.html");
  const indexFile = Bun.file(indexPath);
  return new Response(indexFile, {
    headers: {
      "Content-Type": "text/html",
    },
  });
}

function getContentType(pathname: string): string {
  const ext = pathname.split(".").pop()?.toLowerCase();
  const contentTypes: Record<string, string> = {
    html: "text/html",
    css: "text/css",
    js: "application/javascript",
    json: "application/json",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    svg: "image/svg+xml",
    ico: "image/x-icon",
  };
  return contentTypes[ext || ""] || "application/octet-stream";
}