76 lines · 2.8 KB
import { env } from "cloudflare:workers";
import { contentType, decodePath, lookup, SECURITY_HEADERS } from "../pages/serve";
import { objectKey } from "../pages/config";
import { manifestKey } from "./config";
import type { SiteManifest } from "./config";

const MANIFEST_CACHE_SECONDS = 3600;
const HTTP_OK = 200;

export function plain(status: number, body: string, extra: Record<string, string> = {}): Response {
  return new Response(body, {
    status,
    headers: {
      ...SECURITY_HEADERS,
      "content-type": "text/plain; charset=utf-8",
      "cache-control": "no-store",
      ...extra,
    },
  });
}

export function html(status: number, body: string, extra: Record<string, string> = {}): Response {
  return new Response(body, {
    status,
    headers: {
      ...SECURITY_HEADERS,
      "content-type": "text/html; charset=utf-8",
      "cache-control": "no-store",
      "content-security-policy":
        "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
      ...extra,
    },
  });
}

export function loadManifest(deploymentId: string): Promise<SiteManifest | null> {
  return env.KV.get<SiteManifest>(manifestKey(deploymentId), { type: "json", cacheTtl: MANIFEST_CACHE_SECONDS });
}

/** Serves a static asset from a deployment's manifest; identical semantics to Pages. */