blaizejs 0.5.0 → 0.5.2

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 (27) hide show
  1. package/dist/{chunk-J7KS32ZT.js → chunk-4QEX5ARZ.js} +3 -3
  2. package/dist/chunk-DN5WHXRA.js +11 -0
  3. package/dist/chunk-DN5WHXRA.js.map +1 -0
  4. package/dist/{chunk-6A3MHG3V.js → chunk-EB3TZGU4.js} +3 -3
  5. package/dist/{chunk-2LP25IUP.js → chunk-QYXAQD7H.js} +3 -3
  6. package/dist/{chunk-6XBGCGAR.js → chunk-RUCGYLJ6.js} +3 -3
  7. package/dist/index.cjs +14 -14
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +824 -704
  10. package/dist/index.d.ts +824 -704
  11. package/dist/index.js +15 -15
  12. package/dist/index.js.map +1 -1
  13. package/dist/{internal-server-error-BDHJW7WB.js → internal-server-error-I43ZDXIR.js} +3 -3
  14. package/dist/{payload-too-large-error-PX6RP7T6.js → payload-too-large-error-OQEOP3U2.js} +3 -3
  15. package/dist/{unsupported-media-type-error-IXHPPRCO.js → unsupported-media-type-error-7UF4VYIN.js} +3 -3
  16. package/dist/{validation-error-FNJKIDG6.js → validation-error-ZPBPCFKL.js} +3 -3
  17. package/package.json +1 -1
  18. package/dist/chunk-QD45PRU4.js +0 -11
  19. package/dist/chunk-QD45PRU4.js.map +0 -1
  20. /package/dist/{chunk-J7KS32ZT.js.map → chunk-4QEX5ARZ.js.map} +0 -0
  21. /package/dist/{chunk-6A3MHG3V.js.map → chunk-EB3TZGU4.js.map} +0 -0
  22. /package/dist/{chunk-2LP25IUP.js.map → chunk-QYXAQD7H.js.map} +0 -0
  23. /package/dist/{chunk-6XBGCGAR.js.map → chunk-RUCGYLJ6.js.map} +0 -0
  24. /package/dist/{internal-server-error-BDHJW7WB.js.map → internal-server-error-I43ZDXIR.js.map} +0 -0
  25. /package/dist/{payload-too-large-error-PX6RP7T6.js.map → payload-too-large-error-OQEOP3U2.js.map} +0 -0
  26. /package/dist/{unsupported-media-type-error-IXHPPRCO.js.map → unsupported-media-type-error-7UF4VYIN.js.map} +0 -0
  27. /package/dist/{validation-error-FNJKIDG6.js.map → validation-error-ZPBPCFKL.js.map} +0 -0
package/dist/index.d.cts CHANGED
@@ -135,6 +135,16 @@ interface ValidationFieldError {
135
135
  /** Expected type or format */
136
136
  expectedType?: string;
137
137
  }
138
+ interface ServiceNotAvailableDetails {
139
+ /** Service that's unavailable */
140
+ service?: string;
141
+ /** Seconds to wait before retry */
142
+ retryAfter?: number;
143
+ /** Why service is unavailable */
144
+ reason?: 'maintenance' | 'overload' | 'circuit_breaker' | 'dependency_down';
145
+ /** Additional context */
146
+ [key: string]: unknown;
147
+ }
138
148
  /**
139
149
  * Validation error details structure
140
150
  *
@@ -210,7 +220,9 @@ declare enum ErrorType {
210
220
  /** SSE buffer overflow (503) */
211
221
  SSE_BUFFER_OVERFLOW = "SSE_BUFFER_OVERFLOW",
212
222
  /** SSE stream closed (410) */
213
- SSE_STREAM_CLOSED = "SSE_STREAM_CLOSED"
223
+ SSE_STREAM_CLOSED = "SSE_STREAM_CLOSED",
224
+ /** Service temporarily unavailable (503) */
225
+ SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
214
226
  }
215
227
  /**
216
228
  * Error severity levels for logging and monitoring
@@ -897,6 +909,18 @@ interface Context<S extends State = State, Svc extends Services = Services, TBod
897
909
  */
898
910
  services: Svc;
899
911
  }
