@gravito/radiance 1.0.4 → 2.0.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 (160) 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 +408 -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 +241 -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/AuthException.d.ts +10 -0
  79. package/dist/core/src/exceptions/AuthenticationException.d.ts +8 -0
  80. package/dist/core/src/exceptions/AuthorizationException.d.ts +8 -0
  81. package/dist/core/src/exceptions/CacheException.d.ts +9 -0
  82. package/dist/core/src/exceptions/CircularDependencyException.d.ts +10 -0
  83. package/dist/core/src/exceptions/ConfigurationException.d.ts +9 -0
  84. package/dist/core/src/exceptions/DatabaseException.d.ts +9 -0
  85. package/dist/core/src/exceptions/DomainException.d.ts +9 -0
  86. package/dist/core/src/exceptions/GravitoException.d.ts +23 -0
  87. package/dist/core/src/exceptions/HttpException.d.ts +9 -0
  88. package/dist/core/src/exceptions/InfrastructureException.d.ts +17 -0
  89. package/dist/core/src/exceptions/ModelNotFoundException.d.ts +10 -0
  90. package/dist/core/src/exceptions/QueueException.d.ts +9 -0
  91. package/dist/core/src/exceptions/StorageException.d.ts +9 -0
  92. package/dist/core/src/exceptions/StreamException.d.ts +9 -0
  93. package/dist/core/src/exceptions/SystemException.d.ts +9 -0
  94. package/dist/core/src/exceptions/ValidationException.d.ts +22 -0
  95. package/dist/core/src/exceptions/index.d.ts +17 -0
  96. package/dist/core/src/ffi/NativeAccelerator.d.ts +62 -0
  97. package/dist/core/src/ffi/NativeHasher.d.ts +139 -0
  98. package/dist/core/src/ffi/cbor-fallback.d.ts +96 -0
  99. package/dist/core/src/ffi/hash-fallback.d.ts +33 -0
  100. package/dist/core/src/ffi/index.d.ts +10 -0
  101. package/dist/core/src/ffi/types.d.ts +135 -0
  102. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  103. package/dist/core/src/helpers/Arr.d.ts +19 -0
  104. package/dist/core/src/helpers/Str.d.ts +38 -0
  105. package/dist/core/src/helpers/data.d.ts +25 -0
  106. package/dist/core/src/helpers/errors.d.ts +34 -0
  107. package/dist/core/src/helpers/response.d.ts +41 -0
  108. package/dist/core/src/helpers.d.ts +338 -0
  109. package/dist/core/src/hooks/ActionManager.d.ts +132 -0
  110. package/dist/core/src/hooks/AsyncDetector.d.ts +84 -0
  111. package/dist/core/src/hooks/FilterManager.d.ts +71 -0
  112. package/dist/core/src/hooks/MigrationWarner.d.ts +24 -0
  113. package/dist/core/src/hooks/dlq-operations.d.ts +60 -0
  114. package/dist/core/src/hooks/types.d.ts +107 -0
  115. package/dist/core/src/http/CookieJar.d.ts +51 -0
  116. package/dist/core/src/http/cookie.d.ts +29 -0
  117. package/dist/core/src/http/types.d.ts +395 -0
  118. package/dist/core/src/index.d.ts +565 -0
  119. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  120. package/dist/core/src/observability/contracts.d.ts +137 -0
  121. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +349 -0
  122. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  123. package/dist/core/src/reliability/index.d.ts +6 -0
  124. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  125. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  126. package/dist/core/src/runtime/adapter-bun.d.ts +12 -0
  127. package/dist/core/src/runtime/adapter-deno.d.ts +12 -0
  128. package/dist/core/src/runtime/adapter-node.d.ts +12 -0
  129. package/dist/core/src/runtime/adapter-unknown.d.ts +13 -0
  130. package/dist/core/src/runtime/archive.d.ts +17 -0
  131. package/dist/core/src/runtime/compression.d.ts +21 -0
  132. package/dist/core/src/runtime/deep-equals.d.ts +56 -0
  133. package/dist/core/src/runtime/detection.d.ts +22 -0
  134. package/dist/core/src/runtime/escape.d.ts +34 -0
  135. package/dist/core/src/runtime/index.d.ts +44 -0
  136. package/dist/core/src/runtime/markdown.d.ts +44 -0
  137. package/dist/core/src/runtime/types.d.ts +436 -0
  138. package/dist/core/src/runtime-helpers.d.ts +67 -0
  139. package/dist/core/src/runtime.d.ts +11 -0
  140. package/dist/core/src/security/Encrypter.d.ts +33 -0
  141. package/dist/core/src/security/Hasher.d.ts +29 -0
  142. package/dist/core/src/testing/HttpTester.d.ts +40 -0
  143. package/dist/core/src/testing/TestResponse.d.ts +78 -0
  144. package/dist/core/src/testing/index.d.ts +2 -0
  145. package/dist/core/src/transpiler-utils.d.ts +170 -0
  146. package/dist/core/src/types/events.d.ts +94 -0
  147. package/dist/index.js +3 -294
  148. package/dist/index.js.map +3 -10
  149. package/dist/radiance/src/BroadcastManager.d.ts +124 -0
  150. package/dist/radiance/src/OrbitRadiance.d.ts +98 -0
  151. package/dist/radiance/src/channels/Channel.d.ts +86 -0
  152. package/dist/radiance/src/drivers/AblyDriver.d.ts +73 -0
  153. package/dist/radiance/src/drivers/BroadcastDriver.d.ts +50 -0
  154. package/dist/radiance/src/drivers/PusherDriver.d.ts +95 -0
  155. package/dist/radiance/src/drivers/RedisDriver.d.ts +83 -0
  156. package/dist/radiance/src/drivers/WebSocketDriver.d.ts +89 -0
  157. package/dist/radiance/src/errors/RadianceError.d.ts +29 -0
  158. package/dist/radiance/src/errors/codes.d.ts +18 -0
  159. package/dist/radiance/src/index.d.ts +42 -0
  160. package/package.json +4 -2
