xypriss 2.1.2 → 2.2.1

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.
Files changed (55) hide show
  1. package/README.md +139 -0
  2. package/dist/cjs/src/plugins/modules/network/builtin/CompressionPlugin.js +2 -110
  3. package/dist/cjs/src/plugins/modules/network/builtin/CompressionPlugin.js.map +1 -1
  4. package/dist/cjs/src/plugins/modules/network/builtin/ConnectionPlugin.js.map +1 -1
  5. package/dist/cjs/src/plugins/modules/network/core/NetworkPlugin.js.map +1 -1
  6. package/dist/cjs/src/plugins/modules/network/types/NetworkTypes.js.map +1 -1
  7. package/dist/cjs/src/server/FastServer.js +78 -9
  8. package/dist/cjs/src/server/FastServer.js.map +1 -1
  9. package/dist/cjs/src/server/ServerFactory.js +218 -2
  10. package/dist/cjs/src/server/ServerFactory.js.map +1 -1
  11. package/dist/cjs/src/server/components/fastapi/FileUploadManager.js +175 -0
  12. package/dist/cjs/src/server/components/fastapi/FileUploadManager.js.map +1 -0
  13. package/dist/cjs/src/server/components/fastapi/RouteManager.js.map +1 -1
  14. package/dist/cjs/src/server/components/fastapi/smart-routes.js.map +1 -1
  15. package/dist/cjs/src/server/components/lifecycle/ServerLifecycleManager.js.map +1 -1
  16. package/dist/cjs/src/server/components/multi-server/MultiServerManager.js +200 -0
  17. package/dist/cjs/src/server/components/multi-server/MultiServerManager.js.map +1 -0
  18. package/dist/cjs/src/server/const/default.js +35 -0
  19. package/dist/cjs/src/server/const/default.js.map +1 -1
  20. package/dist/cjs/src/server/core/HttpServer.js +19 -1
  21. package/dist/cjs/src/server/core/HttpServer.js.map +1 -1
  22. package/dist/cjs/src/server/core/XyprissApp.js.map +1 -1
  23. package/dist/cjs/src/server/handlers/NotFoundHandler.js.map +1 -1
  24. package/dist/cjs/src/server/optimization/RequestPreCompiler.js +1 -0
  25. package/dist/cjs/src/server/optimization/RequestPreCompiler.js.map +1 -1
  26. package/dist/cjs/src/server/utils/ConfigLoader.js +245 -148
  27. package/dist/cjs/src/server/utils/ConfigLoader.js.map +1 -1
  28. package/dist/esm/src/plugins/modules/network/builtin/CompressionPlugin.js +2 -110
  29. package/dist/esm/src/plugins/modules/network/builtin/CompressionPlugin.js.map +1 -1
  30. package/dist/esm/src/plugins/modules/network/builtin/ConnectionPlugin.js.map +1 -1
  31. package/dist/esm/src/plugins/modules/network/core/NetworkPlugin.js.map +1 -1
  32. package/dist/esm/src/plugins/modules/network/types/NetworkTypes.js.map +1 -1
  33. package/dist/esm/src/server/FastServer.js +78 -9
  34. package/dist/esm/src/server/FastServer.js.map +1 -1
  35. package/dist/esm/src/server/ServerFactory.js +218 -2
  36. package/dist/esm/src/server/ServerFactory.js.map +1 -1
  37. package/dist/esm/src/server/components/fastapi/FileUploadManager.js +154 -0
  38. package/dist/esm/src/server/components/fastapi/FileUploadManager.js.map +1 -0
  39. package/dist/esm/src/server/components/fastapi/RouteManager.js.map +1 -1
  40. package/dist/esm/src/server/components/fastapi/smart-routes.js.map +1 -1
  41. package/dist/esm/src/server/components/lifecycle/ServerLifecycleManager.js.map +1 -1
  42. package/dist/esm/src/server/components/multi-server/MultiServerManager.js +198 -0
  43. package/dist/esm/src/server/components/multi-server/MultiServerManager.js.map +1 -0
  44. package/dist/esm/src/server/const/default.js +35 -0
  45. package/dist/esm/src/server/const/default.js.map +1 -1
  46. package/dist/esm/src/server/core/HttpServer.js +19 -1
  47. package/dist/esm/src/server/core/HttpServer.js.map +1 -1
  48. package/dist/esm/src/server/core/XyprissApp.js.map +1 -1
  49. package/dist/esm/src/server/handlers/NotFoundHandler.js.map +1 -1
  50. package/dist/esm/src/server/optimization/RequestPreCompiler.js +1 -0
  51. package/dist/esm/src/server/optimization/RequestPreCompiler.js.map +1 -1
  52. package/dist/esm/src/server/utils/ConfigLoader.js +227 -151
  53. package/dist/esm/src/server/utils/ConfigLoader.js.map +1 -1
  54. package/dist/index.d.ts +872 -526
  55. package/package.json +1 -2
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { IncomingMessage, ServerResponse, Server } from 'http';
2
2
  import { EventEmitter } from 'events';
3
- import { Request, Response, NextFunction as NextFunction$1 } from 'express';
4
3
 
5
4
  /**
6
5
  * XyPriss Request interface (Express-compatible)
@@ -32,6 +31,7 @@ interface XyPrisRequest extends IncomingMessage {
32
31
  fresh: boolean;
33
32
  stale: boolean;
34
33
  xhr: boolean;
34
+ get: (name: string) => string | undefined;
35
35
  }
36
36
  /**
37
37
  * XyPriss Response interface (Express-compatible)
@@ -50,6 +50,7 @@ interface XyPrisResponse extends ServerResponse {
50
50
  clearCookie(name: string, options?: any): void;
51
51
  locals: Record<string, any>;
52
52
  headersSent: boolean;
53
+ get: (name: string) => string | number | string[] | undefined;
53
54
  }
54
55
  /**
55
56
  * Middleware function type
@@ -1011,7 +1012,7 @@ interface CompiledRoute {
1011
1012
  }
1012
1013
  interface DynamicResponseGenerator {
1013
1014
  pattern: string | RegExp;
1014
- generator: (req: Request, pattern: RequestPattern) => Promise<any> | any;
1015
+ generator: (req: XyPrisRequest, pattern: RequestPattern) => Promise<any> | any;
1015
1016
  priority?: number;
1016
1017
  }
1017
1018
  interface ResponseTemplate {
@@ -1067,11 +1068,11 @@ declare class RequestPreCompiler {
1067
1068
  /**
1068
1069
  * Analyze incoming request and update patterns
1069
1070
  */
1070
- analyzeRequest(req: Request, res: Response, next: NextFunction$1): void;
1071
+ analyzeRequest(req: XyPrisRequest, res: XyPrisResponse, next: NextFunction): void;
1071
1072
  /**
1072
1073
  * Get optimized handler for request if available
1073
1074
  */
1074
- getOptimizedHandler(req: Request): CompiledRoute | null;
1075
+ getOptimizedHandler(req: XyPrisRequest): CompiledRoute | null;
1075
1076
  /**
1076
1077
  * Pre-compile optimized execution paths for hot routes
1077
1078
  */
