@gravito/echo 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +211 -0
  2. package/dist/atlas/src/DB.d.ts +301 -0
  3. package/dist/atlas/src/OrbitAtlas.d.ts +9 -0
  4. package/dist/atlas/src/config/defineConfig.d.ts +14 -0
  5. package/dist/atlas/src/config/index.d.ts +7 -0
  6. package/dist/atlas/src/config/loadConfig.d.ts +48 -0
  7. package/dist/atlas/src/connection/Connection.d.ts +108 -0
  8. package/dist/atlas/src/connection/ConnectionManager.d.ts +111 -0
  9. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +32 -0
  10. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +118 -0
  11. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +36 -0
  12. package/dist/atlas/src/drivers/MySQLDriver.d.ts +66 -0
  13. package/dist/atlas/src/drivers/PostgresDriver.d.ts +83 -0
  14. package/dist/atlas/src/drivers/RedisDriver.d.ts +43 -0
  15. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +45 -0
  16. package/dist/atlas/src/drivers/types.d.ts +260 -0
  17. package/dist/atlas/src/errors/index.d.ts +45 -0
  18. package/dist/atlas/src/grammar/Grammar.d.ts +342 -0
  19. package/dist/atlas/src/grammar/MongoGrammar.d.ts +47 -0
  20. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +54 -0
  21. package/dist/atlas/src/grammar/NullGrammar.d.ts +35 -0
  22. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +62 -0
  23. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +32 -0
  24. package/dist/atlas/src/index.d.ts +67 -0
  25. package/dist/atlas/src/migration/Migration.d.ts +64 -0
  26. package/dist/atlas/src/migration/MigrationRepository.d.ts +65 -0
  27. package/dist/atlas/src/migration/Migrator.d.ts +110 -0
  28. package/dist/atlas/src/migration/index.d.ts +6 -0
  29. package/dist/atlas/src/observability/AtlasMetrics.d.ts +11 -0
  30. package/dist/atlas/src/observability/AtlasObservability.d.ts +15 -0
  31. package/dist/atlas/src/observability/AtlasTracer.d.ts +12 -0
  32. package/dist/atlas/src/observability/index.d.ts +9 -0
  33. package/dist/atlas/src/orm/index.d.ts +5 -0
  34. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +121 -0
  35. package/dist/atlas/src/orm/model/Model.d.ts +449 -0
  36. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +20 -0
  37. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +136 -0
  38. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +36 -0
  39. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +87 -0
  40. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +117 -0
  41. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +64 -0
  42. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +15 -0
  43. package/dist/atlas/src/orm/model/concerns/index.d.ts +12 -0
  44. package/dist/atlas/src/orm/model/decorators.d.ts +109 -0
  45. package/dist/atlas/src/orm/model/errors.d.ts +52 -0
  46. package/dist/atlas/src/orm/model/index.d.ts +10 -0
  47. package/dist/atlas/src/orm/model/relationships.d.ts +207 -0
  48. package/dist/atlas/src/orm/model/types.d.ts +12 -0
  49. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +123 -0
  50. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +54 -0
  51. package/dist/atlas/src/orm/schema/index.d.ts +6 -0
  52. package/dist/atlas/src/orm/schema/types.d.ts +85 -0
  53. package/dist/atlas/src/query/Expression.d.ts +60 -0
  54. package/dist/atlas/src/query/NPlusOneDetector.d.ts +10 -0
  55. package/dist/atlas/src/query/QueryBuilder.d.ts +573 -0
  56. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +51 -0
  57. package/dist/atlas/src/query/clauses/HavingClause.d.ts +70 -0
  58. package/dist/atlas/src/query/clauses/JoinClause.d.ts +87 -0
  59. package/dist/atlas/src/query/clauses/LimitClause.d.ts +82 -0
  60. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +69 -0
  61. package/dist/atlas/src/query/clauses/SelectClause.d.ts +71 -0
  62. package/dist/atlas/src/query/clauses/WhereClause.d.ts +167 -0
  63. package/dist/atlas/src/query/clauses/index.d.ts +11 -0
  64. package/dist/atlas/src/schema/Blueprint.d.ts +276 -0
  65. package/dist/atlas/src/schema/ColumnDefinition.d.ts +154 -0
  66. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +37 -0
  67. package/dist/atlas/src/schema/Schema.d.ts +131 -0
  68. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +23 -0
  69. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +26 -0
  70. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +28 -0
  71. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +97 -0
  72. package/dist/atlas/src/schema/grammars/index.d.ts +7 -0
  73. package/dist/atlas/src/schema/index.d.ts +8 -0
  74. package/dist/atlas/src/seed/Factory.d.ts +90 -0
  75. package/dist/atlas/src/seed/Seeder.d.ts +28 -0
  76. package/dist/atlas/src/seed/SeederRunner.d.ts +74 -0
  77. package/dist/atlas/src/seed/index.d.ts +6 -0
  78. package/dist/atlas/src/types/index.d.ts +1100 -0
  79. package/dist/atlas/src/utils/levenshtein.d.ts +9 -0
  80. package/dist/core/src/Application.d.ts +43 -17
  81. package/dist/core/src/CommandKernel.d.ts +33 -0
  82. package/dist/core/src/Container.d.ts +78 -14
  83. package/dist/core/src/HookManager.d.ts +422 -8
  84. package/dist/core/src/PlanetCore.d.ts +52 -7
  85. package/dist/core/src/Router.d.ts +41 -7
  86. package/dist/core/src/ServiceProvider.d.ts +14 -8
  87. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  88. package/dist/core/src/adapters/PhotonAdapter.d.ts +1 -0
  89. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  90. package/dist/core/src/adapters/types.d.ts +39 -0
  91. package/dist/core/src/engine/AOTRouter.d.ts +1 -11
  92. package/dist/core/src/engine/FastContext.d.ts +4 -2
  93. package/dist/core/src/engine/Gravito.d.ts +1 -1
  94. package/dist/core/src/engine/MinimalContext.d.ts +4 -2
  95. package/dist/core/src/engine/types.d.ts +6 -1
  96. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  97. package/dist/core/src/events/DeadLetterQueue.d.ts +145 -0
  98. package/dist/core/src/events/EventBackend.d.ts +11 -0
  99. package/dist/core/src/events/EventOptions.d.ts +109 -0
  100. package/dist/core/src/events/EventPriorityQueue.d.ts +202 -0
  101. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  102. package/dist/core/src/events/index.d.ts +14 -0
  103. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  104. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  105. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  106. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +240 -0
  107. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  108. package/dist/core/src/events/observability/index.d.ts +20 -0
  109. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  110. package/dist/core/src/events/types.d.ts +75 -0
  111. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  112. package/dist/core/src/exceptions/index.d.ts +1 -0
  113. package/dist/core/src/http/cookie.d.ts +29 -0
  114. package/dist/core/src/http/types.d.ts +21 -0
  115. package/dist/core/src/index.d.ts +13 -3
  116. package/dist/core/src/instrumentation/index.d.ts +35 -0
  117. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  118. package/dist/core/src/instrumentation/types.d.ts +182 -0
  119. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +316 -0
  120. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  121. package/dist/core/src/reliability/index.d.ts +6 -0
  122. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  123. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  124. package/dist/echo/src/OrbitEcho.d.ts +71 -16
  125. package/dist/echo/src/dlq/DeadLetterQueue.d.ts +94 -0
  126. package/dist/echo/src/dlq/MemoryDeadLetterQueue.d.ts +36 -0
  127. package/dist/echo/src/dlq/index.d.ts +2 -0
  128. package/dist/echo/src/index.d.ts +31 -15
  129. package/dist/echo/src/middleware/RequestBufferMiddleware.d.ts +62 -0
  130. package/dist/echo/src/middleware/index.d.ts +8 -0
  131. package/dist/echo/src/observability/index.d.ts +3 -0
  132. package/dist/echo/src/observability/logging/ConsoleEchoLogger.d.ts +37 -0
  133. package/dist/echo/src/observability/logging/EchoLogger.d.ts +38 -0
  134. package/dist/echo/src/observability/logging/index.d.ts +2 -0
  135. package/dist/echo/src/observability/metrics/MetricsProvider.d.ts +69 -0
  136. package/dist/echo/src/observability/metrics/NoopMetricsProvider.d.ts +17 -0
  137. package/dist/echo/src/observability/metrics/PrometheusMetricsProvider.d.ts +39 -0
  138. package/dist/echo/src/observability/metrics/index.d.ts +3 -0
  139. package/dist/echo/src/observability/tracing/NoopTracer.d.ts +33 -0
  140. package/dist/echo/src/observability/tracing/Tracer.d.ts +75 -0
  141. package/dist/echo/src/observability/tracing/index.d.ts +2 -0
  142. package/dist/echo/src/providers/GenericProvider.d.ts +37 -18
  143. package/dist/echo/src/providers/GitHubProvider.d.ts +21 -12
  144. package/dist/echo/src/providers/LinearProvider.d.ts +27 -0
  145. package/dist/echo/src/providers/PaddleProvider.d.ts +31 -0
  146. package/dist/echo/src/providers/ShopifyProvider.d.ts +27 -0
  147. package/dist/echo/src/providers/SlackProvider.d.ts +27 -0
  148. package/dist/echo/src/providers/StripeProvider.d.ts +20 -12
  149. package/dist/echo/src/providers/TwilioProvider.d.ts +31 -0
  150. package/dist/echo/src/providers/base/BaseProvider.d.ts +87 -0
  151. package/dist/echo/src/providers/base/HeaderUtils.d.ts +34 -0
  152. package/dist/echo/src/providers/index.d.ts +14 -3
  153. package/dist/echo/src/receive/SignatureValidator.d.ts +33 -0
  154. package/dist/echo/src/receive/WebhookReceiver.d.ts +139 -21
  155. package/dist/echo/src/replay/WebhookReplayService.d.ts +35 -0
  156. package/dist/echo/src/replay/index.d.ts +1 -0
  157. package/dist/echo/src/resilience/CircuitBreaker.d.ts +117 -0
  158. package/dist/echo/src/resilience/index.d.ts +10 -0
  159. package/dist/echo/src/rotation/KeyRotationManager.d.ts +127 -0
  160. package/dist/echo/src/rotation/index.d.ts +10 -0
  161. package/dist/echo/src/send/WebhookDispatcher.d.ts +159 -15
  162. package/dist/echo/src/storage/MemoryWebhookStore.d.ts +14 -0
  163. package/dist/echo/src/storage/WebhookStore.d.ts +236 -0
  164. package/dist/echo/src/storage/index.d.ts +2 -0
  165. package/dist/echo/src/types.d.ts +656 -64
  166. package/dist/index.js +1327 -189
  167. package/dist/index.js.map +28 -10
  168. package/dist/photon/src/index.d.ts +69 -5
  169. package/dist/photon/src/middleware/binary.d.ts +12 -15
  170. package/dist/photon/src/middleware/htmx.d.ts +39 -0
  171. package/dist/photon/src/middleware/ratelimit.d.ts +157 -0
  172. package/dist/photon/src/openapi.d.ts +19 -0
  173. package/package.json +7 -5
