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 request_exports = {};
__export(request_exports, {
  DEFAULT_REQUEST_TIMEOUT_MS: () => DEFAULT_REQUEST_TIMEOUT_MS,
  buildBrowserCredentialsInit: () => buildBrowserCredentialsInit,
  createBaseUrlResolver: () => createBaseUrlResolver,
  createRequestExecutor: () => createRequestExecutor,
  parseResponseBody: () => parseResponseBody,
  resolveRequestTimeoutMs: () => resolveRequestTimeoutMs,
  resolveUrl: () => resolveUrl
});
module.exports = __toCommonJS(request_exports);
const DEFAULT_REQUEST_TIMEOUT_MS = 15e3;
function resolveRequestTimeoutMs(value) {
  if (value === void 0) {
    return DEFAULT_REQUEST_TIMEOUT_MS;
  }
  const parsed = Number(value);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    throw new Error("invalid_api_request_timeout_ms");
  }
  return Math.floor(parsed);
}
function trimTrailingSlash(value) {
  return value.replace(/\/+$/, "");
}
function normalizeHostname(value) {
  return value.trim().toLowerCase();
}
function isLoopbackHostname(hostname) {
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0";
}
function resolvePlaydropSurface(hostname) {
  if (hostname === "playdrop.ai" || hostname === "www.playdrop.ai") {
    return "prod";
  }
  if (hostname === "preview.playdrop.ai") {
    return "preview";
  }
  if (hostname === "blue.playdrop.ai") {
    return "blue";
  }
  if (hostname === "green.playdrop.ai") {
    return "green";
  }
  return null;
}
function buildPlaydropApiOrigin(protocol, surface) {
  const host = surface === "prod" ? "api.playdrop.ai" : `api.${surface}.playdrop.ai`;
  return `${protocol}//${host}`;
}
function resolveBrowserApiBaseUrl() {
  const { protocol, hostname } = window.location;
  const normalizedProtocol = protocol === "https:" ? "https:" : "http:";
  const normalizedHostname = normalizeHostname(hostname);
  if (isLoopbackHostname(normalizedHostname)) {
    return "http://localhost:4000";
  }
  if (normalizedHostname === "www.localhost") {
    return `${normalizedProtocol}//api.localhost`;
  }
  if (normalizedHostname === "play.local") {
    return `${normalizedProtocol}//api.local`;
  }
  if (normalizedHostname.endsWith(".localhost")) {
    return `${normalizedProtocol}//api.${normalizedHostname.slice(0, -".localhost".length)}.localhost`;
  }
  if (normalizedHostname.endsWith(".local")) {
    return `${normalizedProtocol}//api.${normalizedHostname.slice(0, -".local".length)}.local`;
  }
  const playdropSurface = resolvePlaydropSurface(normalizedHostname);
  if (playdropSurface) {
    return buildPlaydropApiOrigin(normalizedProtocol, playdropSurface);
  }
  if (normalizedHostname.startsWith("www.") && normalizedHostname.includes(".")) {
    return `${normalizedProtocol}//api.${normalizedHostname.slice("www.".length)}`;
  }
  return `${normalizedProtocol}//${normalizedHostname}:4000`;
}
function createBaseUrlResolver(baseUrl) {
  return () => {
    if (baseUrl) {
      return baseUrl;
    }
    if (typeof window !== "undefined") {
      return resolveBrowserApiBaseUrl();
    }
    if (typeof process !== "undefined" && process.env["NEXT_PUBLIC_API_BASE"]) {
      return trimTrailingSlash(process.env["NEXT_PUBLIC_API_BASE"]);
    }
    return "http://localhost:4000";
  };
}
function resolveUrl(base, path) {
  if (/^https?:/i.test(path)) {
    return path;
  }
  const normalizedBase = base.endsWith("/") ? base : `${base}/`;
  const trimmedPath = path.startsWith("/") ? path.slice(1) : path;
  return new URL(trimmedPath, normalizedBase).toString();
}
function buildBrowserCredentialsInit(includeBrowserCredentials) {
  if (!includeBrowserCredentials || typeof window === "undefined") {
    return {};
  }
  return { credentials: "include" };
}
async function parseResponseBody(response) {
  if (response.status === 204 || response.status === 205 || response.status === 304) {
    return void 0;
  }
  const contentType = response.headers.get("content-type") || "";
  if (contentType.includes("application/json")) {
    try {
      return await response.clone().json();
    } catch {
    }
  }
  try {
    const text = await response.clone().text();
    return text;
  } catch {
    return void 0;
  }
}
function createRequestExecutor(input) {
  const { fetchImpl, resolveBaseUrl, resolveUrl: resolveUrlInput, parseResponseBody: parseResponseBodyInput, resolveToken, getClientHeaders, requestTimeoutMs, includeBrowserCredentials } = input;
  return async function request(req) {
    const base = resolveBaseUrl();
    const targetUrl = resolveUrlInput(base, req.path);
    const headers = new Headers();
    for (const [key, value] of Object.entries(getClientHeaders())) {
      headers.set(key, value);
    }
    headers.set("accept", "application/json");
    if (req.body !== void 0 && req.body !== null && req.method !== "GET") {
      headers.set("content-type", "application/json");
    }
    if (req.headers) {
      for (const [key, value] of Object.entries(req.headers)) {
        headers.set(key, value);
      }
    }
    const token = await resolveToken();
    if (token) {
      headers.set("authorization", `Bearer ${token}`);
    }
    const init = {
      method: req.method,
      headers,
      ...buildBrowserCredentialsInit(includeBrowserCredentials)
    };
    if (req.body !== void 0 && req.body !== null && req.method !== "GET") {
      init.body = typeof req.body === "string" ? req.body : JSON.stringify(req.body);
    }
    let timeoutHandle = null;
    let controller = null;
    if (typeof AbortController !== "undefined") {
      controller = new AbortController();
      init.signal = controller.signal;
      timeoutHandle = setTimeout(() => {
        controller?.abort();
      }, requestTimeoutMs);
    }
    try {
      const response = await fetchImpl(targetUrl, init);
      const parsed = await parseResponseBodyInput(response);
      return {
        status: response.status,
        body: parsed,
        headers: response.headers
      };
    } catch (error) {
      if (controller?.signal.aborted) {
        throw new Error(`api_request_timeout:${req.method}:${req.path}`);
      }
      throw error;
    } finally {
      if (timeoutHandle) {
        clearTimeout(timeoutHandle);
      }
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DEFAULT_REQUEST_TIMEOUT_MS,
  buildBrowserCredentialsInit,
  createBaseUrlResolver,
  createRequestExecutor,
  parseResponseBody,
  resolveRequestTimeoutMs,
  resolveUrl
});
