{"version":3,"sources":["../../../src/server/proxy/index.ts","../../../src/regions/endpoints.ts","../../../src/regions/resolver.ts","../../../src/server/proxy/proxy-base.ts","../../../src/server/proxy/rate-limiter.ts","../../../src/server/proxy/scope-guard.ts","../../../src/server/proxy/cma-proxy.ts","../../../src/server/proxy/launch-proxy.ts","../../../src/server/proxy/brandkit-proxy.ts","../../../src/server/proxy/developer-hub-proxy.ts"],"sourcesContent":["export type { CMAProxyConfig, CMAScope, ProxyAuthConfig, ProxyAuthHeaders } from \"./types.js\"\nexport { createCMAProxy } from \"./cma-proxy.js\"\nexport { resolveScope, checkScope } from \"./scope-guard.js\"\nexport type { LaunchProxyConfig } from \"./launch-proxy.js\"\nexport { createLaunchProxy } from \"./launch-proxy.js\"\nexport type { BrandKitProxyConfig } from \"./brandkit-proxy.js\"\nexport { createBrandKitProxy } from \"./brandkit-proxy.js\"\nexport type { DeveloperHubProxyConfig } from \"./developer-hub-proxy.js\"\nexport { createDeveloperHubProxy } from \"./developer-hub-proxy.js\"\n","import {\n  type ContentstackEndpoints as UpstreamEndpoints,\n  getContentstackEndpoints,\n  getRegionForString,\n} from \"@timbenniks/contentstack-endpoints\"\nimport type { ContentstackEndpoints, ContentstackRegion } from \"./resolver.js\"\n\n/** Brand Kit endpoints not available in upstream package — maintained locally */\nconst BRAND_KIT_URLS: Record<ContentstackRegion, { brandKit: string; brandKitAI: string }> = {\n  us: {\n    brandKit: \"https://brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://ai.contentstack.com/brand-kits\",\n  },\n  eu: {\n    brandKit: \"https://eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://eu-ai.contentstack.com/brand-kits\",\n  },\n  au: {\n    brandKit: \"https://au-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://au-ai.contentstack.com/brand-kits\",\n  },\n  \"azure-na\": {\n    brandKit: \"https://azure-na-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://azure-na-ai.contentstack.com/brand-kits\",\n  },\n  \"azure-eu\": {\n    brandKit: \"https://azure-eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://azure-eu-ai.contentstack.com/brand-kits\",\n  },\n  \"gcp-na\": {\n    brandKit: \"https://gcp-na-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://gcp-na-ai.contentstack.com/brand-kits\",\n  },\n  \"gcp-eu\": {\n    brandKit: \"https://gcp-eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://gcp-eu-ai.contentstack.com/brand-kits\",\n  },\n}\n\nfunction mapEndpoints(\n  upstream: UpstreamEndpoints,\n  region: ContentstackRegion,\n  hostsOnly: boolean,\n): ContentstackEndpoints {\n  const bk = BRAND_KIT_URLS[region]\n  const stripProtocol = (url: string) => url.replace(/^https?:\\/\\//, \"\")\n\n  return Object.freeze({\n    cma: upstream.contentManagement ?? \"\",\n    cda: upstream.contentDelivery ?? \"\",\n    graphql: upstream.graphqlDelivery ?? \"\",\n    images: upstream.images ?? \"\",\n    app: upstream.application ?? \"\",\n    preview: upstream.preview ?? \"\",\n    graphqlPreview: upstream.graphqlPreview ?? \"\",\n    launch: upstream.launch ?? \"\",\n    personalizeEdge: upstream.personalizeEdge ?? \"\",\n    brandKit: hostsOnly ? stripProtocol(bk.brandKit) : bk.brandKit,\n    brandKitAI: hostsOnly ? stripProtocol(bk.brandKitAI) : bk.brandKitAI,\n    developerHub: hostsOnly\n      ? stripProtocol(upstream.developerHub ?? \"\")\n      : (upstream.developerHub ?? \"\"),\n  })\n}\n\nconst ALL_REGIONS: ContentstackRegion[] = [\n  \"us\",\n  \"eu\",\n  \"au\",\n  \"azure-na\",\n  \"azure-eu\",\n  \"gcp-na\",\n  \"gcp-eu\",\n]\n\nfunction buildEndpointMap(): Record<ContentstackRegion, ContentstackEndpoints> {\n  const map = {} as Record<ContentstackRegion, ContentstackEndpoints>\n  for (const region of ALL_REGIONS) {\n    map[region] = mapEndpoints(getContentstackEndpoints(region), region, false)\n  }\n  return Object.freeze(map)\n}\n\nfunction buildHostMap(): Record<ContentstackRegion, ContentstackEndpoints> {\n  const map = {} as Record<ContentstackRegion, ContentstackEndpoints>\n  for (const region of ALL_REGIONS) {\n    map[region] = mapEndpoints(getContentstackEndpoints(region, true), region, true)\n  }\n  return Object.freeze(map)\n}\n\nexport const ENDPOINT_MAP = buildEndpointMap()\nexport const HOST_MAP = buildHostMap()\n\n/** Check if a string is a valid region via the upstream package */\nexport function isValidRegion(input: string): boolean {\n  return getRegionForString(input) !== undefined\n}\n\n/** Map of extra aliases our SDK supports beyond what the upstream package handles */\nexport const EXTRA_ALIASES: Record<string, ContentstackRegion> = {\n  \"north-america\": \"us\",\n  europe: \"eu\",\n  australia: \"au\",\n}\n","import { ContentstackConfigError } from \"../http/errors.js\"\nimport { ENDPOINT_MAP, EXTRA_ALIASES, HOST_MAP, isValidRegion } from \"./endpoints.js\"\n\n/** All 7 Contentstack regions */\nexport type ContentstackRegion = \"us\" | \"eu\" | \"au\" | \"azure-na\" | \"azure-eu\" | \"gcp-na\" | \"gcp-eu\"\n\n/** Resolved endpoint URLs for a region */\nexport interface ContentstackEndpoints {\n  /** CMA base URL, e.g. \"https://api.contentstack.io\" */\n  cma: string\n  /** CDA REST base URL, e.g. \"https://cdn.contentstack.io\" */\n  cda: string\n  /** GraphQL CDA endpoint */\n  graphql: string\n  /** Asset/image delivery base URL */\n  images: string\n  /** Application URL (for OAuth), e.g. \"https://app.contentstack.com\" */\n  app: string\n  /** Preview API base URL */\n  preview: string\n  /** GraphQL preview endpoint */\n  graphqlPreview: string\n  /** Launch API base URL */\n  launch: string\n  /** Personalize edge endpoint */\n  personalizeEdge: string\n  /** Brand Kit Management API base URL */\n  brandKit: string\n  /** Brand Kit GenAI and Knowledge Vault base URL */\n  brandKitAI: string\n  /** Developer Hub (Marketplace) API base URL */\n  developerHub: string\n}\n\nconst VALID_REGIONS = new Set<string>(Object.keys(ENDPOINT_MAP))\n\n/**\n * Resolve all API endpoints for a Contentstack region.\n *\n * @example\n * ```ts\n * const endpoints = resolveEndpoints(\"eu\");\n * // endpoints.cma === \"https://eu-api.contentstack.com\"\n * // endpoints.app === \"https://eu-app.contentstack.com\"\n * ```\n */\nexport function resolveEndpoints(region: ContentstackRegion): ContentstackEndpoints {\n  return ENDPOINT_MAP[region]\n}\n\n/**\n * Resolve endpoints with https:// stripped (for SDK host parameters).\n *\n * @example\n * ```ts\n * const hosts = resolveHosts(\"eu\");\n * // hosts.cda === \"eu-cdn.contentstack.com\"\n * ```\n */\nexport function resolveHosts(region: ContentstackRegion): ContentstackEndpoints {\n  return HOST_MAP[region]\n}\n\n/**\n * Normalize region aliases: \"na\" → \"us\", \"NA\" → \"us\", etc.\n * Case-insensitive. Throws ContentstackConfigError for unknown regions.\n */\nexport function normalizeRegion(input: string): ContentstackRegion {\n  const lower = input.toLowerCase().trim()\n\n  if (VALID_REGIONS.has(lower)) {\n    return lower as ContentstackRegion\n  }\n\n  // Check extra aliases our SDK supports (north-america, europe, australia)\n  const extraAlias = EXTRA_ALIASES[lower]\n  if (extraAlias) {\n    return extraAlias\n  }\n\n  // Check aliases handled by the upstream package (na, us, aws-na, etc.)\n  if (isValidRegion(lower)) {\n    // The upstream package recognized it — map back to our canonical region\n    // \"na\" and \"us\" both map to the NA region which we call \"us\"\n    if (lower === \"na\" || lower === \"aws-na\" || lower === \"aws_na\") return \"us\"\n    if (lower === \"aws-eu\" || lower === \"aws_eu\") return \"eu\"\n    if (lower === \"aws-au\" || lower === \"aws_au\") return \"au\"\n    if (lower === \"azure_na\") return \"azure-na\"\n    if (lower === \"azure_eu\") return \"azure-eu\"\n    if (lower === \"gcp_na\") return \"gcp-na\"\n    if (lower === \"gcp_eu\") return \"gcp-eu\"\n  }\n\n  const validRegions = [...VALID_REGIONS].join(\", \")\n  const validAliases = [...Object.keys(EXTRA_ALIASES), \"na\", \"aws-na\", \"aws-eu\", \"aws-au\"].join(\n    \", \",\n  )\n  throw new ContentstackConfigError(\n    `Unknown region \"${input}\". Valid regions: ${validRegions}. Aliases: ${validAliases}.`,\n  )\n}\n\nexport { ContentstackConfigError }\n","import type { ProxyAuthConfig, ProxyAuthHeaders } from \"./types.js\"\n\n/**\n * Shared proxy infrastructure for Contentstack API proxies.\n *\n * Both the CMA proxy and Launch proxy build on these helpers to avoid\n * duplicating auth checks, URL parsing, body extraction, and fetch logic.\n */\n\nexport type BaseProxyConfig = ProxyAuthConfig & {\n  basePath: string\n  timeout: number\n}\n\nexport interface ProxyRequestContext {\n  authHeaders: ProxyAuthHeaders\n  authKey: string\n  apiPath: string\n  search: string\n  method: string\n  body: ArrayBuffer | undefined\n  request: Request\n}\n\n/** Return a JSON error response with the given message and HTTP status. */\nexport function jsonErrorResponse(error: string, status: number): Response {\n  return new Response(JSON.stringify({ error }), {\n    status,\n    headers: { \"Content-Type\": \"application/json\" },\n  })\n}\n\nfunction normalizeAuthHeaders(headers: ProxyAuthHeaders): ProxyAuthHeaders {\n  return Object.fromEntries(\n    Object.entries(headers)\n      .map(([key, value]) => [key.toLowerCase(), value.trim()] as const)\n      .filter(([, value]) => value.length > 0),\n  )\n}\n\nfunction resolveAuthKey(headers: ProxyAuthHeaders): string | null {\n  const authorization = headers.authorization\n  if (authorization) {\n    return authorization\n  }\n\n  const authtoken = headers.authtoken\n  if (authtoken) {\n    return authtoken\n  }\n\n  const serialized = Object.entries(headers)\n    .sort(([left], [right]) => left.localeCompare(right))\n    .map(([key, value]) => `${key}:${value}`)\n    .join(\"|\")\n\n  return serialized.length > 0 ? serialized : null\n}\n\nasync function resolveRequestAuth(\n  config: BaseProxyConfig,\n  request: Request,\n): Promise<{ authHeaders: ProxyAuthHeaders; authKey: string } | null> {\n  if (config.getAuthHeaders) {\n    const authHeaders = normalizeAuthHeaders((await config.getAuthHeaders(request)) ?? {})\n    const authKey = resolveAuthKey(authHeaders)\n\n    if (!authKey) {\n      return null\n    }\n\n    return { authHeaders, authKey }\n  }\n\n  if (config.getAccessToken) {\n    const token = await config.getAccessToken(request)\n    if (!token) {\n      return null\n    }\n\n    return {\n      authHeaders: { authorization: `Bearer ${token}` },\n      authKey: token,\n    }\n  }\n\n  return null\n}\n\n/**\n * Create the shared proxy pipeline: auth check → URL parse → body extract.\n *\n * The `handleRequest` callback receives a validated context and is responsible\n * for building headers, constructing the target URL, and forwarding the request.\n */\nexport function createBaseProxy(\n  config: BaseProxyConfig,\n  handleRequest: (ctx: ProxyRequestContext) => Promise<Response>,\n): (request: Request) => Promise<Response> {\n  return async (request: Request): Promise<Response> => {\n    const auth = await resolveRequestAuth(config, request)\n    if (!auth) {\n      return jsonErrorResponse(\"Unauthorized\", 401)\n    }\n\n    const url = new URL(request.url)\n    const apiPath = url.pathname.replace(config.basePath, \"\")\n\n    const body =\n      [\"GET\", \"HEAD\"].includes(request.method) || request.body === null\n        ? undefined\n        : await request.arrayBuffer()\n\n    return handleRequest({\n      authHeaders: auth.authHeaders,\n      authKey: auth.authKey,\n      apiPath,\n      search: url.search,\n      method: request.method,\n      body,\n      request,\n    })\n  }\n}\n\n/**\n * Forward a request to an upstream API and stream the response back.\n *\n * Returns a 502 \"Bad Gateway\" response on any fetch failure (network error, timeout).\n */\nexport async function forwardRequest(\n  url: string,\n  method: string,\n  headers: Record<string, string>,\n  body: ArrayBuffer | undefined,\n  timeout: number,\n): Promise<Response> {\n  try {\n    const upstream = await fetch(url, {\n      method,\n      headers,\n      body,\n      signal: AbortSignal.timeout(timeout),\n    })\n\n    return new Response(upstream.body, {\n      status: upstream.status,\n      headers: {\n        \"content-type\": upstream.headers.get(\"content-type\") ?? \"application/json\",\n      },\n    })\n  } catch {\n    return jsonErrorResponse(\"Bad Gateway\", 502)\n  }\n}\n","interface RateWindow {\n  count: number\n  windowStart: number\n}\n\n/**\n * Create a simple in-memory sliding window rate limiter.\n *\n * Each unique key (typically an access token) gets its own counter\n * that resets after the window expires.\n *\n * @param maxRequests - Maximum requests allowed per window\n * @param windowMs - Window duration in milliseconds (default: 60000)\n */\nexport function createRateLimiter(maxRequests: number, windowMs = 60_000) {\n  const windows = new Map<string, RateWindow>()\n\n  return {\n    /**\n     * Check if the request is within rate limits.\n     * @returns `true` if the request is allowed, `false` if rate limited.\n     */\n    check(key: string): boolean {\n      const now = Date.now()\n      const window = windows.get(key)\n\n      // Clean stale entries on each check\n      for (const [k, w] of windows) {\n        if (now - w.windowStart > windowMs) {\n          windows.delete(k)\n        }\n      }\n\n      if (!window || now - window.windowStart > windowMs) {\n        windows.set(key, { count: 1, windowStart: now })\n        return true\n      }\n\n      window.count++\n      return window.count <= maxRequests\n    },\n  }\n}\n","import type { CMAScope } from \"./types.js\"\n\nconst READ_METHODS = new Set([\"GET\", \"HEAD\"])\n\n/**\n * Resolve the required CMA scope for a given HTTP method and path.\n *\n * Path matching checks for known segments. The order matters:\n * `/entries` is checked before `/content_types` because entry URLs\n * like `/content_types/blog/entries` contain both.\n *\n * @returns The required scope, or `null` if the path is unrecognized.\n */\nexport function resolveScope(method: string, path: string): CMAScope | null {\n  const isRead = READ_METHODS.has(method.toUpperCase())\n  const suffix = isRead ? \":read\" : \":write\"\n  const segments = path.split(\"/\")\n\n  if (segments.includes(\"entries\")) return `entries${suffix}` as CMAScope\n  if (segments.includes(\"content_types\")) return `content-types${suffix}` as CMAScope\n  if (segments.includes(\"assets\")) return `assets${suffix}` as CMAScope\n  if (segments.includes(\"environments\")) return \"environments:read\"\n  if (segments.includes(\"locales\")) return \"locales:read\"\n  if (segments.includes(\"releases\")) return `releases${suffix}` as CMAScope\n  if (segments.includes(\"taxonomies\")) return `taxonomies${suffix}` as CMAScope\n  if (segments.includes(\"workflows\")) return `workflows${suffix}` as CMAScope\n  if (segments.includes(\"webhooks\")) return `webhooks${suffix}` as CMAScope\n\n  return null\n}\n\n/**\n * Check whether a required scope is present in the allowed scopes list.\n *\n * @returns An error message if the scope is not allowed, or `null` if permitted.\n */\nexport function checkScope(required: CMAScope, allowed: CMAScope[]): string | null {\n  if (allowed.includes(required)) return null\n  return `Scope \"${required}\" is not allowed. Allowed scopes: ${allowed.join(\", \")}`\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport { createRateLimiter } from \"./rate-limiter.js\"\nimport { checkScope, resolveScope } from \"./scope-guard.js\"\nimport type { CMAProxyConfig } from \"./types.js\"\n\n/**\n * Create a CMA proxy handler that forwards requests to Contentstack.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/cma/[...path]/route.ts\n * const proxy = createCMAProxy({\n *   region: \"us\",\n *   apiKey: \"your-api-key\",\n *   getAccessToken: async (req) => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createCMAProxy(config: CMAProxyConfig): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const cmaBase = `${endpoints.cma}/v3`\n  const timeout = config.timeout ?? 30_000\n  const rateLimiter = config.rateLimit ? createRateLimiter(config.rateLimit) : null\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/cma\",\n      timeout,\n    },\n    async (ctx) => {\n      if (rateLimiter && !rateLimiter.check(ctx.authKey)) {\n        return jsonErrorResponse(\"Too Many Requests\", 429)\n      }\n\n      if (config.allowedScopes) {\n        const scope = resolveScope(ctx.method, ctx.apiPath)\n        if (!scope) {\n          if ((config.unmappedScopeBehavior ?? \"deny\") === \"deny\") {\n            return jsonErrorResponse(\n              `No scope mapping found for \"${ctx.method} ${ctx.apiPath}\". Add a mapping or set unmappedScopeBehavior: \"allow\".`,\n              403,\n            )\n          }\n        } else {\n          const rejection = checkScope(scope, config.allowedScopes)\n          if (rejection) {\n            return jsonErrorResponse(rejection, 403)\n          }\n        }\n      }\n\n      const headers: Record<string, string> = {\n        api_key: config.apiKey,\n        ...ctx.authHeaders,\n      }\n      const contentType = ctx.request.headers.get(\"content-type\")\n      if (contentType) {\n        headers[\"content-type\"] = contentType\n      }\n\n      return forwardRequest(\n        cmaBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type LaunchProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Launch API calls */\n  organizationUid: string\n  /** URL prefix to strip when extracting the Launch API path (default: \"/api/launch\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Launch API proxy handler that forwards requests to Contentstack Launch.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/launch/[...path]/route.ts\n * const proxy = createLaunchProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createLaunchProxy(\n  config: LaunchProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const launchBase = endpoints.launch\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/launch\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        \"content-type\": \"application/json\",\n      }\n\n      return forwardRequest(\n        launchBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type BrandKitProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Brand Kit API calls */\n  organizationUid: string\n  /** Brand Kit UID — required for all Brand Kit API calls */\n  brandKitUid: string\n  /** URL prefix to strip when extracting the API path (default: \"/api/brandkit\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Brand Kit proxy handler that forwards requests to Contentstack\n * Brand Kit Management, Knowledge Vault, and Generative AI APIs.\n *\n * Routes are determined by path:\n * - Paths containing `/knowledge-vault` or `/generative-ai` → brandKitAI base URL\n * - All other paths (brand kits, voice profiles) → brandKit base URL\n *\n * @example\n * ```ts\n * // app/api/brandkit/[...path]/route.ts\n * const proxy = createBrandKitProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   brandKitUid: \"bk-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createBrandKitProxy(\n  config: BrandKitProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const brandKitBase = endpoints.brandKit\n  const brandKitAIBase = endpoints.brandKitAI\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/brandkit\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        brand_kit_uid: config.brandKitUid,\n        \"content-type\": \"application/json\",\n      }\n\n      const isAIPath =\n        ctx.apiPath.includes(\"/knowledge-vault\") || ctx.apiPath.includes(\"/generative-ai\")\n      const baseUrl = isAIPath ? brandKitAIBase : brandKitBase\n\n      return forwardRequest(\n        baseUrl + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type DeveloperHubProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Developer Hub API calls */\n  organizationUid: string\n  /** URL prefix to strip when extracting the Developer Hub API path (default: \"/api/developerhub\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Developer Hub API proxy handler that forwards requests to Contentstack Developer Hub.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/developerhub/[...path]/route.ts\n * const proxy = createDeveloperHubProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createDeveloperHubProxy(\n  config: DeveloperHubProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const devHubBase = endpoints.developerHub\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/developerhub\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        \"content-type\": \"application/json\",\n      }\n\n      return forwardRequest(\n        devHubBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oCAIO;AAIP,IAAM,iBAAuF;AAAA,EAC3F,IAAI;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