"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var api_handler_exports = {};
__export(api_handler_exports, {
  createApiHandler: () => createApiHandler
});
module.exports = __toCommonJS(api_handler_exports);
var import_path_to_regexp = require("path-to-regexp");
var import_site_version = require("../api/site-version");
var import_redirect_live = require("./handlers/redirect-live");
var import_element_tree = require("./handlers/element-tree");
var import_fonts = require("./handlers/fonts");
var import_manifest = require("./handlers/manifest");
var import_merge_translated_data = require("./handlers/merge-translated-data");
var import_revalidate = require("./handlers/revalidate");
var import_translatable_data = require("./handlers/translatable-data");
var import_webhook = require("./handlers/webhook");
var import_request_response = require("./request-response");
var import_cors = require("./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"]] });
    (0, import_cors.applyCorsHeaders)(res.headers, {
      origin: appOrigin,
      allowedHeaders: ["Content-Type", "Authorization"]
    });
    return res;
  };
  async function apiRouteHandler(req, route) {
    const versionHeader = req.headers.get(import_site_version.ApiHandlerHeaders.SiteVersion);
    const siteVersion = versionHeader != null ? (0, import_site_version.deserializeSiteVersion)(versionHeader) : null;
    const matches = (pattern) => (0, import_path_to_regexp.match)(pattern, { decode: decodeURIComponent })(route);
    if (matches("/redirect-live"))
      return (0, import_redirect_live.redirectLiveHandler)(req, { previewCookieNames });
    if (matches("/element-tree"))
      return (0, import_element_tree.elementTreeHandler)(req, { runtime });
    if (matches("/fonts"))
      return (0, import_fonts.fontsHandler)(req, { getFonts });
    if (matches("/manifest"))
      return (0, import_manifest.manifestHandler)(req, { apiKey, manifest });
    if (matches("/merge-translated-data"))
      return (0, import_merge_translated_data.mergeTranslatedDataHandler)(req, { client });
    if (matches("/revalidate")) {
      return (0, import_revalidate.revalidateHandler)(req, { apiKey, revalidatePath: revalidationHandler });
    }
    if (matches("/translatable-data"))
      return (0, import_translatable_data.translatableDataHandler)(req, { client });
    if (matches("/webhook")) {
      return (0, import_webhook.webhookHandler)(req, { apiKey, events, revalidate: revalidationHandler });
    }
    const handleResource = (resource) => {
      return resource !== null ? import_request_response.ApiResponse.json(resource) : import_request_response.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 = (0, import_request_response.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 import_request_response.ApiResponse.json({ message: "Not Found" }, { status: 404 });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createApiHandler
});
//# sourceMappingURL=index.js.map