| 21 | const runtimeCacheControl = "public, max-age=60, s-maxage=300"; |
| 22 | |
| 23 | export async function handleRequest(request: Request, env: Env, context: ExecutionContext): Promise<Response> { |
| 24 | let url = new URL(request.url); |
| 25 | |
| 26 | if (request.method === "OPTIONS") { |
| 27 | return new Response(null, { |
| 28 | headers: { |
| 29 | Allow: "GET, HEAD, OPTIONS, POST", |
| 30 | "Access-Control-Allow-Headers": "*", |
| 31 | "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS, POST", |
| 32 | "Access-Control-Allow-Origin": "*", |
| 33 | }, |
| 34 | }); |
| 35 | } |
| 36 | if (request.method !== "GET" && request.method !== "HEAD") { |
| 37 | return new Response(`Invalid request method: ${request.method}`, { |
| 38 | status: 405, |
| 39 | }); |
| 40 | } |
| 41 | |
| 42 | if (url.pathname === "/_health") { |
| 43 | return new Response("OK"); |
| 44 | } |
| 45 | |
| 46 | if (url.pathname === "/run") { |
| 47 | return new Response(createInlineRunner({ transformOrigin: env.ESM_ORIGIN }), { |
| 48 | headers: { |
| 49 | "Access-Control-Allow-Headers": "*", |
| 50 | "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS", |
| 51 | "Access-Control-Allow-Origin": "*", |
| 52 | "Access-Control-Expose-Headers": "*", |
| 53 | "Cache-Control": runtimeCacheControl, |
| 54 | "Content-Type": "application/javascript; charset=utf-8", |
| 55 | "Cross-Origin-Resource-Policy": "cross-origin", |
| 56 | }, |
| 57 | }); |
| 58 | } |
| 59 | |
| 60 | if (url.pathname === "/favicon.ico") { |
| 61 | return notFound(); |
| 62 | } |
| 63 | if (url.pathname === "/index.html") { |
| 64 | return redirect("/", 301); |
| 65 | } |
| 66 | if (url.pathname === "/") { |
| 67 | return renderPage(env, <Home esmOrigin={env.ESM_ORIGIN} origin={env.ORIGIN} />, { |
| 68 | headers: { |
| 69 | "Cache-Control": env.DEV ? "no-store" : "public, max-age=60, s-maxage=300", |
| 70 | }, |
| 71 | }); |
| 72 | } |
| 73 | |
| 74 | // Redirect legacy /browse/* URLs to the app's /files view |
| 75 | if (url.pathname.startsWith("/browse/")) { |
| 76 | let parsed = parsePackagePathname(url.pathname.slice(7)); |
| 77 | if (parsed) { |
| 78 | return redirect(new URL(filesPathname(parsed.package, parsed.version, parsed.filename), env.APP_ORIGIN), 301); |
| 79 | } |
| 80 | } |