/** * API Gateway * * Enterprise-grade API gateway pattern implementation. * Provides a unified interface for API communication with * middleware support, request/response interception, and routing. * * @module api/advanced/api-gateway */ /** * HTTP methods supported by the gateway. */ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; /** * Request configuration for the gateway. */ export interface GatewayRequest { /** API endpoint path */ path: string; /** HTTP method */ method: HttpMethod; /** Request body */ body?: TBody; /** Query parameters */ params?: Record; /** Request headers */ headers?: Record; /** Request timeout in milliseconds */ timeout?: number; /** Whether to skip authentication */ skipAuth?: boolean; /** API version to use */ apiVersion?: string; /** Retry configuration */ retry?: RetryConfig; /** Cache configuration */ cache?: CacheConfig; /** Request metadata for middleware */ metadata?: Record; /** Abort signal for request cancellation */ signal?: AbortSignal; } /** * Response from the gateway. */ export interface GatewayResponse { /** Response data */ data: TData; /** HTTP status code */ status: number; /** Status text */ statusText: string; /** Response headers */ headers: Record; /** Request duration in milliseconds */ duration: number; /** Whether response was from cache */ fromCache?: boolean; /** Request metadata */ metadata?: Record; } /** * Gateway error structure. */ export interface GatewayError extends Error { /** Error code */ code: string; /** HTTP status code */ status?: number; /** Original response */ response?: GatewayResponse; /** Whether error is retryable */ retryable: boolean; /** Request that caused the error */ request?: GatewayRequest; } /** * Retry configuration. */ export interface RetryConfig { /** Maximum number of retries */ maxRetries: number; /** Initial delay in milliseconds */ initialDelay?: number; /** Maximum delay in milliseconds */ maxDelay?: number; /** Backoff multiplier */ backoffMultiplier?: number; /** Status codes to retry on */ retryStatusCodes?: number[]; /** Custom retry condition */ shouldRetry?: (error: GatewayError, attempt: number) => boolean; } /** * Cache configuration. */ export interface CacheConfig { /** Cache key (auto-generated if not provided) */ key?: string; /** Time-to-live in milliseconds */ ttl?: number; /** Whether to use stale-while-revalidate */ staleWhileRevalidate?: boolean; /** Cache storage type */ storage?: 'memory' | 'session' | 'local'; } /** * Middleware function type. */ export type GatewayMiddleware = (request: GatewayRequest, next: () => Promise) => Promise; /** * Request interceptor. */ export type RequestInterceptor = (request: GatewayRequest) => GatewayRequest | Promise; /** * Response interceptor. */ export type ResponseInterceptor = (response: GatewayResponse, request: GatewayRequest) => GatewayResponse | Promise>; /** * Error interceptor. */ export type ErrorInterceptor = (error: GatewayError, request: GatewayRequest) => GatewayError | Promise; /** * Gateway configuration. */ export interface GatewayConfig { /** Base URL for all requests */ baseUrl: string; /** Default timeout in milliseconds */ timeout?: number; /** Default headers for all requests */ defaultHeaders?: Record; /** Default API version */ defaultApiVersion?: string; /** Authentication token getter */ getAuthToken?: () => string | null | Promise; /** Default retry configuration */ defaultRetry?: RetryConfig; /** Request interceptors */ requestInterceptors?: RequestInterceptor[]; /** Response interceptors */ responseInterceptors?: ResponseInterceptor[]; /** Error interceptors */ errorInterceptors?: ErrorInterceptor[]; /** Middleware stack */ middleware?: GatewayMiddleware[]; /** Enable debug logging */ debug?: boolean; } /** * API Gateway for centralized API communication. * * Provides a unified interface for making API requests with support for * middleware, interceptors, retries, caching, and versioning. * * @example * ```typescript * const gateway = new APIGateway({ * baseUrl: 'https://api.example.com', * defaultApiVersion: 'v1', * getAuthToken: () => localStorage.getItem('token'), * }); * * // Add middleware * gateway.use(loggingMiddleware); * gateway.use(metricsMiddleware); * * // Make requests * const users = await gateway.get('/users'); * const user = await gateway.post('/users', { name: 'John' }); * ``` */ export declare class APIGateway { private config; private middleware; private requestInterceptors; private responseInterceptors; private errorInterceptors; private cache; /** * Create a new API Gateway instance. * * @param config - Gateway configuration */ constructor(config: GatewayConfig); /** * Make a GET request. */ get(path: string, options?: Partial>): Promise>; /** * Make a POST request. */ post(path: string, body?: B, options?: Partial, 'path' | 'method' | 'body'>>): Promise>; /** * Make a PUT request. */ put(path: string, body?: B, options?: Partial, 'path' | 'method' | 'body'>>): Promise>; /** * Make a PATCH request. */ patch(path: string, body?: B, options?: Partial, 'path' | 'method' | 'body'>>): Promise>; /** * Make a DELETE request. */ delete(path: string, options?: Partial>): Promise>; /** * Make an API request. */ request(request: GatewayRequest): Promise>; /** * Add middleware to the gateway. */ use(middleware: GatewayMiddleware): this; /** * Add a request interceptor. */ addRequestInterceptor(interceptor: RequestInterceptor): () => void; /** * Add a response interceptor. */ addResponseInterceptor(interceptor: ResponseInterceptor): () => void; /** * Add an error interceptor. */ addErrorInterceptor(interceptor: ErrorInterceptor): () => void; /** * Clear the cache. */ clearCache(pattern?: string): void; /** * Log debug message. * @internal Used for debug logging when config.debug is enabled */ protected log(message: string, ...args: unknown[]): void; /** * Execute the actual HTTP request. */ private executeRequest; /** * Fetch with retry logic. * * Note: This method intentionally uses raw fetch() because: * 1. The API Gateway IS the low-level HTTP layer that apiClient builds upon * 2. This provides the foundation for retry, routing, and error handling * 3. Using apiClient here would create circular dependencies * * Applications should use apiClient or this gateway, not raw fetch. * @see {@link @/lib/api/api-client} for the high-level API client */ private fetchWithRetry; /** * Build middleware chain. */ private buildMiddlewareChain; /** * Build the full request URL. */ private buildUrl; /** * Build request headers. */ private buildHeaders; /** * Get cached response. */ private getCachedResponse; /** * Cache a response. */ private cacheResponse; /** * Revalidate cached data in background. */ private revalidateCache; /** * Get cache key for a request. */ private getCacheKey; /** * Parse response based on content type. */ private parseResponse; /** * Parse response headers to plain object. */ private parseHeaders; /** * Normalize errors to GatewayError. */ private normalizeError; /** * Create error from response. */ private createErrorFromResponse; /** * Create a GatewayError. */ private createError; /** * Check if error is a GatewayError. */ private isGatewayError; /** * Check if request should be retried. */ private shouldRetry; /** * Calculate retry delay with exponential backoff. */ private calculateDelay; /** * Delay helper. */ private delay; /** * Merge multiple abort signals. */ private mergeAbortSignals; } /** * Create a new API Gateway instance. * * @param config - Gateway configuration * @returns Configured APIGateway */ export declare function createAPIGateway(config: GatewayConfig): APIGateway; /** * Logging middleware for debugging. */ export declare const loggingMiddleware: GatewayMiddleware; /** * Correlation ID middleware. */ export declare const correlationIdMiddleware: GatewayMiddleware;