@@ -1201,7 +1202,7 @@ type RoutePattern = string | RegExp;
1201
1202
  interface OptimizedRoute {
1202
1203
  pattern: RoutePattern;
1203
1204
  methods?: string[];
1204
- handler?: (req: Request, res: Response) => any | Promise<any>;
1205
+ handler?: (req: XyPrisRequest, res: XyPrisResponse) => any | Promise<any>;
1205
1206
  schema?: any;
1206
1207
  cacheTTL?: number;
1207
1208
  priority?: number;
@@ -1571,315 +1572,94 @@ interface RouteSecurityConfig {
1571
1572
  }
1572
1573
 
1573
1574
  /**
1574
- * @fileoverview Core type definitions for XyPrissJS Express integration
1575
+ * @fileoverview Performance-related type definitions for XyPrissJS Express integration
1575
1576
  *
1576
- * This module contains fundamental types and utilities used throughout
1577
- * the Express integration system.
1577
+ * This module contains all performance-related types including monitoring,
1578
+ * optimization, metrics, and configuration.
1578
1579
  *
1579
1580
  * @version 4.5.11
1580
1581
  * @author XyPrissJS Team
1581
1582
  * @since 2025-01-06
1582
1583
  */
1583
-
1584
- /**
1585
- * Deep partial utility type that makes all properties optional recursively.
1586
- *
1587
- * This utility type is used throughout the configuration system to allow
1588
- * partial configuration objects while maintaining type safety.
1589
- *
1590
- * @template T - The type to make deeply partial
1591
- *
1592
- * @example
1593
- * ```typescript
1594
- * interface Config {
1595
- * server: {
1596
- * port: number;
1597
- * host: string;
1598
- * };
1599
- * }
1600
- *
1601
- * type PartialConfig = DeepPartial<Config>;
1602
- * // Result: { server?: { port?: number; host?: string; } }
1603
- * ```
1604
- */
1605
- type DeepPartial<T> = {
1606
- [K in keyof T]?: T[K] extends infer U ? U extends object ? U extends readonly any[] ? U extends readonly (infer V)[] ? readonly DeepPartial<V>[] : U : U extends Function ? U : DeepPartial<U> : U : never;
1607
- };
1608
- /**
1609
- * Validation result interface for request validation operations.
1610
- *
1611
- * Used by validation middleware and request handlers to provide
1612
- * structured validation feedback.
1613
- *
1614
- * @interface ValidationResult
1615
- *
1616
- * @example
1617
- * ```typescript
1618
- * const result: ValidationResult = {
1619
- * valid: false,
1620
- * errors: ['Email is required', 'Password too short'],
1621
- * data: { email: '', password: '123' }
1622
- * };
1623
- * ```
1624
- */
1625
- interface ValidationResult$1 {
1626
- /** Whether the validation passed */
1627
- valid: boolean;
1628
- /** Array of validation error messages */
1629
- errors: string[];
1630
- /** The validated/sanitized data */
1631
- data: any;
1632
- }
1633
- /**
1634
- * User context information for authenticated requests.
1635
- *
1636
- * Contains user identity, permissions, and metadata for
1637
- * authorization and audit purposes.
1638
- *
1639
- * @interface UserContext
1640
- *
1641
- * @example
1642
- * ```typescript
1643
- * const user: UserContext = {
1644
- * id: 'user-123',
1645
- * roles: ['admin', 'user'],
1646
- * permissions: ['read:users', 'write:posts'],
1647
- * metadata: { department: 'engineering', level: 'senior' }
1648
- * };
1649
- * ```
1650
- */
1651
- interface UserContext {
1652
- /** Unique user identifier */
1653
- id: string;
1654
- /** Array of user roles */
1655
- roles: string[];
1656
- /** Array of specific permissions */
1657
- permissions: string[];
1658
- /** Additional user metadata */
1659
- metadata: Record<string, any>;
1660
- }
1661
- /**
1662
- * Session data structure for user sessions.
1663
- *
1664
- * Contains session information including expiration and
1665
- * custom session data.
1666
- *
1667
- * @interface SessionData
1668
- *
1669
- * @example
1670
- * ```typescript
1671
- * const session: SessionData = {
1672
- * id: 'session-abc123',
1673
- * userId: 'user-123',
1674
- * data: { theme: 'dark', language: 'en' },
1675
- * expires: new Date(Date.now() + 3600000) // 1 hour
1676
- * };
1677
- * ```
1678
- */
1679
- interface SessionData {
1680
- /** Unique session identifier */
1681
- id: string;
1682
- /** Associated user ID (optional) */
1683
- userId?: string;
1684
- /** Custom session data */
1685
- data: Record<string, any>;
1686
- /** Session expiration date */
1687
- expires: Date;
1688
- }
1689
1584
  /**
1690
- * Pagination information for paginated responses.
1691
- *
1692
- * Used by API endpoints that return paginated data to provide
1693
- * navigation information to clients.
1694
- *
1695
- * @interface PaginationInfo
1696
- *
1697
- * @example
1698
- * ```typescript
1699
- * const pagination: PaginationInfo = {
1700
- * page: 2,
1701
- * limit: 20,
1702
- * total: 150,
1703
- * pages: 8
1704
- * };
1705
- * ```
1706
- */
1707
- interface PaginationInfo {
1708
- /** Current page number (1-based) */
1709
- page: number;
1710
- /** Number of items per page */
1711
- limit: number;
1712
- /** Total number of items */
1713
- total: number;
1714
- /** Total number of pages */
1715
- pages: number;
1716
- }
1717
- /**
1718
- * Enhanced Express request interface with additional utilities.
1585
+ * Performance configuration interface.
1719
1586
  *
1720
- * Extends the standard Express Request with caching, security,
1721
- * performance, and validation utilities.
1587
+ * Comprehensive configuration for performance monitoring,
1588
+ * optimization, and metrics collection.
1722
1589
  *
1723
- * @interface EnhancedRequest
1724
- * @extends Request
1590
+ * @interface PerformanceConfig
1725
1591
  *
1726
1592
  * @example
1727
1593
  * ```typescript
1728
- * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
1729
- * // Use enhanced features
1730
- * const cached = await req.cache.get('users');
1731
- * const encrypted = await req.security.encrypt(sensitiveData);
1732
- * req.performance.start();
1733
- *
1734
- * // Validation
1735
- * const validation = req.validation.query(userQuerySchema);
1736
- * if (!validation.valid) {
1737
- * return res.error('Invalid query parameters');
1594
+ * const perfConfig: PerformanceConfig = {
1595
+ * enabled: true,
1596
+ * metrics: ['response_time', 'memory_usage', 'cpu_usage'],
1597
+ * interval: 30000, // 30 seconds
1598
+ * alerts: [
1599
+ * {
1600
+ * metric: 'response_time',
1601
+ * threshold: 1000, // 1 second
1602
+ * action: 'log',
1603
+ * cooldown: 300000 // 5 minutes
1604
+ * }
1605
+ * ],
1606
+ * dashboard: true,
1607
+ * export: {
1608
+ * custom: (metrics) => {
1609
+ * console.log('Custom metrics export:', metrics);
1610
+ * }
1738
1611
  * }
1739
- * });
1740
- * ```
1741
- */
1742
- interface EnhancedRequest extends Request {
1743
- /** Cache utilities for request-level caching */
1744
- cache: {
1745
- /** Get cached value by key */
1746
- get: (key: string) => Promise<any>;
1747
- /** Set cached value with optional TTL */
1748
- set: (key: string, value: any, ttl?: number) => Promise<void>;
1749
- /** Delete cached value */
1750
- del: (key: string) => Promise<void>;
1751
- /** Tag cache entries for bulk invalidation */
1752
- tags: (tags: string[]) => Promise<void>;
1753
- };
1754
- /** Security utilities for encryption and authentication */
1755
- security: {
1756
- /** Encrypt data using configured algorithm */
1757
- encrypt: (data: any) => Promise<string>;
1758
- /** Decrypt data using configured algorithm */
1759
- decrypt: (data: string) => Promise<any>;
1760
- /** Hash data using secure algorithm */
1761
- hash: (data: string) => string;
1762
- /** Verify data against hash */
1763
- verify: (data: string, hash: string) => boolean;
1764
- /** Generate secure token */
1765
- generateToken: () => string;
1766
- /** Session encryption key */
1767
- sessionKey: string;
1768
- };
1769
- /** Performance monitoring utilities */
1770
- performance: {
1771
- /** Start performance timer */
1772
- start: () => void;
1773
- /** End performance timer and return duration */
1774
- end: () => number;
1775
- /** Mark a performance point */
1776
- mark: (name: string) => void;
1777
- /** Measure time between marks */
1778
- measure: (name: string, start: string, end: string) => number;
1779
- };
1780
- /** Request validation utilities */
1781
- validation: {
1782
- /** Validate request body against schema */
1783
- body: (schema: any) => ValidationResult$1;
1784
- /** Validate query parameters against schema */
1785
- query: (schema: any) => ValidationResult$1;
1786
- /** Validate route parameters against schema */
1787
- params: (schema: any) => ValidationResult$1;
1788
- };
1789
- /** User context (available after authentication) */
1790
- user?: UserContext;
1791
- /** Session data (available when sessions are enabled) */
1792
- session?: SessionData;
1793
- }
1794
- /**
1795
- * Enhanced Express response interface with additional utilities.
1796
- *
1797
- * Extends the standard Express Response with caching, security,
1798
- * performance, and convenience methods.
1799
- *
1800
- * @interface EnhancedResponse
1801
- * @extends Response
1802
- *
1803
- * @example
1804
- * ```typescript
1805
- * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
1806
- * const users = await getUsersFromDB();
1807
- *
1808
- * // Use enhanced response methods
1809
- * res.cache.set(3600, ['users']); // Cache for 1 hour with 'users' tag
1810
- * res.performance.timing('db_query', 150);
1811
- * res.success(users, 'Users retrieved successfully');
1812
- * });
1612
+ * };
1813
1613
  * ```
1814
1614
  */
1815
- interface EnhancedResponse extends Response {
1816
- /** Cache utilities for response caching */
1817
- cache: {
1818
- /** Set cache headers and TTL for response */
1819
- set: (ttl?: number, tags?: string[]) => void;
1820
- /** Invalidate cache entries by tags */
1821
- invalidate: (tags: string[]) => Promise<void>;
1822
- };
1823
- /** Security utilities for response encryption */
1824
- security: {
1825
- /** Encrypt response data */
1826
- encrypt: (data: any) => EnhancedResponse;
1827
- /** Sign response data */
1828
- sign: (data: any) => EnhancedResponse;
1829
- };
1830
- /** Performance utilities for response metrics */
1831
- performance: {
1832
- /** Record timing metric */
1833
- timing: (name: string, value: number) => void;
1834
- /** Record custom metric */
1835
- metric: (name: string, value: number) => void;
1615
+ interface PerformanceConfig {
1616
+ /** Enable performance monitoring */
1617
+ enabled?: boolean;
1618
+ /** Metrics to collect */
1619
+ metrics?: string[];
1620
+ /** Collection interval in milliseconds */
1621
+ interval?: number;
1622
+ /** Alert configurations */
1623
+ alerts?: AlertConfig[];
1624
+ /** Enable performance dashboard */
1625
+ dashboard?: boolean;
1626
+ /** Export configuration */
1627
+ export?: {
1628
+ /** Custom export function */
1629
+ custom?: (metrics: any) => void;
1836
1630
  };
1837
- /** Send successful response with optional message */
1838
- success: (data?: any, message?: string) => void;
1839
- /** Send error response with message and status code */
1840
- error: (error: string | Error, code?: number) => void;
1841
- /** Send paginated response with pagination info */
1842
- paginated: (data: any[], pagination: PaginationInfo) => void;
1843
1631
  }
1844
1632
  /**
1845
- * Route handler function type with enhanced request/response.
1633
+ * Alert configuration interface.
1846
1634
  *
1847
- * @template T - Return type of the handler
1635
+ * Configuration for performance alerts including thresholds,
1636
+ * actions, and cooldown periods.
1848
1637
  *
1849
- * @example
1850
- * ```typescript
1851
- * const getUserHandler: RouteHandler = async (req, res, next) => {
1852
- * try {
1853
- * const user = await getUserById(req.params.id);
1854
- * res.success(user);
1855
- * } catch (error) {
1856
- * next(error);
1857
- * }
1858
- * };
1859
- * ```
1860
- */
1861
- type RouteHandler = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction$1) => Promise<any> | any;
1862
- /**
1863
- * Middleware function type with enhanced request/response.
1638
+ * @interface AlertConfig
1864
1639
  *
1865
1640
  * @example
1866
1641
  * ```typescript
1867
- * const authMiddleware: MiddlewareFunction = async (req, res, next) => {
1868
- * const token = req.headers.authorization;
1869
- * if (!token) {
1870
- * return res.error('Authorization required', 401);
1871
- * }
1872
- *
1873
- * try {
1874
- * req.user = await verifyToken(token);
1875
- * next();
1876
- * } catch (error) {
1877
- * res.error('Invalid token', 401);
1878
- * }
1642
+ * const alertConfig: AlertConfig = {
1643
+ * metric: 'memory_usage',
1644
+ * threshold: 0.85, // 85%
1645
+ * action: 'webhook',
1646
+ * target: 'https://alerts.example.com/webhook',
1647
+ * cooldown: 600000 // 10 minutes
1879
1648
  * };
1880
1649
  * ```
1881
1650
  */
1882
- type MiddlewareFunction = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction$1) => Promise<void> | void;
1651
+ interface AlertConfig {
1652
+ /** Metric name to monitor */
1653
+ metric: string;
1654
+ /** Threshold value that triggers alert */
1655
+ threshold: number;
1656
+ /** Action to take when alert triggers */
1657
+ action: "log" | "email" | "webhook" | "custom";
1658
+ /** Target for the action (email, webhook URL, etc.) */
1659
+ target?: string;
1660
+ /** Cooldown period in milliseconds */
1661
+ cooldown?: number;
1662
+ }
1883
1663
 
1884
1664
  /**
1885
1665
  * @fileoverview Cache-related type definitions for XyPrissJS Express integration
@@ -2245,102 +2025,323 @@ interface CacheStrategy {
2245
2025
  /** Strategy name for identification */
2246
2026
  name: string;
2247
2027
  /** Condition function to determine if strategy applies */
2248
- condition: (req: Request) => boolean;
2028
+ condition: (req: XyPrisRequest) => boolean;
2249
2029
  /** TTL for this strategy in seconds */
2250
2030
  ttl: number;
2251
2031
  /** Tags for cache invalidation */
2252
2032
  tags?: string[];
2253
2033
  }