@@ -0,0 +1,60 @@
1
+ import type { DeadLetterQueue } from '../events/DeadLetterQueue';
2
+ import type { EventOptions } from '../events/EventOptions';
3
+ import type { DeadLetterQueueManager } from '../reliability/DeadLetterQueueManager';
4
+ /**
5
+ * DLQ 操作輔助函式模組。
6
+ *
7
+ * 提取自 HookManager 的 DLQ 管理邏輯,以降低 HookManager 複雜度。
8
+ * 這些函式接受所需依賴作為參數,便於測試與重用。
9
+ *
10
+ * @internal
11
+ */
12
+ /**
13
+ * 重新加入單一 DLQ 項目到事件佇列。
14
+ *
15
+ * @param dlqEntryId - DLQ 項目 ID
16
+ * @param dlq - 記憶體內 DLQ 實例
17
+ * @param requeue - 重新加入佇列的回調函式
18
+ * @returns 是否成功重新加入
19
+ */
20
+ export declare function requeueDLQEntry(dlqEntryId: string, dlq: DeadLetterQueue, requeue: (eventName: string, payload: unknown, options: EventOptions) => Promise<void>): Promise<boolean>;
21
+ /**
22
+ * 批次重新加入指定事件名稱的所有 DLQ 項目。
23
+ *
24
+ * @param eventName - 事件名稱
25
+ * @param dlq - 記憶體內 DLQ 實例
26
+ * @param requeue - 重新加入佇列的回調函式
27
+ * @returns 成功重新加入的項目數
28
+ */
29
+ export declare function requeueDLQBatch(eventName: string, dlq: DeadLetterQueue, requeue: (entryId: string) => Promise<boolean>): Promise<number>;
30
+ /**
31
+ * 建立 EventPriorityQueue 持久化 DLQ 處理器。
32
+ *
33
+ * @param persistentDlqManager - 持久化 DLQ 管理器
34
+ * @returns 持久化 DLQ 處理器函式
35
+ */
36
+ export declare function createPersistentDLQHandler(persistentDlqManager: DeadLetterQueueManager): (hook: string, args: unknown, options: EventOptions, error: Error, retryCount: number, _firstFailedAt: number) => Promise<void>;
37
+ /**
38
+ * 重新加入持久化 DLQ 單一項目到事件佇列。
39
+ *
40
+ * @param dlqId - 持久化 DLQ 項目 UUID
41
+ * @param persistentDlqManager - 持久化 DLQ 管理器
42
+ * @param doActionAsync - 重新加入佇列的回調函式
43
+ * @returns 是否成功重新加入
44
+ */
45
+ export declare function requeuePersistentDLQEntry(dlqId: string, persistentDlqManager: DeadLetterQueueManager, doActionAsync: (event: string, args: unknown, options: EventOptions) => Promise<void>): Promise<boolean>;
46
+ /**
47
+ * 批次重新加入持久化 DLQ 項目。
48
+ *
49
+ * @param filter - 過濾條件
50
+ * @param persistentDlqManager - 持久化 DLQ 管理器
51
+ * @returns 批次操作結果統計
52
+ */
53
+ export declare function requeuePersistentDLQBatch(filter: {
54
+ eventName?: string;
55
+ status?: 'pending' | 'requeued' | 'resolved' | 'abandoned';
56
+ } | undefined, persistentDlqManager: DeadLetterQueueManager): Promise<{
57
+ total: number;
58
+ succeeded: number;
59
+ failed: number;
60
+ }>;
@@ -0,0 +1,107 @@
1
+ import type { CircuitBreakerOptions } from '../events/CircuitBreaker';
2
+ import type { EventBackend } from '../events/EventBackend';
3
+ import type { EventQueueConfig } from '../events/EventPriorityQueue';
4
+ /**
5
+ * Callback function for filters (transforms values).
6
+ * @public
7
+ */
8
+ export type FilterCallback<T = unknown> = (value: T, ...args: unknown[]) => Promise<T> | T;
9
+ /**
10
+ * Callback function for actions (side effects).
11
+ * @public
12
+ */
13
+ export type ActionCallback<TArgs = unknown> = (args: TArgs) => Promise<void> | void;
14
+ /**
15
+ * Options for listener registration.
16
+ * @public
17
+ */
18
+ export interface ListenerOptions {
19
+ /**
20
+ * Explicitly specify the listener type.
21
+ * - 'sync': Force synchronous dispatch for this listener
22
+ * - 'async': Force asynchronous dispatch for this listener
23
+ * - 'auto': Auto-detect based on function signature (default)
24
+ * @default 'auto'
25
+ */
26
+ type?: 'sync' | 'async' | 'auto';
27
+ /**
28
+ * Circuit breaker configuration for this listener.
29
+ */
30
+ circuitBreaker?: CircuitBreakerOptions;
31
+ }
32
+ /**
33
+ * Information about a registered listener.
34
+ * @public
35
+ */
36
+ export interface ListenerInfo {
37
+ /**
38
+ * The callback function.
39
+ */
40
+ callback: ActionCallback;
41
+ /**
42
+ * Whether the listener is considered async.
43
+ */
44
+ isAsync: boolean;
45
+ /**
46
+ * The explicit type override, if any.
47
+ */
48
+ typeOverride?: 'sync' | 'async' | 'auto';
49
+ }
50
+ /**
51
+ * Configuration for HookManager.
52
+ * @public
53
+ */
54
+ export interface HookManagerConfig {
55
+ /**
56
+ * Enable async event dispatch by default.
57
+ * When true, doAction() will automatically use async dispatch if any listener is async.
58
+ * @default false
59
+ */
60
+ asyncByDefault?: boolean;
61
+ /**
62
+ * Migration mode for backward compatibility.
63
+ * - 'sync': All events use synchronous dispatch (legacy mode)
64
+ * - 'hybrid': Auto-detect and use async for async listeners (recommended)
65
+ * - 'async': All events use async dispatch (future mode)
66
+ * @default 'sync'
67
+ */
68
+ migrationMode?: 'sync' | 'hybrid' | 'async';
69
+ /**
70
+ * Enable deprecation warnings for synchronous event dispatch.
71
+ * @default false
72
+ */
73
+ showDeprecationWarnings?: boolean;
74
+ /**
75
+ * Enable Dead Letter Queue for failed events.
76
+ * @default true
77
+ */
78
+ enableDLQ?: boolean;
79
+ /**
80
+ * Configuration for the event priority queue (Backpressure).
81
+ */
82
+ queue?: EventQueueConfig;
83
+ /**
84
+ * Custom event backend for distributed processing.
85
+ */
86
+ backend?: EventBackend;
87
+ /**
88
+ * Database connection for persistent DLQ (optional).
89
+ * If provided, failed events after max retries will be persisted to database.
90
+ */
91
+ db?: any;
92
+ /**
93
+ * Enable persistent DLQ for failed events (requires db).
94
+ * @default false
95
+ */
96
+ enablePersistentDLQ?: boolean;
97
+ /**
98
+ * Message Queue Bridge for distributed event processing via Bull Queue.
99
+ * When provided, enables dispatchQueued() method for routing events to Redis-backed queue.
100
+ */
101
+ messageQueueBridge?: any;
102
+ /**
103
+ * Event aggregation configuration (FS-102).
104
+ * Enables deduplication and micro-batching for improved throughput.
105
+ */
106
+ aggregation?: any;
107
+ }
@@ -0,0 +1,51 @@
1
+ import type { Encrypter } from '../security/Encrypter';
2
+ import type { GravitoContext } from './types';
3
+ /**
4
+ * Options for setting cookies
5
+ * @public
6
+ */
7
+ export interface CookieOptions {
8
+ path?: string;
9
+ domain?: string;
10
+ secure?: boolean;
11
+ httpOnly?: boolean;
12
+ sameSite?: 'Strict' | 'Lax' | 'None';
13
+ maxAge?: number;
14
+ expires?: Date;
15
+ encrypt?: boolean;
16
+ }
17
+ /**
18
+ * Utility for managing cookies (request/response/encryption).
19
+ * @public
20
+ */
21
+ export declare class CookieJar {
22
+ private encrypter?;
23
+ private queued;
24
+ constructor(encrypter?: Encrypter | undefined);
25
+ /**
26
+ * Parse cookies from a Cookie header string using Bun's native CookieMap
27
+ * @param header - The Cookie header value
28
+ * @returns Parsed cookies as key-value pairs
29
+ */
30
+ static parseCookies(header: string): Record<string, string>;
31
+ /**
32
+ * Queue a cookie to be sent with the response
33
+ */
34
+ queue(name: string, value: string, minutes?: number, options?: CookieOptions): void;
35
+ /**
36
+ * Make a cookie that lasts "forever" (5 years)
37
+ */
38
+ forever(name: string, value: string, options?: CookieOptions): void;
39
+ /**
40
+ * Expire a cookie
41
+ */
42
+ forget(name: string, options?: CookieOptions): void;
43
+ /**
44
+ * Serialize a cookie to a Set-Cookie header value using Bun's native Cookie API
45
+ */
46
+ private serializeCookie;
47
+ /**
48
+ * Attach queued cookies to the context
49
+ */
50
+ attach(c: GravitoContext): void;
51
+ }
@@ -0,0 +1,29 @@
1
+ import { type CookieOptions } from './CookieJar';
2
+ import type { GravitoContext } from './types';
3
+ /**
4
+ * Get a cookie value from the request
5
+ * @param c - Context object
6
+ * @param name - Cookie name
7
+ * @returns Cookie value or undefined
8
+ * @public
9
+ */
10
+ export declare function getCookie(c: GravitoContext, name: string): string | undefined;
11
+ /**
12
+ * Set a cookie in the response
13
+ * @param c - Context object
14
+ * @param name - Cookie name
15
+ * @param value - Cookie value
16
+ * @param options - Cookie options
17
+ * @public
18
+ */
19
+ export declare function setCookie(c: GravitoContext, name: string, value: string, options?: CookieOptions & {
20
+ maxAge?: number;
21
+ }): void;
22
+ /**
23
+ * Delete a cookie (expire it)
24
+ * @param c - Context object
25
+ * @param name - Cookie name
26
+ * @param options - Cookie options (path, domain, etc.)
27
+ * @public
28
+ */
29
+ export declare function deleteCookie(c: GravitoContext, name: string, options?: CookieOptions): void;
@@ -0,0 +1,395 @@
1
+ /**
2
+ * @fileoverview Core HTTP Types for Gravito Framework
3
+ *
4
+ * These types provide a unified abstraction layer that decouples the framework
5
+ * from any specific HTTP engine (Photon, Express, custom, etc.).
6
+ *
7
+ * @module @gravito/core/http
8
+ * @since 2.0.0
9
+ */
10
+ declare global {
11
+ interface ExecutionContext {
12
+ waitUntil(promise: Promise<unknown>): void;
13
+ passThroughOnException(): void;
14
+ }
15
+ }
16
+ /**
17
+ * Standard HTTP methods supported by Gravito
18
+ */
19
+ export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
20
+ /**
21
+ * HTTP status codes
22
+ */
23
+ export type StatusCode = number;
24
+ /**
25
+ * Content-bearing HTTP status codes (excludes 1xx, 204, 304)
26
+ */
27
+ export type ContentfulStatusCode = Exclude<StatusCode, 100 | 101 | 102 | 103 | 204 | 304>;
28
+ /**
29
+ * Base context variables available in every request
30
+ * Orbits can extend this interface via module augmentation
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // Extending variables in your orbit:
35
+ * declare module '@gravito/core' {
36
+ * interface GravitoVariables {
37
+ * myService: MyService
38
+ * }
39
+ * }
40
+ * ```
41
+ */
42
+ export interface GravitoVariables {
43
+ /**
44
+ * The PlanetCore instance
45
+ * @remarks Always available in PlanetCore-managed contexts
46
+ */
47
+ core?: unknown;
48
+ /**
49
+ * Logger instance
50
+ */
51
+ logger?: unknown;
52
+ /**
53
+ * Configuration manager
54
+ */
55
+ config?: unknown;
56
+ /**
57
+ * Cookie jar for managing response cookies
58
+ */
59
+ cookieJar?: unknown;
60
+ /**
61
+ * Middleware scope tracking for Orbit isolation
62
+ * Tracks which Orbit/scope this request belongs to
63
+ * Used to prevent cross-Orbit middleware contamination
64
+ * @since 2.3.0
65
+ */
66
+ middlewareScope?: string;
67
+ /** @deprecated Use ctx.route() instead */
68
+ route?: unknown;
69
+ [key: string]: unknown;
70
+ }
71
+ /**
72
+ * Validated request data targets
73
+ */
74
+ export type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form' | 'cookie';
75
+ /**
76
+ * GravitoRequest - Unified request interface
77
+ *
78
+ * Provides a consistent API for accessing request data regardless of
79
+ * the underlying HTTP engine.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const userId = ctx.req.param('id')
84
+ * const search = ctx.req.query('q')
85
+ * const body = await ctx.req.json<CreateUserDto>()
86
+ * ```
87
+ */
88
+ export interface GravitoRequest {
89
+ /** Full request URL */
90
+ readonly url: string;
91
+ /** HTTP method (uppercase) */
92
+ readonly method: string;
93
+ /** Request path without query string */
94
+ readonly path: string;
95
+ /**
96
+ * Route pattern (e.g., /users/:id) for the matched route
97
+ *
98
+ * This provides the parameterized route pattern instead of the concrete path,
99
+ * which is critical for preventing high cardinality issues in metrics systems.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * // For request: GET /users/123
104
+ * ctx.req.path // => "/users/123"
105
+ * ctx.req.routePattern // => "/users/:id"
106
+ * ```
107
+ */
108
+ readonly routePattern?: string;
109
+ /**
110
+ * Alias for routePattern (for Hono/Express compatibility)
111
+ * @deprecated Use `routePattern` instead
112
+ */
113
+ readonly routePath?: string;
114
+ /**
115
+ * Get a route parameter value
116
+ * @param name - Parameter name (e.g., 'id' for route '/users/:id')
117
+ */
118
+ param(name: string): string | undefined;
119
+ /**
120
+ * Get all route parameters
121
+ */
122
+ params(): Record<string, string>;
123
+ /**
124
+ * Get a query string parameter
125
+ * @param name - Query parameter name
126
+ */
127
+ query(name: string): string | undefined;
128
+ /**
129
+ * Get all query parameters
130
+ */
131
+ queries(): Record<string, string | string[]>;
132
+ /**
133
+ * Get a request header value
134
+ * @param name - Header name (case-insensitive)
135
+ */
136
+ header(name: string): string | undefined;
137
+ /**
138
+ * Get all request headers
139
+ */
140
+ header(): Record<string, string>;
141
+ /**
142
+ * Parse request body as JSON
143
+ * @throws {Error} If body is not valid JSON
144
+ */
145
+ json<T = unknown>(): Promise<T>;
146
+ /**
147
+ * Parse request body as text
148
+ */
149
+ text(): Promise<string>;
150
+ /**
151
+ * Parse request body as FormData
152
+ */
153
+ formData(): Promise<FormData>;
154
+ /**
155
+ * Parse request body as ArrayBuffer
156
+ */
157
+ arrayBuffer(): Promise<ArrayBuffer>;
158
+ /**
159
+ * Parse form data (urlencoded or multipart)
160
+ */
161
+ parseBody<T = unknown>(): Promise<T>;
162
+ /**
163
+ * Get the raw Request object
164
+ */
165
+ readonly raw: Request;
166
+ /**
167
+ * Get validated data from a specific source
168
+ * @param target - The validation target
169
+ * @throws {Error} If validation was not performed for this target
170
+ */
171
+ valid<T = unknown>(target: ValidationTarget): T;
172
+ /**
173
+ * Store validated data for a specific source
174
+ * @param target - The validation target
175
+ * @param data - The validated data to store
176
+ */
177
+ setValidated(target: ValidationTarget, data: unknown): void;
178
+ }
179
+ /**
180
+ * Options for request forwarding (Proxy)
181
+ */
182
+ export interface ProxyOptions {
183
+ /** Override or add request headers */
184
+ headers?: Record<string, string>;
185
+ /** Whether to keep the original Host header (default: false) */
186
+ preserveHost?: boolean;
187
+ /** Whether to add X-Forwarded-* headers (default: true) */
188
+ addForwardedHeaders?: boolean;
189
+ /** Path rewriting logic */
190
+ rewritePath?: (path: string) => string;
191
+ }
192
+ /**
193
+ * GravitoContext - Unified request context
194
+ *
195
+ * This interface encapsulates all HTTP request/response operations,
196
+ * enabling seamless replacement of the underlying HTTP engine.
197
+ *
198
+ * @typeParam V - Context variables type
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * // In a controller
203
+ * async show(ctx: GravitoContext) {
204
+ * const id = ctx.req.param('id')
205
+ * const user = await User.find(id)
206
+ * return ctx.json({ user })
207
+ * }
208
+ * ```
209
+ */
210
+ export interface GravitoContext<V extends GravitoVariables = GravitoVariables> {
211
+ /** The incoming request */
212
+ readonly req: GravitoRequest;
213
+ /**
214
+ * The response object (for middleware introspection).
215
+ * Middleware can read response headers and status, or mutate the response.
216
+ *
217
+ * @remarks
218
+ * This property is mutable, allowing middleware to replace the response object.
219
+ * Example: `c.res = new Response(...)`
220
+ *
221
+ * May be undefined until a handler creates a response.
222
+ */
223
+ res?: Response;
224
+ /**
225
+ * Send a JSON response
226
+ * @param data - Data to serialize as JSON
227
+ * @param status - HTTP status code (default: 200)
228
+ */
229
+ json<T>(data: T, status?: ContentfulStatusCode): Response;
230
+ /**
231
+ * Send a plain text response
232
+ * @param text - Text content
233
+ * @param status - HTTP status code (default: 200)
234
+ */
235
+ text(text: string, status?: ContentfulStatusCode): Response;
236
+ /**
237
+ * Send an HTML response
238
+ * @param html - HTML content
239
+ * @param status - HTTP status code (default: 200)
240
+ */
241
+ html(html: string, status?: ContentfulStatusCode): Response;
242
+ /**
243
+ * Send a redirect response
244
+ * @param url - Target URL
245
+ * @param status - Redirect status code (default: 302)
246
+ */
247
+ redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
248
+ /**
249
+ * Create a Response with no body
250
+ * @param status - HTTP status code
251
+ */
252
+ body(data: BodyInit | null, status?: StatusCode): Response;
253
+ /**
254
+ * Stream a response
255
+ * @param stream - ReadableStream to send
256
+ * @param status - HTTP status code (default: 200)
257
+ */
258
+ stream(stream: ReadableStream, status?: ContentfulStatusCode): Response;
259
+ /**
260
+ * Send a 404 Not Found response
261
+ */
262
+ notFound(message?: string): Response;
263
+ /**
264
+ * Send a 403 Forbidden response
265
+ */
266
+ forbidden(message?: string): Response;
267
+ /**
268
+ * Send a 401 Unauthorized response
269
+ */
270
+ unauthorized(message?: string): Response;
271
+ /**
272
+ * Send a 400 Bad Request response
273
+ */
274
+ badRequest(message?: string): Response;
275
+ /**
276
+ * Forward the current request to another URL (Reverse Proxy)
277
+ * @param target - Target URL or base URL to forward to
278
+ * @param options - Optional proxy options
279
+ */
280
+ forward(target: string, options?: ProxyOptions): Promise<Response>;
281
+ /**
282
+ * Set a response header
283
+ * @param name - Header name
284
+ * @param value - Header value
285
+ * @param options - Options (append: true to add multiple values)
286
+ */
287
+ header(name: string, value: string, options?: {
288
+ append?: boolean;
289
+ }): void;
290
+ /**
291
+ * Get a request header
292
+ * @param name - Header name (case-insensitive)
293
+ */
294
+ header(name: string): string | undefined;
295
+ /**
296
+ * Set the response status code
297
+ * @param code - HTTP status code
298
+ */
299
+ status(code: StatusCode): void;
300
+ /**
301
+ * Get a context variable
302
+ * @param key - Variable key
303
+ */
304
+ get<K extends keyof V>(key: K): V[K];
305
+ /**
306
+ * Set a context variable
307
+ * @param key - Variable key
308
+ * @param value - Variable value
309
+ */
310
+ set<K extends keyof V>(key: K, value: V[K]): void;
311
+ /**
312
+ * Get the execution context (for Cloudflare Workers, etc.)
313
+ */
314
+ readonly executionCtx?: ExecutionContext;
315
+ /**
316
+ * Get environment bindings (for Cloudflare Workers, etc.)
317
+ */
318
+ readonly env?: Record<string, unknown>;
319
+ /**
320
+ * URL generator helper.
321
+ * Generates a URL for a named route.
322
+ */
323
+ route: (name: string, params?: Record<string, any>, query?: Record<string, any>) => string;
324
+ /**
325
+ * Access the native context object from the underlying HTTP engine.
326
+ *
327
+ * ⚠️ WARNING: Using this ties your code to a specific adapter.
328
+ * Prefer using the abstraction methods when possible.
329
+ *
330
+ * @example
331
+ * ```typescript
332
+ * // Only when absolutely necessary
333
+ * const photonCtx = ctx.native as Context // Photon Context
334
+ * ```
335
+ */
336
+ readonly native: unknown;
337
+ /**
338
+ * Access the RequestScopeManager for this request
339
+ * Services resolved through this manager are scoped to the HTTP request lifetime.
340
+ */
341
+ requestScope(): any;
342
+ /**
343
+ * Resolve or create a request-scoped service
344
+ *
345
+ * @param key - Service key (string or symbol)
346
+ * @param factory - Factory function to create the service if not cached
347
+ * @returns The cached or newly created service instance
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * // Subsequent calls in the same request return the same instance
352
+ * const cache = ctx.scoped('product:cache', () => new RequestProductCache())
353
+ * ```
354
+ */
355
+ scoped<T>(key: string | symbol, factory: () => T): T;
356
+ }
357
+ /**
358
+ * Next function for middleware chain
359
+ */
360
+ export type GravitoNext = () => Promise<void>;
361
+ /**
362
+ * GravitoHandler - Standard route handler type
363
+ *
364
+ * @typeParam V - Context variables type
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * const handler: GravitoHandler = async (ctx) => {
369
+ * return ctx.json({ message: 'Hello, World!' })
370
+ * }
371
+ * ```
372
+ */
373
+ export type GravitoHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
374
+ /**
375
+ * GravitoMiddleware - Standard middleware type
376
+ *
377
+ * @typeParam V - Context variables type
378
+ *
379
+ * @example
380
+ * ```typescript
381
+ * const logger: GravitoMiddleware = async (ctx, next) => {
382
+ * console.log(`${ctx.req.method} ${ctx.req.path}`)
383
+ * await next()
384
+ * }
385
+ * ```
386
+ */
387
+ export type GravitoMiddleware<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>, next: GravitoNext) => Response | void | Promise<Response | void>;
388
+ /**
389
+ * Error handler type
390
+ */
391
+ export type GravitoErrorHandler<V extends GravitoVariables = GravitoVariables> = (error: Error, ctx: GravitoContext<V>) => Response | Promise<Response>;
392
+ /**
393
+ * Not found handler type
394
+ */
395
+ export type GravitoNotFoundHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;