@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
@@ -0,0 +1,217 @@
1
+ /**
2
+ * @gravito/core - Retry Policy
3
+ *
4
+ * 重試策略和退避算法的實現
5
+ * 支持指數和線性退避,包含 Jitter 防止雷鳴羊群
6
+ */
7
+ /**
8
+ * 重試策略配置接口
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const policy: RetryPolicy = {
13
+ * maxRetries: 3,
14
+ * backoff: 'exponential',
15
+ * initialDelayMs: 1000,
16
+ * maxDelayMs: 30000,
17
+ * dlqAfterMaxRetries: true
18
+ * }
19
+ * ```
20
+ */
21
+ export interface RetryPolicy {
22
+ /** 最大重試次數 */
23
+ maxRetries: number;
24
+ /** 退避策略:指數或線性 */
25
+ backoff: 'exponential' | 'linear';
26
+ /** 初始延遲時間(毫秒) */
27
+ initialDelayMs: number;
28
+ /** 最大延遲時間(毫秒) */
29
+ maxDelayMs: number;
30
+ /** 超過最大重試次數後是否發送到死信隊列 */
31
+ dlqAfterMaxRetries?: boolean;
32
+ }
33
+ /**
34
+ * 重試引擎
35
+ *
36
+ * 負責計算重試延遲、判斷是否應該重試等邏輯
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const engine = new RetryEngine()
41
+ * const delay = engine.calculateDelay(1, policy)
42
+ * const shouldRetry = engine.shouldRetry(3, policy)
43
+ * ```
44
+ */
45
+ export declare class RetryEngine {
46
+ /**
47
+ * 計算下次重試的延遲時間(毫秒)
48
+ *
49
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
50
+ * @param policy - 重試策略配置
51
+ * @returns 延遲時間(毫秒)
52
+ *
53
+ * @description
54
+ * - 指數退避:delay = initialDelay * 2^(attemptCount - 1)
55
+ * - 線性退避:delay = initialDelay * attemptCount
56
+ * - 添加隨機抖動(Jitter),防止雷鳴羊群問題
57
+ * - 結果不超過 maxDelayMs
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const policy: RetryPolicy = {
62
+ * maxRetries: 3,
63
+ * backoff: 'exponential',
64
+ * initialDelayMs: 1000,
65
+ * maxDelayMs: 30000
66
+ * }
67
+ *
68
+ * // 第 1 次重試:1000ms * 2^0 = 1000ms (加抖動)
69
+ * const delay1 = engine.calculateDelay(1, policy) // ~1100ms
70
+ *
71
+ * // 第 2 次重試:1000ms * 2^1 = 2000ms (加抖動)
72
+ * const delay2 = engine.calculateDelay(2, policy) // ~2200ms
73
+ *
74
+ * // 第 3 次重試:1000ms * 2^2 = 4000ms (加抖動)
75
+ * const delay3 = engine.calculateDelay(3, policy) // ~4400ms
76
+ * ```
77
+ */
78
+ calculateDelay(attemptCount: number, policy: RetryPolicy): number;
79
+ /**
80
+ * 判斷是否應該重試
81
+ *
82
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
83
+ * @param policy - 重試策略配置
84
+ * @returns 是否應該重試
85
+ *
86
+ * @description
87
+ * 當 attemptCount < maxRetries 時返回 true
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const policy = { maxRetries: 3, ... }
92
+ *
93
+ * engine.shouldRetry(1, policy) // true(1 < 3)
94
+ * engine.shouldRetry(3, policy) // false(3 >= 3)
95
+ * engine.shouldRetry(4, policy) // false(4 >= 3)
96
+ * ```
97
+ */
98
+ shouldRetry(attemptCount: number, policy: RetryPolicy): boolean;
99
+ /**
100
+ * 獲取退避時間(包含延遲計算和 Jitter)
101
+ *
102
+ * @param retryCount - 重試次數(從 0 開始)
103
+ * @param policy - 重試策略配置
104
+ * @returns 退避時間(毫秒)
105
+ *
106
+ * @description
107
+ * 這是 calculateDelay 的別名,但接收的是從 0 開始的重試計數
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
112
+ *
113
+ * // 第 0 次重試(第 1 次嘗試失敗)
114
+ * const time1 = engine.getBackoffTime(0, policy) // ~1100ms
115
+ *
116
+ * // 第 1 次重試(第 2 次嘗試失敗)
117
+ * const time2 = engine.getBackoffTime(1, policy) // ~2200ms
118
+ * ```
119
+ */
120
+ getBackoffTime(retryCount: number, policy: RetryPolicy): number;
121
+ /**
122
+ * 計算下次重試的絕對時間
123
+ *
124
+ * @param retryCount - 重試次數(從 0 開始)
125
+ * @param policy - 重試策略配置
126
+ * @param baseTime - 基礎時間戳(默認為當前時間)
127
+ * @returns 下次重試的時間戳(毫秒)
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
132
+ *
133
+ * const now = Date.now()
134
+ * const nextRetryTime = engine.getNextRetryTime(0, policy, now)
135
+ * // 返回大約 now + 1000 + jitter
136
+ * ```
137
+ */
138
+ getNextRetryTime(retryCount: number, policy: RetryPolicy, baseTime?: number): number;
139
+ /**
140
+ * 驗證重試策略配置
141
+ *
142
+ * @param policy - 重試策略配置
143
+ * @returns 是否有效
144
+ *
145
+ * @description
146
+ * 檢查配置是否合理:
147
+ * - maxRetries >= 0
148
+ * - initialDelayMs > 0
149
+ * - maxDelayMs >= initialDelayMs
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const validPolicy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
154
+ * engine.isValidPolicy(validPolicy) // true
155
+ *
156
+ * const invalidPolicy = { maxRetries: 3, initialDelayMs: 5000, maxDelayMs: 1000, backoff: 'exponential' }
157
+ * engine.isValidPolicy(invalidPolicy) // false (maxDelayMs < initialDelayMs)
158
+ * ```
159
+ */
160
+ isValidPolicy(policy: RetryPolicy): boolean;
161
+ /**
162
+ * 獲取人類可讀的重試信息
163
+ *
164
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
165
+ * @param policy - 重試策略配置
166
+ * @returns 描述性文本
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
171
+ *
172
+ * engine.getRetryInfo(1, policy) // "Retry 1 of 3, will retry in ~1100ms"
173
+ * engine.getRetryInfo(3, policy) // "Retry 3 of 3 (final attempt), will retry in ~4400ms"
174
+ * engine.getRetryInfo(4, policy) // "Max retries exceeded (4 >= 3)"
175
+ * ```
176
+ */
177
+ getRetryInfo(attemptCount: number, policy: RetryPolicy): string;
178
+ }
179
+ /**
180
+ * 創建默認的重試策略
181
+ *
182
+ * @returns 默認重試策略
183
+ *
184
+ * @description
185
+ * 默認配置:
186
+ * - 最多重試 3 次
187
+ * - 指數退避
188
+ * - 初始延遲 1 秒
189
+ * - 最大延遲 30 秒
190
+ * - 超過最大重試後發送 DLQ
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * const policy = getDefaultRetryPolicy()
195
+ * // { maxRetries: 3, backoff: 'exponential', initialDelayMs: 1000, maxDelayMs: 30000, dlqAfterMaxRetries: true }
196
+ * ```
197
+ */
198
+ export declare function getDefaultRetryPolicy(): RetryPolicy;
199
+ /**
200
+ * 為不同類型的操作獲取預設的重試策略
201
+ *
202
+ * @param type - 操作類型
203
+ * @returns 推薦的重試策略
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * // 外部 API 調用:更多重試,更長延遲
208
+ * const apiPolicy = getPresetRetryPolicy('external-api')
209
+ *
210
+ * // 數據庫操作:較少重試,短延遲
211
+ * const dbPolicy = getPresetRetryPolicy('database')
212
+ *
213
+ * // 消息隊列:適中重試
214
+ * const mqPolicy = getPresetRetryPolicy('message-queue')
215
+ * ```
216
+ */
217
+ export declare function getPresetRetryPolicy(type: 'external-api' | 'database' | 'message-queue' | 'default'): RetryPolicy;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Reliability and retry exports.
3
+ * @packageDocumentation
4
+ */
5
+ export { DeadLetterQueueManager, type DLQManagerFilter, type DLQRecord, type DLQStats, } from './DeadLetterQueueManager';
6
+ export { getDefaultRetryPolicy, getPresetRetryPolicy, RetryEngine, type RetryPolicy, } from './RetryPolicy';
@@ -0,0 +1,12 @@
1
+ import type { GravitoHandler } from '../http/types';
2
+ import type { PlanetCore } from '../PlanetCore';
3
+ import type { ControllerClass } from '../Router';
4
+ export declare class ControllerDispatcher {
5
+ private core;
6
+ private controllers;
7
+ constructor(core: PlanetCore);
8
+ /**
9
+ * Resolve Controller Instance and Method
10
+ */
11
+ resolve(CtrlClass: ControllerClass, methodName: string): GravitoHandler;
12
+ }
@@ -0,0 +1,20 @@
1
+ import type { GravitoMiddleware } from '../http/types';
2
+ import { type FormRequestClass } from '../Router';
3
+ /**
4
+ * Handles validation of incoming requests using FormRequest classes.
5
+ * Provides mechanisms to detect and convert FormRequest classes into Gravito middleware.
6
+ */
7
+ export declare class RequestValidator {
8
+ /**
9
+ * Check if a value is a FormRequest class.
10
+ * Optimized with Symbol check, prototype check, and caching.
11
+ * @internal
12
+ */
13
+ static isFormRequestClass(value: unknown): value is FormRequestClass;
14
+ /**
15
+ * Convert a FormRequest class to middleware.
16
+ * Uses instance caching to avoid re-instantiation on every request.
17
+ * @internal
18
+ */
19
+ static formRequestToMiddleware(RequestClass: FormRequestClass): GravitoMiddleware;
20
+ }
@@ -1,56 +1,111 @@
1
1
  import type { GravitoOrbit, PlanetCore } from '@gravito/core';
