apienvelope 1.0.0 → 1.1.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.
package/dist/index.d.ts CHANGED
@@ -1,32 +1,19 @@
1
1
  import { Request, Response, NextFunction, RequestHandler, ErrorRequestHandler } from 'express';
2
2
 
3
- /**
4
- * Base response interface with common fields
5
- */
6
3
  interface BaseResponse {
7
4
  timestamp: string;
8
5
  meta?: ResponseMeta;
9
6
  }
10
- /**
11
- * Metadata that can be attached to any response
12
- */
13
7
  interface ResponseMeta {
14
8
  requestId?: string;
15
9
  correlationId?: string;
16
10
  userId?: string;
17
11
  [key: string]: unknown;
18
12
  }
19
- /**
20
- * Successful response structure
21
- * @template T - The type of the data payload
22
- */
23
13
  interface SuccessResponse<T = unknown> extends BaseResponse {
24
14
  success: true;
25
15
  data: T;
26
16
  }
27
- /**
28
- * Error details structure
29
- */
30
17
  interface ErrorDetails {
31
18
  code: string;
32
19
  message: string;
@@ -34,22 +21,13 @@ interface ErrorDetails {
34
21
  stack?: string;
35
22
  fields?: FieldErrors;
36
23
  }
37
- /**
38
- * Field-level validation errors
39
- */
40
24
  interface FieldErrors {
41
25
  [field: string]: string | string[];
42
26
  }
43
- /**
44
- * Error response structure
45
- */
46
27
  interface ErrorResponse extends BaseResponse {
47
28
  success: false;
48
29
  error: ErrorDetails;
49
30
  }
50
- /**
51
- * Pagination metadata
52
- */
53
31
  interface PaginationMeta {
54
32
  page: number;
55
33
  limit: number;
@@ -59,9 +37,6 @@ interface PaginationMeta {
59
37
  hasPreviousPage: boolean;
60
38
  links?: PaginationLinks;
61
39
  }
62
- /**
63
- * HATEOAS-style pagination links
64
- */
65
40
  interface PaginationLinks {
66
41
  self?: string;
67
42
  first?: string;
@@ -69,9 +44,6 @@ interface PaginationLinks {
69
44
  next?: string;
70
45
  previous?: string;
71
46
  }
72
- /**
73
- * Cursor-based pagination metadata
74
- */
75
47
  interface CursorPaginationMeta {
76
48
  limit: number;
77
49
  cursor?: string;
@@ -80,58 +52,24 @@ interface CursorPaginationMeta {
80
52
  hasMore: boolean;
81
53
  links?: PaginationLinks;
82
54
  }
83
- /**
84
- * Paginated response structure (offset-based)
85
- * @template T - The type of items in the data array
86
- */
87
55
  interface PaginatedResponse<T = unknown> extends BaseResponse {
88
56
  success: true;
89
57
  data: T[];
90
58
  pagination: PaginationMeta;
91
59
  }
92
- /**
93
- * Cursor-paginated response structure
94
- * @template T - The type of items in the data array
95
- */
96
60
  interface CursorPaginatedResponse<T = unknown> extends BaseResponse {
97
61
  success: true;
98
62
  data: T[];
99
63
  pagination: CursorPaginationMeta;
100
64
  }
101
- /**
102
- * Discriminated union for type-safe response handling
103
- * @template T - The type of the data payload for success responses
104
- */
105
65
  type ApiResponse<T = unknown> = SuccessResponse<T> | ErrorResponse;
106
- /**
107
- * Discriminated union for paginated responses
108
- * @template T - The type of items in the data array
109
- */
110
66
  type PaginatedApiResponse<T = unknown> = PaginatedResponse<T> | ErrorResponse;
111
- /**
112
- * Type guard for success responses
113
- */
114
67
  declare function isSuccessResponse<T>(response: ApiResponse<T>): response is SuccessResponse<T>;
115
- /**
116
- * Type guard for error responses
117
- */
118
68
  declare function isErrorResponse(response: ApiResponse<unknown>): response is ErrorResponse;
119
- /**
120
- * Type guard for paginated responses
121
- */
122
69
  declare function isPaginatedResponse<T>(response: PaginatedApiResponse<T>): response is PaginatedResponse<T>;
123
70
 
124
- /**
125
- * Error constructor type for mapping
126
- */
127
71
  type ErrorConstructor = new (...args: any[]) => Error;
128
- /**
129
- * Error serializer function type
130
- */
131
72
  type ErrorSerializer = (error: Error) => Record<string, unknown>;
132
- /**
133
- * Error context for traceability
134
- */
135
73
  interface ErrorContext {
136
74
  requestId?: string;
137
75
  correlationId?: string;
@@ -141,9 +79,6 @@ interface ErrorContext {
141
79
  timestamp?: string;
142
80
  [key: string]: unknown;
143
81
  }
144
- /**
145
- * API Error options
146
- */
147
82
  interface ApiErrorOptions {
148
83
  code?: string;
149
84
  statusCode?: number;
@@ -153,9 +88,6 @@ interface ApiErrorOptions {
153
88
  context?: ErrorContext;
154
89
  isOperational?: boolean;
155
90
  }
156
- /**
157
- * Serialized error structure
158
- */
159
91
  interface SerializedError {
160
92
  code: string;
161
93
  message: string;
@@ -165,18 +97,12 @@ interface SerializedError {
165
97
  stack?: string;
166
98
  context?: ErrorContext;
167
99
  }
168
- /**
169
- * Error chain item for nested errors
170
- */
171
100
  interface ErrorChainItem {
172
101
  name: string;
173
102
  message: string;
174
103
  code?: string;
175
104
  stack?: string;
176
105
  }
177
- /**
178
- * Default error codes
179
- */
180
106
  declare const ErrorCodes: {
181
107
  readonly VALIDATION_ERROR: "VALIDATION_ERROR";
182
108
  readonly NOT_FOUND: "NOT_FOUND";
@@ -191,86 +117,44 @@ declare const ErrorCodes: {
191
117
  };
192
118
  type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
193
119
 
194
- /**
195
- * Environment types
196
- */
197
120
  type Environment = 'development' | 'staging' | 'production' | 'test';
198
- /**
199
- * Response hook function types
200
- */
201
121
  type PreResponseHook = (data: unknown, meta?: ResponseMeta) => {
202
122
  data: unknown;
203
123
  meta?: ResponseMeta;
204
124
  };
205
125
  type PostResponseHook = (response: SuccessResponse<unknown> | ErrorResponse) => SuccessResponse<unknown> | ErrorResponse;
206
- /**
207
- * Custom formatter function type
208
- */
209
126
  type CustomFormatter = (response: SuccessResponse<unknown> | ErrorResponse) => Record<string, unknown>;
210
- /**
211
- * Pagination configuration
212
- */
213
127
  interface PaginationConfig {
214
128
  defaultLimit: number;
215
129
  maxLimit: number;
216
130
  includeLinks: boolean;
217
131
  baseUrl?: string;
218
132
  }
219
- /**
220
- * Main formatter configuration
221
- */
222
133
  interface FormatterConfig {
223
- /** Include stack traces in error responses */
224
134
  includeStackTraces: boolean;
225
- /** Current environment */
226
135
  environment: Environment;
227
- /** Custom error to status code mappings */
228
136
  customErrorMappers?: Map<ErrorConstructor, number>;
229
- /** Custom error serializers */
230
137
  customSerializers?: Map<ErrorConstructor, ErrorSerializer>;
231
- /** Include timestamp in responses */
232
138
  includeTimestamp: boolean;
233
- /** Mask sensitive data in errors */
234
139
  maskSensitiveData: boolean;
235
- /** Header name for request ID */
236
140
  requestIdHeader: string;
237
- /** Header name for correlation ID */
238
141
  correlationIdHeader: string;
239
- /** Pagination configuration */
240
142
  pagination: PaginationConfig;
241
- /** Pre-response processing hooks */
242
143
  preResponseHooks: PreResponseHook[];
243
- /** Post-response processing hooks */
244
144
  postResponseHooks: PostResponseHook[];
245
- /** Custom response formatter (passthrough mode) */
246
145
  customFormatter?: CustomFormatter;
247
- /** Enable passthrough mode for backward compatibility */
248
146
  passthroughMode: boolean;
249
- /** Sensitive fields to mask in error details */
250
147
  sensitiveFields: string[];
251
- /** Generate request ID if not present */
252
148
  generateRequestId: boolean;
253
149
  }
254
- /**
255
- * Partial configuration for user input
256
- */
257
150
  type FormatterConfigInput = Partial<FormatterConfig>;
258
- /**
259
- * Default configuration values
260
- */
261
151
  declare const defaultConfig: FormatterConfig;
262
152
 
263
- /**
264
- * Pagination input for offset-based pagination
265
- */
266
153
  interface PaginationInput {
267
154
  page: number;
268
155
  limit: number;
269
156
  total: number;
270
157
  }
271
- /**
272
- * Cursor pagination input
273
- */
274
158
  interface CursorPaginationInput {
275
159
  limit: number;
276
160
  cursor?: string;
@@ -278,236 +162,88 @@ interface CursorPaginationInput {
278
162
  previousCursor?: string;
279
163
  hasMore: boolean;
280
164
  }
281
- /**
282
- * Validate and normalize pagination input
283
- */
284
165
  declare function validatePaginationInput(input: Partial<PaginationInput>, config: PaginationConfig): PaginationInput;
285
- /**
286
- * Calculate pagination metadata
287
- */
288
166
  declare function calculatePaginationMeta(input: PaginationInput, baseUrl?: string): PaginationMeta;
289
- /**
290
- * Generate HATEOAS-style pagination links
291
- */
292
167
  declare function generatePaginationLinks(page: number, totalPages: number, limit: number, baseUrl: string): PaginationMeta['links'];
293
- /**
294
- * Calculate cursor pagination metadata
295
- */
296
168
  declare function calculateCursorPaginationMeta(input: CursorPaginationInput, baseUrl?: string): CursorPaginationMeta;
297
- /**
298
- * Generate cursor pagination links
299
- */
300
169
  declare function generateCursorPaginationLinks(input: CursorPaginationInput, baseUrl: string): CursorPaginationMeta['links'];
301
- /**
302
- * Validate configuration input
303
- */
304
170
  declare function validateConfig(input: FormatterConfigInput): string[];
305
- /**
306
- * Check if value is a plain object
307
- */
308
171
  declare function isPlainObject(value: unknown): value is Record<string, unknown>;
309
- /**
310
- * Generate a unique request ID
311
- */
312
172
  declare function generateRequestId(): string;
313
173
 
314
- /**
315
- * Core response formatter class
316
- * Handles formatting of success, error, and paginated responses
317
- */
318
174
  declare class ResponseFormatter {
319
175
  private config;
320
176
  private statusCodeMapper;
321
177
  constructor(config?: FormatterConfigInput);
322
- /**
323
- * Merge user config with defaults
324
- */
325
178
  private mergeConfig;
326
- /**
327
- * Get current configuration
328
- */
329
179
  getConfig(): Readonly<FormatterConfig>;
330
- /**
331
- * Update configuration
332
- */
333
180
  updateConfig(config: FormatterConfigInput): void;
334
- /**
335
- * Generate timestamp
336
- */
337
181
  private getTimestamp;
338
- /**
339
- * Apply pre-response hooks
340
- */
341
182
  private applyPreHooks;
342
- /**
343
- * Apply post-response hooks
344
- */
345
183
  private applyPostHooks;
346
- /**
347
- * Format a success response
348
- */
349
184
  formatSuccess<T>(data: T, meta?: ResponseMeta): SuccessResponse<T>;
350
- /**
351
- * Format an error response
352
- */
353
185
  formatError(error: Error, meta?: ResponseMeta): ErrorResponse;
354
- /**
355
- * Format a paginated response (offset-based)
356
- */
357
186
  formatPaginated<T>(data: T[], paginationInput: Partial<PaginationInput>, meta?: ResponseMeta, baseUrl?: string): PaginatedResponse<T>;
358
- /**
359
- * Format a cursor-paginated response
360
- */
361
187
  formatCursorPaginated<T>(data: T[], cursorInput: CursorPaginationInput, meta?: ResponseMeta, baseUrl?: string): CursorPaginatedResponse<T>;
362
- /**
363
- * Get status code for an error
364
- */
365
188
  getErrorStatusCode(error: Error): number;
366
- /**
367
- * Get success status code based on HTTP method
368
- */
369
189
  getSuccessStatusCode(method: string, hasData: boolean): number;
370
- /**
371
- * Generate or extract request ID
372
- */
373
190
  getRequestId(existingId?: string): string;
374
191
  }
375
- /**
376
- * Create a response formatter instance
377
- */
378
192
  declare function createResponseFormatter(config?: FormatterConfigInput): ResponseFormatter;
379
193
 
380
- /**
381
- * Error handler options
382
- */
383
194
  interface ErrorHandlerOptions {
384
- /** Log errors to console */
385
195
  logErrors: boolean;
386
- /** Custom error logger */
387
196
  errorLogger?: (error: Error, req: Request) => void;
388
- /** Transform error before formatting */
389
197
  transformError?: (error: Error) => Error;
390
- /** Handle non-operational errors differently */
391
198
  handleNonOperational?: (error: Error, req: Request, res: Response) => void;
392
199
  }
393
- /**
394
- * Error handler class for Express applications
395
- */
396
200
  declare class ErrorHandler {
397
201
  private formatter;
398
202
  private options;
399
203
  private config;
400
204
  constructor(formatter: ResponseFormatter, options?: Partial<ErrorHandlerOptions>);
401
- /**
402
- * Extract request metadata for error context
403
- */
404
205
  private extractMeta;
405
- /**
406
- * Log error if enabled
407
- */
408
206
  private logError;
409
- /**
410
- * Check if error is operational (expected)
411
- */
412
207
  private isOperationalError;
413
- /**
414
- * Handle the error and send response
415
- */
416
208
  handle(error: Error, req: Request, res: Response, _next: NextFunction): void;
417
- /**
418
- * Create Express error handling middleware
419
- */
420
209
  middleware(): (error: Error, req: Request, res: Response, next: NextFunction) => void;
421
210
  }
422
- /**
423
- * Create an error handler instance
424
- */
425
211
  declare function createErrorHandler(formatter: ResponseFormatter, options?: Partial<ErrorHandlerOptions>): ErrorHandler;
426
- /**
427
- * Create error handling middleware directly
428
- */
429
212
  declare function errorHandlerMiddleware(formatter: ResponseFormatter, options?: Partial<ErrorHandlerOptions>): (error: Error, req: Request, res: Response, next: NextFunction) => void;
430
213
 
431
- /**
432
- * Pagination helper class for handling pagination logic
433
- */
434
214
  declare class PaginationHelper {
435
215
  private config;
436
216
  constructor(config?: Partial<PaginationConfig>);
437
- /**
438
- * Extract pagination parameters from request
439
- */
217
+ private safeParseInt;
440
218
  extractFromRequest(req: Request): {
441
219
  page: number;
442
220
  limit: number;
443
221
  };
444
- /**
445
- * Extract cursor pagination parameters from request
446
- */
222
+ private validateCursor;
447
223
  extractCursorFromRequest(req: Request): {
448
224
  cursor?: string;
449
225
  limit: number;
450
226
  };
451
- /**
452
- * Calculate offset for database queries
453
- */
454
227
  calculateOffset(page: number, limit: number): number;
455
- /**
456
- * Build pagination metadata
457
- */
458
228
  buildMeta(input: PaginationInput, baseUrl?: string): PaginationMeta;
459
- /**
460
- * Build cursor pagination metadata
461
- */
462
229
  buildCursorMeta(input: CursorPaginationInput, baseUrl?: string): CursorPaginationMeta;
463
- /**
464
- * Create pagination info from data array and total count
465
- */
466
230
  fromArray<T>(data: T[], page: number, limit: number, total: number): {
467
231
  data: T[];
468
232
  pagination: PaginationMeta;
469
233
  };
470
- /**
471
- * Paginate an in-memory array
472
- */
473
234
  paginateArray<T>(items: T[], page: number, limit: number): {
474
235
  data: T[];
475
236
  pagination: PaginationMeta;
476
237
  };
477
- /**
478
- * Check if there are more pages
479
- */
480
238
  hasNextPage(page: number, limit: number, total: number): boolean;
481
- /**
482
- * Check if there are previous pages
483
- */
484
239
  hasPreviousPage(page: number): boolean;
485
- /**
486
- * Get total pages count
487
- */
488
240
  getTotalPages(total: number, limit: number): number;
489
- /**
490
- * Validate page number is within bounds
491
- */
492
241
  isValidPage(page: number, total: number, limit: number): boolean;
493
- /**
494
- * Get configuration
495
- */
496
242
  getConfig(): Readonly<PaginationConfig>;
497
- /**
498
- * Update configuration
499
- */
500
243
  updateConfig(config: Partial<PaginationConfig>): void;
501
244
  }
502
- /**
503
- * Create a pagination helper instance
504
- */
505
245
  declare function createPaginationHelper(config?: Partial<PaginationConfig>): PaginationHelper;
506
246
 
507
- /**
508
- * Base API Error class for all application errors
509
- * Provides structured error information for consistent API responses
510
- */
511
247
  declare class ApiError extends Error {
512
248
  readonly code: string;
513
249
  readonly statusCode: number;
@@ -517,323 +253,134 @@ declare class ApiError extends Error {
517
253
  readonly isOperational: boolean;
518
254
  readonly timestamp: string;
519
255
  constructor(message: string, options?: ApiErrorOptions);
520
- /**
521
- * Serialize error for response
522
- */
523
256
  serialize(includeStack?: boolean): SerializedError;
524
- /**
525
- * Get error chain for nested errors
526
- */
527
257
  getErrorChain(): Array<{
528
258
  name: string;
529
259
  message: string;
530
260
  code?: string;
531
261
  }>;
532
- /**
533
- * Create a new error with additional context
534
- */
535
262
  withContext(context: ErrorContext): ApiError;
536
- /**
537
- * Convert to JSON for logging
538
- */
539
263
  toJSON(): Record<string, unknown>;
540
264
  }
541
265
 
542
- /**
543
- * Validation Error - 400 Bad Request
544
- * Used for input validation failures
545
- */
546
266
  declare class ValidationError extends ApiError {
547
267
  constructor(message?: string, fields?: FieldErrors, options?: Omit<ApiErrorOptions, 'code' | 'statusCode' | 'fields'>);
548
268
  }
549
- /**
550
- * Not Found Error - 404
551
- * Used when a requested resource doesn't exist
552
- */
553
269
  declare class NotFoundError extends ApiError {
554
270
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
555
271
  }
556
- /**
557
- * Unauthorized Error - 401
558
- * Used when authentication is required but not provided or invalid
559
- */
560
272
  declare class UnauthorizedError extends ApiError {
561
273
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
562
274
  }
563
- /**
564
- * Forbidden Error - 403
565
- * Used when user is authenticated but lacks permission
566
- */
567
275
  declare class ForbiddenError extends ApiError {
568
276
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
569
277
  }
570
- /**
571
- * Conflict Error - 409
572
- * Used for resource conflicts (e.g., duplicate entries)
573
- */
574
278
  declare class ConflictError extends ApiError {
575
279
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
576
280
  }
577
- /**
578
- * Internal Server Error - 500
579
- * Used for unexpected server errors
580
- */
581
281
  declare class InternalServerError extends ApiError {
582
282
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
583
283
  }
584
- /**
585
- * Bad Request Error - 400
586
- * Used for malformed requests
587
- */
588
284
  declare class BadRequestError extends ApiError {
589
285
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
590
286
  }
591
- /**
592
- * Rate Limit Error - 429
593
- * Used when rate limiting is triggered
594
- */
595
287
  declare class RateLimitError extends ApiError {
596
288
  readonly retryAfter?: number;
597
289
  constructor(message?: string, retryAfter?: number, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
598
290
  }
599
- /**
600
- * Service Unavailable Error - 503
601
- * Used when service is temporarily unavailable
602
- */
603
291
  declare class ServiceUnavailableError extends ApiError {
604
292
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
605
293
  }
606
- /**
607
- * Unprocessable Entity Error - 422
608
- * Used when request is valid but cannot be processed
609
- */
610
294
  declare class UnprocessableEntityError extends ApiError {
611
295
  constructor(message?: string, options?: Omit<ApiErrorOptions, 'code' | 'statusCode'>);
612
296
  }
613
- /**
614
- * Factory function to create ApiError with context
615
- */
616
297
  declare function createError(ErrorClass: new (message: string, ...args: unknown[]) => ApiError, message: string, context?: ErrorContext): ApiError;
617
298
 
618
- /**
619
- * Extended Express Response with formatter methods
620
- */
621
299
  interface FormattedResponse extends Response {
622
- /** Send a formatted success response */
623
300
  respond: <T>(data: T, meta?: ResponseMeta, statusCode?: number) => void;
624
- /** Send a formatted paginated response */
625
301
  respondPaginated: <T>(data: T[], pagination: Partial<PaginationInput>, meta?: ResponseMeta) => void;
626
- /** Send a formatted cursor-paginated response */
627
302
  respondCursorPaginated: <T>(data: T[], pagination: CursorPaginationInput, meta?: ResponseMeta) => void;
628
- /** Send a formatted error response */
629
303
  respondError: (error: Error, meta?: ResponseMeta) => void;
630
- /** Get the response formatter instance */
631
304
  formatter: ResponseFormatter;
632
305
  }
633
- /**
634
- * Extended Express Request with formatter context
635
- */
636
306
  interface FormattedRequest extends Request {
637
- /** Request ID for tracing */
638
307
  requestId: string;
639
- /** Correlation ID for distributed tracing */
640
308
  correlationId?: string;
641
309
  }
642
- /**
643
- * Middleware options
644
- */
645
310
  interface ResponseWrapperOptions extends FormatterConfigInput {
646
- /** Skip wrapping for specific paths */
647
311
  skipPaths?: string[];
648
- /** Skip wrapping based on custom condition */
649
312
  skipCondition?: (req: Request) => boolean;
650
313
  }
651
- /**
652
- * Create response wrapper middleware
653
- */
654
314
  declare function responseWrapper(options?: ResponseWrapperOptions): RequestHandler;
655
- /**
656
- * Create response wrapper with custom formatter
657
- */
658
315
  declare function createResponseWrapper(formatter: ResponseFormatter, options?: Omit<ResponseWrapperOptions, keyof FormatterConfigInput>): RequestHandler;
659
316
 
660
- /**
661
- * Error catcher options
662
- */
663
317
  interface ErrorCatcherOptions extends FormatterConfigInput {
664
- /** Log errors to console */
665
318
  logErrors?: boolean;
666
- /** Custom error logger */
667
319
  errorLogger?: (error: Error, req: Request) => void;
668
- /** Transform error before formatting */
669
320
  transformError?: (error: Error) => Error;
670
- /** Custom response handler */
671
321
  customHandler?: (error: Error, req: Request, res: Response) => boolean;
672
322
  }
673
- /**
674
- * Create error catching middleware
675
- */
676
323
  declare function errorCatcher(options?: ErrorCatcherOptions): ErrorRequestHandler;
677
- /**
678
- * Create error catcher with existing formatter
679
- */
680
324
  declare function createErrorCatcher(formatter: ResponseFormatter, options?: Omit<ErrorCatcherOptions, keyof FormatterConfigInput>): ErrorRequestHandler;
681
- /**
682
- * Async handler wrapper to catch errors in async route handlers
683
- */
684
325
  declare function asyncHandler<T>(fn: (req: Request, res: Response, next: NextFunction) => Promise<T>): (req: Request, res: Response, next: NextFunction) => void;
685
- /**
686
- * Create a try-catch wrapper for route handlers
687
- */
688
326
  declare function catchErrors<T>(fn: (req: Request, res: Response) => Promise<T>): (req: Request, res: Response, next: NextFunction) => void;
689
327
 
690
- /**
691
- * Decorator options
692
- */
693
328
  interface ResponseDecoratorOptions {
694
- /** Status code to use for success response */
695
329
  statusCode?: number;
696
- /** Additional metadata to include */
697
330
  meta?: ResponseMeta;
698
- /** Skip formatting and return raw response */
699
331
  raw?: boolean;
700
332
  }
701
- /**
702
- * Create a response decorator factory
703
- */
704
333
  declare function createResponseDecorator(formatter: ResponseFormatter): (options?: ResponseDecoratorOptions) => MethodDecorator;
705
- /**
706
- * Handle errors decorator
707
- * Wraps method in try-catch and passes errors to next()
708
- */
709
334
  declare function HandleErrors(): MethodDecorator;
710
- /**
711
- * API Route decorator factory
712
- * Creates a decorator that handles response formatting and error catching
713
- */
714
335
  declare function ApiRoute(formatter: ResponseFormatter, options?: ResponseDecoratorOptions): MethodDecorator;
715
- /**
716
- * Validate decorator
717
- * Validates request body/params/query before executing handler
718
- */
719
336
  declare function Validate(validator: (data: unknown) => {
720
337
  valid: boolean;
721
338
  errors?: Record<string, string[]>;
722
339
  }, source?: 'body' | 'params' | 'query'): MethodDecorator;
723
340
 
724
- /**
725
- * Pagination decorator options
726
- */
727
341
  interface PaginateDecoratorOptions {
728
- /** Default page size */
729
342
  defaultLimit?: number;
730
- /** Maximum page size */
731
343
  maxLimit?: number;
732
- /** Include HATEOAS links */
733
344
  includeLinks?: boolean;
734
- /** Additional metadata */
735
345
  meta?: ResponseMeta;
736
346
  }
737
- /**
738
- * Result type for paginated handlers
739
- */
740
347
  interface PaginatedResult<T> {
741
348
  data: T[];
742
349
  total: number;
743
350
  }
744
- /**
745
- * Cursor paginated result type
746
- */
747
351
  interface CursorPaginatedResult<T> {
748
352
  data: T[];
749
353
  nextCursor?: string;
750
354
  previousCursor?: string;
751
355
  hasMore: boolean;
752
356
  }
753
- /**
754
- * Paginate decorator factory
755
- * Automatically handles pagination for route handlers
756
- */
757
357
  declare function Paginate(formatter: ResponseFormatter, options?: PaginateDecoratorOptions): MethodDecorator;
758
- /**
759
- * Cursor paginate decorator factory
760
- */
761
358
  declare function CursorPaginate(formatter: ResponseFormatter, options?: PaginateDecoratorOptions): MethodDecorator;
762
359
 
763
- /**
764
- * Status code mapper class
765
- */
766
360
  declare class StatusCodeMapper {
767
361
  private customMappings;
768
362
  constructor(customMappings?: Map<ErrorConstructor, number>);
769
- /**
770
- * Get status code for an error
771
- */
772
363
  getStatusCode(error: Error): number;
773
- /**
774
- * Get success status code based on HTTP method
775
- */
776
364
  getSuccessStatusCode(method: string, hasData: boolean): number;
777
- /**
778
- * Add custom error mapping
779
- */
780
365
  addMapping(ErrorClass: ErrorConstructor, statusCode: number): void;
781
- /**
782
- * Remove custom error mapping
783
- */
784
366
  removeMapping(ErrorClass: ErrorConstructor): boolean;
785
- /**
786
- * Check if status code indicates success
787
- */
788
367
  static isSuccessCode(statusCode: number): boolean;
789
- /**
790
- * Check if status code indicates client error
791
- */
792
368
  static isClientError(statusCode: number): boolean;
793
- /**
794
- * Check if status code indicates server error
795
- */
796
369
  static isServerError(statusCode: number): boolean;
797
370
  }
798
- /**
799
- * Create a status code mapper with custom mappings
800
- */
801
371
  declare function createStatusCodeMapper(customMappings?: Map<ErrorConstructor, number>): StatusCodeMapper;
802
372
 
803
- /**
804
- * Options for error serialization
805
- */
806
373
  interface SerializationOptions {
807
374
  includeStack: boolean;
808
375
  maskSensitiveData: boolean;
809
376
  sensitiveFields: string[];
810
377
  customSerializers?: Map<ErrorConstructor, ErrorSerializer>;
811
378
  }
812
- /**
813
- * Serialize an error to ErrorDetails format
814
- */
815
379
  declare function serializeError(error: Error, options?: Partial<SerializationOptions>): ErrorDetails;
816
- /**
817
- * Extract field errors from validation error
818
- */
819
380
  declare function extractFieldErrors(error: Error): FieldErrors | undefined;
820
- /**
821
- * Extract error context
822
- */
823
381
  declare function extractErrorContext(error: Error): ErrorContext | undefined;
824
- /**
825
- * Create error serializer with options
826
- */
827
382
  declare function createErrorSerializer(options?: Partial<SerializationOptions>): (error: Error) => ErrorDetails;
828
383
 
829
- /**
830
- * Quick setup function that returns both middleware
831
- * @example
832
- * const { wrapper, errorHandler } = responseFormatter({ environment: 'production' });
833
- * app.use(wrapper);
834
- * // ... routes
835
- * app.use(errorHandler);
836
- */
837
384
  declare function responseFormatter(options?: ResponseWrapperOptions & ErrorCatcherOptions): {
838
385
  wrapper: RequestHandler;
839
386
  errorHandler: ErrorRequestHandler;