@gravito/radiance 1.0.4 → 1.0.5

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 (148) hide show
  1. package/README.md +30 -7
  2. package/dist/core/src/Application.d.ts +256 -0
  3. package/dist/core/src/CommandKernel.d.ts +33 -0
  4. package/dist/core/src/ConfigManager.d.ts +65 -0
  5. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  6. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  7. package/dist/core/src/Container.d.ts +153 -0
  8. package/dist/core/src/ErrorHandler.d.ts +66 -0
  9. package/dist/core/src/Event.d.ts +5 -0
  10. package/dist/core/src/EventManager.d.ts +123 -0
  11. package/dist/core/src/GlobalErrorHandlers.d.ts +47 -0
  12. package/dist/core/src/GravitoServer.d.ts +28 -0
  13. package/dist/core/src/HookManager.d.ts +435 -0
  14. package/dist/core/src/Listener.d.ts +4 -0
  15. package/dist/core/src/Logger.d.ts +20 -0
  16. package/dist/core/src/PlanetCore.d.ts +402 -0
  17. package/dist/core/src/RequestContext.d.ts +97 -0
  18. package/dist/core/src/Route.d.ts +36 -0
  19. package/dist/core/src/Router.d.ts +270 -0
  20. package/dist/core/src/ServiceProvider.d.ts +178 -0
  21. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +27 -0
  22. package/dist/core/src/adapters/bun/BunContext.d.ts +54 -0
  23. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +66 -0
  24. package/dist/core/src/adapters/bun/BunRequest.d.ts +31 -0
  25. package/dist/core/src/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  26. package/dist/core/src/adapters/bun/RadixNode.d.ts +19 -0
  27. package/dist/core/src/adapters/bun/RadixRouter.d.ts +32 -0
  28. package/dist/core/src/adapters/bun/index.d.ts +7 -0
  29. package/dist/core/src/adapters/bun/types.d.ts +20 -0
  30. package/dist/core/src/adapters/types.d.ts +235 -0
  31. package/dist/core/src/binary/BinaryUtils.d.ts +105 -0
  32. package/dist/core/src/binary/index.d.ts +5 -0
  33. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  34. package/dist/core/src/compat/async-local-storage.d.ts +7 -0
  35. package/dist/core/src/compat/crypto.d.ts +6 -0
  36. package/dist/core/src/engine/AOTRouter.d.ts +139 -0
  37. package/dist/core/src/engine/FastContext.d.ts +141 -0
  38. package/dist/core/src/engine/Gravito.d.ts +131 -0
  39. package/dist/core/src/engine/MinimalContext.d.ts +102 -0
  40. package/dist/core/src/engine/analyzer.d.ts +113 -0
  41. package/dist/core/src/engine/constants.d.ts +23 -0
  42. package/dist/core/src/engine/index.d.ts +26 -0
  43. package/dist/core/src/engine/path.d.ts +26 -0
  44. package/dist/core/src/engine/pool.d.ts +83 -0
  45. package/dist/core/src/engine/types.d.ts +149 -0
  46. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  47. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  48. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  49. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  50. package/dist/core/src/events/EventBackend.d.ts +12 -0
  51. package/dist/core/src/events/EventOptions.d.ts +204 -0
  52. package/dist/core/src/events/EventPriorityQueue.d.ts +63 -0
  53. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  54. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  55. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  56. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  57. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  58. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  59. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  60. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  61. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  62. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  63. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  64. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  65. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  66. package/dist/core/src/events/index.d.ts +26 -0
  67. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  68. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  69. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  70. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  71. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  72. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  73. package/dist/core/src/events/observability/index.d.ts +24 -0
  74. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  75. package/dist/core/src/events/queue-core.d.ts +77 -0
  76. package/dist/core/src/events/task-executor.d.ts +51 -0
  77. package/dist/core/src/events/types.d.ts +134 -0
  78. package/dist/core/src/exceptions/AuthenticationException.d.ts +8 -0
  79. package/dist/core/src/exceptions/AuthorizationException.d.ts +8 -0
  80. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  81. package/dist/core/src/exceptions/GravitoException.d.ts +23 -0
  82. package/dist/core/src/exceptions/HttpException.d.ts +9 -0
  83. package/dist/core/src/exceptions/ModelNotFoundException.d.ts +10 -0
  84. package/dist/core/src/exceptions/ValidationException.d.ts +22 -0
  85. package/dist/core/src/exceptions/index.d.ts +7 -0
  86. package/dist/core/src/ffi/NativeAccelerator.d.ts +62 -0
  87. package/dist/core/src/ffi/NativeHasher.d.ts +139 -0
  88. package/dist/core/src/ffi/cbor-fallback.d.ts +96 -0
  89. package/dist/core/src/ffi/hash-fallback.d.ts +33 -0
  90. package/dist/core/src/ffi/index.d.ts +10 -0
  91. package/dist/core/src/ffi/types.d.ts +135 -0
  92. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  93. package/dist/core/src/helpers/Arr.d.ts +19 -0
  94. package/dist/core/src/helpers/Str.d.ts +38 -0
  95. package/dist/core/src/helpers/data.d.ts +25 -0
  96. package/dist/core/src/helpers/errors.d.ts +34 -0
  97. package/dist/core/src/helpers/response.d.ts +41 -0
  98. package/dist/core/src/helpers.d.ts +338 -0
  99. package/dist/core/src/hooks/ActionManager.d.ts +132 -0
  100. package/dist/core/src/hooks/AsyncDetector.d.ts +84 -0
  101. package/dist/core/src/hooks/FilterManager.d.ts +71 -0
  102. package/dist/core/src/hooks/MigrationWarner.d.ts +24 -0
  103. package/dist/core/src/hooks/dlq-operations.d.ts +60 -0
  104. package/dist/core/src/hooks/types.d.ts +107 -0
  105. package/dist/core/src/http/CookieJar.d.ts +51 -0
  106. package/dist/core/src/http/cookie.d.ts +29 -0
  107. package/dist/core/src/http/types.d.ts +395 -0
  108. package/dist/core/src/index.d.ts +565 -0
  109. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  110. package/dist/core/src/observability/contracts.d.ts +137 -0
  111. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +349 -0
  112. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  113. package/dist/core/src/reliability/index.d.ts +6 -0
  114. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  115. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  116. package/dist/core/src/runtime/adapter-bun.d.ts +12 -0
  117. package/dist/core/src/runtime/adapter-deno.d.ts +12 -0
  118. package/dist/core/src/runtime/adapter-node.d.ts +12 -0
  119. package/dist/core/src/runtime/adapter-unknown.d.ts +13 -0
  120. package/dist/core/src/runtime/archive.d.ts +17 -0
  121. package/dist/core/src/runtime/compression.d.ts +21 -0
  122. package/dist/core/src/runtime/deep-equals.d.ts +56 -0
  123. package/dist/core/src/runtime/detection.d.ts +22 -0
  124. package/dist/core/src/runtime/escape.d.ts +34 -0
  125. package/dist/core/src/runtime/index.d.ts +44 -0
  126. package/dist/core/src/runtime/markdown.d.ts +44 -0
  127. package/dist/core/src/runtime/types.d.ts +436 -0
  128. package/dist/core/src/runtime-helpers.d.ts +67 -0
  129. package/dist/core/src/runtime.d.ts +11 -0
  130. package/dist/core/src/security/Encrypter.d.ts +33 -0
  131. package/dist/core/src/security/Hasher.d.ts +29 -0
  132. package/dist/core/src/testing/HttpTester.d.ts +40 -0
  133. package/dist/core/src/testing/TestResponse.d.ts +78 -0
  134. package/dist/core/src/testing/index.d.ts +2 -0
  135. package/dist/core/src/transpiler-utils.d.ts +170 -0
  136. package/dist/core/src/types/events.d.ts +94 -0
  137. package/dist/index.js +1 -294
  138. package/dist/index.js.map +3 -10
  139. package/dist/radiance/src/BroadcastManager.d.ts +124 -0
  140. package/dist/radiance/src/OrbitRadiance.d.ts +98 -0
  141. package/dist/radiance/src/channels/Channel.d.ts +86 -0
  142. package/dist/radiance/src/drivers/AblyDriver.d.ts +73 -0
  143. package/dist/radiance/src/drivers/BroadcastDriver.d.ts +50 -0
  144. package/dist/radiance/src/drivers/PusherDriver.d.ts +95 -0
  145. package/dist/radiance/src/drivers/RedisDriver.d.ts +83 -0
  146. package/dist/radiance/src/drivers/WebSocketDriver.d.ts +89 -0
  147. package/dist/radiance/src/index.d.ts +39 -0
  148. package/package.json +4 -2