2
2
  import { WebhookReceiver } from './receive/WebhookReceiver';
3
+ import { KeyRotationManager } from './rotation/KeyRotationManager';
3
4
  import { WebhookDispatcher } from './send/WebhookDispatcher';
4
- import type { EchoConfig } from './types';
5
+ import type { EchoConfig, ProviderKeyEntry } from './types';
5
6
  /**
6
- * OrbitEcho is the official webhook orchestration module for Gravito.
7
+ * OrbitEcho is the official webhook orchestration module for the Gravito ecosystem.
7
8
  *
8
- * It provides a secure way to receive incoming webhooks (e.g., from Stripe, GitHub)
9
- * and a reliable way to dispatch outgoing webhooks to third-party services.
9
+ * It serves as a comprehensive hub for managing the entire webhook lifecycle,
10
+ * including secure reception, signature verification across multiple providers,
11
+ * persistent storage for auditing, and reliable outgoing dispatch with
12
+ * exponential backoff and circuit breaking.
10
13
  *
11
- * @example
14
+ * @example Basic integration with PlanetCore
12
15
  * ```typescript
16
+ * import { PlanetCore } from '@gravito/core';
17
+ * import { OrbitEcho } from '@gravito/echo';
18
+ *
19
+ * const core = new PlanetCore();
13
20
  * const echo = new OrbitEcho({
14
21
  * providers: {
15
- * stripe: { name: 'stripe', secret: 'whsec_...' }
22
+ * stripe: { name: 'stripe', secret: process.env.STRIPE_SECRET }
23
+ * },
24
+ * dispatcher: {
25
+ * secret: process.env.APP_WEBHOOK_SECRET
16
26
  * }
17
27
  * });
18
- * core.addOrbit(echo);
28
+ *
29
+ * core.install(echo);
19
30
  * ```
20
31
  *
21
32
  * @public
22
- * @since 3.0.0
23
33
  */
