import { match as matchPattern } from "path-to-regexp";
import { ApiHandlerHeaders, deserializeSiteVersion } from "../api/site-version";
import { redirectLiveHandler } from "./handlers/redirect-live";
import { elementTreeHandler } from "./handlers/element-tree";
import { fontsHandler } from "./handlers/fonts";
import { manifestHandler } from "./handlers/manifest";
import { mergeTranslatedDataHandler } from "./handlers/merge-translated-data";
import { revalidateHandler } from "./handlers/revalidate";
import { translatableDataHandler } from "./handlers/translatable-data";
import { webhookHandler } from "./handlers/webhook";
import {
  ApiResponse,
  searchParams
} from "./request-response";
import { applyCorsHeaders } from "./cors";
function createApiHandler(apiKey, {
  runtime,
  appOrigin = "https://app.makeswift.com",
  getFonts,
  events,
  client,
  manifest,
  revalidationHandler,
  previewCookieNames
}) {
  if (typeof apiKey !== "string") {
    throw new Error(
      `The Makeswift API handler must be passed a valid Makeswift site API key. Received "${apiKey}" instead.`
    );
  }
  return async function(req, route) {
    const res = req.method.toUpperCase() !== "OPTIONS" ? await apiRouteHandler(req, route) : new Response(null, { status: 204, headers: [["Content-Length", "0"]] });
    applyCorsHeaders(res.headers, {
      origin: appOrigin,
      allowedHeaders: ["Content-Type", "Authorization"]
    });
    return res;
  };
  async function apiRouteHandler(req, route) {
    const versionHeader = req.headers.get(ApiHandlerHeaders.SiteVersion);
    const siteVersion = versionHeader != null ? deserializeSiteVersion(versionHeader) : null;
    const matches = (pattern) => matchPattern(pattern, { decode: decodeURIComponent })(route);
    if (matches("/redirect-live"))
      return redirectLiveHandler(req, { previewCookieNames });
    if (matches("/element-tree"))
      return elementTreeHandler(req, { runtime });
    if (matches("/fonts"))
      return fontsHandler(req, { getFonts });
    if (matches("/manifest"))
      return manifestHandler(req, { apiKey, manifest });
    if (matches("/merge-translated-data"))
      return mergeTranslatedDataHandler(req, { client });
    if (matches("/revalidate")) {
      return revalidateHandler(req, { apiKey, revalidatePath: revalidationHandler });
    }
    if (matches("/translatable-data"))
      return translatableDataHandler(req, { client });
    if (matches("/webhook")) {
      return webhookHandler(req, { apiKey, events, revalidate: revalidationHandler });
    }
    const handleResource = (resource) => {
      return resource !== null ? ApiResponse.json(resource) : ApiResponse.json({ message: "Not Found" }, { status: 404 });
    };
    let m;
    if (m = matches("/swatches/:id")) {
      return client.getSwatch(m.params.id, siteVersion).then(handleResource);
    }
    if (m = matches("/files/:id")) {
      return client.getFile(m.params.id).then(handleResource);
    }
    if (m = matches("/typographies/:id")) {
      return client.getTypography(m.params.id, siteVersion).then(handleResource);
    }
    if (m = matches("/global-elements/:id")) {
      return client.getGlobalElement(m.params.id, siteVersion).then(handleResource);
    }
    if (m = matches(
      "/localized-global-elements/:globalElementId/:locale"
    )) {
      return client.getLocalizedGlobalElement(m.params.globalElementId, m.params.locale, siteVersion).then(handleResource);
    }
    if (m = matches("/page-pathname-slices/:id")) {
      const localeParam = searchParams(req).get("locale");
      const locale = typeof localeParam === "string" ? localeParam : void 0;
      return client.getPagePathnameSlice(m.params.id, siteVersion, { locale }).then(handleResource);
    }
    if (m = matches("/tables/:id")) {
      return client.getTable(m.params.id).then(handleResource);
    }
    return ApiResponse.json({ message: "Not Found" }, { status: 404 });
  }
}
export {
  createApiHandler
};
//# sourceMappingURL=index.js.map