package/README.md CHANGED
@@ -4,14 +4,29 @@ Lightweight, high-performance broadcasting for Gravito with multiple drivers (Pu
4
4
 
5
5
  **Status**: v0.1.0 - core features complete with multiple broadcast drivers.
6
6
 
7
- ## Features
7
+ ## Features
8
8
 
9
- - **Zero runtime overhead**: Pure type wrappers that delegate to drivers
10
- - **Multi-driver support**: Pusher, Ably, Redis, WebSocket
11
- - **Modular**: Install only the driver you need
12
- - **Events integration**: Events can implement `ShouldBroadcast`
13
- - **Channel authorization**: Private and presence channels supported
14
- - **AI-friendly**: Strong typing, clear JSDoc, and predictable APIs
9
+ - 🪐 **Galaxy-Ready Broadcasting**: Native integration with PlanetCore events for automatic real-time delivery.
10
+ - 🔌 **Multi-Driver Support**: Seamlessly switch between **Pusher**, **Ably**, **Redis**, and native **WebSockets**.
11
+ - 📡 **Cross-Satellite Sync**: Synchronize state across multiple isolated Satellite instances.
12
+ - 🛡️ **Channel Authorization**: Built-in support for Private and Presence channels with granular auth logic.
13
+ - 🚀 **Zero Runtime Overhead**: Pure type-safe wrappers designed for maximum performance on Bun.
14
+
15
+ ## 🌌 Role in Galaxy Architecture
16
+
17
+ In the **Gravito Galaxy Architecture**, Radiance acts as the **Event Horizon Layer (State Synchronization)**.
18
+
19
+ - **Real-time Interface**: Connects the internal events of the Galaxy to external observers (Clients) via persistent connections.
20
+ - **Satellite Interconnect**: Allows Satellites to broadcast state changes that other Satellites' frontend components can react to instantly.
21
+ - **Presence Core**: Manages the "Who is Online" state across the entire ecosystem, enabling collaborative features.
22
+
23
+ ```mermaid
24
+ graph LR
25
+ S[Satellite] -->|Dispatch| E[Event]
26
+ E -->|implement ShouldBroadcast| Radiance{Radiance Orbit}
27
+ Radiance --> Driver[Driver: WS/Pusher]
28
+ Driver --> Client([Connected Clients])
29
+ ```
15
30
 
16
31
  ## Installation
17
32
 
@@ -216,6 +231,14 @@ OrbitRadiance.configure({
216
231
  })
217
232
  ```
218
233
 
234
+ ## 📚 Documentation
235
+
236
+ Detailed guides and references for the Galaxy Architecture:
237
+
238
+ - [🏗️ **Architecture Overview**](./README.md) — Multi-driver broadcasting.
239
+ - [📡 **Real-time Sync**](./doc/REAL_TIME_SYNC.md) — **NEW**: Syncing state across Satellites and Clients.
240
+ - [🛡️ **Channel Auth**](#channel-authorization) — Securing private and presence channels.
241
+
219
242
  ## API Reference
220
243
 
221
244
  ### BroadcastManager
@@ -0,0 +1,256 @@
1
+ /**
2
+ * @fileoverview Application - Enterprise Application Container
3
+ *
4
+ * A high-level application class that orchestrates the entire framework.
5
+ * Provides a centralized entry point for enterprise applications with
6
+ * auto-discovery of providers, config loading, and lifecycle management.
7
+ *
8
+ * Phase 4 優化:Provider 預掃描 + 平行載入
9
+ * - Phase 1:預掃描所有 Provider 文件(語法驗證)
10
+ * - Phase 2:篩選有效 Provider(跳過無效的)
11
+ * - Phase 3:平行 import 所有有效 Provider
12
+ * - Phase 4:註冊到容器
13
+ *
14
+ * @module @gravito/core
15
+ * @since 2.0.0
16
+ */
17
+ import { ConfigManager } from './ConfigManager';
18
+ import { Container } from './Container';
19
+ import type { EventManager } from './EventManager';
20
+ import type { Logger } from './Logger';
21
+ import { PlanetCore } from './PlanetCore';
22
+ import type { ServiceProvider } from './ServiceProvider';
23
+ /**
24
+ * Application Config options for the Application class.
25
+ * @public
26
+ */
27
+ export interface ApplicationConfig {
28
+ /**
29
+ * Base path of the application
30
+ */
31
+ basePath: string;
32
+ /**
33
+ * Path to the config directory (relative to basePath)
34
+ * @default 'config'
35
+ */
36
+ configPath?: string;
37
+ /**
38
+ * Path to the providers directory (relative to basePath)
39
+ * @default 'src/Providers'
40
+ */
41
+ providersPath?: string;
42
+ /**
43
+ * Environment (development, production, testing)
44
+ */
45
+ env?: 'development' | 'production' | 'testing';
46
+ /**
47
+ * Logger instance
48
+ */
49
+ logger?: Logger;
50
+ /**
51
+ * Initial configuration values
52
+ */
53
+ config?: Record<string, unknown>;
54
+ /**
55
+ * Service providers to register
56
+ */
57
+ providers?: ServiceProvider[];
58
+ /**
59
+ * Whether to auto-discover providers from providersPath
60
+ * @default true
61
+ */
62
+ autoDiscoverProviders?: boolean;
63
+ }
64
+ /**
65
+ * Application - Enterprise-grade application container.
66
+ *
67
+ * Provides a higher-level abstraction over PlanetCore for building
68
+ * enterprise applications with convention-over-configuration patterns.
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * // Create application
73
+ * const app = new Application({
74
+ * basePath: import.meta.dir,
75
+ * env: process.env.NODE_ENV as 'development' | 'production',
76
+ * });
77
+ *
78
+ * // Boot the application
79
+ * await app.boot();
80
+ *
81
+ * // Access core
82
+ * export default app.core.liftoff();
83
+ * ```
84
+ */
85
+ export declare class Application {
86
+ /**
87
+ * The underlying PlanetCore instance.
88
+ */
89
+ readonly core: PlanetCore;
90
+ /**
91
+ * The IoC container.
92
+ */
93
+ readonly container: Container;
94
+ /**
95
+ * The configuration manager.
96
+ */
97
+ readonly config: ConfigManager;
98
+ /**
99
+ * The event manager.
100
+ */
101
+ readonly events: EventManager;
102
+ /**
103
+ * The logger instance.
104
+ */
105
+ readonly logger: Logger;
106
+ /**
107
+ * Application base path.
108
+ */
109
+ readonly basePath: string;
110
+ /**
111
+ * Environment mode.
112
+ */
113
+ readonly env: 'development' | 'production' | 'testing';
114
+ /**
115
+ * Configuration options.
116
+ */
117
+ private readonly options;
118
+ /**
119
+ * Whether the application has been booted.
120
+ */
121
+ private booted;
122
+ constructor(options: ApplicationConfig);
123
+ /**
124
+ * Boot the application and its dependencies.
125
+ *
126
+ * This method orchestrates the full application lifecycle:
127
+ * 1. Configuration: Loads all config files from the config directory.
128
+ * 2. Discovery: Auto-discovers ServiceProviders from the providers directory.
129
+ * 3. Registration: Registers all discovered and explicit providers.
130
+ * 4. Bootstrapping: Triggers the PlanetCore bootstrap sequence.
131
+ *
132
+ * @returns Promise that resolves to the application instance for chaining.
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * const app = new Application({ basePath: import.meta.dir });
137
+ * await app.boot();
138
+ * ```
139
+ */
140
+ boot(): Promise<this>;
141
+ /**
142
+ * Load configuration files from the config directory.
143
+ *
144
+ * @internal
145
+ */
146
+ private loadConfiguration;
147
+ /**
148
+ * Discover and register providers from the providers directory.
149
+ *
150
+ * Phase 4 優化版本:採用 4-Phase 載入策略
151
+ * - Phase 1:預掃描所有候選 Provider 檔案(語法驗證)
152
+ * - Phase 2:篩選有效 Provider 檔案(跳過語法錯誤的)
153
+ * - Phase 3:平行 import 所有有效 Provider(從循序 → 並行)
154
+ * - Phase 4:逐一註冊到容器
155
+ *
156
+ * 效能改進:N 個 Provider 從 O(N * importTime) 降至 O(importTime + overhead)
157
+ *
158
+ * @internal
159
+ */
160
+ private discoverProviders;
161
+ /**
162
+ * Phase 1+2:預掃描 Provider 目錄中的所有候選檔案。
163
+ *
164
+ * 使用輕量語法驗證(嘗試讀取 + 基本結構檢查)篩選有效的 Provider 檔案,
165
+ * 讓語法錯誤在 import 之前被發現,提供更清晰的錯誤訊息。
166
+ *
167
+ * 策略:
168
+ * 1. 使用 Bun.Transpiler 進行 import 掃描(在 Bun 環境下)
169
+ * 2. Fallback 至基本檔案讀取驗證(在 Node/Deno 環境下)
170
+ *
171
+ * @param providersPath - Provider 目錄絕對路徑
172
+ * @returns 掃描結果陣列(含有效/無效標記)
173
+ * @internal
174
+ */
175
+ private prescribeProviders;
176
+ /**
177
+ * Phase 3:平行 import 所有有效的 Provider 檔案。
178
+ *
179
+ * 使用 Promise.all() 同時 import 所有通過預掃描的 Provider 檔案,
180
+ * 從循序載入(O(N))改善為平行載入(O(1) 理論上),
181
+ * 實際效能受 I/O、CPU 和 V8 模組解析限制。
182
+ *
183
+ * @param validProviders - 通過預掃描的 Provider 掃描結果
184
+ * @returns 模組載入結果陣列
185
+ * @internal
186
+ */
187
+ private loadProvidersInParallel;
188
+ /**
189
+ * Resolve a service instance from the IoC container.
190
+ *
191
+ * This is a convenience wrapper around `container.make()`.
192
+ *
193
+ * @template T - The expected type of the service.
194
+ * @param key - The unique identifier or class name of the service.
195
+ * @returns The resolved service instance.
196
+ * @throws Error if the service is not bound in the container.
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * const db = app.make<Database>('db');
201
+ * ```
202
+ */
203
+ make<T>(key: string): T;
204
+ /**
205
+ * Check if a service is bound.
206
+ *
207
+ * @param key - The service key
208
+ * @returns True if bound
209
+ */
210
+ has(key: string): boolean;
211
+ /**
212
+ * Retrieve a configuration value using dot notation.
213
+ *
214
+ * @template T - The expected type of the configuration value.
215
+ * @param key - The configuration key (e.g., 'app.name', 'database.connections.mysql').
216
+ * @param defaultValue - Optional value to return if the key is not found.
217
+ * @returns The configuration value or the default value.
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * const port = app.getConfig<number>('app.port', 3000);
222
+ * ```
223
+ */
224
+ getConfig<T>(key: string, defaultValue?: T): T;
225
+ /**
226
+ * Resolve an absolute path relative to the application base path.
227
+ *
228
+ * @param segments - Path segments to join with the base path.
229
+ * @returns The absolute path string.
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * const storagePath = app.path('storage', 'logs');
234
+ * ```
235
+ */
236
+ path(...segments: string[]): string;
237
+ /**
238
+ * Get the config path.
239
+ *
240
+ * @param segments - Additional path segments
241
+ * @returns Absolute path to config directory
242
+ */
243
+ configPath(...segments: string[]): string;
244
+ /**
245
+ * Check if running in production.
246
+ */
247
+ isProduction(): boolean;
248
+ /**
249
+ * Check if running in development.
250
+ */
251
+ isDevelopment(): boolean;
252
+ /**
253
+ * Check if running in testing.
254
+ */
255
+ isTesting(): boolean;
256
+ }
@@ -0,0 +1,33 @@
1
+ import type { Container } from './Container';
2
+ /**
3
+ * CommandHandler type for custom CLI commands.
4
+ */
5
+ export type CommandHandler = (args: string[], container: Container) => Promise<void> | void;
6
+ /**
7
+ * CommandKernel - Structured CLI Command handling.
8
+ *
9
+ * Manages registration and execution of custom CLI commands that can
10
+ * reuse the application container and providers.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const kernel = new CommandKernel(container);
15
+ * kernel.register('greet', (args) => console.log('Hello', args[0]));
16
+ * await kernel.handle(['greet', 'Universe']);
17
+ * ```
18
+ */
19
+ export declare class CommandKernel {
20
+ private container;
21
+ private commands;
22
+ constructor(container: Container);
23
+ /**
24
+ * Register a new command handler.
25
+ */
26
+ register(name: string, handler: CommandHandler): void;
27
+ /**
28
+ * Handle an incoming CLI command.
29
+ *
30
+ * @param argv - Array of command line arguments (e.g. process.argv.slice(2))
31
+ */
32
+ handle(argv: string[]): Promise<void>;
33
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Configuration manager (ConfigManager)
3
+ *
4
+ * Unifies environment variables and application configuration access.
5
+ */
6
+ import type { ZodSchema } from 'zod';
7
+ /**
8
+ * ConfigManager - Central configuration store.
9
+ * Supports loading from environment variables and initial objects.
10
+ * @public
11
+ */
12
+ export declare class ConfigManager {
13
+ private config;
14
+ private schema;
15
+ constructor(initialConfig?: Record<string, unknown>);
16
+ /**
17
+ * Load all environment variables from the active runtime.
18
+ */
19
+ private loadEnv;
20
+ /**
21
+ * Get a configuration value (generic return type supported).
22
+ * Supports dot notation for deep access (e.g. 'app.name').
23
+ */
24
+ get<T = unknown>(key: string, defaultValue?: T): T;
25
+ /**
26
+ * Set a configuration value.
27
+ */
28
+ set(key: string, value: unknown): void;
29
+ /**
30
+ * Check whether a key exists.
31
+ */
32
+ has(key: string): boolean;
33
+ /**
34
+ * Define a Zod schema for configuration validation.
35
+ *
36
+ * @param schema - Zod schema for validation
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * config.defineSchema(z.object({
41
+ * DATABASE_URL: z.string().url(),
42
+ * PORT: z.number().default(3000),
43
+ * }))
44
+ * ```
45
+ */
46
+ defineSchema(schema: ZodSchema): void;
47
+ /**
48
+ * Validate configuration against the defined schema.
49
+ *
50
+ * Should be called during bootstrap to catch configuration errors early.
51
+ *
52
+ * @throws Error if validation fails with details about missing/invalid fields
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * try {
57
+ * config.validate()
58
+ * } catch (error) {
59
+ * console.error('Config validation failed:', error.message)
60
+ * process.exit(1)
61
+ * }
62
+ * ```
63
+ */
64
+ validate(): void;
65
+ }
@@ -0,0 +1,62 @@
1
+ import type { ServiceKey } from '../Container';
2
+ import { RequestScopeMetrics, type RequestScopeObserver } from './RequestScopeMetrics';
3
+ /**
4
+ * Manages request-scoped service instances within a single HTTP request.
5
+ *
6
+ * Each request gets its own RequestScopeManager instance with isolated state.
7
+ * Services are cached within the request and automatically cleaned up when
8
+ * the request ends.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const scope = new RequestScopeManager()
13
+ * const cache = scope.resolve('productCache', () => new ProductCache())
14
+ * // ... use cache ...
15
+ * await scope.cleanup() // Called automatically by Gravito engine
16
+ * ```
17
+ */
18
+ export declare class RequestScopeManager {
19
+ private scoped;
20
+ private metadata;
21
+ private metrics;
22
+ private observer;
23
+ constructor(observer?: RequestScopeObserver);
24
+ /**
25
+ * Set observer for monitoring scope lifecycle
26
+ */
27
+ setObserver(observer: RequestScopeObserver): void;
28
+ /**
29
+ * Get metrics for this scope
30
+ */
31
+ getMetrics(): RequestScopeMetrics;
32
+ /**
33
+ * Resolve or retrieve a request-scoped service instance.
34
+ *
35
+ * If the service already exists in this scope, returns the cached instance.
36
+ * Otherwise, calls the factory function to create a new instance and caches it.
37
+ *
38
+ * Automatically detects and records services with cleanup methods.
39
+ *
40
+ * @template T - The type of the service.
41
+ * @param key - The service key (for caching).
42
+ * @param factory - Factory function to create the instance if not cached.
43
+ * @returns The cached or newly created instance.
44
+ */
45
+ resolve<T>(key: ServiceKey, factory: () => T): T;
46
+ /**
47
+ * Clean up all request-scoped instances.
48
+ *
49
+ * Calls the cleanup() method on each service that has one.
50
+ * Silently ignores cleanup errors to prevent cascading failures.
51
+ * Called automatically by the Gravito engine in the request finally block.
52
+ *
53
+ * @returns Promise that resolves when all cleanup is complete.
54
+ */
55
+ cleanup(): Promise<void>;
56
+ /**
57
+ * Get the number of services in this scope (for monitoring).
58
+ *
59
+ * @returns The count of cached services.
60
+ */
61
+ size(): number;
62
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * RequestScopeMetrics - Observability for RequestScope lifecycle
3
+ *
4
+ * Tracks cleanup execution time, scope size, and service counts
5
+ * for performance monitoring and diagnostics.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const metrics = new RequestScopeMetrics()
10
+ * metrics.recordCleanupStart()
11
+ * await scope.cleanup()
12
+ * metrics.recordCleanupEnd()
13
+ *
14
+ * console.log(metrics.toJSON())
15
+ * // { cleanupDuration: 2.5, scopeSize: 3, servicesCleaned: 3 }
16
+ * ```
17
+ */
18
+ export declare class RequestScopeMetrics {
19
+ private cleanupStartTime;
20
+ private cleanupDuration;
21
+ private scopeSize;
22
+ private servicesCleaned;
23
+ private errorsOccurred;
24
+ /**
25
+ * Record start of cleanup operation
26
+ */
27
+ recordCleanupStart(): void;
28
+ /**
29
+ * Record end of cleanup operation
30
+ *
31
+ * @param scopeSize - Number of services in the scope
32
+ * @param servicesCleaned - Number of services that had cleanup called
33
+ * @param errorsOccurred - Number of cleanup errors
34
+ */
35
+ recordCleanupEnd(scopeSize: number, servicesCleaned: number, errorsOccurred?: number): void;
36
+ /**
37
+ * Get cleanup duration in milliseconds
38
+ *
39
+ * @returns Duration in ms, or null if cleanup not completed
40
+ */
41
+ getCleanupDuration(): number | null;
42
+ /**
43
+ * Check if cleanup took longer than threshold (default 2ms)
44
+ * Useful for detecting slow cleanups
45
+ *
46
+ * @param thresholdMs - Threshold in milliseconds
47
+ * @returns True if cleanup exceeded threshold
48
+ */
49
+ isSlowCleanup(thresholdMs?: number): boolean;
50
+ /**
51
+ * Export metrics as JSON for logging/monitoring
52
+ */
53
+ toJSON(): {
54
+ cleanupDuration: number | null;
55
+ scopeSize: number;
56
+ servicesCleaned: number;
57
+ errorsOccurred: number;
58
+ hasErrors: boolean;
59
+ isSlowCleanup: boolean;
60
+ };
61
+ /**
62
+ * Export metrics as compact string for logging
63
+ */
64
+ toString(): string;
65
+ }
66
+ /**
67
+ * RequestScopeObserver - Hook for monitoring RequestScope lifecycle
68
+ *
69
+ * Implement this interface to receive callbacks during scope operations
70
+ */
71
+ export interface RequestScopeObserver {
72
+ /**
73
+ * Called when a service is resolved in the scope
74
+ */
75
+ onServiceResolved?(key: string | symbol, isFromCache: boolean): void;
76
+ /**
77
+ * Called when cleanup starts
78
+ */
79
+ onCleanupStart?(): void;
80
+ /**
81
+ * Called when cleanup completes
82
+ */
83
+ onCleanupEnd?(metrics: RequestScopeMetrics): void;
84
+ /**
85
+ * Called when cleanup encounters an error
86
+ */
87
+ onCleanupError?(error: Error): void;
88
+ }
89
+ /**
90
+ * RequestScopeMetricsCollector - Aggregates metrics across multiple scopes
91
+ *
92
+ * Used for application-level monitoring and performance tracking
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const collector = new RequestScopeMetricsCollector()
97
+ *
98
+ * // Record metrics from multiple requests
99
+ * collector.record(metrics1)
100
+ * collector.record(metrics2)
101
+ * collector.record(metrics3)
102
+ *
103
+ * // Get aggregated stats
104
+ * const stats = collector.getStats()
105
+ * console.log(stats.averageCleanupTime) // 3.5ms
106
+ * ```
107
+ */
108
+ export declare class RequestScopeMetricsCollector {
109
+ private metrics;
110
+ /**
111
+ * Record metrics from a request scope
112
+ */
113
+ record(metrics: RequestScopeMetrics): void;
114
+ /**
115
+ * Get aggregated statistics
116
+ */
117
+ getStats(): {
118
+ count: number;
119
+ averageCleanupTime: number | null;
120
+ maxCleanupTime: number | null;
121
+ minCleanupTime: number | null;
122
+ totalErrorCount: number;
123
+ errorRate: number;
124
+ };
125
+ /**
126
+ * Clear collected metrics
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get number of recorded metrics
131
+ */
132
+ size(): number;
133
+ /**
134
+ * Export metrics as JSON array
135
+ */
136
+ toJSON(): {
137
+ cleanupDuration: number | null;
138
+ scopeSize: number;
139
+ servicesCleaned: number;
140
+ errorsOccurred: number;
141
+ hasErrors: boolean;
142
+ isSlowCleanup: boolean;
143
+ }[];
144
+ }