import { z } from 'zod'; /** * Cache configuration */ interface CacheConfig { enabled: boolean; algorithm: 'lru' | 'lfu' | 'arc'; maxSize: number; maxBytes?: number; defaultTtl: number; staleWhileRevalidate?: boolean; staleThreshold?: number; enableTags?: boolean; } /** * Compression configuration */ interface CompressionConfig { enabled: boolean; threshold: number; preferredAlgorithms: Array<'gzip' | 'br' | 'zstd' | 'deflate'>; level?: number; compressRequest: boolean; requestTypes?: string[]; decompressResponse: boolean; } /** * Stream configuration */ interface StreamConfig { enableUploadProgress: boolean; uploadChunkSize?: number; enableDownloadProgress: boolean; downloadChunkSize?: number; enableResume: boolean; resumeHeader?: string; chunkTimeout?: number; } /** * Progress callback */ interface ProgressInfo { loaded: number; total: number; percentage: number; rate: number; estimated: number; } type ProgressCallback = (progress: ProgressInfo) => void; /** * Deduplication configuration */ interface DeduplicationConfig { enabled: boolean; windowMs: number; keyGenerator?: (request: Request) => string; storage: 'memory' | 'sharded' | 'custom'; customStorage?: unknown; allowedMethods?: Array<'GET' | 'HEAD' | 'OPTIONS' | 'PUT'>; varyHeaders?: string[]; includeAuthScope?: boolean; maxInFlightKeys?: number; maxSubscribersPerKey?: number; jitterPct?: number; shouldDedup?: (request: Request) => boolean; adaptive?: boolean; metrics?: { onEvent?: (evt: { type: 'hit' | 'miss' | 'reject' | 'subscribe'; key: string; subscribers?: number; }) => void; }; useNativeHash?: boolean; } /** * Security-related types and configurations */ /** * Request signing configuration (AWS Signature v4 style) */ interface SigningConfig { algorithm: 'HMAC-SHA256' | 'HMAC-SHA512'; accessKeyId: string; secretAccessKey: string; service: string; region: string; includeHeaders: string[]; includeQueryParams: boolean; clockSkewTolerance?: number; deriveSigningKey?: (secret: string, date: string, region: string, service: string) => Promise; } /** * OAuth 2.0 configuration */ interface OAuth2Config { type: 'client_credentials' | 'authorization_code' | 'password' | 'refresh_token'; tokenEndpoint: string; clientId: string; clientSecret?: string; scopes?: string[]; autoRefresh: boolean; refreshBuffer: number; usePKCE?: boolean; codeChallenge?: string; codeChallengeMethod?: 'S256' | 'plain'; tokenStorage?: TokenStorage; } /** * Token storage interface */ interface TokenStorage { getToken(): Promise; setToken(token: TokenInfo): Promise; clearToken(): Promise; } /** * Token information */ interface TokenInfo { accessToken: string; tokenType: string; expiresIn: number; expiresAt: number; refreshToken?: string; scope?: string; } /** * API Key configuration */ interface ApiKeyConfig { keyLocation: 'header' | 'query' | 'cookie'; keyName: string; keyValue: string | (() => string | Promise); rotation?: { enabled: boolean; gracePeriod: number; onRotate?: (newKey: string) => void | Promise; }; } /** * TLS/SSL configuration */ interface TLSConfig { pinning?: { enabled: boolean; pins: Array<{ hostname: string; fingerprints: string[]; algorithm: 'sha256' | 'sha512'; }>; validateChain: boolean; }; clientCert?: { cert: string | Buffer; key: string | Buffer; passphrase?: string; }; rejectUnauthorized?: boolean; ca?: string | Buffer | string[]; minVersion?: 'TLSv1.2' | 'TLSv1.3'; maxVersion?: 'TLSv1.2' | 'TLSv1.3'; ciphers?: string; } /** * SSRF protection configuration */ interface SSRFProtectionConfig { enabled: boolean; blockedHosts?: string[]; blockedPorts?: number[]; blockedIPs?: string[]; allowedHosts?: string[]; allowedSchemes?: Array<'http' | 'https'>; blockPrivateNetworks?: boolean; blockLoopback?: boolean; blockLinkLocal?: boolean; dnsRebindingProtection?: boolean; maxRedirects?: number; } /** * Secrets management configuration */ interface SecretsConfig { provider: 'env' | 'vault' | 'aws-secrets-manager' | 'custom'; vault?: { address: string; token: string; namespace?: string; path: string; }; aws?: { region: string; secretName: string; versionId?: string; }; custom?: { getSecret: (key: string) => Promise; }; rotation?: { enabled: boolean; checkInterval: number; onRotate?: (secrets: Record) => void | Promise; }; } /** * Genel security configuration */ interface SecurityConfig { signing?: SigningConfig; oauth?: OAuth2Config; apiKey?: ApiKeyConfig; tls?: TLSConfig; ssrf?: SSRFProtectionConfig; secrets?: SecretsConfig; } /** * Resilience patterns - Rate Limiting, Circuit Breaker, Retry */ /** * Rate limiting configuration */ interface RateLimitConfig { algorithm: 'token-bucket' | 'leaky-bucket' | 'fixed-window' | 'sliding-window'; maxRequests: number; windowMs: number; burst?: number; endpoints?: Record; backoff?: { type: 'exponential' | 'linear' | 'fibonacci'; initialDelay: number; maxDelay: number; jitter: boolean; }; queue?: { enabled: boolean; maxSize: number; strategy: 'fifo' | 'lifo' | 'priority'; timeout?: number; }; adaptive?: { enabled: boolean; initialRate: number; increaseRate: number; decreaseRate: number; minRate: number; maxRate: number; }; onRateLimited?: (endpoint: string, retryAfter: number) => void; onQueueFull?: (endpoint: string) => void; } /** * Retry configuration */ interface RetryConfig { maxAttempts: number; backoff: { type: 'exponential' | 'linear' | 'fibonacci' | 'decorrelated-jitter'; initialDelay: number; maxDelay: number; multiplier: number; jitter?: { enabled: boolean; type: 'full' | 'equal' | 'decorrelated'; }; }; retryOn: { statusCodes: number[]; networkErrors: boolean; timeoutErrors: boolean; idempotentOnly: boolean; shouldRetry?: (error: Error, attempt: number) => boolean; }; timeout?: { perAttempt: number; total: number; }; budget?: { enabled: boolean; maxRetryPercentage: number; windowMs: number; }; onRetry?: (error: Error, attempt: number, delay: number) => void; } /** * Circuit breaker configuration */ interface CircuitBreakerConfig { failureThreshold: number; successThreshold: number; timeout: number; windowSize: number; minimumRequests: number; states: { openOnFailureRate: boolean; openOnSlowCallRate: boolean; halfOpenMaxCalls: number; halfOpenSuccessThreshold: number; }; fallback?: { enabled: boolean; strategy: 'cache' | 'default-value' | 'custom'; customFallback?: (error: Error) => unknown; }; onStateChange?: (from: CircuitBreakerState, to: CircuitBreakerState) => void; onFailure?: (error: Error) => void; onSuccess?: () => void; } /** * Circuit breaker states */ type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN'; /** * Bulkhead configuration */ interface BulkheadConfig { maxConcurrent: number; maxQueued: number; services?: Record; onRejection: 'throw' | 'queue' | 'fallback'; type: 'semaphore' | 'thread-pool'; } /** * Genel resilience configuration */ interface ResilienceConfig { retry?: RetryConfig; circuitBreaker?: CircuitBreakerConfig; rateLimit?: RateLimitConfig; bulkhead?: BulkheadConfig; } /** * HTTP methods desteklenen methodlar */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'; /** * Request query parameters */ type QueryParams = Record; /** * Request headers */ type HeadersInit = Record | Headers; /** * Response types */ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'basic' | 'cors'; /** * Retry configuration */ interface RetryOptions { limit: number; delay: number | ((attempt: number) => number); statusCodes?: number[]; methods?: HttpMethod[]; maxDelay?: number; } /** * Cache configuration */ interface CacheOptions { ttl: number; methods?: HttpMethod[]; keyGenerator?: (request: Request) => string; shouldInvalidate?: (request: Request, cachedEntry: unknown) => boolean; } /** * Interceptor context */ interface InterceptorContext { request: string | URL; options: RequestOptions; } /** * Response interceptor context */ interface ResponseInterceptorContext { request: string | URL; options: RequestOptions; response: HttpResponse; } /** * Error interceptor context */ interface ErrorInterceptorContext { request: string | URL; options: RequestOptions; response: Response; error: Error; } /** * Interceptor functions */ type OnRequestInterceptor = (context: InterceptorContext) => void | Promise; type OnResponseInterceptor = (context: ResponseInterceptorContext) => T | Promise; type OnResponseErrorInterceptor = (context: ErrorInterceptorContext) => unknown | Promise; type OnRequestErrorInterceptor = (context: Pick) => void | Promise; /** * Hook functions */ interface Hooks { beforeRequest?: Array<(request: Request) => void | Promise>; beforeRetry?: Array<(context: RetryContext) => void | symbol | Promise>; afterResponse?: Array<(request: Request, options: RequestOptions, response: Response) => void | Promise>; beforeError?: Array<(error: HttpError) => HttpError | Promise>; } /** * Retry context for beforeRetry hook */ interface RetryContext { request: Request; options: RequestOptions; error: Error; retryCount: number; } /** * Request options */ interface RequestOptions { signal?: AbortSignal; credentials?: RequestCredentials; mode?: RequestMode; redirect?: RequestRedirect; referrer?: string; referrerPolicy?: ReferrerPolicy; integrity?: string; keepalive?: boolean; baseURL?: string; query?: QueryParams; headers?: HeadersInit; body?: unknown; timeout?: number; retry?: Partial | false; cache?: Partial | false; responseType?: ResponseType; throwHttpErrors?: boolean; onRequest?: OnRequestInterceptor | OnRequestInterceptor[]; onResponse?: OnResponseInterceptor | OnResponseInterceptor[]; onResponseError?: OnResponseErrorInterceptor | OnResponseErrorInterceptor[]; onRequestError?: OnRequestErrorInterceptor | OnRequestErrorInterceptor[]; hooks?: Hooks; schema?: z.ZodSchema; cacheConfig?: CacheConfig; compressionConfig?: CompressionConfig; streamConfig?: StreamConfig; deduplicationConfig?: DeduplicationConfig; onUploadProgress?: ProgressCallback; onDownloadProgress?: ProgressCallback; securityConfig?: SecurityConfig; resilienceConfig?: ResilienceConfig; dispatcher?: unknown; } /** * HTTP Response wrapper */ interface HttpResponse { _data: T; status: number; statusText: string; ok: boolean; headers: Headers; redirected: boolean; type: ResponseType; url: string; } /** * HTTP Error class interface */ interface HttpError extends Error { name: 'HttpError'; request: Request; response: Response; options: RequestOptions; status: number; statusText: string; data?: unknown; } export type { CacheOptions as C, DeduplicationConfig as D, ErrorInterceptorContext as E, HttpMethod as H, InterceptorContext as I, OnRequestInterceptor as O, ProgressInfo as P, QueryParams as Q, RequestOptions as R, StreamConfig as S, TLSConfig as T, HttpResponse as a, HeadersInit as b, ResponseType as c, RetryOptions as d, HttpError as e, ResponseInterceptorContext as f, OnResponseInterceptor as g, OnResponseErrorInterceptor as h, OnRequestErrorInterceptor as i, Hooks as j, RetryContext as k, CacheConfig as l, CompressionConfig as m, ProgressCallback as n, SecurityConfig as o, SigningConfig as p, OAuth2Config as q, SSRFProtectionConfig as r, SecretsConfig as s, ResilienceConfig as t, RetryConfig as u, RateLimitConfig as v, CircuitBreakerConfig as w };