@@ -23,4 +23,5 @@ export declare class GravitoEngineAdapter<V extends GravitoVariables = GravitoVa
23
23
  fetch: (request: Request, _server?: unknown) => Response | Promise<Response>;
24
24
  warmup(paths: string[]): Promise<void>;
25
25
  createContext(_request: Request): GravitoContext<V>;
26
+ useScoped(scope: string, path: string, ...middleware: GravitoMiddleware<V>[]): void;
26
27
  }
@@ -136,6 +136,7 @@ export declare class PhotonAdapter<V extends GravitoVariables = GravitoVariables
136
136
  routes(routes: RouteDefinition[]): void;
137
137
  use(path: string, ...middleware: GravitoMiddleware<V>[]): void;
138
138
  useGlobal(...middleware: GravitoMiddleware<V>[]): void;
139
+ useScoped(scope: string, path: string, ...middleware: GravitoMiddleware<V>[]): void;
139
140
  mount(path: string, subAdapter: HttpAdapter<V>): void;
140
141
  onError(handler: GravitoErrorHandler<V>): void;
141
142
  onNotFound(handler: GravitoNotFoundHandler<V>): void;
@@ -17,6 +17,7 @@ export declare class BunNativeAdapter implements HttpAdapter {
17
17
  routes(routes: RouteDefinition[]): void;
18
18
  use(path: string, ...middleware: GravitoMiddleware[]): void;
19
19
  useGlobal(...middleware: GravitoMiddleware[]): void;
20
+ useScoped(scope: string, path: string, ...middleware: GravitoMiddleware[]): void;
20
21
  mount(path: string, subAdapter: HttpAdapter): void;
21
22
  createContext(request: Request): GravitoContext;
22
23
  onError(handler: GravitoErrorHandler): void;
@@ -115,6 +115,33 @@ export interface HttpAdapter<V extends GravitoVariables = GravitoVariables> {
115
115
  * @param middleware - Middleware function
116
116
  */
117
117
  useGlobal(...middleware: GravitoMiddleware<V>[]): void;
118
+ /**
119
+ * Register a scoped middleware for Orbit-level isolation
120
+ *
121
+ * Unlike regular `use()`, this method enforces stricter scoping rules:
122
+ * - REJECTS '*' wildcard paths (prevents global middleware in Orbits)
123
+ * - ENFORCES that all middleware paths must include the scope prefix
124
+ * - Throws error if attempting to register global middleware within an Orbit scope
125
+ *
126
+ * This is designed to prevent accidental middleware cross-contamination
127
+ * when multiple Orbits are mounted to a single PlanetCore instance.
128
+ *
129
+ * @param scope - The scope/path prefix (e.g., '/api', '/blog')
130
+ * @param path - Path pattern to match (cannot be '*')
131
+ * @param middleware - One or more middleware functions
132
+ * @throws {Error} If path is '*' when in Orbit scope
133
+ * @since 2.3.0
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * // Correct: Scoped to specific path
138
+ * adapter.useScoped('/api', '/users/*', authMiddleware)
139
+ *
140
+ * // Error: Cannot use wildcard in Orbit scope
141
+ * adapter.useScoped('/api', '*', loggerMiddleware)
142
+ * ```
143
+ */
144
+ useScoped(scope: string, path: string, ...middleware: GravitoMiddleware<V>[]): void;
118
145
  /**
119
146
  * Mount a sub-adapter at a path
120
147
  *
@@ -164,6 +191,18 @@ export interface HttpAdapter<V extends GravitoVariables = GravitoVariables> {
164
191
  * @since 2.1.0
165
192
  */
166
193
  warmup?(paths: string[]): Promise<void>;
194
+ /**
195
+ * WebSocket Handler for Bun.serve
196
+ *
197
+ * @since 2.2.0
198
+ */
199
+ websocket?: {
200
+ open?(ws: unknown): void | Promise<void>;
201
+ message?(ws: unknown, message: string | Buffer | Uint8Array): void | Promise<void>;
202
+ close?(ws: unknown, code: number, message: string): void | Promise<void>;
203
+ drain?(ws: unknown): void | Promise<void>;
204
+ [key: string]: unknown;
205
+ };
167
206
  /**
168
207
  * Initialize the adapter
169
208
  *
@@ -34,6 +34,7 @@ export declare class AOTRouter {
34
34
  readonly globalMiddleware: Middleware[];
35
35
  /** @internal */
36
36
  readonly pathMiddleware: Map<string, Middleware[]>;
37
+ private dynamicRoutePatterns;
37
38
  private middlewareCache;
38
39
  private cacheMaxSize;
39
40
  private version;
@@ -111,17 +112,6 @@ export declare class AOTRouter {
111
112
  * @returns True if pattern matches
112
113
  */
113
114
  private matchPattern;
114
- /**
115
- * Find the original route key for a matched dynamic route
116
- *
117
- * This is needed to look up route-specific middleware.
118
- * It's a bit of a hack, but avoids storing duplicate data.
119
- *
120
- * @param method - HTTP method
121
- * @param path - Matched path
122
- * @returns Route key or null
123
- */
124
- private findDynamicRouteKey;
125
115
  /**
126
116
  * Get all registered routes (for debugging)
127
117
  */
@@ -17,6 +17,7 @@ declare class FastRequestImpl implements FastRequest {
17
17
  private _request;
18
18
  private _params;
19
19
  private _path;
20
+ private _routePattern?;
20
21
  private _url;
21
22
  private _query;
22
23
  private _headers;
@@ -27,7 +28,7 @@ declare class FastRequestImpl implements FastRequest {
27
28
  /**
28
29
  * Initialize for new request
29
30
  */
30
- init(request: Request, params?: Record<string, string>, path?: string): this;
31
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
31
32
  /**
32
33
  * Reset for pooling
33
34
  */
@@ -36,6 +37,7 @@ declare class FastRequestImpl implements FastRequest {
36
37
  get url(): string;
37
38
  get method(): string;
38
39
  get path(): string;
40
+ get routePattern(): string | undefined;
39
41
  param(name: string): string | undefined;
40
42
  params(): Record<string, string>;
41
43
  private getUrl;
@@ -63,7 +65,7 @@ export declare class FastContext implements IFastContext {
63
65
  *
64
66
  * This is called when acquiring from the pool.
65
67
  */
66
- init(request: Request, params?: Record<string, string>, path?: string): this;
68
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
67
69
  /**
68
70
  * Reset context for pooling (Cleanup)
69
71
  *
@@ -97,7 +97,7 @@ export declare class Gravito {
97
97
  /**
98
98
  * Handle an incoming request
99
99
  */
100
- fetch: (request: Request) => Response | Promise<Response>;
100
+ fetch: (request: Request) => Promise<Response>;
101
101
  /**
102
102
  * Handle routes with middleware (async path)
103
103
  */
@@ -19,11 +19,13 @@ declare class MinimalRequest implements FastRequest {
19
19
  private readonly _request;
20
20
  private readonly _params;
21
21
  private readonly _path;
22
+ private readonly _routePattern?;
22
23
  private _searchParams;
23
- constructor(_request: Request, _params: Record<string, string>, _path: string);
24
+ constructor(_request: Request, _params: Record<string, string>, _path: string, _routePattern?: string | undefined);
24
25
  get url(): string;
25
26
  get method(): string;
26
27
  get path(): string;
28
+ get routePattern(): string | undefined;
27
29
  param(name: string): string | undefined;
28
30
  params(): Record<string, string>;
29
31
  /**
@@ -51,7 +53,7 @@ declare class MinimalRequest implements FastRequest {
51
53
  export declare class MinimalContext implements IFastContext {
52
54
  readonly req: MinimalRequest;
53
55
  private _resHeaders;
54
- constructor(request: Request, params: Record<string, string>, path: string);
56
+ constructor(request: Request, params: Record<string, string>, path: string, routePattern?: string);
55
57
  private getHeaders;
56
58
  json<T>(data: T, status?: number): Response;
57
59
  text(text: string, status?: number): Response;
@@ -36,7 +36,7 @@ export interface FastContext {
36
36
  route: (name: string, params?: any, query?: any) => string;
37
37
  readonly native: any;
38
38
  /** Internal initialization for pooling */
39
- init(request: Request, params?: Record<string, string>, path?: string): this;
39
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
40
40
  /** Internal cleanup for pooling */
41
41
  reset(): void;
42
42
  }
@@ -50,6 +50,11 @@ export interface FastRequest {
50
50
  readonly method: string;
51
51
  /** Path without query */
52
52
  readonly path: string;
53
+ /**
54
+ * Route pattern (e.g., /users/:id) for metrics labeling
55
+ * Prevents high cardinality issues in monitoring systems
56
+ */
57
+ readonly routePattern?: string;
53
58
  /** Get route parameter */
54
59
  param(name: string): string | undefined;
55
60
  /** Get all route parameters */
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Circuit Breaker state enum.
3
+ * @public
4
+ */
5
+ export declare enum CircuitBreakerState {
6
+ CLOSED = "CLOSED",
7
+ OPEN = "OPEN",
8
+ HALF_OPEN = "HALF_OPEN"
9
+ }
10
+ /**
11
+ * Circuit Breaker metrics snapshot.
12
+ * @public
13
+ */
14
+ export interface CircuitBreakerMetrics {
15
+ /**
16
+ * Current state of the circuit breaker
17
+ */
18
+ state: CircuitBreakerState;
19
+ /**
20
+ * Number of failures in the current window
21
+ */
22
+ failures: number;
23
+ /**
24
+ * Number of successes in the current window
25
+ */
26
+ successes: number;
27
+ /**
28
+ * Timestamp of the last failure
29
+ */
30
+ lastFailureAt?: Date;
31
+ /**
32
+ * Timestamp of the last success
33
+ */
34
+ lastSuccessAt?: Date;
35
+ /**
36
+ * Timestamp when the circuit was opened
37
+ */
38
+ openedAt?: Date;
39
+ /**
40
+ * Total requests processed
41
+ */
42
+ totalRequests: number;
43
+ /**
44
+ * Total failures recorded
45
+ */
46
+ totalFailures: number;
47
+ /**
48
+ * Total successes recorded
49
+ */
50
+ totalSuccesses: number;
51
+ }
52
+ /**
53
+ * Circuit Breaker metrics recorder interface.
54
+ * @public
55
+ */
56
+ export interface CircuitBreakerMetricsRecorder {
57
+ /**
58
+ * Record current state of the circuit breaker.
59
+ * @param eventName - Name of the event
60
+ * @param state - State as number (0=CLOSED, 1=HALF_OPEN, 2=OPEN)
61
+ */
62
+ recordState: (eventName: string, state: number) => void;
63
+ /**
64
+ * Record state transition.
65
+ */
66
+ recordTransition: (eventName: string, fromState: string, toState: string) => void;
67
+ /**
68
+ * Record a failure.
69
+ */
70
+ recordFailure: (eventName: string) => void;
71
+ /**
72
+ * Record a success.
73
+ */
74
+ recordSuccess: (eventName: string) => void;
75
+ /**
76
+ * Record OPEN state duration.
77
+ */
78
+ recordOpenDuration: (eventName: string, seconds: number) => void;
79
+ }
80
+ /**
81
+ * Circuit Breaker configuration options.
82
+ * @public
83
+ */
84
+ export interface CircuitBreakerOptions {
85
+ /**
86
+ * Number of consecutive failures before opening the circuit.
87
+ * @default 5
88
+ */
89
+ failureThreshold?: number;
90
+ /**
91
+ * Time in milliseconds to wait before attempting to close the circuit (move to HALF_OPEN).
92
+ * @default 30000
93
+ */
94
+ resetTimeout?: number;
95
+ /**
96
+ * Number of test requests to allow given the circuit is in HALF_OPEN state.
97
+ * If these succeed, the circuit closes. If any fail, it opens again.
98
+ * @default 3
99
+ */
100
+ halfOpenRequests?: number;
101
+ /**
102
+ * Number of successes required in HALF_OPEN state to close the circuit.
103
+ * @default 2
104
+ */
105
+ successThreshold?: number;
106
+ /**
107
+ * Time in milliseconds for the sliding window to track failures.
108
+ * Failures outside this window are not counted.
109
+ * @default 60000
110
+ */
111
+ windowSize?: number;
112
+ /**
113
+ * Enable or disable the circuit breaker.
114
+ * @default true
115
+ */
116
+ enabled?: boolean;
117
+ /**
118
+ * Callback when circuit opens.
119
+ */
120
+ onOpen?: (name?: string) => void;
121
+ /**
122
+ * Callback when circuit moves to half-open.
123
+ */
124
+ onHalfOpen?: (name?: string) => void;
125
+ /**
126
+ * Callback when circuit closes.
127
+ */
128
+ onClose?: (name?: string) => void;
129
+ /**
130
+ * Metrics recorder for recording circuit breaker events.
131
+ * Optional - if not provided, metrics will not be recorded.
132
+ */
133
+ metricsRecorder?: CircuitBreakerMetricsRecorder | undefined;
134
+ }
135
+ /**
136
+ * Required Circuit Breaker configuration (with defaults applied).
137
+ * @internal
138
+ */
139
+ export interface RequiredCircuitBreakerOptions extends Required<Omit<CircuitBreakerOptions, 'metricsRecorder'>> {
140
+ metricsRecorder?: CircuitBreakerMetricsRecorder;
141
+ }
142
+ /**
143
+ * Circuit Breaker implementation for fault tolerance.
144
+ *
145
+ * Prevents cascading failures by stopping execution of a failing operation
146
+ * for a specified period after a threshold of failures is reached.
147
+ *
148
+ * Supports sliding window algorithm, enabling/disabling, and detailed metrics.
149
+ *
150
+ * @public
151
+ */
152
+ export declare class CircuitBreaker {
153
+ private state;
154
+ private failureCount;
155
+ private successCount;
156
+ private name;
157
+ private config;
158
+ private metricsRecorder?;
159
+ private lastFailureAt?;
160
+ private lastSuccessAt?;
161
+ private openedAt?;
162
+ private totalRequests;
163
+ private totalFailures;
164
+ private totalSuccesses;
165
+ private halfOpenAttempts;
166
+ /**
167
+ * Create a new Circuit Breaker.
168
+ *
169
+ * Supports two signatures for backward compatibility:
170
+ * - CircuitBreaker(options?: CircuitBreakerOptions) - anonymous breaker
171
+ * - CircuitBreaker(name: string, options?: CircuitBreakerOptions) - named breaker
172
+ *
173
+ * @param nameOrOptions - Circuit breaker name or options
174
+ * @param maybeOptions - Options (used when first param is a string)
175
+ */
176
+ constructor(nameOrOptions?: string | CircuitBreakerOptions, maybeOptions?: CircuitBreakerOptions);
177
+ /**
178
+ * Execute an operation through the circuit breaker.
179
+ *
180
+ * @param operation - Async operation to execute
181
+ * @returns Operation result
182
+ * @throws Error if circuit is open or operation fails
183
+ */
184
+ execute<T>(operation: () => Promise<T>): Promise<T>;
185
+ /**
186
+ * Check if the circuit breaker is currently OPEN.
187
+ */
188
+ isOpen(): boolean;
189
+ /**
190
+ * Check if the circuit breaker is currently HALF_OPEN.
191
+ */
192
+ isHalfOpen(): boolean;
193
+ /**
194
+ * Check if the circuit breaker is currently CLOSED.
195
+ */
196
+ isClosed(): boolean;
197
+ /**
198
+ * Get current state of the circuit breaker.
199
+ */
200
+ getState(): CircuitBreakerState;
201
+ /**
202
+ * Get failure count (deprecated, use getMetrics for complete information).
203
+ */
204
+ getFailureCount(): number;
205
+ /**
206
+ * Get the name of this circuit breaker.
207
+ */
208
+ getName(): string;
209
+ /**
210
+ * Get detailed metrics snapshot of the circuit breaker.
211
+ */
212
+ getMetrics(): CircuitBreakerMetrics;
213
+ /**
214
+ * Manually reset the circuit breaker to CLOSED state.
215
+ */
216
+ reset(): void;
217
+ /**
218
+ * Forcefully reset the circuit breaker (alias for reset).
219
+ */
220
+ manualReset(): void;
221
+ /**
222
+ * Check for automatic state transitions based on time and sliding window.
223
+ */
224
+ checkStateTransition(): void;
225
+ private onSuccess;
226
+ private onFailure;
227
+ private transitionTo;
228
+ private stateToNumber;
229
+ }
@@ -0,0 +1,145 @@
1
+ import type { EventOptions } from './EventOptions';
2
+ /**
3
+ * Dead Letter Queue entry representing a failed event.
4
+ * @public
5
+ */
6
+ export interface DLQEntry {
7
+ /**
8
+ * Unique identifier for this DLQ entry.
9
+ */
10
+ id: string;
11
+ /**
12
+ * Event hook name.
13
+ */
14
+ eventName: string;
15
+ /**
16
+ * Event payload.
17
+ */
18
+ payload: unknown;
19
+ /**
20
+ * Event options used when dispatching.
21
+ */
22
+ options: EventOptions;
23
+ /**
24
+ * Error that caused the event to fail.
25
+ */
26
+ error: {
27
+ message: string;
28
+ stack?: string;
29
+ code?: string;
30
+ };
31
+ /**
32
+ * Number of retry attempts made.
33
+ */
34
+ retryCount: number;
35
+ /**
36
+ * Timestamp when the event first failed.
37
+ */
38
+ firstFailedAt: number;
39
+ /**
40
+ * Timestamp when the event was added to DLQ.
41
+ */
42
+ failedAt: number;
43
+ /**
44
+ * Timestamp when the event was last retried (if any).
45
+ */
46
+ lastRetriedAt?: number;
47
+ }
48
+ /**
49
+ * Filter options for querying DLQ entries.
50
+ * @public
51
+ */
52
+ export interface DLQFilter {
53
+ /**
54
+ * Filter by event name.
55
+ */
56
+ eventName?: string;
57
+ /**
58
+ * Filter by entries failed after this timestamp.
59
+ */
60
+ from?: number;
61
+ /**
62
+ * Filter by entries failed before this timestamp.
63
+ */
64
+ to?: number;
65
+ /**
66
+ * Maximum number of entries to return.
67
+ */
68
+ limit?: number;
69
+ }
70
+ /**
71
+ * Dead Letter Queue Manager for handling failed events.
72
+ *
73
+ * The DLQ stores events that have exceeded their retry limit,
74
+ * allowing for manual inspection, reprocessing, or analysis.
75
+ *
76
+ * @public
77
+ */
78
+ export declare class DeadLetterQueue {
79
+ private entries;
80
+ private entryIdCounter;
81
+ /**
82
+ * Add a failed event to the Dead Letter Queue.
83
+ *
84
+ * @param eventName - Name of the failed event
85
+ * @param payload - Event payload
86
+ * @param options - Event options
87
+ * @param error - Error that caused the failure
88
+ * @param retryCount - Number of retry attempts made
89
+ * @param firstFailedAt - Timestamp of first failure
90
+ * @returns DLQ entry ID
91
+ */
92
+ add(eventName: string, payload: unknown, options: EventOptions, error: Error, retryCount: number, firstFailedAt: number): string;
93
+ /**
94
+ * Get a specific DLQ entry by ID.
95
+ *
96
+ * @param entryId - DLQ entry ID
97
+ * @returns DLQ entry or undefined if not found
98
+ */
99
+ get(entryId: string): DLQEntry | undefined;
100
+ /**
101
+ * List DLQ entries with optional filtering.
102
+ *
103
+ * @param filter - Filter options
104
+ * @returns Array of DLQ entries
105
+ */
106
+ list(filter?: DLQFilter): DLQEntry[];
107
+ /**
108
+ * Delete a DLQ entry.
109
+ *
110
+ * @param entryId - DLQ entry ID
111
+ * @returns True if entry was deleted, false if not found
112
+ */
113
+ delete(entryId: string): boolean;
114
+ /**
115
+ * Delete all DLQ entries matching the filter.
116
+ *
117
+ * @param filter - Filter options
118
+ * @returns Number of entries deleted
119
+ */
120
+ deleteAll(filter?: DLQFilter): number;
121
+ /**
122
+ * Get the total number of entries in the DLQ.
123
+ *
124
+ * @returns Total entry count
125
+ */
126
+ getCount(): number;
127
+ /**
128
+ * Get the count of entries for a specific event.
129
+ *
130
+ * @param eventName - Event name
131
+ * @returns Entry count for the event
132
+ */
133
+ getCountByEvent(eventName: string): number;
134
+ /**
135
+ * Clear all entries from the DLQ.
136
+ */
137
+ clear(): void;
138
+ /**
139
+ * Update the last retried timestamp for an entry.
140
+ *
141
+ * @param entryId - DLQ entry ID
142
+ * @internal
143
+ */
144
+ updateLastRetried(entryId: string): void;
145
+ }
@@ -0,0 +1,11 @@
1
+ import type { EventTask } from './types';
2
+ /**
3
+ * Interface for event dispatch backends.
4
+ */
5
+ export interface EventBackend {
6
+ /**
7
+ * Enqueue an event for processing.
8
+ * @param task - The event task to process
9
+ */
10
+ enqueue(task: EventTask): Promise<void> | void;
11
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Event dispatch options for async event handling.
3
+ * @public
4
+ */
5
+ export interface EventOptions {
6
+ /**
7
+ * Whether to dispatch the event asynchronously.
8
+ * @default false
9
+ */
10
+ async?: boolean;
11
+ /**
12
+ * Priority level for event processing.
13
+ * - 'high': Critical events (e.g., order:created, payment:succeeded)
14
+ * - 'normal': Standard events (e.g., order:confirmed)
15
+ * - 'low': Non-critical events (e.g., analytics, logging)
16
+ * @default 'normal'
17
+ */
18
+ priority?: 'high' | 'normal' | 'low';
19
+ /**
20
+ * Execution timeout in milliseconds.
21
+ * If a listener exceeds this timeout, it will be terminated.
22
+ * @default 5000
23
+ */
24
+ timeout?: number;
25
+ /**
26
+ * Ordering guarantee strategy.
27
+ * - 'strict': Global strict ordering (slow, serialized)
28
+ * - 'partition': Partition-based ordering (recommended, balanced)
29
+ * - 'none': No ordering guarantee (fastest, parallel)
30
+ * @default 'none'
31
+ */
32
+ ordering?: 'strict' | 'partition' | 'none';
33
+ /**
34
+ * Partition key for partition-based ordering.
35
+ * Events with the same partition key are processed in order.
36
+ * Only used when ordering is 'partition'.
37
+ * @example 'order:123' or 'user:456'
38
+ */
39
+ partitionKey?: string;
40
+ /**
41
+ * Idempotency key for deduplication.
42
+ * Events with the same idempotency key within the TTL window
43
+ * will be processed only once.
44
+ * @example 'order:123:created'
45
+ */
46
+ idempotencyKey?: string;
47
+ /**
48
+ * Time-to-live for idempotency key in milliseconds.
49
+ * @default 3600000 (1 hour)
50
+ */
51
+ ttl?: number;
52
+ /**
53
+ * Retry policy for failed event processing.
54
+ */
55
+ retry?: {
56
+ /**
57
+ * Maximum number of retry attempts.
58
+ * @default 0
59
+ */
60
+ maxRetries?: number;
61
+ /**
62
+ * Backoff strategy for retries.
63
+ * - 'exponential': Delay doubles with each retry (1s, 2s, 4s, 8s...)
64
+ * - 'linear': Fixed delay between retries
65
+ * @default 'exponential'
66
+ */
67
+ backoff?: 'exponential' | 'linear';
68
+ /**
69
+ * Initial delay in milliseconds before first retry.
70
+ * @default 1000
71
+ */
72
+ initialDelayMs?: number;
73
+ /**
74
+ * Maximum delay in milliseconds between retries.
75
+ * @default 30000
76
+ */
77
+ maxDelayMs?: number;
78
+ /**
79
+ * Whether to send failed events to Dead Letter Queue after max retries.
80
+ * @default false
81
+ */
82
+ dlqAfterMaxRetries?: boolean;
83
+ };
84
+ /**
85
+ * Circuit breaker options for this event.
86
+ */
87
+ circuitBreaker?: {
88
+ /**
89
+ * Number of consecutive failures before opening the circuit.
90
+ * @default 5
91
+ */
92
+ failureThreshold?: number;
93
+ /**
94
+ * Time in milliseconds to wait before attempting to close the circuit.
95
+ * @default 30000
96
+ */
97
+ resetTimeout?: number;
98
+ /**
99
+ * Number of test requests to allow in half-open state.
100
+ * @default 3
101
+ */
102
+ halfOpenRequests?: number;
103
+ };
104
+ }
105
+ /**
106
+ * Default event options.
107
+ * @internal
108
+ */
109
+ export declare const DEFAULT_EVENT_OPTIONS: Required<EventOptions>;