912
+ interface BodyLimits {
913
+ /** Maximum JSON body size in bytes (default: 512KB) */
914
+ json: number;
915
+ /** Maximum form data size in bytes (default: 1MB) */
916
+ form: number;
917
+ /** Maximum text body size in bytes (default: 5MB) */
918
+ text: number;
919
+ /** Maximum raw/binary body size in bytes (default: 10MB) */
920
+ raw: number;
921
+ /** Multipart/form-data limits */
922
+ multipart: MultipartLimits;
923
+ }
900
924
  type MultipartLimits = {
901
925
  maxFileSize?: number;
902
926
  maxTotalSize?: number;
@@ -924,13 +948,7 @@ interface ContextOptions {
924
948
  /**
925
949
  * Limits for various body types to prevent abuse
926
950
  */
927
- bodyLimits?: {
928
- json?: number;
929
- form?: number;
930
- text?: number;
931
- multipart?: MultipartLimits;
932
- raw?: number;
933
- };
951
+ bodyLimits: BodyLimits;
934
952
  }
935
953
  /**
936
954
  * Function to get the current context from AsyncLocalStorage
@@ -1369,853 +1387,891 @@ type CreateOptionsRoute = <TState extends State = State, TServices extends Servi
1369
1387
  declare function compose(middlewareStack: Middleware[]): MiddlewareFunction;
1370
1388
 
1371
1389
  /**
1372
- * Create a middleware
1373
- */
1374
- declare function create$2<TState = {}, TServices = {}>(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware<TState, TServices>;
1375
- /**
1376
- * Create a middleware that only contributes state (no services)
1377
- * Convenience helper for state-only middleware
1378
- *
1379
- * @template T - Type of state to contribute
1380
- * @param handler - Middleware function that adds state
1381
- * @returns Middleware that contributes state only
1382
- *
1383
- */
1384
- declare function stateMiddleware<T = {}>(handler: MiddlewareFunction): Middleware<T, {}>;
1385
- /**
1386
- * Create a middleware that only contributes services (no state)
1387
- * Convenience helper for service-only middleware
1390
+ * CORS Types for BlaizeJS Framework
1388
1391
  *
1389
- * @template T - Type of services to contribute
1390
- * @param handler - Middleware function that adds services
1391
- * @returns Middleware that contributes services only
1392
+ * Comprehensive type definitions for W3C-compliant CORS middleware
1393
+ * with support for string, regex, and async function origin validation.
1392
1394
  *
1395
+ * @module @blaizejs/types/cors
1393
1396
  */
1394
- declare function serviceMiddleware<T = {}>(handler: MiddlewareFunction): Middleware<{}, T>;
1395
1397
 
1396
1398
  /**
1397
- * Represents a single Server-Sent Event
1398
- * @template T - The type of data payload
1399
+ * Origin configuration type supporting multiple validation methods
1399
1400
  *
1400
1401
  * @example
1401
1402
  * ```typescript
1402
- * const event: SSEEvent<{ message: string }> = {
1403
- * id: '123',
1404
- * event: 'message',
1405
- * data: { message: 'Hello, world!' },
1406
- * retry: 5000
1407
- * };
1408
- * ```
1409
- */
1410
- interface SSEEvent<T = unknown> {
1411
- /** Unique identifier for the event */
1412
- id: string;
1413
- /** Event type/name for client-side event listeners */
1414
- event: string;
1415
- /** The actual data payload of the event */
1416
- data: T;
1417
- /** Optional retry interval in milliseconds for reconnection */
1418
- retry?: number;
1419
- }
1420
- /**
1421
- * Backpressure handling strategies for SSE streams
1403
+ * // String origin (exact match)
1404
+ * const origin: CorsOrigin = 'https://example.com';
1422
1405
  *
1423
- * - `drop-oldest`: Remove oldest events from buffer when full
1424
- * - `drop-newest`: Reject new events when buffer is full
1425
- * - `close`: Close the stream when buffer limit is reached
1426
- */
1427
- type SSEBufferStrategy = 'drop-oldest' | 'drop-newest' | 'close';
1428
- /**
1429
- * Configuration options for SSE streams
1406
+ * // RegExp pattern
1407
+ * const origin: CorsOrigin = /^https:\/\/.*\.example\.com$/;
1430
1408
  *
1431
- * @example
1432
- * ```typescript
1433
- * const options: SSEOptions = {
1434
- * autoClose: true,
1435
- * maxBufferSize: 100,
1436
- * bufferStrategy: 'drop-oldest'
1409
+ * // Dynamic validation function
1410
+ * const origin: CorsOrigin = async (origin, ctx) => {
1411
+ * return await checkOriginAllowed(origin, ctx?.state.user);
1437
1412
  * };
1413
+ *
1414
+ * // Array of mixed types
1415
+ * const origin: CorsOrigin = [
1416
+ * 'https://localhost:3000',
1417
+ * /^https:\/\/.*\.example\.com$/,
1418
+ * (origin) => origin.endsWith('.trusted.com')
1419
+ * ];
1438
1420
  * ```
1439
1421
  */
1440
- interface SSEOptions {
1441
- /** ms between heartbeat pings (0 to disable) */
1442
- heartbeatInterval?: number;
1443
- /** Maximum size in bytes for a single event */
1444
- maxEventSize?: number;
1445
- /** Automatically close stream when client disconnects */
1446
- autoClose?: boolean;
1447
- /** Maximum number of events to buffer before applying strategy */
1448
- maxBufferSize?: number;
1449
- /** Strategy to handle buffer overflow conditions */
1450
- bufferStrategy?: SSEBufferStrategy;
1451
- }
1422
+ type CorsOrigin = string | RegExp | ((origin: string, ctx?: Context<any, any>) => boolean | Promise<boolean>) | Array<string | RegExp | ((origin: string, ctx?: Context<any, any>) => boolean | Promise<boolean>)>;
1452
1423
  /**
1453
- * Connection states for SSE streams
1424
+ * HTTP methods that can be allowed in CORS
1425
+ * Based on W3C CORS specification
1454
1426
  */
1455
- type SSEConnectionState = 'connecting' | 'connected' | 'disconnected' | 'closed';
1427
+ type CorsHttpMethod = HttpMethod | 'CONNECT' | 'TRACE';
1456
1428
  /**
1457
- * SSE stream interface for managing server-sent events
1429
+ * Main CORS configuration options
1458
1430
  *
1459
1431
  * @example
1460
1432
  * ```typescript
1461
- * const stream: SSEStream = createSSEStream(response);
1462
- *
1463
- * // Send typed event
1464
- * stream.send('notification', { type: 'info', message: 'Update available' });
1465
- *
1466
- * // Send error event
1467
- * stream.sendError(new Error('Processing failed'));
1468
- *
1469
- * // Clean up on close
1470
- * stream.onClose(() => {
1471
- * console.log('Client disconnected');
1472
- * });
1473
- *
1474
- * // Close stream
1475
- * stream.close();
1433
+ * const corsOptions: CorsOptions = {
1434
+ * origin: 'https://example.com',
1435
+ * methods: ['GET', 'POST'],
1436
+ * credentials: true,
1437
+ * maxAge: 86400
1438
+ * };
1476
1439
  * ```
1477
1440
  */
1478
- interface SSEStream {
1441
+ interface CorsOptions {
1479
1442
  /**
1480
- * Send an event with typed data to the client
1481
- * @template T - Type of the data payload
1482
- * @param event - Event name/type
1483
- * @param data - Event data payload
1443
+ * Configures the Access-Control-Allow-Origin header
1444
+ *
1445
+ * Possible values:
1446
+ * - `true`: Allow all origins (sets to '*' unless credentials is true, then reflects origin)
1447
+ * - `false`: Disable CORS (no headers set)
1448
+ * - `string`: Specific origin to allow
1449
+ * - `RegExp`: Pattern to match origins
1450
+ * - `function`: Custom validation logic
1451
+ * - `array`: Multiple origin configurations
1452
+ *
1453
+ * @default false
1484
1454
  */
1485
- send<T>(event: string, data: T): void;
1455
+ origin?: boolean | CorsOrigin;
1486
1456
  /**
1487
- * Send an error event to the client
1488
- * @param error - Error object to send
1457
+ * Configures the Access-Control-Allow-Methods header
1458
+ *
1459
+ * @default ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']
1460
+ * @example ['GET', 'POST']
1489
1461
  */
1490
- sendError(error: Error): void;
1462
+ methods?: CorsHttpMethod[] | string;
1491
1463
  /**
1492
- * Close the SSE stream connection
1464
+ * Configures the Access-Control-Allow-Headers header
1465
+ *
1466
+ * Pass an array of allowed headers or a comma-delimited string.
1467
+ *
1468
+ * @default Request's Access-Control-Request-Headers header value
1469
+ * @example ['Content-Type', 'Authorization']
1493
1470
  */
1494
- close(): void;
1471
+ allowedHeaders?: string[] | string;
1495
1472
  /**
1496
- * Register a callback for stream closure
1497
- * @param cb - Callback function to execute on close
1473
+ * Configures the Access-Control-Expose-Headers header
1474
+ *
1475
+ * Headers that the browser is allowed to access.
1476
+ *
1477
+ * @default []
1478
+ * @example ['Content-Range', 'X-Content-Range']
1498
1479
  */
1499
- onClose(cb: () => void): void;
1500
- }
1501
- /**
1502
- * Extended SSE stream with additional control methods
1503
- */
1504
- interface SSEStreamExtended extends SSEStream {
1505
- readonly id: string;
1506
- [Symbol.asyncIterator](): AsyncGenerator<BufferedEvent, void, unknown>;
1507
- /** Current connection state */
1508
- readonly state: SSEConnectionState;
1509
- /** Number of events in the buffer */
1510
- readonly bufferSize: number;
1511
- /** Check if stream is writable */
1512
- readonly isWritable: boolean;
1480
+ exposedHeaders?: string[] | string;
1513
1481
  /**
1514
- * Ping the client to keep connection alive
1515
- * @param comment - Optional comment to include in ping
1482
+ * Configures the Access-Control-Allow-Credentials header
1483
+ *
1484
+ * Set to true to allow credentials (cookies, authorization headers, TLS client certificates).
1485
+ * Note: Cannot be used with origin: '*' for security reasons.
1486
+ *
1487
+ * @default false
1516
1488
  */
1517
- ping(comment?: string): void;
1489
+ credentials?: boolean;
1518
1490
  /**
1519
- * Set retry interval for client reconnection
1520
- * @param milliseconds - Retry interval in milliseconds
1491
+ * Configures the Access-Control-Max-Age header in seconds
1492
+ *
1493
+ * Indicates how long browsers can cache preflight response.
1494
+ * Set to -1 to disable caching.
1495
+ *
1496
+ * @default undefined (browser decides)
1497
+ * @example 86400 // 24 hours
1521
1498
  */
1522
- setRetry(milliseconds: number): void;
1499
+ maxAge?: number;
1523
1500
  /**
1524
- * Flush any buffered events immediately
1501
+ * Whether to pass the CORS preflight response to the next handler
1502
+ *
1503
+ * When false, the preflight response is sent immediately.
1504
+ * When true, control passes to the next middleware/handler.
1505
+ *
1506
+ * @default false
1525
1507
  */
1526
- flush(): void;
1527
- getMetrics(): StreamMetrics;
1508
+ preflightContinue?: boolean;
1509
+ /**
1510
+ * HTTP status code for successful OPTIONS requests
1511
+ *
1512
+ * Some legacy browsers require 200, while 204 is more correct.
1513
+ *
1514
+ * @default 204
1515
+ */
1516
+ optionsSuccessStatus?: number;
1528
1517
  }
1529
1518
  /**
1530
- * SSE event serialization format
1519
+ * Internal CORS validation result
1520
+ * Used by middleware implementation
1531
1521
  */
1532
- interface SSESerializedEvent {
1533
- /** Event ID field */
1534
- id?: string;
1535
- /** Event type field */
1536
- event?: string;
1537
- /** Data field (can be multi-line) */
1538
- data: string;
1539
- /** Retry field */
1540
- retry?: number;
1541
- /** Comment field for keep-alive */
1542
- comment?: string;
1522
+ interface CorsValidationResult {
1523
+ /**
1524
+ * Whether the origin is allowed
1525
+ */
1526
+ allowed: boolean;
1527
+ /**
1528
+ * The origin value to set in the header
1529
+ * Can be '*', specific origin, or 'null'
1530
+ */
1531
+ origin?: string;
1532
+ /**
1533
+ * Whether to add Vary: Origin header
1534
+ */
1535
+ vary?: boolean;
1543
1536
  }
1544
1537
  /**
1545
- * SSE event handler function type
1546
- * @template T - Type of the event data
1547
- */
1548
- type SSEEventHandler<T = unknown> = (event: SSEEvent<T>) => void | Promise<void>;
1549
- /**
1550
- * SSE event listener registration
1538
+ * CORS preflight request information
1539
+ * Extracted from OPTIONS request headers
1551
1540
  */
1552
- interface SSEEventListener {
1553
- /** Event type to listen for (use '*' for all events) */
1554
- event: string;
1555
- /** Handler function for the event */
1556
- handler: SSEEventHandler;
1557
- /** Optional listener identifier for removal */
1558
- id?: string;
1541
+ interface CorsPreflightInfo {
1542
+ /**
1543
+ * The origin making the request
1544
+ */
1545
+ origin?: string;
1546
+ /**
1547
+ * The method that will be used in the actual request
1548
+ * From Access-Control-Request-Method header
1549
+ */
1550
+ requestedMethod?: string;
1551
+ /**
1552
+ * The headers that will be sent in the actual request
1553
+ * From Access-Control-Request-Headers header
1554
+ */
1555
+ requestedHeaders?: string[];
1559
1556
  }
1560
1557
  /**
1561
- * SSE metrics for monitoring stream performance
1558
+ * Cache entry for origin validation results
1559
+ * Used for performance optimization
1562
1560
  */
1563
- interface SSEMetrics {
1564
- /** Total number of events sent */
1565
- eventsSent: number;
1566
- /** Total number of events dropped */
1567
- eventsDropped: number;
1568
- /** Current number of connected clients */
1569
- activeConnections: number;
1570
- /** Total bytes sent */
1571
- bytesSent: number;
1572
- /** Average event send latency in milliseconds */
1573
- averageLatency: number;
1574
- /** Connection duration in milliseconds */
1575
- connectionDuration: number;
1561
+ interface CorsOriginCacheEntry {
1562
+ /**
1563
+ * Whether the origin is allowed
1564
+ */
1565
+ allowed: boolean;
1566
+ /**
1567
+ * When this cache entry expires (timestamp)
1568
+ */
1569
+ expiresAt: number;
1570
+ /**
1571
+ * Optional user identifier for cache key
1572
+ */
1573
+ userId?: string;
1576
1574
  }
1577
1575
  /**
1578
- * SSE stream manager for handling multiple clients
1576
+ * Configuration for CORS origin validation cache
1579
1577
  */
1580
- interface SSEStreamManager {
1578
+ interface CorsOriginCacheConfig {
1581
1579
  /**
1582
- * Create a new SSE stream for a client
1583
- * @param clientId - Unique identifier for the client
1584
- * @param options - Stream configuration options
1580
+ * Time-to-live for cache entries in milliseconds
1581
+ * @default 60000 (1 minute)
1585
1582
  */
1586
- createStream(clientId: string, options?: SSEOptions): SSEStream;
1583
+ ttl?: number;
1587
1584
  /**
1588
- * Get an existing stream by client ID
1589
- * @param clientId - Client identifier
1585
+ * Maximum number of entries in the cache
1586
+ * @default 1000
1590
1587
  */
1591
- getStream(clientId: string): SSEStream | undefined;
1588
+ maxSize?: number;
1592
1589
  /**
1593
- * Broadcast an event to all connected clients
1594
- * @template T - Type of the event data
1595
- * @param event - Event name
1596
- * @param data - Event data
1590
+ * Whether to include user ID in cache key
1591
+ * @default true
1597
1592
  */
1598
- broadcast<T>(event: string, data: T): void;
1593
+ includeUserId?: boolean;
1594
+ }
1595
+ /**
1596
+ * Statistics for CORS middleware performance monitoring
1597
+ */
1598
+ interface CorsStats {
1599
1599
  /**
1600
- * Broadcast to specific clients
1601
- * @template T - Type of the event data
1602
- * @param clientIds - Array of client IDs
1603
- * @param event - Event name
1604
- * @param data - Event data
1600
+ * Total number of CORS requests processed
1605
1601
  */
1606
- multicast<T>(clientIds: string[], event: string, data: T): void;
1602
+ totalRequests: number;
1607
1603
  /**
1608
- * Close a specific client stream
1609
- * @param clientId - Client identifier
1604
+ * Number of preflight requests handled
1610
1605
  */
1611
- closeStream(clientId: string): void;
1606
+ preflightRequests: number;
1612
1607
  /**
1613
- * Close all active streams
1608
+ * Number of allowed origins
1614
1609
  */
1615
- closeAll(): void;
1610
+ allowedOrigins: number;
1616
1611
  /**
1617
- * Get metrics for all streams
1612
+ * Number of denied origins
1618
1613
  */
1619
- getMetrics(): SSEMetrics;
1614
+ deniedOrigins: number;
1615
+ /**
1616
+ * Cache hit rate for origin validation
1617
+ */
1618
+ cacheHitRate: number;
1619
+ /**
1620
+ * Average origin validation time in milliseconds
1621
+ */
1622
+ avgValidationTime: number;
1620
1623
  }
1621
1624
  /**
1622
- * Result type for operations that can fail
1623
- */
1624
- type RegistryResult<T> = {
1625
- success: true;
1626
- value: T;
1627
- } | {
1628
- success: false;
1629
- error: string;
1630
- };
1631
- /**
1632
- * Connection metadata stored in the registry
1625
+ * Cache entry type
1633
1626
  */
1634
- interface ConnectionEntry {
1635
- stream: SSEStream;
1636
- connectedAt: number;
1637
- lastActivity: number;
1638
- clientIp?: string;
1639
- userAgent?: string;
1627
+ interface CacheEntry {
1628
+ allowed: boolean;
1629
+ expiresAt: number;
1630
+ lastAccessed: number;
1640
1631
  }
1641
1632
  /**
1642
- * Internal connection registry interface
1633
+ * Cache configuration
1643
1634
  */
1644
- interface ConnectionRegistry {
1645
- /** Add a new connection to the registry */
1646
- add: (id: string, stream: SSEStream, metadata?: {
1647
- clientIp?: string;
1648
- userAgent?: string;
1649
- }) => void;
1650
- /** Remove a connection from the registry */
1651
- remove: (id: string) => void;
1652
- /** Get current connection count */
1653
- count: () => number;
1654
- /** Clean up inactive or closed connections */
1655
- cleanup: () => void;
1656
- /** Get connection by ID (for internal use) */
1657
- get: (id: string) => SSEStream | undefined;
1658
- /** Check if a connection exists */
1659
- has: (id: string) => boolean;
1660
- /** Get all connection IDs */
1661
- getIds: () => string[];
1662
- /** Shutdown the registry and close all connections */
1663
- shutdown: () => void;
1635
+ interface CacheConfig {
1636
+ ttl: number;
1637
+ maxSize: number;
1664
1638
  }
1639
+
1665
1640
  /**
1666
- * Extended stream interface for typed events
1641
+ * Create CORS middleware with the specified options
1642
+ *
1643
+ * @param userOptions - CORS configuration options or boolean
1644
+ * @returns Middleware function that handles CORS
1645
+ *
1646
+ * @example
1647
+ * ```typescript
1648
+ * import { cors } from '@blaize-core/middleware/cors';
1649
+ *
1650
+ * // Development mode - allow all origins
1651
+ * server.use(cors(true));
1652
+ *
1653
+ * // Production - specific origin
1654
+ * server.use(cors({
1655
+ * origin: 'https://app.example.com',
1656
+ * credentials: true,
1657
+ * maxAge: 86400
1658
+ * }));
1659
+ *
1660
+ * // Multiple origins with regex
1661
+ * server.use(cors({
1662
+ * origin: [
1663
+ * 'https://app.example.com',
1664
+ * /^https:\/\/.*\.example\.com$/
1665
+ * ]
1666
+ * }));
1667
+ *
1668
+ * // Dynamic origin validation
1669
+ * server.use(cors({
1670
+ * origin: async (origin, ctx) => {
1671
+ * return await checkOriginAllowed(origin, ctx.state.user);
1672
+ * }
1673
+ * }));
1674
+ * ```
1667
1675
  */
1668
- interface TypedSSEStream<TEvents extends Record<string, z.ZodType>> extends SSEStreamExtended {
1669
- send<K extends keyof TEvents>(event: K & string, data: z.infer<TEvents[K]>): void;
1670
- }
1676
+ declare function cors(userOptions?: CorsOptions | boolean): Middleware;
1677
+
1671
1678
  /**
1672
- * Schema for SSE route validation with generic type parameters
1679
+ * Create a middleware
1673
1680
  */
1674
- interface SSERouteSchema<P extends z.ZodType = z.ZodType<any>, Q extends z.ZodType = z.ZodType<any>, E = any> {
1675
- /** Parameter schema for validation */
1676
- params?: P;
1677
- /** Query schema for validation */
1678
- query?: Q;
1679
- /** Events schema for validation (SSE-specific, replaces response) */
1680
- events?: E;
1681
- }
1681
+ declare function create$2<TState = {}, TServices = {}>(handlerOrOptions: MiddlewareFunction | MiddlewareOptions): Middleware<TState, TServices>;
1682
1682
  /**
1683
- * SSE route handler function with stream as first parameter
1684
- * This is the user-facing API - they write handlers with this signature
1683
+ * Create a middleware that only contributes state (no services)
1684
+ * Convenience helper for state-only middleware
1685
+ *
1686
+ * @template T - Type of state to contribute
1687
+ * @param handler - Middleware function that adds state
1688
+ * @returns Middleware that contributes state only
1689
+ *
1685
1690
  */
1686
- type SSERouteHandler<TStream extends SSEStreamExtended = SSEStreamExtended, TParams = Record<string, string>, TQuery = Record<string, string | string[] | undefined>, TState extends State = State, TServices extends Services = Services> = (stream: TStream, ctx: Context<TState, TServices, never, TQuery>, // SSE never has body
1687
- params: TParams) => Promise<void> | void;
1691
+ declare function stateMiddleware<T = {}>(handler: MiddlewareFunction): Middleware<T, {}>;
1688
1692
  /**
1689
- * SSE route creator with state and services support
1690
- * Returns a higher-order function to handle generics properly
1693
+ * Create a middleware that only contributes services (no state)
1694
+ * Convenience helper for service-only middleware
1695
+ *
1696
+ * @template T - Type of services to contribute
1697
+ * @param handler - Middleware function that adds services
1698
+ * @returns Middleware that contributes services only
1691
1699
  *
1692
- * The return type matches what the implementation actually returns:
1693
- * - A route object with a GET property
1694
- * - The GET property contains the wrapped handler and schemas
1695
- * - The wrapped handler has the standard (ctx, params) signature expected by the router
1696
1700
  */
1697
- type CreateSSERoute = <TState extends State = State, TServices extends Services = Services>() => <P = never, Q = never, E = never>(config: {
1698
- schema?: {
1699
- params?: P extends never ? never : P;
1700
- query?: Q extends never ? never : Q;
1701
- events?: E extends never ? never : E;
1702
- };
1703
- handler: SSERouteHandler<E extends Record<string, z.ZodType> ? TypedSSEStream<E> : SSEStreamExtended, P extends z.ZodType ? Infer<P> : Record<string, string>, Q extends z.ZodType ? Infer<Q> : QueryParams, TState, TServices>;
1704
- middleware?: Middleware[];
1705
- options?: Record<string, unknown>;
1706
- }) => {
1707
- GET: {
1708
- handler: (ctx: any, params: any) => Promise<void>;
1709
- schema?: {
1710
- params?: P extends never ? undefined : P;
1711
- query?: Q extends never ? undefined : Q;
1712
- };
1713
- middleware?: Middleware[];
1714
- options?: Record<string, unknown>;
1715
- };
1716
- path: string;
1717
- };
1701
+ declare function serviceMiddleware<T = {}>(handler: MiddlewareFunction): Middleware<{}, T>;
1702
+
1718
1703
  /**
1719
- * Buffered event with metadata
1704
+ * Represents a single Server-Sent Event
1705
+ * @template T - The type of data payload
1706
+ *
1707
+ * @example
1708
+ * ```typescript
1709
+ * const event: SSEEvent<{ message: string }> = {
1710
+ * id: '123',
1711
+ * event: 'message',
1712
+ * data: { message: 'Hello, world!' },
1713
+ * retry: 5000
1714
+ * };
1715
+ * ```
1720
1716
  */
1721
- interface BufferedEvent {
1717
+ interface SSEEvent<T = unknown> {
1718
+ /** Unique identifier for the event */
1722
1719
  id: string;
1720
+ /** Event type/name for client-side event listeners */
1723
1721
  event: string;
1724
- data: unknown;
1725
- size: number;
1726
- timestamp: number;
1727
- correlationId: string;
1722
+ /** The actual data payload of the event */
1723
+ data: T;
1724
+ /** Optional retry interval in milliseconds for reconnection */
1725
+ retry?: number;
1728
1726
  }
1729
1727
  /**
1730
- * Stream metrics for monitoring
1728
+ * Backpressure handling strategies for SSE streams
1729
+ *
1730
+ * - `drop-oldest`: Remove oldest events from buffer when full
1731
+ * - `drop-newest`: Reject new events when buffer is full
1732
+ * - `close`: Close the stream when buffer limit is reached
1731
1733
  */
1732
- interface StreamMetrics {
1733
- eventsSent: number;
1734
- eventsDropped: number;
1735
- bytesWritten: number;
1736
- bufferHighWatermark: number;
1737
- lastEventTime: number;
1734
+ type SSEBufferStrategy = 'drop-oldest' | 'drop-newest' | 'close';
1735
+ /**
1736
+ * Configuration options for SSE streams
1737
+ *
1738
+ * @example
1739
+ * ```typescript
1740
+ * const options: SSEOptions = {
1741
+ * autoClose: true,
1742
+ * maxBufferSize: 100,
1743
+ * bufferStrategy: 'drop-oldest'
1744
+ * };
1745
+ * ```
1746
+ */
1747
+ interface SSEOptions {
1748
+ /** ms between heartbeat pings (0 to disable) */
1749
+ heartbeatInterval?: number;
1750
+ /** Maximum size in bytes for a single event */
1751
+ maxEventSize?: number;
1752
+ /** Automatically close stream when client disconnects */
1753
+ autoClose?: boolean;
1754
+ /** Maximum number of events to buffer before applying strategy */
1755
+ maxBufferSize?: number;
1756
+ /** Strategy to handle buffer overflow conditions */
1757
+ bufferStrategy?: SSEBufferStrategy;
1738
1758
  }
1739
-
1740
1759
  /**
1741
- * SSE Client Types for BlaizeJS
1742
- * Location: packages/blaize-client/src/sse/types.ts
1760
+ * Connection states for SSE streams
1743
1761
  */
1744
-
1762
+ type SSEConnectionState = 'connecting' | 'connected' | 'disconnected' | 'closed';
1745
1763
  /**
1746
- * Event handlers map
1764
+ * SSE stream interface for managing server-sent events
1765
+ *
1766
+ * @example
1767
+ * ```typescript
1768
+ * const stream: SSEStream = createSSEStream(response);
1769
+ *
1770
+ * // Send typed event
1771
+ * stream.send('notification', { type: 'info', message: 'Update available' });
1772
+ *
1773
+ * // Send error event
1774
+ * stream.sendError(new Error('Processing failed'));
1775
+ *
1776
+ * // Clean up on close
1777
+ * stream.onClose(() => {
1778
+ * console.log('Client disconnected');
1779
+ * });
1780
+ *
1781
+ * // Close stream
1782
+ * stream.close();
1783
+ * ```
1747
1784
  */
1748
- interface EventHandlers {
1749
- [event: string]: Set<(data: any) => void>;
1785
+ interface SSEStream {
1786
+ /**
1787
+ * Send an event with typed data to the client
1788
+ * @template T - Type of the data payload
1789
+ * @param event - Event name/type
1790
+ * @param data - Event data payload
1791
+ */
1792
+ send<T>(event: string, data: T): void;
1793
+ /**
1794
+ * Send an error event to the client
1795
+ * @param error - Error object to send
1796
+ */
1797
+ sendError(error: Error): void;
1798
+ /**
1799
+ * Close the SSE stream connection
1800
+ */
1801
+ close(): void;
1802
+ /**
1803
+ * Register a callback for stream closure
1804
+ * @param cb - Callback function to execute on close
1805
+ */
1806
+ onClose(cb: () => void): void;
1750
1807
  }
1751
1808
  /**
1752
- * SSE connection configuration options
1809
+ * Extended SSE stream with additional control methods
1753
1810
  */
1754
- interface SSEClientOptions {
1755
- headers?: Record<string, string>;
1756
- withCredentials?: boolean;
1757
- reconnect?: {
1758
- enabled: boolean;
1759
- maxAttempts?: number;
1760
- strategy?: ReconnectStrategy;
1761
- initialDelay?: number;
1762
- };
1763
- bufferMissedEvents?: boolean;
1764
- maxMissedEvents?: number;
1765
- heartbeatTimeout?: number;
1766
- parseJSON?: boolean;
1811
+ interface SSEStreamExtended extends SSEStream {
1812
+ readonly id: string;
1813
+ [Symbol.asyncIterator](): AsyncGenerator<BufferedEvent, void, unknown>;
1814
+ /** Current connection state */
1815
+ readonly state: SSEConnectionState;
1816
+ /** Number of events in the buffer */
1817
+ readonly bufferSize: number;
1818
+ /** Check if stream is writable */
1819
+ readonly isWritable: boolean;
1767
1820
  /**
1768
- * Whether to wait for connection before resolving the promise.
1769
- * If false, returns the client immediately without waiting.
1770
- * Default: true
1821
+ * Ping the client to keep connection alive
1822
+ * @param comment - Optional comment to include in ping
1771
1823
  */
1772
- waitForConnection?: boolean;
1824
+ ping(comment?: string): void;
1773
1825
  /**
1774
- * Optional timeout for initial connection in milliseconds.
1775
- * If not set, no timeout is applied (relies on EventSource native timeout).
1776
- * Only applies if waitForConnection is true.
1826
+ * Set retry interval for client reconnection
1827
+ * @param milliseconds - Retry interval in milliseconds
1777
1828
  */
1778
- connectionTimeout?: number;
1829
+ setRetry(milliseconds: number): void;
1830
+ /**
1831
+ * Flush any buffered events immediately
1832
+ */
1833
+ flush(): void;
1834
+ getMetrics(): StreamMetrics;
1779
1835
  }
1780
1836
  /**
1781
- * Metrics for SSE connection monitoring
1837
+ * SSE event serialization format
1782
1838
  */
1783
- interface SSEClientMetrics {
1784
- eventsReceived: number;
1785
- bytesReceived: number;
1786
- connectionDuration: number;
1787
- reconnectAttempts: number;
1788
- lastEventId?: string;
1839
+ interface SSESerializedEvent {
1840
+ /** Event ID field */
1841
+ id?: string;
1842
+ /** Event type field */
1843
+ event?: string;
1844
+ /** Data field (can be multi-line) */
1845
+ data: string;
1846
+ /** Retry field */
1847
+ retry?: number;
1848
+ /** Comment field for keep-alive */
1849
+ comment?: string;
1789
1850
  }
1790
1851
  /**
1791
- * Reconnection delay calculation strategy
1852
+ * SSE event handler function type
1853
+ * @template T - Type of the event data
1792
1854
  */
1793
- type ReconnectStrategy = (attempt: number) => number;
1855
+ type SSEEventHandler<T = unknown> = (event: SSEEvent<T>) => void | Promise<void>;
1794
1856
  /**
1795
- * SSE Client interface with type-safe event handling
1857
+ * SSE event listener registration
1796
1858
  */
1797
- interface SSEClient<TEvents extends Record<string, unknown> = Record<string, unknown>> {
1798
- on<K extends keyof TEvents>(event: K & string, handler: (data: TEvents[K]) => void): void;
1799
- on(event: 'error', handler: (error: BlaizeError) => void): void;
1800
- on(event: 'open', handler: () => void): void;
1801
- on(event: 'close', handler: (event: CloseEvent) => void): void;
1802
- off<K extends keyof TEvents>(event: K & string, handler?: (data: TEvents[K]) => void): void;
1803
- off(event: 'error', handler?: (error: BlaizeError) => void): void;
1804
- off(event: 'open', handler?: () => void): void;
1805
- off(event: 'close', handler?: (event: CloseEvent) => void): void;
1806
- once<K extends keyof TEvents>(event: K & string, handler: (data: TEvents[K]) => void): void;
1807
- once(event: 'error', handler: (error: BlaizeError) => void): void;
1808
- once(event: 'open', handler: () => void): void;
1809
- once(event: 'close', handler: (event: CloseEvent) => void): void;
1810
- close(): void;
1811
- readonly state: SSEConnectionState;
1812
- readonly metrics: SSEClientMetrics;
1813
- readonly lastEventId?: string;
1859
+ interface SSEEventListener {
1860
+ /** Event type to listen for (use '*' for all events) */
1861
+ event: string;
1862
+ /** Handler function for the event */
1863
+ handler: SSEEventHandler;
1864
+ /** Optional listener identifier for removal */
1865
+ id?: string;
1814
1866
  }
1815
1867
  /**
1816
- * Close event for SSE connections
1868
+ * SSE metrics for monitoring stream performance
1817
1869
  */
1818
- interface CloseEvent {
1819
- reconnect: boolean;
1820
- reason?: string;
1870
+ interface SSEMetrics {
1871
+ /** Total number of events sent */
1872
+ eventsSent: number;
1873
+ /** Total number of events dropped */
1874
+ eventsDropped: number;
1875
+ /** Current number of connected clients */
1876
+ activeConnections: number;
1877
+ /** Total bytes sent */
1878
+ bytesSent: number;
1879
+ /** Average event send latency in milliseconds */
1880
+ averageLatency: number;
1881
+ /** Connection duration in milliseconds */
1882
+ connectionDuration: number;
1821
1883
  }
1822
1884
  /**
1823
- * Internal SSE connection factory
1824
- * Returns a Promise that resolves to an SSEClient instance
1885
+ * SSE stream manager for handling multiple clients
1825
1886
  */
1826
- type SSEConnectionFactory<TEvents extends Record<string, unknown> = Record<string, unknown>> = (options?: SSEClientOptions) => Promise<SSEClient<TEvents>>;
1827
-
1828
- type ExtractMethod<T> = T extends {
1829
- GET: any;
1830
- } ? 'GET' : T extends {
1831
- POST: any;
1832
- } ? 'POST' : T extends {
1833
- PUT: any;
1834
- } ? 'PUT' : T extends {
1835
- DELETE: any;
1836
- } ? 'DELETE' : T extends {
1837
- PATCH: any;
1838
- } ? 'PATCH' : T extends {
1839
- HEAD: any;
1840
- } ? 'HEAD' : T extends {
1841
- OPTIONS: any;
1842
- } ? 'OPTIONS' : never;
1843
- type BuildRoutesRegistry<TRoutes extends Record<string, any>> = {
1844
- [Method in ExtractMethod<TRoutes[keyof TRoutes]> as `$${Lowercase<Method>}`]: {
1845
- [K in keyof TRoutes as ExtractMethod<TRoutes[K]> extends Method ? K : never]: TRoutes[K];
1846
- };
1847
- };
1848
- type GetRouteMethodOptions<TRoute> = TRoute extends {
1849
- GET: infer M;
1850
- } ? M : TRoute extends {
1851
- POST: infer M;
1852
- } ? M : TRoute extends {
1853
- PUT: infer M;
1854
- } ? M : TRoute extends {
1855
- DELETE: infer M;
1856
- } ? M : TRoute extends {
1857
- PATCH: infer M;
1858
- } ? M : TRoute extends {
1859
- HEAD: infer M;
1860
- } ? M : TRoute extends {
1861
- OPTIONS: infer M;
1862
- } ? M : never;
1863
- type IsNever$1<T> = [T] extends [never] ? true : false;
1864
- type BuildArgsObject<P, Q, B> = (IsNever$1<P> extends true ? {} : {
1865
- params: Infer<P>;
1866
- }) & (IsNever$1<Q> extends true ? {} : {
1867
- query: Infer<Q>;
1868
- }) & (IsNever$1<B> extends true ? {} : {
1869
- body: Infer<B>;
1870
- });
1871
- type IsEmptyObject<T> = keyof T extends never ? true : false;
1872
- type BuildArgs<P, Q, B> = IsEmptyObject<BuildArgsObject<P, Q, B>> extends true ? void : BuildArgsObject<P, Q, B>;
1873
- type CreateClientMethod<TRoute> = GetRouteMethodOptions<TRoute> extends RouteMethodOptions<infer P, infer Q, infer B, infer R> ? BuildArgs<P, Q, B> extends void ? () => Promise<R extends z.ZodType ? Infer<R> : unknown> : (args: BuildArgs<P, Q, B>) => Promise<R extends z.ZodType ? Infer<R> : unknown> : never;
1874
- type CreateClient<TRoutes extends Record<string, Record<string, any>>> = {
1875
- [Method in keyof TRoutes]: {
1876
- [RouteName in keyof TRoutes[Method]]: CreateClientMethod<TRoutes[Method][RouteName]>;
1877
- };
1878
- };
1879
- interface ClientConfig {
1880
- baseUrl: string;
1881
- defaultHeaders?: Record<string, string>;
1882
- timeout?: number;
1883
- sse?: SSEClientOptions;
1884
- }
1885
- interface InternalRequestArgs {
1886
- params?: Record<string, any>;
1887
- query?: Record<string, any>;
1888
- body?: any;
1889
- }
1890
- interface RequestOptions {
1891
- method: string;
1892
- url: string;
1893
- headers: Record<string, string>;
1894
- body?: string;
1895
- timeout: number;
1887
+ interface SSEStreamManager {
1888
+ /**
1889
+ * Create a new SSE stream for a client
1890
+ * @param clientId - Unique identifier for the client
1891
+ * @param options - Stream configuration options
1892
+ */
1893
+ createStream(clientId: string, options?: SSEOptions): SSEStream;
1894
+ /**
1895
+ * Get an existing stream by client ID
1896
+ * @param clientId - Client identifier
1897
+ */
1898
+ getStream(clientId: string): SSEStream | undefined;
1899
+ /**
1900
+ * Broadcast an event to all connected clients
1901
+ * @template T - Type of the event data
1902
+ * @param event - Event name
1903
+ * @param data - Event data
1904
+ */
1905
+ broadcast<T>(event: string, data: T): void;
1906
+ /**
1907
+ * Broadcast to specific clients
1908
+ * @template T - Type of the event data
1909
+ * @param clientIds - Array of client IDs
1910
+ * @param event - Event name
1911
+ * @param data - Event data
1912
+ */
1913
+ multicast<T>(clientIds: string[], event: string, data: T): void;
1914
+ /**
1915
+ * Close a specific client stream
1916
+ * @param clientId - Client identifier
1917
+ */
1918
+ closeStream(clientId: string): void;
1919
+ /**
1920
+ * Close all active streams
1921
+ */
1922
+ closeAll(): void;
1923
+ /**
1924
+ * Get metrics for all streams
1925
+ */
1926
+ getMetrics(): SSEMetrics;
1896
1927
  }
1897
1928
  /**
1898
- * Detect if a route has SSE support
1899
- * SSE routes have a special 'SSE' method key
1929
+ * Result type for operations that can fail
1900
1930
  */
1901
- type HasSSEMethod<TRoute> = TRoute extends {
1902
- SSE: any;
1903
- } ? true : false;
1931
+ type RegistryResult<T> = {
1932
+ success: true;
1933
+ value: T;
1934
+ } | {
1935
+ success: false;
1936
+ error: string;
1937
+ };
1904
1938
  /**
1905
- * Extract SSE event types from route schema
1939
+ * Connection metadata stored in the registry
1906
1940
  */
1907
- type ExtractSSEEvents<TRoute> = TRoute extends {
1908
- SSE: {
1909
- events?: infer E;
1910
- };
1911
- } ? E extends z.ZodType ? z.infer<E> : Record<string, unknown> : Record<string, unknown>;
1941
+ interface ConnectionEntry {
1942
+ stream: SSEStream;
1943
+ connectedAt: number;
1944
+ lastActivity: number;
1945
+ clientIp?: string;
1946
+ userAgent?: string;
1947
+ }
1912
1948
  /**
1913
- * Extract SSE query parameters from route
1949
+ * Internal connection registry interface
1914
1950
  */
1915
- type ExtractSSEQuery<TRoute> = TRoute extends {
1916
- SSE: {
1917
- schema?: {
1918
- query?: infer Q;
1919
- };
1920
- };
1921
- } ? Q extends z.ZodType ? z.infer<Q> : Record<string, unknown> : never;
1951
+ interface ConnectionRegistry {
1952
+ /** Add a new connection to the registry */
1953
+ add: (id: string, stream: SSEStream, metadata?: {
1954
+ clientIp?: string;
1955
+ userAgent?: string;
1956
+ }) => void;
1957
+ /** Remove a connection from the registry */
1958
+ remove: (id: string) => void;
1959
+ /** Get current connection count */
1960
+ count: () => number;
1961
+ /** Clean up inactive or closed connections */
1962
+ cleanup: () => void;
1963
+ /** Get connection by ID (for internal use) */
1964
+ get: (id: string) => SSEStream | undefined;
1965
+ /** Check if a connection exists */
1966
+ has: (id: string) => boolean;
1967
+ /** Get all connection IDs */
1968
+ getIds: () => string[];
1969
+ /** Shutdown the registry and close all connections */
1970
+ shutdown: () => void;
1971
+ }
1922
1972
  /**
1923
- * Extract SSE params from route
1973
+ * Extended stream interface for typed events
1924
1974
  */
1925
- type ExtractSSEParams<TRoute> = TRoute extends {
1926
- SSE: {
1927
- schema?: {
1928
- params?: infer P;
1929
- };
1930
- };
1931
- } ? P extends z.ZodType ? z.infer<P> : Record<string, string> : never;
1975
+ interface TypedSSEStream<TEvents extends Record<string, z.ZodType>> extends SSEStreamExtended {
1976
+ send<K extends keyof TEvents>(event: K & string, data: z.infer<TEvents[K]>): void;
1977
+ }
1932
1978
  /**
1933
- * Build SSE method arguments
1979
+ * Schema for SSE route validation with generic type parameters
1934
1980
  */
1935
- type BuildSSEArgs<TRoute> = ExtractSSEParams<TRoute> extends never ? ExtractSSEQuery<TRoute> extends never ? {
1936
- options?: SSEClientOptions;
1937
- } : {
1938
- query: ExtractSSEQuery<TRoute>;
1939
- options?: SSEClientOptions;
1940
- } : ExtractSSEQuery<TRoute> extends never ? {
1941
- params: ExtractSSEParams<TRoute>;
1942
- options?: SSEClientOptions;
1943
- } : {
1944
- params: ExtractSSEParams<TRoute>;
1945
- query: ExtractSSEQuery<TRoute>;
1946
- options?: SSEClientOptions;
1947
- };
1981
+ interface SSERouteSchema<P extends z.ZodType = z.ZodType<any>, Q extends z.ZodType = z.ZodType<any>, E = any> {
1982
+ /** Parameter schema for validation */
1983
+ params?: P;
1984
+ /** Query schema for validation */
1985
+ query?: Q;
1986
+ /** Events schema for validation (SSE-specific, replaces response) */
1987
+ events?: E;
1988
+ }
1948
1989
  /**
1949
- * Create SSE client method
1990
+ * SSE route handler function with stream as first parameter
1991
+ * This is the user-facing API - they write handlers with this signature
1950
1992
  */
1951
- type CreateSSEMethod<TRoute> = HasSSEMethod<TRoute> extends true ? BuildSSEArgs<TRoute> extends {
1952
- options?: SSEClientOptions;
1953
- } ? (args?: BuildSSEArgs<TRoute>) => Promise<SSEClient<ExtractSSEEvents<TRoute>>> : (args: BuildSSEArgs<TRoute>) => Promise<SSEClient<ExtractSSEEvents<TRoute>>> : never;
1993
+ type SSERouteHandler<TStream extends SSEStreamExtended = SSEStreamExtended, TParams = Record<string, string>, TQuery = Record<string, string | string[] | undefined>, TState extends State = State, TServices extends Services = Services> = (stream: TStream, ctx: Context<TState, TServices, never, TQuery>, // SSE never has body
1994
+ params: TParams) => Promise<void> | void;
1954
1995
  /**
1955
- * Extract SSE routes from registry
1996
+ * SSE route creator with state and services support
1997
+ * Returns a higher-order function to handle generics properly
1998
+ *
1999
+ * The return type matches what the implementation actually returns:
2000
+ * - A route object with a GET property
2001
+ * - The GET property contains the wrapped handler and schemas
2002
+ * - The wrapped handler has the standard (ctx, params) signature expected by the router
1956
2003
  */
1957
- type ExtractSSERoutes<TRoutes extends Record<string, any>> = {
1958
- [K in keyof TRoutes as HasSSEMethod<TRoutes[K]> extends true ? K : never]: TRoutes[K];
2004
+ type CreateSSERoute = <TState extends State = State, TServices extends Services = Services>() => <P = never, Q = never, E = never>(config: {
2005
+ schema?: {
2006
+ params?: P extends never ? never : P;
2007
+ query?: Q extends never ? never : Q;
2008
+ events?: E extends never ? never : E;
2009
+ };
2010
+ handler: SSERouteHandler<E extends Record<string, z.ZodType> ? TypedSSEStream<E> : SSEStreamExtended, P extends z.ZodType ? Infer<P> : Record<string, string>, Q extends z.ZodType ? Infer<Q> : QueryParams, TState, TServices>;
2011
+ middleware?: Middleware[];
2012
+ options?: Record<string, unknown>;
2013
+ }) => {
2014
+ GET: {
2015
+ handler: (ctx: any, params: any) => Promise<void>;
2016
+ schema?: {
2017
+ params?: P extends never ? undefined : P;
2018
+ query?: Q extends never ? undefined : Q;
2019
+ };
2020
+ middleware?: Middleware[];
2021
+ options?: Record<string, unknown>;
2022
+ };
2023
+ path: string;
1959
2024
  };
1960
2025
  /**
1961
- * Enhanced client with SSE support
2026
+ * Buffered event with metadata
1962
2027
  */
1963
- type CreateEnhancedClient<TRoutes extends Record<string, any>, TRegistry> = TRegistry & {
1964
- $sse: {
1965
- [K in keyof ExtractSSERoutes<TRoutes>]: CreateSSEMethod<TRoutes[K]>;
1966
- };
1967
- };
1968
-
2028
+ interface BufferedEvent {
2029
+ id: string;
2030
+ event: string;
2031
+ data: unknown;
2032
+ size: number;
2033
+ timestamp: number;
2034
+ correlationId: string;
2035
+ }
1969
2036
  /**
1970
- * CORS Types for BlaizeJS Framework
1971
- *
1972
- * Comprehensive type definitions for W3C-compliant CORS middleware
1973
- * with support for string, regex, and async function origin validation.
1974
- *
1975
- * @module @blaizejs/types/cors
2037
+ * Stream metrics for monitoring
1976
2038
  */
2039
+ interface StreamMetrics {
2040
+ eventsSent: number;
2041
+ eventsDropped: number;
2042
+ bytesWritten: number;
2043
+ bufferHighWatermark: number;
2044
+ lastEventTime: number;
2045
+ }
1977
2046
 
1978
2047
  /**
1979
- * Origin configuration type supporting multiple validation methods
1980
- *
1981
- * @example
1982
- * ```typescript
1983
- * // String origin (exact match)
1984
- * const origin: CorsOrigin = 'https://example.com';
1985
- *
1986
- * // RegExp pattern
1987
- * const origin: CorsOrigin = /^https:\/\/.*\.example\.com$/;
1988
- *
1989
- * // Dynamic validation function
1990
- * const origin: CorsOrigin = async (origin, ctx) => {
1991
- * return await checkOriginAllowed(origin, ctx?.state.user);
1992
- * };
1993
- *
1994
- * // Array of mixed types
1995
- * const origin: CorsOrigin = [
1996
- * 'https://localhost:3000',
1997
- * /^https:\/\/.*\.example\.com$/,
1998
- * (origin) => origin.endsWith('.trusted.com')
1999
- * ];
2000
- * ```
2048
+ * SSE Client Types for BlaizeJS
2049
+ * Location: packages/blaize-client/src/sse/types.ts
2001
2050
  */
2002
- type CorsOrigin = string | RegExp | ((origin: string, ctx?: Context<any, any>) => boolean | Promise<boolean>) | Array<string | RegExp | ((origin: string, ctx?: Context<any, any>) => boolean | Promise<boolean>)>;
2051
+
2003
2052
  /**
2004
- * HTTP methods that can be allowed in CORS
2005
- * Based on W3C CORS specification
2053
+ * Event handlers map
2006
2054
  */
2007
- type CorsHttpMethod = HttpMethod | 'CONNECT' | 'TRACE';
2055
+ interface EventHandlers {
2056
+ [event: string]: Set<(data: any) => void>;
2057
+ }
2008
2058
  /**
2009
- * Main CORS configuration options
2010
- *
2011
- * @example
2012
- * ```typescript
2013
- * const corsOptions: CorsOptions = {
2014
- * origin: 'https://example.com',
2015
- * methods: ['GET', 'POST'],
2016
- * credentials: true,
2017
- * maxAge: 86400
2018
- * };
2019
- * ```
2059
+ * SSE connection configuration options
2020
2060
  */
2021
- interface CorsOptions {
2022
- /**
2023
- * Configures the Access-Control-Allow-Origin header
2024
- *
2025
- * Possible values:
2026
- * - `true`: Allow all origins (sets to '*' unless credentials is true, then reflects origin)
2027
- * - `false`: Disable CORS (no headers set)
2028
- * - `string`: Specific origin to allow
2029
- * - `RegExp`: Pattern to match origins
2030
- * - `function`: Custom validation logic
2031
- * - `array`: Multiple origin configurations
2032
- *
2033
- * @default false
2034
- */
2035
- origin?: boolean | CorsOrigin;
2036
- /**
2037
- * Configures the Access-Control-Allow-Methods header
2038
- *
2039
- * @default ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']
2040
- * @example ['GET', 'POST']
2041
- */
2042
- methods?: CorsHttpMethod[] | string;
2043
- /**
2044
- * Configures the Access-Control-Allow-Headers header
2045
- *
2046
- * Pass an array of allowed headers or a comma-delimited string.
2047
- *
2048
- * @default Request's Access-Control-Request-Headers header value
2049
- * @example ['Content-Type', 'Authorization']
2050
- */
2051
- allowedHeaders?: string[] | string;
2052
- /**
2053
- * Configures the Access-Control-Expose-Headers header
2054
- *
2055
- * Headers that the browser is allowed to access.
2056
- *
2057
- * @default []
2058
- * @example ['Content-Range', 'X-Content-Range']
2059
- */
2060
- exposedHeaders?: string[] | string;
2061
- /**
2062
- * Configures the Access-Control-Allow-Credentials header
2063
- *
2064
- * Set to true to allow credentials (cookies, authorization headers, TLS client certificates).
2065
- * Note: Cannot be used with origin: '*' for security reasons.
2066
- *
2067
- * @default false
2068
- */
2069
- credentials?: boolean;
2070
- /**
2071
- * Configures the Access-Control-Max-Age header in seconds
2072
- *
2073
- * Indicates how long browsers can cache preflight response.
2074
- * Set to -1 to disable caching.
2075
- *
2076
- * @default undefined (browser decides)
2077
- * @example 86400 // 24 hours
2078
- */
2079
- maxAge?: number;
2061
+ interface SSEClientOptions {
2062
+ headers?: Record<string, string>;
2063
+ withCredentials?: boolean;
2064
+ reconnect?: {
2065
+ enabled: boolean;
2066
+ maxAttempts?: number;
2067
+ strategy?: ReconnectStrategy;
2068
+ initialDelay?: number;
2069
+ };
2070
+ bufferMissedEvents?: boolean;
2071
+ maxMissedEvents?: number;
2072
+ heartbeatTimeout?: number;
2073
+ parseJSON?: boolean;
2080
2074
  /**
2081
- * Whether to pass the CORS preflight response to the next handler
2082
- *
2083
- * When false, the preflight response is sent immediately.
2084
- * When true, control passes to the next middleware/handler.
2085
- *
2086
- * @default false
2075
+ * Whether to wait for connection before resolving the promise.
2076
+ * If false, returns the client immediately without waiting.
2077
+ * Default: true
2087
2078
  */
2088
- preflightContinue?: boolean;
2079
+ waitForConnection?: boolean;
2089
2080
  /**
2090
- * HTTP status code for successful OPTIONS requests
2091
- *
2092
- * Some legacy browsers require 200, while 204 is more correct.
2093
- *
2094
- * @default 204
2081
+ * Optional timeout for initial connection in milliseconds.
2082
+ * If not set, no timeout is applied (relies on EventSource native timeout).
2083
+ * Only applies if waitForConnection is true.
2095
2084
  */
2096
- optionsSuccessStatus?: number;
2085
+ connectionTimeout?: number;
2086
+ }
2087
+ /**
2088
+ * Metrics for SSE connection monitoring
2089
+ */
2090
+ interface SSEClientMetrics {
2091
+ eventsReceived: number;
2092
+ bytesReceived: number;
2093
+ connectionDuration: number;
2094
+ reconnectAttempts: number;
2095
+ lastEventId?: string;
2096
+ }
2097
+ /**
2098
+ * Reconnection delay calculation strategy
2099
+ */
2100
+ type ReconnectStrategy = (attempt: number) => number;
2101
+ /**
2102
+ * SSE Client interface with type-safe event handling
2103
+ */
2104
+ interface SSEClient<TEvents extends Record<string, unknown> = Record<string, unknown>> {
2105
+ on<K extends keyof TEvents>(event: K & string, handler: (data: TEvents[K]) => void): void;
2106
+ on(event: 'error', handler: (error: BlaizeError) => void): void;
2107
+ on(event: 'open', handler: () => void): void;
2108
+ on(event: 'close', handler: (event: CloseEvent) => void): void;
2109
+ off<K extends keyof TEvents>(event: K & string, handler?: (data: TEvents[K]) => void): void;
2110
+ off(event: 'error', handler?: (error: BlaizeError) => void): void;
2111
+ off(event: 'open', handler?: () => void): void;
2112
+ off(event: 'close', handler?: (event: CloseEvent) => void): void;
2113
+ once<K extends keyof TEvents>(event: K & string, handler: (data: TEvents[K]) => void): void;
2114
+ once(event: 'error', handler: (error: BlaizeError) => void): void;
2115
+ once(event: 'open', handler: () => void): void;
2116
+ once(event: 'close', handler: (event: CloseEvent) => void): void;
2117
+ close(): void;
2118
+ readonly state: SSEConnectionState;
2119
+ readonly metrics: SSEClientMetrics;
2120
+ readonly lastEventId?: string;
2121
+ }
2122
+ /**
2123
+ * Close event for SSE connections
2124
+ */
2125
+ interface CloseEvent {
2126
+ reconnect: boolean;
2127
+ reason?: string;
2128
+ }
2129
+ /**
2130
+ * Internal SSE connection factory
2131
+ * Returns a Promise that resolves to an SSEClient instance
2132
+ */
2133
+ type SSEConnectionFactory<TEvents extends Record<string, unknown> = Record<string, unknown>> = (options?: SSEClientOptions) => Promise<SSEClient<TEvents>>;
2134
+
2135
+ type ExtractMethod<T> = T extends {
2136
+ GET: any;
2137
+ } ? 'GET' : T extends {
2138
+ POST: any;
2139
+ } ? 'POST' : T extends {
2140
+ PUT: any;
2141
+ } ? 'PUT' : T extends {
2142
+ DELETE: any;
2143
+ } ? 'DELETE' : T extends {
2144
+ PATCH: any;
2145
+ } ? 'PATCH' : T extends {
2146
+ HEAD: any;
2147
+ } ? 'HEAD' : T extends {
2148
+ OPTIONS: any;
2149
+ } ? 'OPTIONS' : never;
2150
+ type BuildRoutesRegistry<TRoutes extends Record<string, any>> = {
2151
+ [Method in ExtractMethod<TRoutes[keyof TRoutes]> as `$${Lowercase<Method>}`]: {
2152
+ [K in keyof TRoutes as ExtractMethod<TRoutes[K]> extends Method ? K : never]: TRoutes[K];
2153
+ };
2154
+ };
2155
+ type GetRouteMethodOptions<TRoute> = TRoute extends {
2156
+ GET: infer M;
2157
+ } ? M : TRoute extends {
2158
+ POST: infer M;
2159
+ } ? M : TRoute extends {
2160
+ PUT: infer M;
2161
+ } ? M : TRoute extends {
2162
+ DELETE: infer M;
2163
+ } ? M : TRoute extends {
2164
+ PATCH: infer M;
2165
+ } ? M : TRoute extends {
2166
+ HEAD: infer M;
2167
+ } ? M : TRoute extends {
2168
+ OPTIONS: infer M;
2169
+ } ? M : never;
2170
+ type IsNever$1<T> = [T] extends [never] ? true : false;
2171
+ type BuildArgsObject<P, Q, B> = (IsNever$1<P> extends true ? {} : {
2172
+ params: Infer<P>;
2173
+ }) & (IsNever$1<Q> extends true ? {} : {
2174
+ query: Infer<Q>;
2175
+ }) & (IsNever$1<B> extends true ? {} : {
2176
+ body: Infer<B>;
2177
+ });
2178
+ type IsEmptyObject<T> = keyof T extends never ? true : false;
2179
+ type BuildArgs<P, Q, B> = IsEmptyObject<BuildArgsObject<P, Q, B>> extends true ? void : BuildArgsObject<P, Q, B>;
2180
+ type CreateClientMethod<TRoute> = GetRouteMethodOptions<TRoute> extends RouteMethodOptions<infer P, infer Q, infer B, infer R> ? BuildArgs<P, Q, B> extends void ? () => Promise<R extends z.ZodType ? Infer<R> : unknown> : (args: BuildArgs<P, Q, B>) => Promise<R extends z.ZodType ? Infer<R> : unknown> : never;
2181
+ type CreateClient<TRoutes extends Record<string, Record<string, any>>> = {
2182
+ [Method in keyof TRoutes]: {
2183
+ [RouteName in keyof TRoutes[Method]]: CreateClientMethod<TRoutes[Method][RouteName]>;
2184
+ };
2185
+ };
2186
+ interface ClientConfig {
2187
+ baseUrl: string;
2188
+ defaultHeaders?: Record<string, string>;
2189
+ timeout?: number;
2190
+ sse?: SSEClientOptions;
2191
+ }
2192
+ interface InternalRequestArgs {
2193
+ params?: Record<string, any>;
2194
+ query?: Record<string, any>;
2195
+ body?: any;
2196
+ }
2197
+ interface RequestOptions {
2198
+ method: string;
2199
+ url: string;
2200
+ headers: Record<string, string>;
2201
+ body?: string;
2202
+ timeout: number;
2097
2203
  }
2098
2204
  /**
2099
- * Internal CORS validation result
2100
- * Used by middleware implementation
2205
+ * Detect if a route has SSE support
2206
+ * SSE routes have a special 'SSE' method key
2101
2207
  */
2102
- interface CorsValidationResult {
2103
- /**
2104
- * Whether the origin is allowed
2105
- */
2106
- allowed: boolean;
2107
- /**
2108
- * The origin value to set in the header
2109
- * Can be '*', specific origin, or 'null'
2110
- */
2111
- origin?: string;
2112
- /**
2113
- * Whether to add Vary: Origin header
2114
- */
2115
- vary?: boolean;
2116
- }
2208
+ type HasSSEMethod<TRoute> = TRoute extends {
2209
+ SSE: any;
2210
+ } ? true : false;
2117
2211
  /**
2118
- * CORS preflight request information
2119
- * Extracted from OPTIONS request headers
2212
+ * Extract SSE event types from route schema
2120
2213
  */
2121
- interface CorsPreflightInfo {
2122
- /**
2123
- * The origin making the request
2124
- */
2125
- origin?: string;
2126
- /**
2127
- * The method that will be used in the actual request
2128
- * From Access-Control-Request-Method header
2129
- */
2130
- requestedMethod?: string;
2131
- /**
2132
- * The headers that will be sent in the actual request
2133
- * From Access-Control-Request-Headers header
2134
- */
2135
- requestedHeaders?: string[];
2136
- }
2214
+ type ExtractSSEEvents<TRoute> = TRoute extends {
2215
+ SSE: {
2216
+ events?: infer E;
2217
+ };
2218
+ } ? E extends z.ZodType ? z.infer<E> : Record<string, unknown> : Record<string, unknown>;
2137
2219
  /**
2138
- * Cache entry for origin validation results
2139
- * Used for performance optimization
2220
+ * Extract SSE query parameters from route
2140
2221
  */
2141
- interface CorsOriginCacheEntry {
2142
- /**
2143
- * Whether the origin is allowed
2144
- */
2145
- allowed: boolean;
2146
- /**
2147
- * When this cache entry expires (timestamp)
2148
- */
2149
- expiresAt: number;
2150
- /**
2151
- * Optional user identifier for cache key
2152
- */
2153
- userId?: string;
2154
- }
2222
+ type ExtractSSEQuery<TRoute> = TRoute extends {
2223
+ SSE: {
2224
+ schema?: {
2225
+ query?: infer Q;
2226
+ };
2227
+ };
2228
+ } ? Q extends z.ZodType ? z.infer<Q> : Record<string, unknown> : never;
2155
2229
  /**
2156
- * Configuration for CORS origin validation cache
2230
+ * Extract SSE params from route
2157
2231
  */
2158
- interface CorsOriginCacheConfig {
2159
- /**
2160
- * Time-to-live for cache entries in milliseconds
2161
- * @default 60000 (1 minute)
2162
- */
2163
- ttl?: number;
2164
- /**
2165
- * Maximum number of entries in the cache
2166
- * @default 1000
2167
- */
2168
- maxSize?: number;
2169
- /**
2170
- * Whether to include user ID in cache key
2171
- * @default true
2172
- */
2173
- includeUserId?: boolean;
2174
- }
2232
+ type ExtractSSEParams<TRoute> = TRoute extends {
2233
+ SSE: {
2234
+ schema?: {
2235
+ params?: infer P;
2236
+ };
2237
+ };
2238
+ } ? P extends z.ZodType ? z.infer<P> : Record<string, string> : never;
2175
2239
  /**
2176
- * Statistics for CORS middleware performance monitoring
2240
+ * Build SSE method arguments
2177
2241
  */
2178
- interface CorsStats {
2179
- /**
2180
- * Total number of CORS requests processed
2181
- */
2182
- totalRequests: number;
2183
- /**
2184
- * Number of preflight requests handled
2185
- */
2186
- preflightRequests: number;
2187
- /**
2188
- * Number of allowed origins
2189
- */
2190
- allowedOrigins: number;
2191
- /**
2192
- * Number of denied origins
2193
- */
2194
- deniedOrigins: number;
2195
- /**
2196
- * Cache hit rate for origin validation
2197
- */
2198
- cacheHitRate: number;
2199
- /**
2200
- * Average origin validation time in milliseconds
2201
- */
2202
- avgValidationTime: number;
2203
- }
2242
+ type BuildSSEArgs<TRoute> = ExtractSSEParams<TRoute> extends never ? ExtractSSEQuery<TRoute> extends never ? {
2243
+ options?: SSEClientOptions;
2244
+ } : {
2245
+ query: ExtractSSEQuery<TRoute>;
2246
+ options?: SSEClientOptions;
2247
+ } : ExtractSSEQuery<TRoute> extends never ? {
2248
+ params: ExtractSSEParams<TRoute>;
2249
+ options?: SSEClientOptions;
2250
+ } : {
2251
+ params: ExtractSSEParams<TRoute>;
2252
+ query: ExtractSSEQuery<TRoute>;
2253
+ options?: SSEClientOptions;
2254
+ };
2204
2255
  /**
2205
- * Cache entry type
2256
+ * Create SSE client method
2206
2257
  */
2207
- interface CacheEntry {
2208
- allowed: boolean;
2209
- expiresAt: number;
2210
- lastAccessed: number;
2211
- }
2258
+ type CreateSSEMethod<TRoute> = HasSSEMethod<TRoute> extends true ? BuildSSEArgs<TRoute> extends {
2259
+ options?: SSEClientOptions;
2260
+ } ? (args?: BuildSSEArgs<TRoute>) => Promise<SSEClient<ExtractSSEEvents<TRoute>>> : (args: BuildSSEArgs<TRoute>) => Promise<SSEClient<ExtractSSEEvents<TRoute>>> : never;
2212
2261
  /**
2213
- * Cache configuration
2262
+ * Extract SSE routes from registry
2214
2263
  */
2215
- interface CacheConfig {
2216
- ttl: number;
2217
- maxSize: number;
2218
- }
2264
+ type ExtractSSERoutes<TRoutes extends Record<string, any>> = {
2265
+ [K in keyof TRoutes as HasSSEMethod<TRoutes[K]> extends true ? K : never]: TRoutes[K];
2266
+ };
2267
+ /**
2268
+ * Enhanced client with SSE support
2269
+ */
2270
+ type CreateEnhancedClient<TRoutes extends Record<string, any>, TRegistry> = TRegistry & {
2271
+ $sse: {
2272
+ [K in keyof ExtractSSERoutes<TRoutes>]: CreateSSEMethod<TRoutes[K]>;
2273
+ };
2274
+ };
2219
2275
 
2220
2276
  /**
2221
2277
  * BlaizeJS Server Module - Enhanced with Correlation Configuration
@@ -2312,6 +2368,7 @@ interface ServerOptionsInput {
2312
2368
  * ```
2313
2369
  */
2314
2370
  cors?: CorsOptions | boolean;
2371
+ bodyLimits?: Partial<BodyLimits>;
2315
2372
  }
2316
2373
  /**
2317
2374
  * Configuration for a BlaizeJS server
@@ -2346,6 +2403,7 @@ interface ServerOptions {
2346
2403
  * @since 0.5.0
2347
2404
  */
2348
2405
  cors?: CorsOptions | boolean;
2406
+ bodyLimits: BodyLimits;
2349
2407
  }
2350
2408
  /**
2351
2409
  * BlaizeJS Server instance with generic type accumulation
@@ -2361,6 +2419,8 @@ interface Server<TState, TServices> {
2361
2419
  port: number;
2362
2420
  /** CORS configuration for this server */
2363
2421
  corsOptions?: CorsOptions | boolean;
2422
+ /** Body size limits for incoming requests */
2423
+ bodyLimits: BodyLimits;
2364
2424
  /** The host the server is bound to */
2365
2425
  host: string;
2366
2426
  events: EventEmitter;
@@ -2468,7 +2528,7 @@ interface Plugin<TState = {}, TServices = {}> extends PluginHooks {
2468
2528
  /**
2469
2529
  * Plugin factory function
2470
2530
  */
2471
- type PluginFactory<T = any, TState extends Record<string, unknown> = {}, TServices extends Record<string, unknown> = {}> = (options?: T) => Plugin<TState, TServices>;
2531
+ type PluginFactory<TConfig = any, TState = {}, TServices = {}> = (options?: TConfig) => Plugin<TState, TServices>;
2472
2532
  interface PluginLifecycleManager {
2473
2533
  initializePlugins(server: Server<any, any>): Promise<void>;
2474
2534
  terminatePlugins(server: Server<any, any>): Promise<void>;
@@ -2730,7 +2790,7 @@ declare function createPluginArray<T extends ReadonlyArray<Plugin<any, any>>>(..
2730
2790
  /**
2731
2791
  * Create a plugin with the given name, version, and setup function
2732
2792
  */
2733
- declare function create$1<T = any>(name: string, version: string, setup: (app: UnknownServer, options: T) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>, defaultOptions?: Partial<T>): PluginFactory<T>;
2793
+ declare function create$1<TConfig = any, TState = {}, TServices = {}>(name: string, version: string, setup: (app: UnknownServer, options: TConfig) => void | Partial<PluginHooks> | Promise<void> | Promise<Partial<PluginHooks>>, defaultOptions?: Partial<TConfig>): PluginFactory<TConfig, TState, TServices>;
2734
2794
 
2735
2795
  /**
2736
2796
  * Create a GET route
@@ -2899,6 +2959,31 @@ declare function createRouteFactory<TState extends State = State, TServices exte
2899
2959
  };
2900
2960
  };
2901
2961
 
2962
+ /**
2963
+ * Create a route matcher
2964
+ */
2965
+ declare function createMatcher(): Matcher;
2966
+
2967
+ /**
2968
+ * Extract parameter values from a URL path
2969
+ */
2970
+ declare function extractParams(path: string, pattern: RegExp, paramNames: string[]): Record<string, string>;
2971
+ /**
2972
+ * Compile a path pattern with parameters
2973
+ */
2974
+ declare function compilePathPattern(path: string): {
2975
+ pattern: RegExp;
2976
+ paramNames: string[];
2977
+ };
2978
+ /**
2979
+ * Convert parameters object to URL query string
2980
+ */
2981
+ declare function paramsToQuery(params: Record<string, string | number | boolean>): string;
2982
+ /**
2983
+ * Build a URL with path parameters
2984
+ */
2985
+ declare function buildUrl(pathPattern: string, params?: Record<string, string | number | boolean>, query?: Record<string, string | number | boolean>): string;
2986
+
2902
2987
  /**
2903
2988
  * Creates a BlaizeJS server instance
2904
2989
  */
@@ -3244,14 +3329,37 @@ declare class RequestTimeoutError extends BlaizeError {
3244
3329
  constructor(title: string, details?: unknown, correlationId?: string);
3245
3330
  }
3246
3331
 
3247
- declare class UnsupportedMediaTypeError extends BlaizeError {
3332
+ declare class UnprocessableEntityError extends BlaizeError {
3248
3333
  constructor(title: string, details?: unknown, correlationId?: string);
3249
3334
  }
3250
3335
 
3251
- declare class UnprocessableEntityError extends BlaizeError {
3336
+ declare class UnsupportedMediaTypeError extends BlaizeError {
3252
3337
  constructor(title: string, details?: unknown, correlationId?: string);
3253
3338
  }
3254
3339
 
3340
+ /**
3341
+ * Error thrown when a service is temporarily unavailable
3342
+ *
3343
+ * Automatically sets HTTP status to 503 and optionally includes Retry-After.
3344
+ *
3345
+ * @example Basic usage:
3346
+ * ```typescript
3347
+ * throw new ServiceNotAvailableError('Database unavailable');
3348
+ * ```
3349
+ *
3350
+ * @example With retry guidance:
3351
+ * ```typescript
3352
+ * throw new ServiceNotAvailableError('Payment service down', {
3353
+ * service: 'stripe',
3354
+ * retryAfter: 30,
3355
+ * reason: 'circuit_breaker'
3356
+ * });
3357
+ * ```
3358
+ */
3359
+ declare class ServiceNotAvailableError extends BlaizeError<ServiceNotAvailableDetails> {
3360
+ constructor(title: string, details?: ServiceNotAvailableDetails | undefined, correlationId?: string | undefined);
3361
+ }
3362
+
3255
3363
  declare const VERSION = "0.1.0";
3256
3364
  declare const ServerAPI: {
3257
3365
  createServer: typeof create;
@@ -3266,12 +3374,18 @@ declare const RouterAPI: {
3266
3374
  createPostRoute: CreatePostRoute;
3267
3375
  createPutRoute: CreatePutRoute;
3268
3376
  createRouteFactory: typeof createRouteFactory;
3377
+ createMatcher: typeof createMatcher;
3378
+ extractParams: typeof extractParams;
3379
+ compilePathPattern: typeof compilePathPattern;
3380
+ paramsToQuery: typeof paramsToQuery;
3381
+ buildUrl: typeof buildUrl;
3269
3382
  };
3270
3383
  declare const MiddlewareAPI: {
3271
3384
  createMiddleware: typeof create$2;
3272
3385
  createServiceMiddleware: typeof serviceMiddleware;
3273
3386
  createStateMiddleware: typeof stateMiddleware;
3274
3387
  compose: typeof compose;
3388
+ cors: typeof cors;
3275
3389
  };
3276
3390
  declare const PluginsAPI: {
3277
3391
  createPlugin: typeof create$1;
@@ -3297,12 +3411,18 @@ declare const Blaize: {
3297
3411
  createPostRoute: CreatePostRoute;
3298
3412
  createPutRoute: CreatePutRoute;
3299
3413
  createRouteFactory: typeof createRouteFactory;
3414
+ createMatcher: typeof createMatcher;
3415
+ extractParams: typeof extractParams;
3416
+ compilePathPattern: typeof compilePathPattern;
3417
+ paramsToQuery: typeof paramsToQuery;
3418
+ buildUrl: typeof buildUrl;
3300
3419
  };
3301
3420
  Middleware: {
3302
3421
  createMiddleware: typeof create$2;
3303
3422
  createServiceMiddleware: typeof serviceMiddleware;
3304
3423
  createStateMiddleware: typeof stateMiddleware;
3305
3424
  compose: typeof compose;
3425
+ cors: typeof cors;
3306
3426
  };
3307
3427
  Plugins: {
3308
3428
  createPlugin: typeof create$1;
@@ -3310,4 +3430,4 @@ declare const Blaize: {
3310
3430
  VERSION: string;
3311
3431
  };
3312
3432
 
3313
- export { Blaize, BlaizeError, type BlaizeErrorResponse, type BodyParseError, type BufferedEvent, type BuildRoutesRegistry, type BuildSSEArgs, type CacheConfig, type CacheEntry, type ClientConfig, type CloseEvent, type ComposeMiddlewareServices, type ComposeMiddlewareStates, type ComposeMiddlewareTypes, type ComposePluginServices, type ComposePluginStates, type ComposePluginTypes, ConflictError, type ConflictErrorDetails, type ConnectionEntry, type ConnectionRegistry, type Context, type ContextOptions, type ContextRequest, type ContextResponse, type CorrelationOptions, type CorsHttpMethod, type CorsOptions, type CorsOrigin, type CorsOriginCacheConfig, type CorsOriginCacheEntry, type CorsPreflightInfo, type CorsStats, type CorsValidationResult, type CreateClient, type CreateContextFn, type CreateDeleteRoute, type CreateEnhancedClient, type CreateGetRoute, type CreateHeadRoute, type CreateOptionsRoute, type CreatePatchRoute, type CreatePostRoute, type CreatePutRoute, type CreateSSEMethod, type CreateSSERoute, type ErrorHandlerOptions, ErrorSeverity, type ErrorTransformContext, ErrorType, type EventHandlers, type ExtractMethod, type ExtractMiddlewareServices, type ExtractMiddlewareState, type ExtractMiddlewareTypes, type ExtractPluginServices, type ExtractPluginState, type ExtractPluginTypes, type ExtractSSEEvents, type ExtractSSEParams, type ExtractSSEQuery, type ExtractSSERoutes, type FileCache, type FindRouteFilesOptions, ForbiddenError, type ForbiddenErrorDetails, type GetContextFn, type HasSSEMethod, type Http2Options, type HttpMethod, type Infer, type InferContext, type InternalRequestArgs, InternalServerError, type InternalServerErrorDetails, type Matcher, type MergeServices, type MergeStates, type Middleware, MiddlewareAPI, type MiddlewareFunction, type MiddlewareOptions, type MultipartData, type MultipartError, type MultipartLimits, type NetworkErrorContext, type NextFunction, NotFoundError, type NotFoundErrorDetails, type ParseErrorContext, type ParseOptions, type ParseResult, type ParsedRoute, type ParserState, PayloadTooLargeError, type PayloadTooLargeErrorDetails, type Plugin, type PluginFactory, type PluginHooks, type PluginLifecycleManager, type PluginLifecycleOptions, type PluginOptions, PluginsAPI, type ProcessResponseOptions, type ProcessingConfig, type QueryParams, RateLimitError, type RateLimitErrorDetails, type ReconnectStrategy, type RegistryResult, type ReloadMetrics, type RequestHandler, type RequestOptions, type RequestParams, RequestTimeoutError, type Result, type Route, type RouteDefinition, type RouteEntry, type RouteHandler, type RouteMatch, type RouteMethodOptions, type RouteNode, type RouteOptions, type RouteRegistry, type RouteSchema, type Router, RouterAPI, type RouterOptions, type SSEBufferOverflowErrorDetails, type SSEBufferStrategy, type SSEClient, type SSEClientMetrics, type SSEClientOptions, type SSEConnectionErrorContext, type SSEConnectionErrorDetails, type SSEConnectionFactory, type SSEConnectionState, type SSEEvent, type SSEEventHandler, type SSEEventListener, type SSEHeartbeatErrorContext, type SSEMetrics, type SSEOptions, type SSERouteHandler, type SSERouteSchema, type SSESerializedEvent, type SSEStream, type SSEStreamClosedErrorDetails, type SSEStreamErrorContext, type SSEStreamExtended, type SSEStreamManager, type SafeComposeMiddlewareServices, type SafeComposeMiddlewareStates, type SafeComposePluginServices, type SafeComposePluginStates, type SafeExtractMiddlewareServices, type SafeExtractMiddlewareState, type SafeExtractPluginServices, type SafeExtractPluginState, type Server, ServerAPI, type ServerOptions, type ServerOptionsInput, type Services, type StandardErrorResponse, type StartOptions, type State, type StopOptions, type StreamMetrics, type StreamOptions, type TimeoutErrorContext, type TypedSSEStream, UnauthorizedError, type UnauthorizedErrorDetails, type UnifiedRequest, type UnifiedResponse, type UnionToIntersection, type UnknownFunction, type UnknownServer, UnprocessableEntityError, UnsupportedMediaTypeError, type UnsupportedMediaTypeErrorDetails, type UploadProgress, type UploadedFile, VERSION, type ValidationConfig, ValidationError, type ValidationErrorDetails, type ValidationFieldError, type WatchOptions, asMiddlewareArray, asPluginArray, compose, createDeleteRoute, createGetRoute, createHeadRoute, create$2 as createMiddleware, createMiddlewareArray, createOptionsRoute, createPatchRoute, create$1 as createPlugin, createPluginArray, createPostRoute, createPutRoute, createRouteFactory, create as createServer, serviceMiddleware as createServiceMiddleware, stateMiddleware as createStateMiddleware, getCorrelationId, inferContext, isBodyParseError, isMiddleware, isPlugin };
3433
+ export { Blaize, BlaizeError, type BlaizeErrorResponse, type BodyLimits, type BodyParseError, type BufferedEvent, type BuildRoutesRegistry, type BuildSSEArgs, type CacheConfig, type CacheEntry, type ClientConfig, type CloseEvent, type ComposeMiddlewareServices, type ComposeMiddlewareStates, type ComposeMiddlewareTypes, type ComposePluginServices, type ComposePluginStates, type ComposePluginTypes, ConflictError, type ConflictErrorDetails, type ConnectionEntry, type ConnectionRegistry, type Context, type ContextOptions, type ContextRequest, type ContextResponse, type CorrelationOptions, type CorsHttpMethod, type CorsOptions, type CorsOrigin, type CorsOriginCacheConfig, type CorsOriginCacheEntry, type CorsPreflightInfo, type CorsStats, type CorsValidationResult, type CreateClient, type CreateContextFn, type CreateDeleteRoute, type CreateEnhancedClient, type CreateGetRoute, type CreateHeadRoute, type CreateOptionsRoute, type CreatePatchRoute, type CreatePostRoute, type CreatePutRoute, type CreateSSEMethod, type CreateSSERoute, type ErrorHandlerOptions, ErrorSeverity, type ErrorTransformContext, ErrorType, type EventHandlers, type ExtractMethod, type ExtractMiddlewareServices, type ExtractMiddlewareState, type ExtractMiddlewareTypes, type ExtractPluginServices, type ExtractPluginState, type ExtractPluginTypes, type ExtractSSEEvents, type ExtractSSEParams, type ExtractSSEQuery, type ExtractSSERoutes, type FileCache, type FindRouteFilesOptions, ForbiddenError, type ForbiddenErrorDetails, type GetContextFn, type HasSSEMethod, type Http2Options, type HttpMethod, type Infer, type InferContext, type InternalRequestArgs, InternalServerError, type InternalServerErrorDetails, type Matcher, type MergeServices, type MergeStates, type Middleware, MiddlewareAPI, type MiddlewareFunction, type MiddlewareOptions, type MultipartData, type MultipartError, type MultipartLimits, type NetworkErrorContext, type NextFunction, NotFoundError, type NotFoundErrorDetails, type ParseErrorContext, type ParseOptions, type ParseResult, type ParsedRoute, type ParserState, PayloadTooLargeError, type PayloadTooLargeErrorDetails, type Plugin, type PluginFactory, type PluginHooks, type PluginLifecycleManager, type PluginLifecycleOptions, type PluginOptions, PluginsAPI, type ProcessResponseOptions, type ProcessingConfig, type QueryParams, RateLimitError, type RateLimitErrorDetails, type ReconnectStrategy, type RegistryResult, type ReloadMetrics, type RequestHandler, type RequestOptions, type RequestParams, RequestTimeoutError, type Result, type Route, type RouteDefinition, type RouteEntry, type RouteHandler, type RouteMatch, type RouteMethodOptions, type RouteNode, type RouteOptions, type RouteRegistry, type RouteSchema, type Router, RouterAPI, type RouterOptions, type SSEBufferOverflowErrorDetails, type SSEBufferStrategy, type SSEClient, type SSEClientMetrics, type SSEClientOptions, type SSEConnectionErrorContext, type SSEConnectionErrorDetails, type SSEConnectionFactory, type SSEConnectionState, type SSEEvent, type SSEEventHandler, type SSEEventListener, type SSEHeartbeatErrorContext, type SSEMetrics, type SSEOptions, type SSERouteHandler, type SSERouteSchema, type SSESerializedEvent, type SSEStream, type SSEStreamClosedErrorDetails, type SSEStreamErrorContext, type SSEStreamExtended, type SSEStreamManager, type SafeComposeMiddlewareServices, type SafeComposeMiddlewareStates, type SafeComposePluginServices, type SafeComposePluginStates, type SafeExtractMiddlewareServices, type SafeExtractMiddlewareState, type SafeExtractPluginServices, type SafeExtractPluginState, type Server, ServerAPI, type ServerOptions, type ServerOptionsInput, type ServiceNotAvailableDetails, ServiceNotAvailableError, type Services, type StandardErrorResponse, type StartOptions, type State, type StopOptions, type StreamMetrics, type StreamOptions, type TimeoutErrorContext, type TypedSSEStream, UnauthorizedError, type UnauthorizedErrorDetails, type UnifiedRequest, type UnifiedResponse, type UnionToIntersection, type UnknownFunction, type UnknownServer, UnprocessableEntityError, UnsupportedMediaTypeError, type UnsupportedMediaTypeErrorDetails, type UploadProgress, type UploadedFile, VERSION, type ValidationConfig, ValidationError, type ValidationErrorDetails, type ValidationFieldError, type WatchOptions, asMiddlewareArray, asPluginArray, buildUrl, compilePathPattern, compose, cors, createDeleteRoute, createGetRoute, createHeadRoute, createMatcher, create$2 as createMiddleware, createMiddlewareArray, createOptionsRoute, createPatchRoute, create$1 as createPlugin, createPluginArray, createPostRoute, createPutRoute, createRouteFactory, create as createServer, serviceMiddleware as createServiceMiddleware, stateMiddleware as createStateMiddleware, extractParams, getCorrelationId, inferContext, isBodyParseError, isMiddleware, isPlugin, paramsToQuery };