stats-proxy.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { APIEvent } from "@solidjs/start/server"
  2. import { Resource } from "@opencode-ai/console-resource"
  3. const dataPath = "/data"
  4. export async function statsProxy(evt: APIEvent) {
  5. const req = evt.request.clone()
  6. const targetUrl = new URL(req.url)
  7. targetUrl.protocol = "https:"
  8. targetUrl.hostname = Resource.App.stage === "production" ? "stats.opencode.ai" : "stats.dev.opencode.ai"
  9. targetUrl.port = ""
  10. if (
  11. targetUrl.pathname.startsWith(`${dataPath}/_build/`) ||
  12. targetUrl.pathname === `${dataPath}/banner.jpg` ||
  13. targetUrl.pathname === `${dataPath}/banner.png`
  14. ) {
  15. targetUrl.pathname = targetUrl.pathname.slice(dataPath.length)
  16. }
  17. const response = await fetch(targetUrl, {
  18. method: req.method,
  19. headers: req.headers,
  20. body: req.body,
  21. })
  22. if (!response.headers.get("content-type")?.includes("text/html")) return response
  23. const headers = new Headers(response.headers)
  24. headers.delete("content-encoding")
  25. headers.delete("content-length")
  26. headers.delete("etag")
  27. return new Response(rewriteStatsHtml(await response.text()), {
  28. status: response.status,
  29. statusText: response.statusText,
  30. headers,
  31. })
  32. }
  33. export function statsRedirect(evt: APIEvent) {
  34. const url = new URL(evt.request.url)
  35. url.pathname = `${dataPath}${url.pathname.slice("/stats".length)}`
  36. return new Response(null, {
  37. status: 308,
  38. headers: {
  39. Location: url.toString(),
  40. },
  41. })
  42. }
  43. function rewriteStatsHtml(html: string) {
  44. return html.replaceAll('"/_build/', `"${dataPath}/_build/`).replaceAll("'/_build/", `'${dataPath}/_build/`)
  45. }