2254
-
2034
+
2035
+ /**
2036
+ * @fileoverview Core type definitions for XyPrissJS Express integration
2037
+ *
2038
+ * This module contains fundamental types and utilities used throughout
2039
+ * the Express integration system.
2040
+ *
2041
+ * @version 4.5.11
2042
+ * @author XyPrissJS Team
2043
+ * @since 2025-01-06
2044
+ */
2045
+
2046
+ /**
2047
+ * Deep partial utility type that makes all properties optional recursively.
2048
+ *
2049
+ * This utility type is used throughout the configuration system to allow
2050
+ * partial configuration objects while maintaining type safety.
2051
+ *
2052
+ * @template T - The type to make deeply partial
2053
+ *
2054
+ * @example
2055
+ * ```typescript
2056
+ * interface Config {
2057
+ * server: {
2058
+ * port: number;
2059
+ * host: string;
2060
+ * };
2061
+ * }
2062
+ *
2063
+ * type PartialConfig = DeepPartial<Config>;
2064
+ * // Result: { server?: { port?: number; host?: string; } }
2065
+ * ```
2066
+ */
2067
+ type DeepPartial<T> = {
2068
+ [K in keyof T]?: T[K] extends infer U ? U extends object ? U extends readonly any[] ? U extends readonly (infer V)[] ? readonly DeepPartial<V>[] : U : U extends Function ? U : DeepPartial<U> : U : never;
2069
+ };
2070
+ /**
2071
+ * Validation result interface for request validation operations.
2072
+ *
2073
+ * Used by validation middleware and request handlers to provide
2074
+ * structured validation feedback.
2075
+ *
2076
+ * @interface ValidationResult
2077
+ *
2078
+ * @example
2079
+ * ```typescript
2080
+ * const result: ValidationResult = {
2081
+ * valid: false,
2082
+ * errors: ['Email is required', 'Password too short'],
2083
+ * data: { email: '', password: '123' }
2084
+ * };
2085
+ * ```
2086
+ */
2087
+ interface ValidationResult$1 {
2088
+ /** Whether the validation passed */
2089
+ valid: boolean;
2090
+ /** Array of validation error messages */
2091
+ errors: string[];
2092
+ /** The validated/sanitized data */
2093
+ data: any;
2094
+ }
2095
+ /**
2096
+ * User context information for authenticated requests.
2097
+ *
2098
+ * Contains user identity, permissions, and metadata for
2099
+ * authorization and audit purposes.
2100
+ *
2101
+ * @interface UserContext
2102
+ *
2103
+ * @example
2104
+ * ```typescript
2105
+ * const user: UserContext = {
2106
+ * id: 'user-123',
2107
+ * roles: ['admin', 'user'],
2108
+ * permissions: ['read:users', 'write:posts'],
2109
+ * metadata: { department: 'engineering', level: 'senior' }
2110
+ * };
2111
+ * ```
2112
+ */
2113
+ interface UserContext {
2114
+ /** Unique user identifier */
2115
+ id: string;
2116
+ /** Array of user roles */
2117
+ roles: string[];
2118
+ /** Array of specific permissions */
2119
+ permissions: string[];
2120
+ /** Additional user metadata */
2121
+ metadata: Record<string, any>;
2122
+ }
2123
+ /**
2124
+ * Session data structure for user sessions.
2125
+ *
2126
+ * Contains session information including expiration and
2127
+ * custom session data.
2128
+ *
2129
+ * @interface SessionData
2130
+ *
2131
+ * @example
2132
+ * ```typescript
2133
+ * const session: SessionData = {
2134
+ * id: 'session-abc123',
2135
+ * userId: 'user-123',
2136
+ * data: { theme: 'dark', language: 'en' },
2137
+ * expires: new Date(Date.now() + 3600000) // 1 hour
2138
+ * };
2139
+ * ```
2140
+ */
2141
+ interface SessionData {
2142
+ /** Unique session identifier */
2143
+ id: string;
2144
+ /** Associated user ID (optional) */
2145
+ userId?: string;
2146
+ /** Custom session data */
2147
+ data: Record<string, any>;
2148
+ /** Session expiration date */
2149
+ expires: Date;
2150
+ }
2151
+ /**
2152
+ * Pagination information for paginated responses.
2153
+ *
2154
+ * Used by API endpoints that return paginated data to provide
2155
+ * navigation information to clients.
2156
+ *
2157
+ * @interface PaginationInfo
2158
+ *
2159
+ * @example
2160
+ * ```typescript
2161
+ * const pagination: PaginationInfo = {
2162
+ * page: 2,
2163
+ * limit: 20,
2164
+ * total: 150,
2165
+ * pages: 8
2166
+ * };
2167
+ * ```
2168
+ */
2169
+ interface PaginationInfo {
2170
+ /** Current page number (1-based) */
2171
+ page: number;
2172
+ /** Number of items per page */
2173
+ limit: number;
2174
+ /** Total number of items */
2175
+ total: number;
2176
+ /** Total number of pages */
2177
+ pages: number;
2178
+ }
2179
+ /**
2180
+ * Enhanced Express request interface with additional utilities.
2181
+ *
2182
+ * Extends the standard Express Request with caching, security,
2183
+ * performance, and validation utilities.
2184
+ *
2185
+ * @interface EnhancedRequest
2186
+ * @extends Request
2187
+ *
2188
+ * @example
2189
+ * ```typescript
2190
+ * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
2191
+ * // Use enhanced features
2192
+ * const cached = await req.cache.get('users');
2193
+ * const encrypted = await req.security.encrypt(sensitiveData);
2194
+ * req.performance.start();
2195
+ *
2196
+ * // Validation
2197
+ * const validation = req.validation.query(userQuerySchema);
2198
+ * if (!validation.valid) {
2199
+ * return res.error('Invalid query parameters');
2200
+ * }
2201
+ * });
2202
+ * ```
2203
+ */
2204
+ interface EnhancedRequest extends XyPrisRequest {
2205
+ /** Cache utilities for request-level caching */
2206
+ cache: {
2207
+ /** Get cached value by key */
2208
+ get: (key: string) => Promise<any>;
2209
+ /** Set cached value with optional TTL */
2210
+ set: (key: string, value: any, ttl?: number) => Promise<void>;
2211
+ /** Delete cached value */
2212
+ del: (key: string) => Promise<void>;
2213
+ /** Tag cache entries for bulk invalidation */
2214
+ tags: (tags: string[]) => Promise<void>;
2215
+ };
2216
+ /** Security utilities for encryption and authentication */
2217
+ security: {
2218
+ /** Encrypt data using configured algorithm */
2219
+ encrypt: (data: any) => Promise<string>;
2220
+ /** Decrypt data using configured algorithm */
2221
+ decrypt: (data: string) => Promise<any>;
2222
+ /** Hash data using secure algorithm */
2223
+ hash: (data: string) => string;
2224
+ /** Verify data against hash */
2225
+ verify: (data: string, hash: string) => boolean;
2226
+ /** Generate secure token */
2227
+ generateToken: () => string;
2228
+ /** Session encryption key */
2229
+ sessionKey: string;
2230
+ };
2231
+ /** Performance monitoring utilities */
2232
+ performance: {
2233
+ /** Start performance timer */
2234
+ start: () => void;
2235
+ /** End performance timer and return duration */
2236
+ end: () => number;
2237
+ /** Mark a performance point */
2238
+ mark: (name: string) => void;
2239
+ /** Measure time between marks */
2240
+ measure: (name: string, start: string, end: string) => number;
2241
+ };
2242
+ /** Request validation utilities */
2243
+ validation: {
2244
+ /** Validate request body against schema */
2245
+ body: (schema: any) => ValidationResult$1;
2246
+ /** Validate query parameters against schema */
2247
+ query: (schema: any) => ValidationResult$1;
2248
+ /** Validate route parameters against schema */
2249
+ params: (schema: any) => ValidationResult$1;
2250
+ };
2251
+ /** User context (available after authentication) */
2252
+ user?: UserContext;
2253
+ /** Session data (available when sessions are enabled) */
2254
+ session?: SessionData;
2255
+ }
2256
+ /**
2257
+ * Enhanced Express response interface with additional utilities.
2258
+ *
2259
+ * Extends the standard Express Response with caching, security,
2260
+ * performance, and convenience methods.
2261
+ *
2262
+ * @interface EnhancedResponse
2263
+ * @extends Response
2264
+ *
2265
+ * @example
2266
+ * ```typescript
2267
+ * app.get('/api/users', async (req: EnhancedRequest, res: EnhancedResponse) => {
2268
+ * const users = await getUsersFromDB();
2269
+ *
2270
+ * // Use enhanced response methods
2271
+ * res.cache.set(3600, ['users']); // Cache for 1 hour with 'users' tag
2272
+ * res.performance.timing('db_query', 150);
2273
+ * res.success(users, 'Users retrieved successfully');
2274
+ * });
2275
+ * ```
2276
+ */
2277
+ interface EnhancedResponse extends XyPrisResponse {
2278
+ /** Cache utilities for response caching */
2279
+ cache: {
2280
+ /** Set cache headers and TTL for response */
2281
+ set: (ttl?: number, tags?: string[]) => void;
2282
+ /** Invalidate cache entries by tags */
2283
+ invalidate: (tags: string[]) => Promise<void>;
2284
+ };
2285
+ /** Security utilities for response encryption */
2286
+ security: {
2287
+ /** Encrypt response data */
2288
+ encrypt: (data: any) => EnhancedResponse;
2289
+ /** Sign response data */
2290
+ sign: (data: any) => EnhancedResponse;
2291
+ };
2292
+ /** Performance utilities for response metrics */
2293
+ performance: {
2294
+ /** Record timing metric */
2295
+ timing: (name: string, value: number) => void;
2296
+ /** Record custom metric */
2297
+ metric: (name: string, value: number) => void;
2298
+ };
2299
+ /** Send successful response with optional message */
2300
+ success: (data?: any, message?: string) => void;
2301
+ /** Send error response with message and status code */
2302
+ error: (error: string | Error, code?: number) => void;
2303
+ /** Send paginated response with pagination info */
2304
+ paginated: (data: any[], pagination: PaginationInfo) => void;
2305
+ }
2255
2306
  /**
2256
- * @fileoverview Performance-related type definitions for XyPrissJS Express integration
2257
- *
2258
- * This module contains all performance-related types including monitoring,
2259
- * optimization, metrics, and configuration.
2260
- *
2261
- * @version 4.5.11
2262
- * @author XyPrissJS Team
2263
- * @since 2025-01-06
2264
- */
2265
- /**
2266
- * Performance configuration interface.
2267
- *
2268
- * Comprehensive configuration for performance monitoring,
2269
- * optimization, and metrics collection.
2307
+ * Route handler function type with enhanced request/response.
2270
2308
  *
2271
- * @interface PerformanceConfig
2309
+ * @template T - Return type of the handler
2272
2310
  *
2273
2311
  * @example
2274
2312
  * ```typescript
2275
- * const perfConfig: PerformanceConfig = {
2276
- * enabled: true,
2277
- * metrics: ['response_time', 'memory_usage', 'cpu_usage'],
2278
- * interval: 30000, // 30 seconds
2279
- * alerts: [
2280
- * {
2281
- * metric: 'response_time',
2282
- * threshold: 1000, // 1 second
2283
- * action: 'log',
2284
- * cooldown: 300000 // 5 minutes
2285
- * }
2286
- * ],
2287
- * dashboard: true,
2288
- * export: {
2289
- * custom: (metrics) => {
2290
- * console.log('Custom metrics export:', metrics);
2291
- * }
2313
+ * const getUserHandler: RouteHandler = async (req, res, next) => {
2314
+ * try {
2315
+ * const user = await getUserById(req.params.id);
2316
+ * res.success(user);
2317
+ * } catch (error) {
2318
+ * next(error);
2292
2319
  * }
2293
2320
  * };
2294
2321
  * ```
2295
2322
  */
