{"version":3,"file":"request-orchestrator.mjs","sources":["../../../../src/lib/api/advanced/request-orchestrator.ts"],"sourcesContent":["/**\n * Request Orchestrator\n *\n * Orchestrates complex API request patterns including parallel requests,\n * sequential chains, conditional execution, and dependency resolution.\n *\n * @module api/advanced/request-orchestrator\n */\n\nimport type { GatewayRequest, GatewayResponse } from './api-gateway';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Request definition for orchestration.\n */\nexport interface OrchestratedRequest<T = unknown> {\n  /** Unique request identifier */\n  id: string;\n  /** The request to execute */\n  request: GatewayRequest | (() => Promise<T>);\n  /** Dependencies (other request IDs that must complete first) */\n  dependsOn?: string[];\n  /** Transform the result before storing */\n  transform?: (result: T) => unknown;\n  /** Condition to determine if request should execute */\n  condition?: (results: Record<string, unknown>) => boolean;\n  /** Custom error handler */\n  onError?: (error: Error, results: Record<string, unknown>) => T | Promise<T>;\n  /** Priority (higher executes first when dependencies are equal) */\n  priority?: number;\n  /** Request metadata */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Orchestration result.\n */\nexport interface OrchestrationResult<T extends Record<string, unknown>> {\n  /** Whether all requests succeeded */\n  success: boolean;\n  /** Results keyed by request ID */\n  results: T;\n  /** Errors keyed by request ID */\n  errors: Record<string, Error>;\n  /** Execution order */\n  executionOrder: string[];\n  /** Total duration in milliseconds */\n  duration: number;\n  /** Individual request durations */\n  durations: Record<string, number>;\n}\n\n/**\n * Batch request configuration.\n */\nexport interface BatchConfig {\n  /** Maximum concurrent requests */\n  maxConcurrency?: number;\n  /** Stop on first error */\n  stopOnError?: boolean;\n  /** Delay between batches in milliseconds */\n  batchDelay?: number;\n  /** Timeout for entire batch in milliseconds */\n  timeout?: number;\n}\n\n/**\n * Chain configuration.\n */\nexport interface ChainConfig {\n  /** Stop chain on error */\n  stopOnError?: boolean;\n  /** Delay between requests in milliseconds */\n  delay?: number;\n  /** Pass result to next request */\n  passResult?: boolean;\n}\n\n/**\n * Waterfall step.\n */\nexport interface WaterfallStep<TInput, TOutput> {\n  /** Step identifier */\n  id: string;\n  /** Execute function */\n  execute: (input: TInput, context: WaterfallContext) => Promise<TOutput>;\n  /** Condition to skip step */\n  skip?: (input: TInput, context: WaterfallContext) => boolean;\n  /** Error handler */\n  onError?: (error: Error, input: TInput, context: WaterfallContext) => TOutput | Promise<TOutput>;\n}\n\n/**\n * Waterfall execution context.\n */\nexport interface WaterfallContext {\n  /** All results so far */\n  results: Record<string, unknown>;\n  /** Original input */\n  originalInput: unknown;\n  /** Metadata */\n  metadata: Record<string, unknown>;\n}\n\n// =============================================================================\n// Request Orchestrator Class\n// =============================================================================\n\n/**\n * Request Orchestrator for complex API request patterns.\n *\n * @example\n * ```typescript\n * const orchestrator = new RequestOrchestrator(apiGateway.request.bind(apiGateway));\n *\n * // Parallel requests\n * const results = await orchestrator.parallel([\n *   { path: '/users', method: 'GET' },\n *   { path: '/posts', method: 'GET' },\n *   { path: '/comments', method: 'GET' },\n * ]);\n *\n * // Dependent requests\n * const orchestrated = await orchestrator.orchestrate([\n *   { id: 'user', request: { path: '/users/1', method: 'GET' } },\n *   {\n *     id: 'posts',\n *     request: { path: '/posts?userId=1', method: 'GET' },\n *     dependsOn: ['user'],\n *   },\n * ]);\n * ```\n */\nexport class RequestOrchestrator {\n  private readonly executor: <T>(request: GatewayRequest) => Promise<GatewayResponse<T>>;\n\n  /**\n   * Create a new orchestrator.\n   *\n   * @param executor - Function to execute requests\n   */\n  constructor(executor: <T>(request: GatewayRequest) => Promise<GatewayResponse<T>>) {\n    this.executor = executor;\n  }\n\n  // ===========================================================================\n  // Parallel Execution\n  // ===========================================================================\n\n  /**\n   * Execute multiple requests in parallel.\n   *\n   * @param requests - Requests to execute\n   * @param config - Batch configuration\n   * @returns Array of results\n   */\n  async parallel<T = unknown>(\n    requests: GatewayRequest[],\n    config?: BatchConfig\n  ): Promise<GatewayResponse<T>[]> {\n    const maxConcurrency = config?.maxConcurrency ?? Infinity;\n    const stopOnError = config?.stopOnError ?? false;\n    const results: GatewayResponse<T>[] = [];\n    const errors: Error[] = [];\n\n    // Process in batches\n    for (let i = 0; i < requests.length; i += maxConcurrency) {\n      const batch = requests.slice(i, i + maxConcurrency);\n\n      const batchPromises = batch.map(async (request) => {\n        try {\n          return await this.executor<T>(request);\n        } catch (error) {\n          if (stopOnError) throw error;\n          errors.push(error as Error);\n          return null;\n        }\n      });\n\n      const batchResults = await Promise.all(batchPromises);\n      results.push(...batchResults.filter((r): r is GatewayResponse<T> => r !== null));\n\n      // Add delay between batches if configured\n      if ((config?.batchDelay != null && config.batchDelay > 0) && i + maxConcurrency < requests.length) {\n        await this.delay(config.batchDelay);\n      }\n    }\n\n    if (errors.length > 0 && stopOnError) {\n      const [firstError] = errors;\n      if (firstError instanceof Error) {\n        throw firstError;\n      }\n      throw new Error(String(firstError));\n    }\n\n    return results;\n  }\n\n  /**\n   * Execute requests in parallel, settling all regardless of errors.\n   *\n   * @param requests - Requests to execute\n   * @returns Results and errors\n   */\n  async allSettled<T = unknown>(\n    requests: GatewayRequest[]\n  ): Promise<{\n    fulfilled: GatewayResponse<T>[];\n    rejected: { request: GatewayRequest; error: Error }[];\n  }> {\n    const results = await Promise.allSettled(\n      requests.map(async request => this.executor<T>(request))\n    );\n\n    const fulfilled: GatewayResponse<T>[] = [];\n    const rejected: { request: GatewayRequest; error: Error }[] = [];\n\n    results.forEach((result, index) => {\n      if (result.status === 'fulfilled') {\n        fulfilled.push(result.value);\n      } else {\n        const request = requests[index];\n        if (request != null) {\n          rejected.push({ request, error: result.reason as Error });\n        }\n      }\n    });\n\n    return { fulfilled, rejected };\n  }\n\n  /**\n   * Race multiple requests, returning the first to complete.\n   *\n   * @param requests - Requests to race\n   * @returns First completed result\n   */\n  async race<T = unknown>(requests: GatewayRequest[]): Promise<GatewayResponse<T>> {\n    return Promise.race(requests.map(async request => this.executor<T>(request)));\n  }\n\n  // ===========================================================================\n  // Sequential Execution\n  // ===========================================================================\n\n  /**\n   * Execute requests sequentially.\n   *\n   * @param requests - Requests to execute in order\n   * @param config - Chain configuration\n   * @returns Array of results\n   */\n  async sequence<T = unknown>(\n    requests: GatewayRequest[],\n    config?: ChainConfig\n  ): Promise<GatewayResponse<T>[]> {\n    const results: GatewayResponse<T>[] = [];\n\n    for (const request of requests) {\n      try {\n        const result = await this.executor<T>(request);\n        results.push(result);\n\n        if (config?.delay !== undefined && config.delay > 0) {\n          await this.delay(config.delay);\n        }\n      } catch (error) {\n        if (config?.stopOnError !== false) {\n          throw error;\n        }\n      }\n    }\n\n    return results;\n  }\n\n  /**\n   * Execute a waterfall pattern where each step's output feeds the next.\n   *\n   * @param steps - Waterfall steps\n   * @param initialInput - Initial input to first step\n   * @returns Final result and all intermediate results\n   */\n  async waterfall<TInput, TOutput>(\n    steps: WaterfallStep<unknown, unknown>[],\n    initialInput: TInput\n  ): Promise<{ result: TOutput; results: Record<string, unknown> }> {\n    const context: WaterfallContext = {\n      results: {},\n      originalInput: initialInput,\n      metadata: {},\n    };\n\n    let currentInput: unknown = initialInput;\n\n    for (const step of steps) {\n      // Check skip condition\n      if ((step.skip?.(currentInput, context)) === true) {\n        continue;\n      }\n\n      try {\n        const result = await step.execute(currentInput, context);\n        context.results[step.id] = result;\n        currentInput = result;\n      } catch (error) {\n        if (step.onError) {\n          const recovered = await step.onError(error as Error, currentInput, context);\n          context.results[step.id] = recovered;\n          currentInput = recovered;\n        } else {\n          throw error;\n        }\n      }\n    }\n\n    return {\n      result: currentInput as TOutput,\n      results: context.results,\n    };\n  }\n\n  // ===========================================================================\n  // Dependency-Based Orchestration\n  // ===========================================================================\n\n  /**\n   * Orchestrate requests with dependencies.\n   *\n   * Requests are executed in optimal order based on their dependencies,\n   * maximizing parallelism while respecting dependency constraints.\n   *\n   * @param requests - Orchestrated requests\n   * @returns Orchestration result\n   */\n  async orchestrate<T extends Record<string, unknown>>(\n    requests: OrchestratedRequest[]\n  ): Promise<OrchestrationResult<T>> {\n    const startTime = Date.now();\n    const results: Record<string, unknown> = {};\n    const errors: Record<string, Error> = {};\n    const durations: Record<string, number> = {};\n    const executionOrder: string[] = [];\n\n    // Build dependency graph\n    const { levels, requestMap } = this.buildDependencyGraph(requests);\n\n    // Execute level by level\n    for (const level of levels) {\n      const levelRequests = level\n        .map(id => {\n          const req = requestMap.get(id);\n          if (req === undefined) {\n            throw new Error(`Request not found: ${id}`);\n          }\n          return req;\n        })\n        .filter(req => {\n          // Check condition\n          return !(req.condition !== undefined && !req.condition(results));\n\n        })\n        .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n      const levelPromises = levelRequests.map(async (req) => {\n        const reqStartTime = Date.now();\n\n        try {\n          let result: unknown;\n\n          if (typeof req.request === 'function') {\n            result = await req.request();\n          } else {\n            const response = await this.executor(req.request);\n            result = response.data;\n          }\n\n          if (req.transform) {\n            result = req.transform(result);\n          }\n\n          results[req.id] = result;\n          durations[req.id] = Date.now() - reqStartTime;\n          executionOrder.push(req.id);\n        } catch (error) {\n          if (req.onError) {\n            try {\n\n              results[req.id] = await req.onError(error as Error, results);\n              durations[req.id] = Date.now() - reqStartTime;\n              executionOrder.push(req.id);\n            } catch (recoveryError) {\n              errors[req.id] = recoveryError as Error;\n            }\n          } else {\n            errors[req.id] = error as Error;\n          }\n        }\n      });\n\n      await Promise.all(levelPromises);\n    }\n\n    return {\n      success: Object.keys(errors).length === 0,\n      results: results as T,\n      errors,\n      executionOrder,\n      duration: Date.now() - startTime,\n      durations,\n    };\n  }\n\n  /**\n   * Execute with fallback options.\n   *\n   * @param primary - Primary request\n   * @param fallbacks - Fallback requests in order of preference\n   * @returns First successful result\n   */\n  async withFallback<T = unknown>(\n    primary: GatewayRequest,\n    fallbacks: GatewayRequest[]\n  ): Promise<GatewayResponse<T>> {\n    const allRequests = [primary, ...fallbacks];\n\n    for (let i = 0; i < allRequests.length; i++) {\n      try {\n        const request = allRequests[i];\n        if (request === undefined) {\n          throw new Error('Request not found');\n        }\n        return await this.executor<T>(request);\n      } catch (error) {\n        if (i === allRequests.length - 1) {\n          throw error;\n        }\n      }\n    }\n\n    throw new Error('All requests failed');\n  }\n\n  // ===========================================================================\n  // Retry & Fallback Patterns\n  // ===========================================================================\n\n  /**\n   * Execute with retry and exponential backoff.\n   *\n   * @param request - Request to execute\n   * @param maxRetries - Maximum retry attempts\n   * @param baseDelay - Base delay in milliseconds\n   * @returns Response\n   */\n  async withRetry<T = unknown>(\n    request: GatewayRequest,\n    maxRetries = 3,\n    baseDelay = 1000\n  ): Promise<GatewayResponse<T>> {\n    let lastError: Error | null = null;\n\n    for (let attempt = 0; attempt <= maxRetries; attempt++) {\n      try {\n        return await this.executor<T>(request);\n      } catch (error) {\n        lastError = error as Error;\n\n        if (attempt < maxRetries) {\n          const delay = baseDelay * Math.pow(2, attempt);\n          await this.delay(delay);\n        }\n      }\n    }\n\n    throw lastError ?? new Error('Request failed after retries');\n  }\n\n  /**\n   * Execute with timeout.\n   *\n   * @param request - Request to execute\n   * @param timeout - Timeout in milliseconds\n   * @returns Response\n   */\n  async withTimeout<T = unknown>(\n    request: GatewayRequest,\n    timeout: number\n  ): Promise<GatewayResponse<T>> {\n    return Promise.race([\n      this.executor<T>(request),\n      new Promise<never>((_, reject) =>\n        setTimeout(() => reject(new Error('Request timeout')), timeout)\n      ),\n    ]);\n  }\n\n  /**\n   * Aggregate paginated results.\n   *\n   * @param baseRequest - Base request\n   * @param options - Pagination options\n   * @returns All aggregated results\n   */\n  async paginate<T = unknown>(\n    baseRequest: GatewayRequest,\n    options: {\n      /** Page parameter name */\n      pageParam?: string;\n      /** Limit parameter name */\n      limitParam?: string;\n      /** Items per page */\n      pageSize?: number;\n      /** Maximum pages to fetch */\n      maxPages?: number;\n      /** Extract items from response */\n      getItems?: (data: unknown) => T[];\n      /** Check if more pages exist */\n      hasMore?: (data: unknown, page: number) => boolean;\n    } = {}\n  ): Promise<T[]> {\n    const {\n      pageParam = 'page',\n      limitParam = 'limit',\n      pageSize = 100,\n      maxPages = 100,\n      getItems = (data: unknown) => (data as { items: T[] }).items ?? (data as T[]),\n      hasMore = (data: unknown) => getItems(data).length >= pageSize,\n    } = options;\n\n    const allItems: T[] = [];\n    let page = 1;\n\n    while (page <= maxPages) {\n      const request: GatewayRequest = {\n        ...baseRequest,\n        params: {\n          ...baseRequest.params,\n          [pageParam]: page,\n          [limitParam]: pageSize,\n        },\n      };\n\n      const response = await this.executor(request);\n      const items = getItems(response.data);\n      allItems.push(...items);\n\n      if (!hasMore(response.data, page)) {\n        break;\n      }\n\n      page++;\n    }\n\n    return allItems;\n  }\n\n  // ===========================================================================\n  // Aggregation Patterns\n  // ===========================================================================\n\n  /**\n   * Build dependency graph and determine execution levels.\n   */\n  private buildDependencyGraph(\n    requests: OrchestratedRequest[]\n  ): {\n    levels: string[][];\n    requestMap: Map<string, OrchestratedRequest>;\n  } {\n    const requestMap = new Map<string, OrchestratedRequest>();\n    const inDegree = new Map<string, number>();\n    const dependents = new Map<string, string[]>();\n\n    // Initialize\n    for (const req of requests) {\n      requestMap.set(req.id, req);\n      inDegree.set(req.id, 0);\n      dependents.set(req.id, []);\n    }\n\n    // Build graph\n    for (const req of requests) {\n      if (req.dependsOn) {\n        for (const dep of req.dependsOn) {\n          if (!requestMap.has(dep)) {\n            throw new Error(`Unknown dependency: ${dep}`);\n          }\n          inDegree.set(req.id, (inDegree.get(req.id) ?? 0) + 1);\n          const depList = dependents.get(dep);\n          if (depList !== undefined) {\n            depList.push(req.id);\n          }\n        }\n      }\n    }\n\n    // Topological sort with levels\n    const levels: string[][] = [];\n    const remaining = new Set(requests.map(r => r.id));\n\n    while (remaining.size > 0) {\n      const level: string[] = [];\n\n      for (const id of remaining) {\n        if (inDegree.get(id) === 0) {\n          level.push(id);\n        }\n      }\n\n      if (level.length === 0) {\n        throw new Error('Circular dependency detected');\n      }\n\n      levels.push(level);\n\n      for (const id of level) {\n        remaining.delete(id);\n        for (const dependent of dependents.get(id) ?? []) {\n          inDegree.set(dependent, (inDegree.get(dependent) ?? 1) - 1);\n        }\n      }\n    }\n\n    return { levels, requestMap };\n  }\n\n  // ===========================================================================\n  // Helper Methods\n  // ===========================================================================\n\n  /**\n   * Delay execution.\n   */\n  private async delay(ms: number): Promise<void> {\n    return new Promise(resolve => setTimeout(resolve, ms));\n  }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a new request orchestrator.\n *\n * @param executor - Request executor function\n * @returns RequestOrchestrator instance\n */\nexport function createRequestOrchestrator(\n  executor: <T>(request: GatewayRequest) => Promise<GatewayResponse<T>>\n): RequestOrchestrator {\n  return new RequestOrchestrator(executor);\n}\n"],"names":["RequestOrchestrator","executor","requests","config","maxConcurrency","stopOnError","results","errors","i","batchPromises","request","error","batchResults","r","firstError","fulfilled","rejected","result","index","steps","initialInput","context","currentInput","step","recovered","startTime","durations","executionOrder","levels","requestMap","level","levelPromises","id","req","b","reqStartTime","recoveryError","primary","fallbacks","allRequests","maxRetries","baseDelay","lastError","attempt","delay","timeout","_","reject","baseRequest","options","pageParam","limitParam","pageSize","maxPages","getItems","data","hasMore","allItems","page","response","items","inDegree","dependents","dep","depList","remaining","dependent","ms","resolve","createRequestOrchestrator"],"mappings":"AAwIO,MAAMA,EAAoB;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,YAAYC,GAAuE;AACjF,SAAK,WAAWA;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,SACJC,GACAC,GAC+B;AAC/B,UAAMC,IAAiBD,GAAQ,kBAAkB,OAC3CE,IAAcF,GAAQ,eAAe,IACrCG,IAAgC,CAAA,GAChCC,IAAkB,CAAA;AAGxB,aAASC,IAAI,GAAGA,IAAIN,EAAS,QAAQM,KAAKJ,GAAgB;AAGxD,YAAMK,IAFQP,EAAS,MAAMM,GAAGA,IAAIJ,CAAc,EAEtB,IAAI,OAAOM,MAAY;AACjD,YAAI;AACF,iBAAO,MAAM,KAAK,SAAYA,CAAO;AAAA,QAC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