24
34
  export declare class OrbitEcho implements GravitoOrbit {
25
35
  private receiver;
26
36
  private dispatcher?;
27
37
  private echoConfig;
38
+ private keyRotationManager?;
28
39
  /**
29
- * Create a new OrbitEcho instance.
40
+ * Constructs a new OrbitEcho instance with the specified configuration.
30
41
  *
31
- * @param config - The configuration object for providers and dispatcher.
42
+ * This constructor initializes the core receiver component, sets up key rotation
43
+ * orchestration if enabled, registers defined providers, and connects the
44
+ * observability stack (metrics, tracing, logging).
45
+ *
46
+ * @param config - The global configuration defining providers, dispatchers, and infrastructure.
32
47
  */
33
48
  constructor(config?: EchoConfig);
34
49
  /**
35
- * Install into PlanetCore
50
+ * Integrates the Echo module into the Gravito application lifecycle.
36
51
  *
37
- * Registers the OrbitEcho instance and its components into the service container.
52
+ * This method performs the following setup tasks:
53
+ * 1. Installs request buffering middleware (if enabled) to preserve raw bodies.
54
+ * 2. Binds Echo components to the service container (`echo`, `echo.receiver`).
55
+ * 3. Injects the Echo instance into the request context for easy access in handlers.
38
56
  *
39
- * @param core - The PlanetCore instance.
57
+ * @param core - The PlanetCore instance managing the application.
58
+ * @throws {Error} If the core adapter is missing or improperly configured.
40
59
  */
41
60
  install(core: PlanetCore): void;
42
61
  /**
43
- * Get webhook receiver
62
+ * Retrieves the underlying receiver instance for manual webhook processing.
63
+ *
64
+ * Use this when you need fine-grained control over how incoming webhooks
65
+ * are routed or verified outside of the standard middleware flow.
66
+ *
67
+ * @returns The active WebhookReceiver instance.
44
68
  */
45
69
  getReceiver(): WebhookReceiver;
46
70
  /**
47
- * Get webhook dispatcher
71
+ * Retrieves the dispatcher instance for sending outgoing webhooks.
72
+ *
73
+ * @returns The configured WebhookDispatcher, or undefined if dispatch is disabled.
48
74
  */
49
75
  getDispatcher(): WebhookDispatcher | undefined;
50
76
  /**
51
- * Get configuration
77
+ * Accesses the active configuration used by this OrbitEcho instance.
78
+ *
79
+ * @returns The immutable EchoConfig object.
52
80
  */
53
81
  getConfig(): EchoConfig;
82
+ /**
83
+ * Retrieves the key rotation manager responsible for secret lifecycle.
84
+ *
85
+ * @returns The manager instance, or undefined if key rotation is disabled.
86
+ */
87
+ getKeyRotationManager(): KeyRotationManager | undefined;
88
+ /**
89
+ * Initiates a zero-downtime primary key rotation for a specific provider.
90
+ *
91
+ * This method promotes a new key to primary status while maintaining valid old keys
92
+ * for a grace period, ensuring that webhooks signed with either key are accepted
93
+ * during the transition.
94
+ *
95
+ * @param providerName - The identifier of the provider to update.
96
+ * @param newKey - Metadata and value for the replacement key.
97
+ * @throws {Error} If key rotation is not enabled in the global configuration.
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * await echo.rotateProviderKey('stripe', {
102
+ * key: 'whsec_new_secret',
103
+ * version: 'v2',
104
+ * activeFrom: new Date()
105
+ * });
106
+ * ```
107
+ */
108
+ rotateProviderKey(providerName: string, newKey: Omit<ProviderKeyEntry, 'isPrimary'>): Promise<void>;
54
109
  }