2296
- interface PerformanceConfig {
2297
- /** Enable performance monitoring */
2298
- enabled?: boolean;
2299
- /** Metrics to collect */
2300
- metrics?: string[];
2301
- /** Collection interval in milliseconds */
2302
- interval?: number;
2303
- /** Alert configurations */
2304
- alerts?: AlertConfig[];
2305
- /** Enable performance dashboard */
2306
- dashboard?: boolean;
2307
- /** Export configuration */
2308
- export?: {
2309
- /** Custom export function */
2310
- custom?: (metrics: any) => void;
2311
- };
2312
- }
2323
+ type RouteHandler = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction) => Promise<any> | any;
2313
2324
  /**
2314
- * Alert configuration interface.
2315
- *
2316
- * Configuration for performance alerts including thresholds,
2317
- * actions, and cooldown periods.
2318
- *
2319
- * @interface AlertConfig
2325
+ * Middleware function type with enhanced request/response.
2320
2326
  *
2321
2327
  * @example
2322
2328
  * ```typescript
2323
- * const alertConfig: AlertConfig = {
2324
- * metric: 'memory_usage',
2325
- * threshold: 0.85, // 85%
2326
- * action: 'webhook',
2327
- * target: 'https://alerts.example.com/webhook',
2328
- * cooldown: 600000 // 10 minutes
2329
+ * const authMiddleware: MiddlewareFunction = async (req, res, next) => {
2330
+ * const token = req.headers.authorization;
2331
+ * if (!token) {
2332
+ * return res.error('Authorization required', 401);
2333
+ * }
2334
+ *
2335
+ * try {
2336
+ * req.user = await verifyToken(token);
2337
+ * next();
2338
+ * } catch (error) {
2339
+ * res.error('Invalid token', 401);
2340
+ * }
2329
2341
  * };
2330
2342
  * ```
2331
2343
  */
2332
- interface AlertConfig {
2333
- /** Metric name to monitor */
2334
- metric: string;
2335
- /** Threshold value that triggers alert */
2336
- threshold: number;
2337
- /** Action to take when alert triggers */
2338
- action: "log" | "email" | "webhook" | "custom";
2339
- /** Target for the action (email, webhook URL, etc.) */
2340
- target?: string;
2341
- /** Cooldown period in milliseconds */
2342
- cooldown?: number;
2343
- }
2344
+ type MiddlewareFunction = (req: EnhancedRequest, res: EnhancedResponse, next: NextFunction) => Promise<void> | void;
2344
2345
 
2345
2346
  /**
2346
2347
  * @fileoverview Routing-related type definitions for XyPrissJS Express integration
@@ -2441,7 +2442,7 @@ interface RouteCacheConfig {
2441
2442
  /** Cache TTL in seconds */
2442
2443
  ttl?: number;
2443
2444
  /** Cache key generator */
2444
- key?: string | ((req: Request) => string);
2445
+ key?: string | ((req: XyPrisRequest) => string);
2445
2446
  /** Cache tags for invalidation */
2446
2447
  tags?: string[];
