async function handleRequest(req) {
  // Load the url into a JavaScript URL object
  const url = new URL(req.url)

  // Get the response from the origin
  const backendResponse = await fetch(req, {
    backend: "origin_0"
  });

  // Load up the current Surrogate-Key value (if there is one)
  let keys = backendResponse.headers.get("Surrogate-Key") || ""

  // Check if the origin is sending back "immutable" in the Cache-Control header
  if (!/immutable/i.exec(backendResponse.headers.get("cache-control"))) {
    // Immutable not found, so add the "all" surrogate key
    keys += " all";
  }
  // Add the pathname as a surrogate key as well
  keys += " " + url.pathname;
  
  // Update the Surrogate-Key header with the new keys
  backendResponse.headers.set('Surrogate-Key', keys.trim());

  // Log the surrogate key
  console.log("Surrogate Keys: " + backendResponse.headers.get("Surrogate-Key"));

  return backendResponse;
}

addEventListener("fetch", (event) => event.respondWith(handleRequest(event.request)))