/// <reference types="@fastly/js-compute" />

// List of header patterns (Unix shell style).
const HEADER_PATTERNS = [
  "fastly-debug-*",
  "x-goog-*",
  "x-github-*",
  "x-amz-*",
  "x-generator",
  "via",
];

// Define how the list above will be used – "allow" or "block".
const LIST_POLICY = "block";

// Transform the patterns into anchored regular expressions.
const headerRxList = HEADER_PATTERNS.map((globPattern) => {
  const rx = `^${globPattern.replace("*",".*")}$`;
  return new RegExp(rx, "i");
});

const handler = async (event) => {
  // Get the request from the client.
  const req = event.request;
  const backendResponse = await fetch(req, {
    backend: "origin_0"
  });

  for (const headerName of backendResponse.headers.keys()) {
    const headerMatchesPattern = headerRxList.some(rx => rx.test(headerName));
    if (
      (LIST_POLICY === "allow" && headerMatchesPattern)
      || (LIST_POLICY === "block" && !headerMatchesPattern)
    ) {
      continue;
    }
    backendResponse.headers.delete(headerName);
  }

  // Send the backend response back to the client.
  return backendResponse;
};

addEventListener("fetch", event => event.respondWith(handler(event)));