55
110
  declare module '@gravito/core' {
56
111
  interface GravitoVariables {
@@ -0,0 +1,94 @@
1
+ import type { IncomingWebhookRecord, OutgoingWebhookRecord } from '../storage/WebhookStore';
2
+ /**
3
+ * Interface for a Dead Letter Queue (DLQ) implementation.
4
+ *
5
+ * A DLQ serves as a safety net for webhook events that have permanently failed
6
+ * all processing or delivery attempts. It enables manual inspection, diagnostic
7
+ * analysis, and eventual re-processing of high-value events that would otherwise
8
+ * be lost due to transient or permanent failures.
9
+ *
10
+ * @example Inspected failed events
11
+ * ```typescript
12
+ * const dlq: DeadLetterQueue = new MyPersistentDlq();
13
+ *
14
+ * // Retrieve recent failures for manual triage
15
+ * const failedEvents = await dlq.peek(10);
16
+ * for (const event of failedEvents) {
17
+ * console.log(`Event ${event.id} failed after ${event.retryCount} attempts: ${event.failureReason}`);
18
+ * }
19
+ * ```
20
+ *
21
+ * @public
22
+ */
23
+ export interface DeadLetterQueue {
24
+ /**
25
+ * Appends a permanently failed event to the queue for later inspection.
26
+ *
27
+ * @param event - The dead letter event metadata and original record.
28
+ * @returns A promise resolving to a unique identifier for the event within the queue.
29
+ * @throws {Error} If the underlying storage fails to persist the event.
30
+ */
31
+ enqueue(event: DeadLetterEvent): Promise<string>;
32
+ /**
33
+ * Retrieves a snapshot of failed events from the queue without removing them.
34
+ *
35
+ * @param limit - Maximum number of events to retrieve (ordered by failure time).
36
+ * @returns A collection of dead letter events.
37
+ */
38
+ peek(limit?: number): Promise<DeadLetterEvent[]>;
39
+ /**
40
+ * Permanently removes an event from the queue after successful manual resolution.
41
+ *
42
+ * @param id - The unique identifier assigned during the `enqueue` process.
43
+ * @throws {Error} If the event ID is invalid or not found in the queue.
44
+ */
45
+ dequeue(id: string): Promise<void>;
46
+ /**
47
+ * Calculates the total number of events currently residing in the queue.
48
+ *
49
+ * @returns The total count of dead letter events.
50
+ */
51
+ size(): Promise<number>;
52
+ /**
53
+ * Removes all events from the queue, resetting it to an empty state.
54
+ */
55
+ clear(): Promise<void>;
56
+ }
57
+ /**
58
+ * Metadata and payload for a failed webhook event stored in the Dead Letter Queue.
59
+ *
60
+ * This structure captures the complete context of a failure, including the original
61
+ * data and the diagnostic reason for the final failure.
62
+ *
63
+ * @public
64
+ */
65
+ export interface DeadLetterEvent {
66
+ /**
67
+ * A unique identifier for the entry within the DLQ storage.
68
+ */
69
+ id?: string;
70
+ /**
71
+ * Indicates whether the failure occurred during reception or dispatch.
72
+ */
73
+ type: 'incoming' | 'outgoing';
74
+ /**
75
+ * The complete original record of the webhook at the moment of failure.
76
+ */
77
+ originalEvent: IncomingWebhookRecord | OutgoingWebhookRecord;
78
+ /**
79
+ * A descriptive diagnostic message explaining why the event was sent to the DLQ.
80
+ */
81
+ failureReason: string;
82
+ /**
83
+ * The exact timestamp when the event reached its maximum retry limit or terminal error.
84
+ */
85
+ failedAt: Date;
86
+ /**
87
+ * The total number of automated attempts made before giving up on the event.
88
+ */
89
+ retryCount: number;
90
+ /**
91
+ * The timestamp of the final attempted processing or delivery action.
92
+ */
93
+ lastRetryAt?: Date;
94
+ }
@@ -0,0 +1,36 @@
1
+ import type { DeadLetterEvent, DeadLetterQueue } from './DeadLetterQueue';
2
+ /**
3
+ * An in-memory implementation of {@link DeadLetterQueue}.
4
+ * Suitable for development, testing, or small-scale applications where persistence is not required.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const dlq = new MemoryDeadLetterQueue();
9
+ * await dlq.enqueue(failedEvent);
10
+ * const size = await dlq.size();
11
+ * ```
12
+ */
13
+ export declare class MemoryDeadLetterQueue implements DeadLetterQueue {
14
+ private queue;
15
+ /**
16
+ * Stores the event in an internal Map.
17
+ * Generates a UUID if the event does not have an ID.
18
+ */
19
+ enqueue(event: DeadLetterEvent): Promise<string>;
20
+ /**
21
+ * Returns events sorted by failure timestamp.
22
+ */
23
+ peek(limit?: number): Promise<DeadLetterEvent[]>;
24
+ /**
25
+ * Removes the event from the internal Map.
26
+ */
27
+ dequeue(id: string): Promise<void>;
28
+ /**
29
+ * Returns the number of items in the internal Map.
30
+ */
31
+ size(): Promise<number>;
32
+ /**
33
+ * Clears the internal Map.
34
+ */
35
+ clear(): Promise<void>;
36
+ }
@@ -0,0 +1,2 @@
1
+ export * from './DeadLetterQueue';
2
+ export * from './MemoryDeadLetterQueue';
@@ -1,48 +1,64 @@
1
1
  /**
2
- * @fileoverview @gravito/echo - Enterprise Webhook Module
2
+ * @fileoverview \@gravito/echo - Enterprise Webhook Orchestration
3
3
  *
4
- * Secure webhook receiving and reliable webhook sending for Gravito.
4
+ * Echo provides a secure, reliable, and observable layer for handling webhooks
5
+ * in Gravito applications. It standardizes incoming webhook reception with
6
+ * signature verification and dynamic key rotation, while ensuring reliable
7
+ * outgoing delivery via exponential backoff and circuit breaking.
5
8
  *
6
- * @example Receiving webhooks
9
+ * @example Receiving webhooks from Stripe
7
10
  * ```typescript
8
11
  * import { OrbitEcho, WebhookReceiver } from '@gravito/echo'
9
12
  *
10
13
  * const core = new PlanetCore()
11
- *
12
14
  * core.install(new OrbitEcho({
13
15
  * providers: {
14
- * stripe: { name: 'stripe', secret: process.env.STRIPE_WEBHOOK_SECRET! }
16
+ * stripe: { name: 'stripe', secret: process.env.STRIPE_SECRET! }
15
17
  * }
16
18
  * }))
17
19
  *
18
20
  * const receiver = core.container.make<WebhookReceiver>('echo.receiver')
19
21
  * receiver.on('stripe', 'payment_intent.succeeded', async (event) => {
20
- * console.log('Payment:', event.payload)
22
+ * // Securely process validated payment
21
23
  * })
22
24
  * ```
23
25
  *
24
- * @example Sending webhooks
26
+ * @example Dispatching reliable outgoing webhooks
25
27
  * ```typescript
26
28
  * import { WebhookDispatcher } from '@gravito/echo'
27
29
  *
28
- * const dispatcher = new WebhookDispatcher({
29
- * secret: 'my-secret'
30
- * })
31
- *
30
+ * const dispatcher = new WebhookDispatcher({ secret: 'app-secret' })
32
31
  * await dispatcher.dispatch({
33
- * url: 'https://example.com/webhook',
32
+ * url: 'https://consumer.com/hook',
34
33
  * event: 'order.created',
35
- * data: { orderId: 123 }
34
+ * data: { id: 123 }
36
35
  * })
37
36
  * ```
38
37
  *
39
38
  * @module @gravito/echo
40
39
  */
40
+ export type { DeadLetterEvent, DeadLetterQueue } from './dlq/DeadLetterQueue';
41
+ export { MemoryDeadLetterQueue } from './dlq/MemoryDeadLetterQueue';
42
+ export { createRequestBufferMiddleware, RequestBufferMiddleware } from './middleware';
41
43
  export { OrbitEcho } from './OrbitEcho';
44
+ export type { EchoLogEvent, EchoLogger } from './observability/logging';
45
+ export { ConsoleEchoLogger } from './observability/logging';
46
+ export type { MetricsProvider, WebhookMetricLabels } from './observability/metrics';
47
+ export { EchoMetrics, NoopMetricsProvider, PrometheusMetricsProvider, } from './observability/metrics';
48
+ export type { Span, SpanOptions, Tracer } from './observability/tracing';
49
+ export { NoopSpan, NoopTracer, SpanStatusCode } from './observability/tracing';
50
+ export { BaseProvider, type ProviderOptions } from './providers/base/BaseProvider';
42
51
  export { GenericProvider } from './providers/GenericProvider';
43
52
  export { GitHubProvider } from './providers/GitHubProvider';
53
+ export { LinearProvider } from './providers/LinearProvider';
54
+ export { PaddleProvider } from './providers/PaddleProvider';
55
+ export { ShopifyProvider } from './providers/ShopifyProvider';
56
+ export { SlackProvider } from './providers/SlackProvider';
44
57
  export { StripeProvider } from './providers/StripeProvider';
58
+ export { TwilioProvider } from './providers/TwilioProvider';
45
59
  export { computeHmacSha1, computeHmacSha256, parseStripeSignature, timingSafeEqual, validateTimestamp, } from './receive/SignatureValidator';
46
60
  export { WebhookReceiver } from './receive/WebhookReceiver';
47
- export { WebhookDispatcher } from './send/WebhookDispatcher';
48
- export type { EchoConfig, RetryConfig, WebhookDeliveryResult, WebhookDispatcherConfig, WebhookEvent, WebhookHandler, WebhookPayload, WebhookProvider, WebhookProviderConfig, WebhookVerificationResult, } from './types';
61
+ export { WebhookReplayService } from './replay/WebhookReplayService';
62
+ export { CircuitBreaker } from './resilience';
63
+ export { KeyRotationManager } from './rotation';
64
+ export type { BufferedRequest, CircuitBreakerConfig, CircuitBreakerMetrics, CircuitBreakerState, EchoConfig, EchoObservabilityConfig, KeyRotationConfig, ProviderKeyEntry, ReplayOptions, ReplayResult, RequestBufferConfig, RetryConfig, WebhookDeliveryResult, WebhookDispatcherConfig, WebhookEvent, WebhookHandler, WebhookPayload, WebhookProvider, WebhookProviderConfig, WebhookProviderConfigWithRotation, WebhookVerificationResult, } from './types';
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Request Buffer Middleware
3
+ *
4
+ * 在驗證前緩存原始 Request Body,防止框架自動解析 JSON 導致簽章驗證失敗。
5
+ * 這個中介軟體會在請求處理鏈的早期階段攔截並緩存原始內容。
6
+ *
7
+ * @module @gravito/echo/middleware
8
+ * @since v1.1
9
+ */
10
+ import type { GravitoContext } from '@gravito/core';
11
+ import type { BufferedRequest, RequestBufferConfig } from '../types';
12
+ /**
13
+ * Request Buffer 中介軟體類別
14
+ *
15
+ * 提供原始 Body 緩存功能,確保簽章驗證使用正確的未解析內容。
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const middleware = new RequestBufferMiddleware({
20
+ * maxBodySize: 5 * 1024 * 1024, // 5MB
21
+ * })
22
+ *
23
+ * core.adapter.use('*', middleware.handler())
24
+ * ```
25
+ */
26
+ export declare class RequestBufferMiddleware {
27
+ private config;
28
+ constructor(config?: RequestBufferConfig);
29
+ /**
30
+ * 建立中介軟體處理函式
31
+ *
32
+ * @returns 中介軟體處理函式
33
+ */
34
+ handler(): (c: GravitoContext, next: () => Promise<Response | undefined>) => Promise<Response | undefined>;
35
+ /**
36
+ * 從請求中讀取原始 body
37
+ *
38
+ * @param c - Gravito Context
39
+ * @returns 原始 body(string 或 Buffer)
40
+ */
41
+ private readRawBody;
42
+ }
43
+ /**
44
+ * 便捷工廠函式,用於建立 Request Buffer 中介軟體
45
+ *
46
+ * @param config - 中介軟體配置
47
+ * @returns 中介軟體處理函式
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * core.adapter.use('*', createRequestBufferMiddleware({
52
+ * maxBodySize: 5 * 1024 * 1024
53
+ * }))
54
+ * ```
55
+ */
56
+ export declare function createRequestBufferMiddleware(config?: RequestBufferConfig): (c: GravitoContext, next: () => Promise<Response | undefined>) => Promise<Response | undefined>;
57
+ declare module '@gravito/core' {
58
+ interface GravitoVariables {
59
+ /** Buffered request for signature verification */
60
+ bufferedRequest?: BufferedRequest;
61
+ }
62
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Echo Middleware
3
+ *
4
+ * @module @gravito/echo/middleware
5
+ * @since v1.1
6
+ */
7
+ export type { BufferedRequest, RequestBufferConfig } from '../types';
8
+ export { createRequestBufferMiddleware, RequestBufferMiddleware } from './RequestBufferMiddleware';
@@ -0,0 +1,3 @@
1
+ export * from './logging';
2
+ export * from './metrics';
3
+ export * from './tracing';