@flow-conductor/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,674 @@
1
+ /**
2
+ * Handler function for processing errors that occur during request execution.
3
+ *
4
+ * @param error - The error that occurred
5
+ */
6
+ interface ErrorHandler {
7
+ (error: Error): void;
8
+ }
9
+ /**
10
+ * Handler function for processing successful request results.
11
+ *
12
+ * @template T - The type of result being handled
13
+ * @param result - The result to process
14
+ */
15
+ interface ResultHandler<T = unknown> {
16
+ (result: T): void;
17
+ }
18
+ /**
19
+ * Handler function for processing chunks of data as they arrive from streaming responses.
20
+ * This enables progressive processing of large responses without loading everything into memory.
21
+ *
22
+ * @template Chunk - The type of chunk data being processed
23
+ * @param chunk - The chunk of data to process
24
+ * @param metadata - Optional metadata about the chunk (index, total size, etc.)
25
+ * @returns A promise that resolves when chunk processing is complete (optional)
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * chunkHandler: async (chunk, metadata) => {
30
+ * console.log(`Processing chunk ${metadata.index}:`, chunk);
31
+ * await processChunk(chunk);
32
+ * }
33
+ * ```
34
+ */
35
+ interface ChunkHandler<Chunk = unknown> {
36
+ (chunk: Chunk, metadata?: {
37
+ index: number;
38
+ isLast: boolean;
39
+ totalBytesRead?: number;
40
+ }): void | Promise<void>;
41
+ }
42
+
43
+ /**
44
+ * Abstract base class for managing request pipelines and flows.
45
+ * Provides functionality for chaining requests, error handling, and result processing.
46
+ *
47
+ * @template Out - The output type of the request flow
48
+ * @template AdapterExecutionResult - The type of result returned by the adapter
49
+ * @template RequestConfig - The type of request configuration, must extend IRequestConfig
50
+ */
51
+ declare abstract class RequestFlow<Out, AdapterExecutionResult = Out, RequestConfig extends IRequestConfig = IRequestConfig> {
52
+ /**
53
+ * List of pipeline stages to execute
54
+ */
55
+ protected requestList: (PipelineRequestStage<any, any, any> | PipelineManagerStage<any, any, any>)[];
56
+ /**
57
+ * Optional error handler callback
58
+ */
59
+ protected errorHandler?: ErrorHandler;
60
+ /**
61
+ * Optional result handler callback
62
+ */
63
+ protected resultHandler?: ResultHandler<Out | Out[]>;
64
+ /**
65
+ * Optional finish handler callback executed after completion
66
+ */
67
+ protected finishHandler?: () => void;
68
+ /**
69
+ * The request adapter used to execute HTTP requests
70
+ */
71
+ protected adapter: RequestAdapter<AdapterExecutionResult, RequestConfig>;
72
+ /**
73
+ * Executes the request flow and returns the final result.
74
+ * Must be implemented by concrete subclasses.
75
+ *
76
+ * @returns A promise that resolves to the output result
77
+ */
78
+ abstract execute(): Promise<Out>;
79
+ /**
80
+ * Sets the request adapter to use for executing HTTP requests.
81
+ *
82
+ * @param adapter - The request adapter instance
83
+ * @returns The current RequestFlow instance for method chaining
84
+ */
85
+ setRequestAdapter(adapter: RequestAdapter<AdapterExecutionResult, RequestConfig>): RequestFlow<Out, AdapterExecutionResult, RequestConfig>;
86
+ /**
87
+ * Adds multiple pipeline stages to the request list.
88
+ *
89
+ * @param requestList - Array of pipeline stages to add
90
+ * @returns The current RequestFlow instance for method chaining
91
+ */
92
+ addAll(requestList?: Array<PipelineRequestStage<AdapterExecutionResult, Out, RequestConfig> | PipelineManagerStage<Out, AdapterExecutionResult, RequestConfig>>): RequestFlow<Out, AdapterExecutionResult, RequestConfig>;
93
+ /**
94
+ * Sets an error handler callback that will be called when an error occurs during execution.
95
+ *
96
+ * @param errorHandler - Function to handle errors
97
+ * @returns The current RequestFlow instance for method chaining
98
+ */
99
+ withErrorHandler(errorHandler: ErrorHandler): RequestFlow<Out, AdapterExecutionResult, RequestConfig>;
100
+ /**
101
+ * Sets a result handler callback that will be called with the execution result.
102
+ *
103
+ * @param resultHandler - Function to handle results
104
+ * @returns The current RequestFlow instance for method chaining
105
+ */
106
+ withResultHandler(resultHandler: ResultHandler<Out | Out[]>): RequestFlow<Out, AdapterExecutionResult, RequestConfig>;
107
+ /**
108
+ * Sets a finish handler callback that will be called after execution completes (success or failure).
109
+ *
110
+ * @param finishHandler - Function to execute on completion
111
+ * @returns The current RequestFlow instance for method chaining
112
+ */
113
+ withFinishHandler(finishHandler: () => void): RequestFlow<Out, AdapterExecutionResult, RequestConfig>;
114
+ }
115
+
116
+ /**
117
+ * Supported HTTP methods for requests
118
+ */
119
+ type HttpMethods = "GET" | "POST" | "PATCH" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "CONNECT" | "TRACE";
120
+ /**
121
+ * Base interface for HTTP request configuration.
122
+ * Extend this interface to add adapter-specific configuration options.
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * interface MyRequestConfig extends IRequestConfig {
127
+ * timeout?: number;
128
+ * retries?: number;
129
+ * }
130
+ * ```
131
+ */
132
+ interface IRequestConfig {
133
+ /** Optional request ID */
134
+ id?: string;
135
+ /** The URL to make the request to */
136
+ url: string;
137
+ /** The HTTP method to use */
138
+ method: HttpMethods;
139
+ /** Optional request body data */
140
+ data?: any;
141
+ /** Additional adapter-specific configuration options */
142
+ [key: string]: any;
143
+ }
144
+ /**
145
+ * Factory function type for creating request configurations dynamically based on previous results.
146
+ *
147
+ * @template Result - The type of the previous result
148
+ * @template AdapterRequestConfig - The type of request configuration to create
149
+ * @param previousResult - The result from the previous pipeline stage (optional)
150
+ * @returns The request configuration object
151
+ */
152
+ type IRequestConfigFactory<Result, AdapterRequestConfig extends IRequestConfig = IRequestConfig> = (previousResult?: Result) => AdapterRequestConfig;
153
+ /**
154
+ * Configuration for retry behavior when a request fails.
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * // Retry on network errors and 5xx status codes
159
+ * retry: {
160
+ * maxRetries: 3,
161
+ * retryDelay: 1000,
162
+ * exponentialBackoff: true,
163
+ * maxDelay: 10000,
164
+ * retryCondition: (error, attempt) => {
165
+ * // Retry on network errors
166
+ * if (error.name === 'TypeError' || error.name === 'NetworkError') {
167
+ * return true;
168
+ * }
169
+ * // Retry on 5xx and 429 status codes
170
+ * const status = getErrorStatus(error);
171
+ * return status !== undefined && (status >= 500 || status === 429);
172
+ * }
173
+ * }
174
+ * ```
175
+ */
176
+ interface RetryConfig {
177
+ /**
178
+ * Maximum number of retry attempts. Defaults to 3.
179
+ */
180
+ maxRetries?: number;
181
+ /**
182
+ * Delay between retries in milliseconds.
183
+ * Can be a fixed number or a function that calculates delay based on attempt number and error.
184
+ * Defaults to 1000ms.
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * // Fixed delay
189
+ * retryDelay: 2000
190
+ *
191
+ * // Custom delay function
192
+ * retryDelay: (attempt, error) => attempt * 1000
193
+ *
194
+ * // Exponential backoff (use exponentialBackoff: true instead)
195
+ * retryDelay: (attempt) => Math.min(1000 * Math.pow(2, attempt), 10000)
196
+ * ```
197
+ */
198
+ retryDelay?: number | ((attempt: number, error: Error) => number);
199
+ /**
200
+ * Whether to use exponential backoff for retry delays.
201
+ * When true, delays will be: delay * 2^attempt, capped at maxDelay if provided.
202
+ * Defaults to false.
203
+ */
204
+ exponentialBackoff?: boolean;
205
+ /**
206
+ * Maximum delay cap in milliseconds when using exponential backoff.
207
+ * Prevents delays from growing too large.
208
+ * Only applies when exponentialBackoff is true.
209
+ */
210
+ maxDelay?: number;
211
+ /**
212
+ * Function that determines whether to retry based on the error and attempt number.
213
+ * Return true to retry, false to stop retrying.
214
+ * If not provided, defaults to retrying on network errors only.
215
+ *
216
+ * @param error - The error that occurred
217
+ * @param attempt - The current attempt number (0-indexed, so first retry is attempt 1)
218
+ * @returns True if the request should be retried, false otherwise
219
+ */
220
+ retryCondition?: (error: Error, attempt: number) => boolean;
221
+ }
222
+ /**
223
+ * Base interface for pipeline stages.
224
+ * Defines common properties shared by all pipeline stage types.
225
+ *
226
+ * @template Result - The type of result from the stage
227
+ * @template Out - The output type after mapping (defaults to Result)
228
+ * @template PrevOut - The output type of the previous stage (defaults to Out for backward compatibility)
229
+ */
230
+ interface BasePipelineStage<Result, Out = Result, PrevOut = Out> {
231
+ /**
232
+ * Optional precondition function. If provided and returns false, the stage will be skipped.
233
+ */
234
+ precondition?: () => boolean;
235
+ /**
236
+ * The result produced by this stage (set after execution)
237
+ */
238
+ result?: Out;
239
+ /**
240
+ * Optional mapper function to transform the stage result.
241
+ * Can return a value or a promise.
242
+ * @param result - The result from the current stage
243
+ * @param prev - The result from the previous stage (undefined for the first stage)
244
+ */
245
+ mapper?: (result: Result, prev?: PrevOut) => Out | Promise<Out>;
246
+ /**
247
+ * Optional result interceptor function to process the stage result.
248
+ * Can be used to perform additional actions on the result.
249
+ * @param result - The result from the stage
250
+ */
251
+ resultInterceptor?: (result: Out) => void | Promise<void>;
252
+ /**
253
+ * Optional error handler function to process the stage error.
254
+ * Can be used to perform additional actions on the error.
255
+ * @param error - The error from the stage
256
+ */
257
+ errorHandler?: (error: Error) => void | Promise<void>;
258
+ }
259
+ /**
260
+ * Configuration for progressive chunk processing of streaming responses.
261
+ * Enables processing large responses incrementally without loading everything into memory.
262
+ *
263
+ * @example
264
+ * ```typescript
265
+ * chunkProcessing: {
266
+ * enabled: true,
267
+ * chunkHandler: async (chunk, metadata) => {
268
+ * console.log(`Chunk ${metadata.index}:`, chunk);
269
+ * await processChunk(chunk);
270
+ * },
271
+ * chunkSize: 1024, // Process in 1KB chunks
272
+ * encoding: 'utf-8'
273
+ * }
274
+ * ```
275
+ */
276
+ interface ChunkProcessingConfig<Chunk = string | Uint8Array> {
277
+ /**
278
+ * Whether chunk processing is enabled. Defaults to false.
279
+ * When enabled, the response body will be processed as a stream.
280
+ */
281
+ enabled: boolean;
282
+ /**
283
+ * Handler function called for each chunk as it arrives.
284
+ * Required when chunk processing is enabled.
285
+ */
286
+ chunkHandler: ChunkHandler<Chunk>;
287
+ /**
288
+ * Size of each chunk in bytes. Only applies to binary data.
289
+ * For text streams, chunks are delimited by newlines or the stream.
290
+ * Defaults to 8192 (8KB).
291
+ */
292
+ chunkSize?: number;
293
+ /**
294
+ * Text encoding for text-based streams. Defaults to 'utf-8'.
295
+ * Ignored for binary streams.
296
+ * Common values: 'utf-8', 'utf-16', 'ascii', etc.
297
+ */
298
+ encoding?: string;
299
+ /**
300
+ * Whether to accumulate chunks and return them as a complete result.
301
+ * When false, only the chunk handler is called and the final result may be empty.
302
+ * Defaults to false.
303
+ */
304
+ accumulate?: boolean;
305
+ }
306
+ /**
307
+ * Pipeline stage that executes an HTTP request using the adapter.
308
+ *
309
+ * @template Result - The type of result from the adapter
310
+ * @template Out - The output type after mapping (defaults to Result)
311
+ * @template AdapterRequestConfig - The type of request configuration
312
+ * @template PrevOut - The output type of the previous stage (defaults to Out for backward compatibility)
313
+ */
314
+ interface PipelineRequestStage<Result, Out = Result, AdapterRequestConfig extends IRequestConfig = IRequestConfig, PrevOut = Out> extends BasePipelineStage<Result, Out, PrevOut> {
315
+ /**
316
+ * Request configuration. Can be a static config object or a factory function
317
+ * that creates the config based on previous results.
318
+ */
319
+ config: AdapterRequestConfig | IRequestConfigFactory<PrevOut, AdapterRequestConfig>;
320
+ /**
321
+ * Optional retry configuration for handling request failures.
322
+ * Only applies to request stages, not nested manager stages.
323
+ */
324
+ retry?: RetryConfig;
325
+ /**
326
+ * Optional chunk processing configuration for progressive processing of streaming responses.
327
+ * Enables processing large responses incrementally without loading everything into memory.
328
+ * Only applies to request stages that support streaming (e.g., Fetch API with ReadableStream).
329
+ */
330
+ chunkProcessing?: ChunkProcessingConfig;
331
+ }
332
+ /**
333
+ * Pipeline stage that executes a nested request flow/chain.
334
+ *
335
+ * @template Out - The output type of the nested request flow
336
+ * @template AdapterExecutionResult - The type of result returned by the adapter
337
+ * @template AdapterRequestConfig - The type of request configuration
338
+ * @template PrevOut - The output type of the previous stage (defaults to Out for backward compatibility)
339
+ */
340
+ interface PipelineManagerStage<Out, AdapterExecutionResult, AdapterRequestConfig extends IRequestConfig = IRequestConfig, PrevOut = Out> extends BasePipelineStage<Out, Out, PrevOut> {
341
+ /**
342
+ * The nested request flow to execute
343
+ */
344
+ request: RequestFlow<Out, AdapterExecutionResult, AdapterRequestConfig>;
345
+ }
346
+
347
+ /**
348
+ * URL validation utilities to prevent SSRF (Server-Side Request Forgery) attacks
349
+ */
350
+ interface UrlValidationOptions {
351
+ /**
352
+ * Allow private/internal IP addresses (default: false)
353
+ * WARNING: Enabling this can expose your application to SSRF attacks
354
+ */
355
+ allowPrivateIPs?: boolean;
356
+ /**
357
+ * Allow localhost addresses (default: false)
358
+ * WARNING: Enabling this can expose your application to SSRF attacks
359
+ */
360
+ allowLocalhost?: boolean;
361
+ /**
362
+ * Custom list of allowed protocols (default: ['http:', 'https:'])
363
+ */
364
+ allowedProtocols?: string[];
365
+ /**
366
+ * Disable URL validation entirely (default: false)
367
+ * WARNING: This completely disables SSRF protection
368
+ */
369
+ disableValidation?: boolean;
370
+ }
371
+ declare class SSRFError extends Error {
372
+ constructor(message: string);
373
+ }
374
+ /**
375
+ * Validates a URL to prevent SSRF attacks
376
+ * @param url - The URL to validate
377
+ * @param options - Validation options
378
+ * @throws {SSRFError} If the URL is invalid or potentially dangerous
379
+ */
380
+ declare function validateUrl(url: string, options?: UrlValidationOptions): void;
381
+
382
+ /**
383
+ * Abstract base class for request adapters that handle HTTP requests.
384
+ * Provides URL validation and a common interface for different HTTP client implementations.
385
+ *
386
+ * @template ExecutionResult - The type of result returned by the adapter's HTTP client
387
+ * @template RequestConfig - The type of request configuration, must extend IRequestConfig
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * class MyAdapter extends RequestAdapter<Response> {
392
+ * async createRequest(config: IRequestConfig): Promise<Response> {
393
+ * // Implementation
394
+ * }
395
+ * }
396
+ * ```
397
+ */
398
+ declare abstract class RequestAdapter<ExecutionResult, RequestConfig extends IRequestConfig = IRequestConfig> {
399
+ /**
400
+ * URL validation options used to prevent SSRF attacks
401
+ */
402
+ protected urlValidationOptions: UrlValidationOptions;
403
+ /**
404
+ * Creates a new RequestAdapter instance.
405
+ *
406
+ * @param urlValidationOptions - Options for URL validation to prevent SSRF attacks
407
+ */
408
+ constructor(urlValidationOptions?: UrlValidationOptions);
409
+ /**
410
+ * Creates and executes an HTTP request using the adapter's underlying HTTP client.
411
+ * This method must be implemented by concrete adapter classes.
412
+ *
413
+ * @param requestConfig - The request configuration object
414
+ * @returns A promise that resolves to the execution result
415
+ */
416
+ abstract createRequest(requestConfig: RequestConfig): Promise<ExecutionResult>;
417
+ /**
418
+ * Type-safe getter for the execution result.
419
+ * Allows casting the result to a specific type.
420
+ *
421
+ * @template T - The desired result type
422
+ * @param result - The execution result to cast
423
+ * @returns The result cast to type T
424
+ */
425
+ getResult<T extends ExecutionResult>(result: ExecutionResult): T;
426
+ /**
427
+ * Executes a request with URL validation.
428
+ * Validates the URL to prevent SSRF attacks before creating the request.
429
+ *
430
+ * @param requestConfig - The request configuration object
431
+ * @returns A promise that resolves to the execution result
432
+ * @throws {SSRFError} If the URL is invalid or potentially dangerous
433
+ */
434
+ executeRequest(requestConfig: RequestConfig): Promise<ExecutionResult>;
435
+ }
436
+
437
+ /**
438
+ * A chainable request pipeline that allows sequential execution of HTTP requests.
439
+ * Each stage can depend on the result of the previous stage, and stages can be conditionally executed.
440
+ *
441
+ * @template Out - The output type of the current chain
442
+ * @template AdapterExecutionResult - The type of result returned by the adapter
443
+ * @template AdapterRequestConfig - The type of request configuration
444
+ * @template Types - Tuple type tracking all output types in the chain
445
+ *
446
+ * @example
447
+ * ```typescript
448
+ * const chain = RequestChain.begin(
449
+ * { config: { url: 'https://api.example.com/users', method: 'GET' } },
450
+ * adapter
451
+ * ).next({ config: { url: 'https://api.example.com/posts', method: 'GET' } });
452
+ *
453
+ * const result = await chain.execute();
454
+ * ```
455
+ */
456
+ declare class RequestChain<Out, AdapterExecutionResult = Out, AdapterRequestConfig extends IRequestConfig = IRequestConfig, Types extends readonly unknown[] = [Out]> extends RequestFlow<Out, AdapterExecutionResult, AdapterRequestConfig> {
457
+ /**
458
+ * Creates a new RequestChain with an initial stage.
459
+ * This is the entry point for building a request chain.
460
+ *
461
+ * @template Out - The output type of the initial stage
462
+ * @template AdapterExecutionResult - The type of result returned by the adapter
463
+ * @template AdapterRequestConfig - The type of request configuration
464
+ * @param stage - The initial pipeline stage (request or manager stage)
465
+ * @param adapter - The request adapter to use for HTTP requests
466
+ * @returns A new RequestChain instance with the initial stage
467
+ */
468
+ static begin: <Out_1, AdapterExecutionResult_1, AdapterRequestConfig_1 extends IRequestConfig = IRequestConfig>(stage: PipelineRequestStage<AdapterExecutionResult_1, Out_1, AdapterRequestConfig_1> | PipelineManagerStage<Out_1, AdapterExecutionResult_1, AdapterRequestConfig_1>, adapter: RequestAdapter<AdapterExecutionResult_1, AdapterRequestConfig_1>) => RequestChain<Out_1, AdapterExecutionResult_1, AdapterRequestConfig_1, [Out_1]>;
469
+ /**
470
+ * Adds a new stage to the request chain and returns a new chain with updated types.
471
+ * This method enables type-safe chaining of requests.
472
+ *
473
+ * @template NewOut - The output type of the new stage
474
+ * @param stage - The pipeline stage to add (request or manager stage)
475
+ * @returns A new RequestChain instance with the added stage
476
+ */
477
+ next: <NewOut>(stage: PipelineRequestStage<AdapterExecutionResult, NewOut, AdapterRequestConfig, Out> | PipelineManagerStage<NewOut, AdapterExecutionResult, AdapterRequestConfig, Out>) => RequestChain<NewOut, AdapterExecutionResult, AdapterRequestConfig, [...Types, NewOut]>;
478
+ /**
479
+ * Executes all stages in the chain sequentially and returns the final result.
480
+ * Handles errors and calls registered handlers appropriately.
481
+ *
482
+ * @returns A promise that resolves to the final output result
483
+ * @throws {Error} If an error occurs and no error handler is registered
484
+ */
485
+ execute: () => Promise<Out>;
486
+ /**
487
+ * Executes all stages in the chain and returns all results as a tuple.
488
+ * Useful when you need access to intermediate results.
489
+ *
490
+ * @returns A promise that resolves to a tuple of all stage results
491
+ * @throws {Error} If an error occurs and no error handler is registered
492
+ */
493
+ executeAll(): Promise<Types>;
494
+ /**
495
+ * Adds a request entity (stage) to the internal request list.
496
+ *
497
+ * @template NewOut - The output type of the new stage
498
+ * @param stage - The pipeline stage to add
499
+ * @returns A new RequestChain instance with updated types
500
+ */
501
+ private addRequestEntity;
502
+ /**
503
+ * Executes all request entities in sequence, handling preconditions and mappers.
504
+ * Stages with failed preconditions are skipped but preserve the previous result.
505
+ *
506
+ * @template Out - The output type
507
+ * @param requestEntityList - List of pipeline stages to execute
508
+ * @returns A promise that resolves to an array of all stage results
509
+ */
510
+ private executeAllRequests;
511
+ /**
512
+ * Executes a single request entity (stage).
513
+ * Handles both request stages and nested manager stages.
514
+ * Implements retry logic for request stages when retry configuration is provided.
515
+ * Supports progressive chunk processing for streaming responses.
516
+ *
517
+ * @template Out - The output type
518
+ * @param requestEntity - The pipeline stage to execute
519
+ * @param previousResult - The result from the previous stage (optional)
520
+ * @returns A promise that resolves to the stage result
521
+ * @throws {Error} If the stage type is unknown or all retries are exhausted
522
+ */
523
+ private executeSingle;
524
+ /**
525
+ * Executes a request with retry logic based on the provided retry configuration.
526
+ * Supports chunk processing for streaming responses.
527
+ *
528
+ * @template Out - The output type
529
+ * @param requestConfig - The request configuration
530
+ * @param retryConfig - The retry configuration
531
+ * @param chunkProcessing - Optional chunk processing configuration
532
+ * @returns A promise that resolves to the request result
533
+ * @throws {Error} If all retry attempts are exhausted
534
+ */
535
+ private executeWithRetry;
536
+ /**
537
+ * Processes a result with chunk processing if enabled.
538
+ * Handles streaming responses by processing chunks progressively.
539
+ *
540
+ * @template Out - The output type
541
+ * @param rawResult - The raw result from the adapter
542
+ * @param chunkProcessing - Optional chunk processing configuration
543
+ * @returns A promise that resolves to the processed result
544
+ */
545
+ private processResultWithChunks;
546
+ /**
547
+ * Calculates the delay before the next retry attempt.
548
+ *
549
+ * @param attempt - The current attempt number (1-indexed for retries)
550
+ * @param error - The error that occurred
551
+ * @param retryConfig - The retry configuration
552
+ * @returns The delay in milliseconds
553
+ */
554
+ private calculateRetryDelay;
555
+ /**
556
+ * Sleeps for the specified number of milliseconds.
557
+ *
558
+ * @param ms - Milliseconds to sleep
559
+ * @returns A promise that resolves after the delay
560
+ */
561
+ private sleep;
562
+ }
563
+ /**
564
+ * Creates a new RequestChain with an initial stage.
565
+ * This is a convenience function that wraps RequestChain.begin.
566
+ *
567
+ * @template Out - The output type of the initial stage
568
+ * @template AdapterExecutionResult - The type of result returned by the adapter
569
+ * @template AdapterRequestConfig - The type of request configuration
570
+ * @param stage - The initial pipeline stage (request or manager stage)
571
+ * @param adapter - The request adapter to use for HTTP requests
572
+ * @returns A new RequestChain instance with the initial stage
573
+ */
574
+ declare function begin<Out, AdapterExecutionResult, AdapterRequestConfig extends IRequestConfig = IRequestConfig>(stage: PipelineRequestStage<AdapterExecutionResult, Out, AdapterRequestConfig> | PipelineManagerStage<Out, AdapterExecutionResult, AdapterRequestConfig>, adapter: RequestAdapter<AdapterExecutionResult, AdapterRequestConfig>): RequestChain<Out, AdapterExecutionResult, AdapterRequestConfig, [Out]>;
575
+
576
+ /**
577
+ * Utility functions for retry logic and error handling.
578
+ */
579
+ /**
580
+ * Attempts to extract HTTP status code from an error object.
581
+ * Works with different adapter error formats (Axios, Fetch, etc.).
582
+ *
583
+ * @param error - The error object
584
+ * @returns The HTTP status code if available, undefined otherwise
585
+ */
586
+ declare function getErrorStatus(error: Error): number | undefined;
587
+ /**
588
+ * Checks if an error is a network error (connection failure, timeout, etc.).
589
+ *
590
+ * @param error - The error object
591
+ * @returns True if the error appears to be a network error
592
+ */
593
+ declare function isNetworkError(error: Error): boolean;
594
+ /**
595
+ * Default retry condition that retries on network errors.
596
+ * This is used when no retryCondition is provided in RetryConfig.
597
+ *
598
+ * @param error - The error that occurred
599
+ * @returns True if the error is a network error
600
+ */
601
+ declare function defaultRetryCondition(error: Error): boolean;
602
+ /**
603
+ * Helper function to create a retry condition that retries on specific HTTP status codes.
604
+ *
605
+ * @param statusCodes - Array of HTTP status codes to retry on
606
+ * @returns A retry condition function
607
+ *
608
+ * @example
609
+ * ```typescript
610
+ * retry: {
611
+ * retryCondition: retryOnStatusCodes(500, 502, 503, 504, 429)
612
+ * }
613
+ * ```
614
+ */
615
+ declare function retryOnStatusCodes(...statusCodes: number[]): (error: Error) => boolean;
616
+ /**
617
+ * Helper function to create a retry condition that retries on network errors OR specific status codes.
618
+ *
619
+ * @param statusCodes - Array of HTTP status codes to retry on
620
+ * @returns A retry condition function
621
+ *
622
+ * @example
623
+ * ```typescript
624
+ * retry: {
625
+ * retryCondition: retryOnNetworkOrStatusCodes(500, 502, 503, 504, 429)
626
+ * }
627
+ * ```
628
+ */
629
+ declare function retryOnNetworkOrStatusCodes(...statusCodes: number[]): (error: Error, attempt: number) => boolean;
630
+
631
+ /**
632
+ * Processes a ReadableStream progressively, calling the chunk handler for each chunk.
633
+ * Supports both text and binary streams.
634
+ *
635
+ * @template Chunk - The type of chunk data
636
+ * @param stream - The ReadableStream to process
637
+ * @param config - The chunk processing configuration
638
+ * @returns A promise that resolves when processing is complete, optionally with accumulated data
639
+ */
640
+ declare function processStream<Chunk = string | Uint8Array>(stream: ReadableStream<Uint8Array>, config: ChunkProcessingConfig<Chunk>): Promise<Chunk | undefined>;
641
+ /**
642
+ * Processes a text stream line by line (useful for NDJSON, CSV, or line-delimited data).
643
+ *
644
+ * @param stream - The ReadableStream to process
645
+ * @param config - The chunk processing configuration
646
+ * @returns A promise that resolves when processing is complete
647
+ */
648
+ declare function processTextStreamLineByLine(stream: ReadableStream<Uint8Array>, config: ChunkProcessingConfig<string>): Promise<string | undefined>;
649
+ /**
650
+ * Processes a Response body as a stream with chunk processing.
651
+ * Automatically detects if the response has a readable stream and processes it.
652
+ *
653
+ * @template Chunk - The type of chunk data
654
+ * @param response - The Response object
655
+ * @param config - The chunk processing configuration
656
+ * @returns A promise that resolves with the processed result or the original response
657
+ */
658
+ declare function processResponseStream<Chunk = string | Uint8Array>(response: Response, config: ChunkProcessingConfig<Chunk>): Promise<Response | Chunk>;
659
+ /**
660
+ * Checks if a value is a ReadableStream.
661
+ *
662
+ * @param value - The value to check
663
+ * @returns True if the value is a ReadableStream
664
+ */
665
+ declare function isReadableStream(value: unknown): value is ReadableStream<Uint8Array>;
666
+ /**
667
+ * Checks if a Response has a readable body stream.
668
+ *
669
+ * @param response - The Response to check
670
+ * @returns True if the response has a readable body stream
671
+ */
672
+ declare function hasReadableStream(response: Response): boolean;
673
+
674
+ export { type BasePipelineStage, type ChunkHandler, type ChunkProcessingConfig, type ErrorHandler, type IRequestConfig, type IRequestConfigFactory, type PipelineManagerStage, type PipelineRequestStage, RequestAdapter, RequestChain, RequestFlow as RequestManager, type ResultHandler, type RetryConfig, SSRFError, type UrlValidationOptions, begin, RequestChain as default, defaultRetryCondition, getErrorStatus, hasReadableStream, isNetworkError, isReadableStream, processResponseStream, processStream, processTextStreamLineByLine, retryOnNetworkOrStatusCodes, retryOnStatusCodes, validateUrl };