2447
2448
  /** Events that should invalidate this cache */
@@ -2480,9 +2481,9 @@ interface RouteRateLimitConfig {
2480
2481
  /** Include legacy rate limit headers */
2481
2482
  legacyHeaders?: boolean;
2482
2483
  /** Custom key generator for rate limiting */
2483
- keyGenerator?: (req: Request) => string;
2484
+ keyGenerator?: (req: XyPrisRequest) => string;
2484
2485
  /** Function to skip rate limiting for certain requests */
2485
- skip?: (req: Request) => boolean;
2486
+ skip?: (req: XyPrisRequest) => boolean;
2486
2487
  }
2487
2488
  /**
2488
2489
  * Route validation configuration interface.
@@ -2559,7 +2560,7 @@ interface RouteOptions {
2559
2560
  /** Cache TTL in seconds */
2560
2561
  ttl?: number;
2561
2562
  /** Cache key generator */
2562
- key?: string | ((req: Request) => string);
2563
+ key?: string | ((req: XyPrisRequest) => string);
2563
2564
  /** Cache tags */
2564
2565
  tags?: string[];
2565
2566
  /** Cache invalidation events */
@@ -2599,6 +2600,11 @@ interface RouteOptions {
2599
2600
  * Comprehensive types for the fluent middleware management API
2600
2601
  */
2601
2602
  type MiddlewarePriority = "critical" | "high" | "normal" | "low";
2603
+ interface MiddlewareConfiguration {
2604
+ enabled?: boolean;
2605
+ priority?: MiddlewarePriority;
2606
+ order?: number;
2607
+ }
2602
2608
  interface SecurityMiddlewareConfig {
2603
2609
  helmet?: boolean | {
2604
2610
  contentSecurityPolicy?: boolean | object;
@@ -2735,6 +2741,206 @@ interface XyPrissMiddlewareAPI {
2735
2741
  getConfig(): any;
2736
2742
  }
2737
2743
 
2744
+ /**
2745
+ * Centralized Logger for FastApi.ts Server
2746
+ * Provides granular control over logging output with enhanced robustness
2747
+ */
2748
+
2749
+ declare class Logger {
2750
+ private config;
2751
+ private static instance;
2752
+ private buffer;
2753
+ private flushTimer?;
2754
+ private isDisposed;
2755
+ private logQueue;
2756
+ private isProcessingQueue;
2757
+ private errorCount;
2758
+ private lastErrorTime;
2759
+ private suppressedComponents;
2760
+ constructor(config?: ServerOptions["logging"]);
2761
+ /**
2762
+ * Initialize log buffer system
2763
+ */
2764
+ private initializeBuffer;
2765
+ /**
2766
+ * Setup error handling and recovery mechanisms
2767
+ */
2768
+ private setupErrorHandling;
2769
+ /**
2770
+ * Emergency logging that bypasses normal filtering
2771
+ */
2772
+ private emergencyLog;
2773
+ /**
2774
+ * Start auto-flush timer for buffered logging
2775
+ */
2776
+ private startAutoFlush;
2777
+ /**
2778
+ * Flush buffered log entries
2779
+ */
2780
+ flush(): void;
2781
+ /**
2782
+ * Get or create singleton instance
2783
+ */
2784
+ static getInstance(config?: ServerOptions["logging"]): Logger;
2785
+ /**
2786
+ * Deep merge two objects
2787
+ */
2788
+ private deepMerge;
2789
+ /**
2790
+ * Update logger configuration
2791
+ */
2792
+ updateConfig(config: ServerOptions["logging"]): void;
2793
+ /**
2794
+ * Get current logger configuration (for debugging)
2795
+ */
2796
+ getConfig(): ServerOptions["logging"];
2797
+ /**
2798
+ * Check if we should suppress this log due to error rate limiting
2799
+ */
2800
+ private shouldSuppressError;
2801
+ /**
2802
+ * Check if logging is enabled for a specific component and type
2803
+ */
2804
+ private shouldLog;
2805
+ /**
2806
+ * Get memory usage information
2807
+ */
2808
+ private getMemoryInfo;
2809
+ /**
2810
+ * Get process ID
2811
+ */
2812
+ private getProcessId;
2813
+ /**
2814
+ * Truncate message if it exceeds max line length
2815
+ */
2816
+ private truncateMessage;
2817
+ /**
2818
+ * Format log message
2819
+ */
2820
+ private formatMessage;
2821
+ /**
2822
+ * Write log entry to output
2823
+ */
2824
+ private writeLog;
2825
+ /**
2826
+ * Process log queue
2827
+ */
2828
+ private processLogQueue;
2829
+ /**
2830
+ * Log a message
2831
+ */
2832
+ private log;
2833
+ error(component: LogComponent, message: string, ...args: any[]): void;
2834
+ warn(component: LogComponent, message: string, ...args: any[]): void;
2835
+ info(component: LogComponent, message: string, ...args: any[]): void;
2836
+ debug(component: LogComponent, message: string, ...args: any[]): void;
2837
+ verbose(component: LogComponent, message: string, ...args: any[]): void;
2838
+ startup(component: LogComponent, message: string, ...args: any[]): void;
2839
+ performance(component: LogComponent, message: string, ...args: any[]): void;
2840
+ hotReload(component: LogComponent, message: string, ...args: any[]): void;
2841
+ portSwitching(component: LogComponent, message: string, ...args: any[]): void;
2842
+ securityWarning(message: string, ...args: any[]): void;
2843
+ isEnabled(): boolean;
2844
+ getLevel(): LogLevel;
2845
+ isComponentEnabled(component: LogComponent): boolean;
2846
+ isTypeEnabled(type: LogType): boolean;
2847
+ /**
2848
+ * Get logging statistics
2849
+ */
2850
+ getStats(): {
2851
+ errorCount: number;
2852
+ lastErrorTime: number;
2853
+ suppressedComponents: string[];
2854
+ bufferSize: number;
2855
+ queueSize: number;
2856
+ };
2857
+ /**
2858
+ * Clear suppressed components
2859
+ */
2860
+ clearSuppression(): void;
2861
+ /**
2862
+ * Dispose logger and cleanup resources
2863
+ */
2864
+ dispose(): void;
2865
+ /**
2866
+ * Create a child logger with component-specific configuration
2867
+ */
2868
+ child(component: LogComponent, config?: Partial<ServerOptions["logging"]>): Logger;
2869
+ }
2870
+
2871
+ /**
2872
+ * File Upload Manager for XyPriss Server
2873
+ * Handles multer configuration and file upload middleware setup
2874
+ */
2875
+
2876
+ interface FileUploadConfig {
2877
+ /** Enable file upload handling */
2878
+ enabled?: boolean;
2879
+ /** Maximum file size in bytes */
2880
+ maxFileSize?: number;
2881
+ /** Maximum number of files per request */
2882
+ maxFiles?: number;
2883
+ /** Allowed MIME types */
2884
+ allowedMimeTypes?: string[];
2885
+ /** Allowed file extensions */
2886
+ allowedExtensions?: string[];
2887
+ /** Upload destination directory */
2888
+ destination?: string;
2889
+ /** Custom filename function */
2890
+ filename?: (req: any, file: any, callback: (error: Error | null, filename: string) => void) => void;
2891
+ /** Detailed limits configuration */
2892
+ limits?: {
2893
+ /** Max field name size in bytes */
2894
+ fieldNameSize?: number;
2895
+ /** Max field value size in bytes */
2896
+ fieldSize?: number;
2897
+ /** Max number of non-file fields */
2898
+ fields?: number;
2899
+ /** Max file size in bytes */
2900
+ fileSize?: number;
2901
+ /** Max number of file fields */
2902
+ files?: number;
2903
+ /** Max number of header key=>value pairs */
2904
+ headerPairs?: number;
2905
+ };
2906
+ /** Preserve full paths instead of just filenames */
2907
+ preservePath?: boolean;
2908
+ /** Custom file filter function */
2909
+ fileFilter?: (req: any, file: any, callback: (error: Error | null, acceptFile: boolean) => void) => void;
2910
+ /** Storage type */
2911
+ storage?: 'disk' | 'memory' | 'custom';
2912
+ /** Create parent directories if they don't exist */
2913
+ createParentPath?: boolean;
2914
+ /** Abort request on limit reached */
2915
+ abortOnLimit?: boolean;
2916
+ /** Response message when limit is reached */
2917
+ responseOnLimit?: string;
2918
+ /** Use temporary files for large uploads */
2919
+ useTempFiles?: boolean;
2920
+ /** Temporary file directory */
2921
+ tempFileDir?: string;
2922
+ /** Parse nested objects in multipart data */
2923
+ parseNested?: boolean;
2924
+ /** Enable debug logging */
2925
+ debug?: boolean;
2926
+ /** Custom multer options */
2927
+ multerOptions?: {
2928
+ dest?: string;
2929
+ storage?: any;
2930
+ limits?: {
2931
+ fieldNameSize?: number;
2932
+ fieldSize?: number;
2933
+ fields?: number;
2934
+ fileSize?: number;
2935
+ files?: number;
2936
+ headerPairs?: number;
2937
+ };
2938
+ preservePath?: boolean;
2939
+ fileFilter?: (req: any, file: any, callback: (error: Error | null, acceptFile: boolean) => void) => void;
2940
+ [key: string]: any;
2941
+ };
2942
+ }
2943
+
2738
2944
  /**
2739
2945
  * XyPrissJS Express Types - Main Export File
2740
2946
  *
@@ -2757,6 +2963,47 @@ interface XyPrissMiddlewareAPI {
2757
2963
 
2758
2964
  type RequestHandler = (req: XyPrisRequest, res: XyPrisResponse, next?: NextFunction) => void | Promise<void>;
2759
2965
 
2966
+ /**
2967
+ * Configuration for individual servers in multi-server mode
2968
+ *
2969
+ * @interface MultiServerConfig
2970
+ * @version 4.5.11
2971
+ * @author XyPrissJS Team
2972
+ * @since 2025-01-06
2973
+ */
2974
+ interface MultiServerConfig {
2975
+ /** Unique identifier for this server instance */
2976
+ id: string;
2977
+ /** Port number for this server */
2978
+ port: number;
2979
+ /** Host for this server (optional, defaults to main config) */
2980
+ host?: string;
2981
+ /** Route prefix that this server should handle */
2982
+ routePrefix?: string;
2983
+ /** Array of allowed route patterns for this server */
2984
+ allowedRoutes?: string[];
2985
+ /** Server-specific overrides */
2986
+ server?: {
2987
+ host?: string;
2988
+ trustProxy?: boolean;
2989
+ jsonLimit?: string;
2990
+ urlEncodedLimit?: string;
2991
+ enableMiddleware?: boolean;
2992
+ autoParseJson?: boolean;
2993
+ };
2994
+ /** Security overrides for this server */
2995
+ security?: SecurityConfig;
2996
+ /** Performance overrides for this server */
2997
+ performance?: PerformanceConfig;
2998
+ /** Cache overrides for this server */
2999
+ cache?: CacheConfig;
3000
+ /** File upload overrides for this server */
3001
+ fileUpload?: FileUploadConfig;
3002
+ /** Middleware configuration specific to this server */
3003
+ middleware?: MiddlewareConfiguration;
3004
+ /** Logging configuration specific to this server */
3005
+ logging?: ComponentLogConfig;
3006
+ }
2760
3007
  /**
2761
3008
  * @fileoverview Comprehensive server options interface for XyPrissJS Express integration
2762
3009
  *
@@ -2996,6 +3243,45 @@ interface ServerOptions {
2996
3243
  onPortSwitch?: (originalPort: number, newPort: number) => void;
2997
3244
  };
2998
3245
  };
3246
+ /**
3247
+ * Multi-server configuration for creating multiple server instances
3248
+ *
3249
+ * Allows running multiple server instances with different configurations,
3250
+ * ports, and route scopes from a single configuration.
3251
+ *
3252
+ * @example
3253
+ * ```typescript
3254
+ * multiServer: {
3255
+ * enabled: true,
3256
+ * servers: [
3257
+ * {
3258
+ * id: "api-server",
3259
+ * port: 3001,
3260
+ * routePrefix: "/api/v1",
3261
+ * allowedRoutes: ["/api/v1/*"],
3262
+ * server: {
3263
+ * host: "localhost"
3264
+ * }
3265
+ * },
3266
+ * {
3267
+ * id: "admin-server",
3268
+ * port: 3002,
3269
+ * routePrefix: "/admin",
3270
+ * allowedRoutes: ["/admin/*"],
3271
+ * security: {
3272
+ * level: "maximum"
3273
+ * }
3274
+ * }
3275
+ * ]
3276
+ * }
3277
+ * ```
3278
+ */
3279
+ multiServer?: {
3280
+ /** Enable multi-server mode */
3281
+ enabled?: boolean;
3282
+ /** Array of server configurations */
3283
+ servers?: MultiServerConfig[];
3284
+ };
2999
3285
  /**
3000
3286
  * Request management configuration for handling timeouts, network quality, and request lifecycle
3001
3287
  *
@@ -3116,6 +3402,49 @@ interface ServerOptions {
3116
3402
  customValidator?: (req: any) => boolean | Promise<boolean>;
3117
3403
  };
3118
3404
  };
3405
+ /**
3406
+ * File upload configuration for handling multipart/form-data requests.
3407
+ *
3408
+ * Comprehensive file upload settings including size limits, allowed types,
3409
+ * storage options, and security features for file handling.
3410
+ *
3411
+ * @example
3412
+ * ```typescript
3413
+ * fileUpload: {
3414
+ * enabled: true,
3415
+ * maxFileSize: 10 * 1024 * 1024, // 10MB
3416
+ * maxFiles: 5,
3417
+ * allowedMimeTypes: ['image/jpeg', 'image/png', 'application/pdf'],
3418
+ * allowedExtensions: ['.jpg', '.jpeg', '.png', '.pdf'],
3419
+ * destination: './uploads',
3420
+ * filename: (req, file, callback) => {
3421
+ * callback(null, `${Date.now()}-${file.originalname}`);
3422
+ * },
3423
+ * limits: {
3424
+ * fieldNameSize: 100,
3425
+ * fieldSize: 1024,
3426
+ * fields: 10,
3427
+ * fileSize: 10 * 1024 * 1024,
3428
+ * files: 5,
3429
+ * headerPairs: 2000
3430
+ * },
3431
+ * preservePath: false,
3432
+ * fileFilter: (req, file, callback) => {
3433
+ * // Custom file validation logic
3434
+ * callback(null, true);
3435
+ * },
3436
+ * storage: 'disk', // 'disk' | 'memory' | 'custom'
3437
+ * createParentPath: true,
3438
+ * abortOnLimit: false,
3439
+ * responseOnLimit: 'File too large',
3440
+ * useTempFiles: false,
3441
+ * tempFileDir: '/tmp',
3442
+ * parseNested: true,
3443
+ * debug: false
3444
+ * }
3445
+ * ```
3446
+ */
3447
+ fileUpload?: FileUploadConfig;
3119
3448
  /**
3120
3449
  * Security configuration for the server.
3121
3450
  *
@@ -4019,6 +4348,73 @@ interface UltraFastApp {
4019
4348
  * ```
4020
4349
  */
4021
4350
  middleware: () => XyPrissMiddlewareAPI;
4351
+ /**
4352
+ * Multer instance for file uploads (available when fileUpload.enabled is true)
4353
+ */
4354
+ upload?: any;
4355
+ /**
4356
+ * Create single file upload middleware
4357
+ *
4358
+ * @param fieldname - Name of the form field
4359
+ * @returns Multer middleware for single file upload
4360
+ *
4361
+ * @example
4362
+ * ```typescript
4363
+ * app.post('/upload', app.uploadSingle('file'), (req, res) => {
4364
+ * console.log(req.file);
4365
+ * res.send('File uploaded');
4366
+ * });
4367
+ * ```
4368
+ */
4369
+ uploadSingle: (fieldname: string) => any;
4370
+ /**
4371
+ * Create array file upload middleware
4372
+ *
4373
+ * @param fieldname - Name of the form field
4374
+ * @param maxCount - Maximum number of files (optional)
4375
+ * @returns Multer middleware for array file upload
4376
+ *
4377
+ * @example
4378
+ * ```typescript
4379
+ * app.post('/upload', app.uploadArray('files', 5), (req, res) => {
4380
+ * console.log(req.files);
4381
+ * res.send('Files uploaded');
4382
+ * });
4383
+ * ```
4384
+ */
4385
+ uploadArray?: (fieldname: string, maxCount?: number) => any;
4386
+ /**
4387
+ * Create fields file upload middleware
4388
+ *
4389
+ * @param fields - Array of field configurations
4390
+ * @returns Multer middleware for multiple fields upload
4391
+ *
4392
+ * @example
4393
+ * ```typescript
4394
+ * app.post('/upload', app.uploadFields([
4395
+ * { name: 'avatar', maxCount: 1 },
4396
+ * { name: 'gallery', maxCount: 8 }
4397
+ * ]), (req, res) => {
4398
+ * console.log(req.files);
4399
+ * res.send('Files uploaded');
4400
+ * });
4401
+ * ```
4402
+ */
4403
+ uploadFields?: (fields: any[]) => any;
4404
+ /**
4405
+ * Create any file upload middleware
4406
+ *
4407
+ * @returns Multer middleware that accepts any files
4408
+ *
4409
+ * @example
4410
+ * ```typescript
4411
+ * app.post('/upload', app.uploadAny(), (req, res) => {
4412
+ * console.log(req.files);
4413
+ * res.send('Files uploaded');
4414
+ * });
4415
+ * ```
4416
+ */
4417
+ uploadAny?: () => any;
4022
4418
  /**
4023
4419
  * Scale up the cluster by adding workers.
4024
4420
  *
@@ -4179,6 +4575,49 @@ interface UltraFastApp {
4179
4575
  getServerStats?: () => Promise<any>;
4180
4576
  }
4181
4577
 
4578
+ /**
4579
+ * @fileoverview Main export file for XyPrissJS Express integration types
4580
+ *
4581
+ * This file provides a centralized export point for all Express integration
4582
+ * types, organized into modular categories for better maintainability.
4583
+ *
4584
+ * @version 4.5.11
4585
+ * @author XyPrissJS Team
4586
+ * @since 2025-01-06
4587
+ *
4588
+ * @example
4589
+ * ```typescript
4590
+ * // Import all types
4591
+ * import * as XyPrissTypes from './types';
4592
+ *
4593
+ * // Import specific categories
4594
+ * import { CacheConfig, SecurityConfig } from './types';
4595
+ *
4596
+ * // Import from specific modules
4597
+ * import { PerformanceMetrics } from './types/performance';
4598
+ * import { RouteConfig } from './types/routing';
4599
+ * ```
4600
+ */
4601
+
4602
+ declare global {
4603
+ const Bun: {
4604
+ spawn: (options: {
4605
+ cmd: string[];
4606
+ env?: Record<string, string>;
4607
+ stdio?: string[];
4608
+ }) => BunSubprocess;
4609
+ };
4610
+ }
4611
+ type BunSubprocess = {
4612
+ exited: Promise<number | null>;
4613
+ kill: (signal?: string) => void;
4614
+ killed: boolean;
4615
+ pid: number;
4616
+ stdout?: ReadableStream<Uint8Array>;
4617
+ stderr?: ReadableStream<Uint8Array>;
4618
+ stdin?: WritableStream<Uint8Array>;
4619
+ };
4620
+
4182
4621
  /**
4183
4622
  * XyPrissJS Cluster Manager
4184
4623
  * cluster management for Express applications with advanced monitoring
@@ -4502,133 +4941,6 @@ declare class ClusterManager extends EventEmitter implements RobustClusterManage
4502
4941
  private closePersistenceManager;
4503
4942
  }
4504
4943
 
4505
- /**
4506
- * Centralized Logger for FastApi.ts Server
4507
- * Provides granular control over logging output with enhanced robustness
4508
- */
4509
-
4510
- declare class Logger {
4511
- private config;
4512
- private static instance;
4513
- private buffer;
4514
- private flushTimer?;
4515
- private isDisposed;
4516
- private logQueue;
4517
- private isProcessingQueue;
4518
- private errorCount;
4519
- private lastErrorTime;
4520
- private suppressedComponents;
4521
- constructor(config?: ServerOptions["logging"]);
4522
- /**
4523
- * Initialize log buffer system
4524
- */
4525
- private initializeBuffer;
4526
- /**
4527
- * Setup error handling and recovery mechanisms
4528
- */
4529
- private setupErrorHandling;
4530
- /**
4531
- * Emergency logging that bypasses normal filtering
4532
- */
4533
- private emergencyLog;
4534
- /**
4535
- * Start auto-flush timer for buffered logging
4536
- */
4537
- private startAutoFlush;
4538
- /**
4539
- * Flush buffered log entries
4540
- */
4541
- flush(): void;
4542
- /**
4543
- * Get or create singleton instance
4544
- */
4545
- static getInstance(config?: ServerOptions["logging"]): Logger;
4546
- /**
4547
- * Deep merge two objects
4548
- */
4549
- private deepMerge;
4550
- /**
4551
- * Update logger configuration
4552
- */
4553
- updateConfig(config: ServerOptions["logging"]): void;
4554
- /**
4555
- * Get current logger configuration (for debugging)
4556
- */
4557
- getConfig(): ServerOptions["logging"];
4558
- /**
4559
- * Check if we should suppress this log due to error rate limiting
4560
- */
4561
- private shouldSuppressError;
4562
- /**
4563
- * Check if logging is enabled for a specific component and type
4564
- */
4565
- private shouldLog;
4566
- /**
4567
- * Get memory usage information
4568
- */
4569
- private getMemoryInfo;
4570
- /**
4571
- * Get process ID
4572
- */
4573
- private getProcessId;
4574
- /**
4575
- * Truncate message if it exceeds max line length
4576
- */
4577
- private truncateMessage;
4578
- /**
4579
- * Format log message
4580
- */
4581
- private formatMessage;
4582
- /**
4583
- * Write log entry to output
4584
- */
4585
- private writeLog;
4586
- /**
4587
- * Process log queue
4588
- */
4589
- private processLogQueue;
4590
- /**
4591
- * Log a message
4592
- */
4593
- private log;
4594
- error(component: LogComponent, message: string, ...args: any[]): void;
4595
- warn(component: LogComponent, message: string, ...args: any[]): void;
4596
- info(component: LogComponent, message: string, ...args: any[]): void;
4597
- debug(component: LogComponent, message: string, ...args: any[]): void;
4598
- verbose(component: LogComponent, message: string, ...args: any[]): void;
4599
- startup(component: LogComponent, message: string, ...args: any[]): void;
4600
- performance(component: LogComponent, message: string, ...args: any[]): void;
4601
- hotReload(component: LogComponent, message: string, ...args: any[]): void;
4602
- portSwitching(component: LogComponent, message: string, ...args: any[]): void;
4603
- securityWarning(message: string, ...args: any[]): void;
4604
- isEnabled(): boolean;
4605
- getLevel(): LogLevel;
4606
- isComponentEnabled(component: LogComponent): boolean;
4607
- isTypeEnabled(type: LogType): boolean;
4608
- /**
4609
- * Get logging statistics
4610
- */
4611
- getStats(): {
4612
- errorCount: number;
4613
- lastErrorTime: number;
4614
- suppressedComponents: string[];
4615
- bufferSize: number;
4616
- queueSize: number;
4617
- };
4618
- /**
4619
- * Clear suppressed components
4620
- */
4621
- clearSuppression(): void;
4622
- /**
4623
- * Dispose logger and cleanup resources
4624
- */
4625
- dispose(): void;
4626
- /**
4627
- * Create a child logger with component-specific configuration
4628
- */
4629
- child(component: LogComponent, config?: Partial<ServerOptions["logging"]>): Logger;
4630
- }
4631
-
4632
4944
  /**
4633
4945
  * Ultra-Fast Plugin System Types
4634
4946
  *
@@ -4663,9 +4975,9 @@ declare enum PluginPriority {
4663
4975
  * Plugin execution context with performance tracking
4664
4976
  */
4665
4977
  interface PluginExecutionContext {
4666
- req: Request;
4667
- res: Response;
4668
- next: NextFunction$1;
4978
+ req: XyPrisRequest;
4979
+ res: XyPrisResponse;
4980
+ next: NextFunction;
4669
4981
  startTime: number;
4670
4982
  executionId: string;
4671
4983
  cache: SecureCacheAdapter;
@@ -5484,11 +5796,16 @@ declare class XyPrissServer {
5484
5796
  private fileWatcherManager;
5485
5797
  private consoleInterceptor;
5486
5798
  private workerPoolComponent;
5799
+ private fileUploadManager;
5487
5800
  private notFoundHandler;
5488
5801
  private serverPluginManager;
5489
5802
  private securityMiddleware?;
5490
5803
  private lifecycleManager;
5491
5804
  constructor(userOptions?: ServerOptions);
5805
+ /**
5806
+ * Initialize file upload methods synchronously for immediate availability
5807
+ */
5808
+ private initializeFileUploadMethodsSync;
5492
5809
  /**
5493
5810
  * Initialize the ServerLifecycleManager
5494
5811
  */
@@ -5629,6 +5946,19 @@ declare class XyPrissServer {
5629
5946
  stop(): Promise<void>;
5630
5947
  }
5631
5948
 
5949
+ /**
5950
+ * Multi-Server Manager for XyPriss
5951
+ * Handles creation and management of multiple server instances
5952
+ */
5953
+
5954
+ interface MultiServerInstance {
5955
+ id: string;
5956
+ server: XyPrissServer;
5957
+ config: MultiServerConfig;
5958
+ port: number;
5959
+ host: string;
5960
+ }
5961
+
5632
5962
  /**
5633
5963
  * Safe JSON Middleware for Express
5634
5964
  * Automatically handles circular references in JSON responses
@@ -5668,7 +5998,7 @@ interface SafeJsonOptions {
5668
5998
  /**
5669
5999
  * Creates middleware that safely handles JSON serialization
5670
6000
  */
5671
- declare function createSafeJsonMiddleware(options?: SafeJsonOptions): (req: Request, res: Response, next: NextFunction$1) => void;
6001
+ declare function createSafeJsonMiddleware(options?: SafeJsonOptions): (req: XyPrisRequest, res: XyPrisResponse, next: NextFunction) => void;
5672
6002
  /**
5673
6003
  * Quick setup function for common use cases
5674
6004
  */
@@ -5680,11 +6010,11 @@ declare function safeJsonStringify(obj: any, options?: SafeJsonOptions): string;
5680
6010
  /**
5681
6011
  * Enhanced res.json replacement that can be used manually
5682
6012
  */
5683
- declare function sendSafeJson(res: Response, obj: any, options?: SafeJsonOptions): void;
6013
+ declare function sendSafeJson(res: XyPrisResponse, obj: any, options?: SafeJsonOptions): void;
5684
6014
  /**
5685
6015
  * Middleware specifically for debugging circular references
5686
6016
  */
5687
- declare function createCircularRefDebugger(): (req: Request, res: Response, next: NextFunction$1) => void;
6017
+ declare function createCircularRefDebugger(): (req: XyPrisRequest, res: XyPrisResponse, next: NextFunction) => void;
5688
6018
 
5689
6019
  /**
5690
6020
  * **CONVENIENCE FUNCTIONS: Quick access to common serialization patterns**
@@ -5728,8 +6058,9 @@ declare const expressStringify: (obj: any) => string;
5728
6058
  /**
5729
6059
  * Create ultra-fast Express server (zero-async)
5730
6060
  * Returns app instance ready to use immediately
6061
+ * If multi-server mode is enabled, returns a MultiServerApp interface
5731
6062
  */
5732
- declare function createServer(options?: ServerOptions): UltraFastApp;
6063
+ declare function createServer(options?: ServerOptions): UltraFastApp | MultiServerApp;
5733
6064
  /**
5734
6065
  * Create ultra-fast Express server class instance
5735
6066
  */
@@ -5739,6 +6070,41 @@ declare function createServerInstance(options?: ServerOptions): XyPrissServer;
5739
6070
  */
5740
6071
  declare function createCacheMiddleware(cache: SecureCacheAdapter, options?: RouteOptions): RequestHandler;
5741
6072
 
6073
+ /**
6074
+ * Multi-Server App interface for managing multiple server instances
6075
+ * Extends UltraFastApp to maintain API compatibility
6076
+ */
6077
+ interface MultiServerApp extends Omit<UltraFastApp, 'start'> {
6078
+ /**
6079
+ * Start all server instances (simple API - hides complexity)
6080
+ */
6081
+ start(): Promise<void>;
6082
+ /**
6083
+ * Start all servers (alias for start - more explicit)
6084
+ */
6085
+ startAllServers(): Promise<void>;
6086
+ /**
6087
+ * Stop all server instances
6088
+ */
6089
+ stop(): Promise<void>;
6090
+ /**
6091
+ * Stop all servers (alias for stop - more explicit)
6092
+ */
6093
+ stopAllServers(): Promise<void>;
6094
+ /**
6095
+ * Get all server instances
6096
+ */
6097
+ getServers(): MultiServerInstance[];
6098
+ /**
6099
+ * Get a specific server instance by ID
6100
+ */
6101
+ getServer(id: string): MultiServerInstance | undefined;
6102
+ /**
6103
+ * Get multi-server statistics
6104
+ */
6105
+ getStats(): any;
6106
+ }
6107
+
5742
6108
  /**
5743
6109
  * XyPrissJS Smart Routes
5744
6110
  * Intelligent route handlers with automatic optimization, caching, and security
@@ -6417,7 +6783,7 @@ declare class SecureString {
6417
6783
  /**
6418
6784
  * Generates a cryptographically secure salt
6419
6785
  */
6420
- static generateSalt(length?: number, format?: HashOutputFormat): string | Uint8Array<ArrayBufferLike>;
6786
+ static generateSalt(length?: number, format?: HashOutputFormat): string | Uint8Array;
6421
6787
  /**
6422
6788
  * Performs constant-time hash comparison
6423
6789
  */
@@ -9327,7 +9693,7 @@ declare class PluginEngine extends EventEmitter {
9327
9693
  /**
9328
9694
  * Execute plugins for a specific type with ultra-fast performance
9329
9695
  */
9330
- executePlugins(type: PluginType, req: Request, res: Response, next: NextFunction$1): Promise<boolean>;
9696
+ executePlugins(type: PluginType, req: XyPrisRequest, res: XyPrisResponse, next: NextFunction): Promise<boolean>;
9331
9697
  /**
9332
9698
  * Execute a single plugin with comprehensive error handling
9333
9699
  */
@@ -9938,7 +10304,7 @@ declare class ConnectionPlugin extends NetworkPlugin {
9938
10304
  /**
9939
10305
  * Serve a static file with proper headers and caching
9940
10306
  */
9941
- serveStaticFile(resource: string, res: Response): Promise<boolean>;
10307
+ serveStaticFile(resource: string, res: XyPrisResponse): Promise<boolean>;
9942
10308
  /**
9943
10309
  * Cleanup resources
9944
10310
  */
@@ -9996,26 +10362,6 @@ declare class CompressionPlugin extends NetworkPlugin {
9996
10362
  * Match content type with pattern (supports wildcards)
9997
10363
  */
9998
10364
  private matchesContentType;
9999
- /**
10000
- * Select best compression algorithm based on client support and preferences
10001
- */
10002
- private selectCompressionAlgorithm;
10003
- /**
10004
- * Apply compression to response
10005
- */
10006
- private applyCompression;
10007
- /**
10008
- * Create compression stream for algorithm
10009
- */
10010
- private createCompressionStream;
10011
- /**
10012
- * Intercept response to apply compression
10013
- */
10014
- private interceptResponse;
10015
- /**
10016
- * Update compression statistics
10017
- */
10018
- private updateCompressionStats;
10019
10365
  /**
10020
10366
  * Get compression configuration
10021
10367
  */
@@ -10430,7 +10776,7 @@ declare class PluginDevelopmentHelpers {
10430
10776
  /**
10431
10777
  * Quick development server with sensible defaults
10432
10778
  */
10433
- declare function quickServer(port?: number): UltraFastApp;
10779
+ declare function quickServer(port?: number): UltraFastApp | MultiServerApp;
10434
10780
 
10435
10781
  /***************************************************************************
10436
10782
  * XyPrissJS - Advanced JavaScript Security Library
@@ -10465,4 +10811,4 @@ declare function quickServer(port?: number): UltraFastApp;
10465
10811
  declare function Router(): XyPrissRouter;
10466
10812
 
10467
10813
  export { CachePlugin as CachePluginBase, CompressionPlugin, ConnectionPlugin, DEFAULT_PLUGIN_CONFIG, JWTAuthPlugin, NetworkCategory, NetworkPlugin, NetworkPluginFactory, NetworkPluginUtils, PERFORMANCE_TARGETS, PLUGIN_SYSTEM_NAME, PLUGIN_SYSTEM_VERSION, PerformanceMonitor, PerformancePlugin as PerformancePluginBase, PluginDevelopmentHelpers, PluginEngine, PluginEventType, PluginPriority, PluginRegistry, PluginSystemFactory, PluginSystemUtils, PluginType, ProxyPlugin, RateLimitPlugin, ResponseTimePlugin, Route, Router, SecurityMiddleware, SecurityPlugin as SecurityPluginBase, SmartCachePlugin, XyPrissRouter, createCacheMiddleware, createCircularRefDebugger, createOptimalCache, createSafeJsonMiddleware, createServer, createServerInstance, expressStringify, fastStringify, quickServer, safeJsonStringify, safeStringify, sendSafeJson, setupSafeJson };
10468
- export type { BasePlugin, CacheConfig, CachePlugin$1 as CachePlugin, CompressionAlgorithm, CompressionConfig, ConnectionConfig, FailoverConfig, HTTPCacheConfig, HealthCheckConfig, CachePlugin$1 as ICachePlugin, PerformancePlugin$1 as IPerformancePlugin, SecurityPlugin$1 as ISecurityPlugin, LoadBalancingStrategy, NativePlugin, NetworkExecutionContext, NetworkExecutionResult, NetworkHealthStatus, NetworkPluginConfig, NetworkSecurityConfig, NextFunction, PerformanceConfig, PerformanceMetrics, PerformancePlugin$1 as PerformancePlugin, PluginConfiguration, PluginEvent, PluginExecutionContext, PluginExecutionResult, PluginExecutionStats, PluginInitializationContext, PluginRegistryConfig, ProxyConfig, RateLimitConfig, RateLimitRule, RateLimitStrategy, RedisConfig, XyPrisRequest as Request, RequestHandler, XyPrisResponse as Response, RouteConfig, RouteOptions, SecurityConfig, SecurityPlugin$1 as SecurityPlugin, ServerOptions, SmartRouteConfig, UltraFastApp, UpstreamServer, WebSocketConfig };
10814
+ export type { BasePlugin, CacheConfig, CachePlugin$1 as CachePlugin, CompressionAlgorithm, CompressionConfig, ConnectionConfig, FailoverConfig, HTTPCacheConfig, HealthCheckConfig, CachePlugin$1 as ICachePlugin, PerformancePlugin$1 as IPerformancePlugin, SecurityPlugin$1 as ISecurityPlugin, LoadBalancingStrategy, MultiServerApp, MultiServerConfig, NativePlugin, NetworkExecutionContext, NetworkExecutionResult, NetworkHealthStatus, NetworkPluginConfig, NetworkSecurityConfig, NextFunction, PerformanceConfig, PerformanceMetrics, PerformancePlugin$1 as PerformancePlugin, PluginConfiguration, PluginEvent, PluginExecutionContext, PluginExecutionResult, PluginExecutionStats, PluginInitializationContext, PluginRegistryConfig, ProxyConfig, RateLimitConfig, RateLimitRule, RateLimitStrategy, RedisConfig, XyPrisRequest as Request, RequestHandler, XyPrisResponse as Response, RouteConfig, RouteOptions, SecurityConfig, SecurityPlugin$1 as SecurityPlugin, ServerOptions, SmartRouteConfig, UltraFastApp, UpstreamServer, WebSocketConfig, MultiServerApp as XyPMS, XyPrisRequest as XyPrissRequest, XyPrisResponse as XyPrissResponse };