@stacksjs/bun-router 0.0.12 → 0.0.14

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 (273) hide show
  1. package/CHANGELOG.md +770 -0
  2. package/README.md +584 -261
  3. package/package.json +43 -48
  4. package/bin/cli.ts +0 -9
  5. package/dist/auth.d.ts +0 -134
  6. package/dist/cache/lru-cache.d.ts +0 -139
  7. package/dist/cache/middleware-memoization.d.ts +0 -151
  8. package/dist/cache/route-cache-warmer.d.ts +0 -161
  9. package/dist/cache/sqlite-cache.d.ts +0 -209
  10. package/dist/cache/streaming-cache.d.ts +0 -132
  11. package/dist/chunk-1mvtv6jw.js +0 -13012
  12. package/dist/cli/colors.d.ts +0 -15
  13. package/dist/cli/index.d.ts +0 -10
  14. package/dist/cli/middleware.d.ts +0 -31
  15. package/dist/cli/openapi.d.ts +0 -17
  16. package/dist/cli/router.d.ts +0 -15
  17. package/dist/cli/routes.d.ts +0 -29
  18. package/dist/cli/utils.d.ts +0 -74
  19. package/dist/cli.d.ts +0 -1
  20. package/dist/cli.js +0 -3195
  21. package/dist/config.d.ts +0 -7
  22. package/dist/container/container.d.ts +0 -273
  23. package/dist/container/contextual-binding.d.ts +0 -240
  24. package/dist/container/decorators.d.ts +0 -141
  25. package/dist/container/service-provider.d.ts +0 -285
  26. package/dist/development/hot-reload.d.ts +0 -187
  27. package/dist/development/index.d.ts +0 -167
  28. package/dist/development/performance-profiler.d.ts +0 -217
  29. package/dist/development/route-debugger.d.ts +0 -154
  30. package/dist/development/route-inspector.d.ts +0 -211
  31. package/dist/development/typescript-utilities.d.ts +0 -209
  32. package/dist/docs.d.ts +0 -11
  33. package/dist/errors/circuit-breaker.d.ts +0 -195
  34. package/dist/errors/error-handler.d.ts +0 -88
  35. package/dist/errors/error-reporting.d.ts +0 -144
  36. package/dist/errors/exceptions.d.ts +0 -184
  37. package/dist/errors/graceful-degradation.d.ts +0 -154
  38. package/dist/errors/index.d.ts +0 -9
  39. package/dist/errors/router-errors.d.ts +0 -110
  40. package/dist/file-serving/static-files.d.ts +0 -143
  41. package/dist/index.d.ts +0 -14
  42. package/dist/index.js +0 -13933
  43. package/dist/middleware/auth.d.ts +0 -63
  44. package/dist/middleware/content_security_policy.d.ts +0 -53
  45. package/dist/middleware/cors.d.ts +0 -5
  46. package/dist/middleware/csrf.d.ts +0 -7
  47. package/dist/middleware/ddos_protection.d.ts +0 -39
  48. package/dist/middleware/file_security.d.ts +0 -26
  49. package/dist/middleware/file_upload.d.ts +0 -38
  50. package/dist/middleware/helmet.d.ts +0 -54
  51. package/dist/middleware/index.d.ts +0 -44
  52. package/dist/middleware/input_validation.d.ts +0 -45
  53. package/dist/middleware/json_body.d.ts +0 -4
  54. package/dist/middleware/performance_alerting.d.ts +0 -87
  55. package/dist/middleware/performance_dashboard.d.ts +0 -87
  56. package/dist/middleware/performance_monitor.d.ts +0 -209
  57. package/dist/middleware/pipeline.d.ts +0 -131
  58. package/dist/middleware/rate_limit.d.ts +0 -36
  59. package/dist/middleware/request_id.d.ts +0 -4
  60. package/dist/middleware/request_signing.d.ts +0 -153
  61. package/dist/middleware/request_tracer.d.ts +0 -72
  62. package/dist/middleware/response_cache.d.ts +0 -97
  63. package/dist/middleware/security.d.ts +0 -69
  64. package/dist/middleware/security_suite.d.ts +0 -46
  65. package/dist/middleware/session.d.ts +0 -23
  66. package/dist/model-binding/index.d.ts +0 -2
  67. package/dist/model-binding/model-middleware.d.ts +0 -118
  68. package/dist/model-binding/model-registry.d.ts +0 -164
  69. package/dist/model-binding.d.ts +0 -185
  70. package/dist/model-resolver-factory.d.ts +0 -31
  71. package/dist/observability/correlation.d.ts +0 -187
  72. package/dist/observability/health-checks.d.ts +0 -186
  73. package/dist/observability/index.d.ts +0 -60
  74. package/dist/observability/integration.d.ts +0 -147
  75. package/dist/observability/metrics.d.ts +0 -184
  76. package/dist/observability/tracing.d.ts +0 -187
  77. package/dist/optimization/bun-utilities.d.ts +0 -224
  78. package/dist/query-builder-integration.d.ts +0 -36
  79. package/dist/request/context.d.ts +0 -34
  80. package/dist/request/enhanced-request.d.ts +0 -213
  81. package/dist/request/macros.d.ts +0 -300
  82. package/dist/response/macros.d.ts +0 -245
  83. package/dist/response/response-factory.d.ts +0 -133
  84. package/dist/router/api-routes.d.ts +0 -5
  85. package/dist/router/file-based-routing.d.ts +0 -118
  86. package/dist/router/file-streaming.d.ts +0 -5
  87. package/dist/router/fluent-router.d.ts +0 -315
  88. package/dist/router/fluent-routing.d.ts +0 -271
  89. package/dist/router/group-organization.d.ts +0 -5
  90. package/dist/router/handler-resolver.d.ts +0 -24
  91. package/dist/router/http-methods.d.ts +0 -10
  92. package/dist/router/index.d.ts +0 -114
  93. package/dist/router/middleware-groups.d.ts +0 -94
  94. package/dist/router/middleware-integration.d.ts +0 -112
  95. package/dist/router/middleware.d.ts +0 -5
  96. package/dist/router/model-binding.d.ts +0 -5
  97. package/dist/router/optimized-route-matching.d.ts +0 -6
  98. package/dist/router/route-building.d.ts +0 -5
  99. package/dist/router/route-compiler.d.ts +0 -153
  100. package/dist/router/route-matching.d.ts +0 -5
  101. package/dist/router/route-trie.d.ts +0 -114
  102. package/dist/router/router.d.ts +0 -294
  103. package/dist/router/server.d.ts +0 -5
  104. package/dist/router/validation-integration.d.ts +0 -170
  105. package/dist/router/view-rendering.d.ts +0 -5
  106. package/dist/router/websocket.d.ts +0 -5
  107. package/dist/routing/route-caching.d.ts +0 -129
  108. package/dist/routing/route-throttling.d.ts +0 -150
  109. package/dist/routing/subdomain-routing.d.ts +0 -206
  110. package/dist/session/database-store.d.ts +0 -51
  111. package/dist/session/file-store.d.ts +0 -22
  112. package/dist/session/index.d.ts +0 -106
  113. package/dist/session/memory-store.d.ts +0 -21
  114. package/dist/session/redis-store.d.ts +0 -31
  115. package/dist/streaming/index.d.ts +0 -3
  116. package/dist/streaming/sse-handler.d.ts +0 -138
  117. package/dist/streaming/stream-handler.d.ts +0 -114
  118. package/dist/testing/auth-testing.d.ts +0 -156
  119. package/dist/testing/file-upload-testing.d.ts +0 -190
  120. package/dist/testing/index.d.ts +0 -10
  121. package/dist/testing/middleware-testing.d.ts +0 -138
  122. package/dist/testing/model-binding-testing.d.ts +0 -186
  123. package/dist/testing/performance-testing.d.ts +0 -235
  124. package/dist/testing/test-client.d.ts +0 -117
  125. package/dist/testing/test-request.d.ts +0 -85
  126. package/dist/testing/test-response.d.ts +0 -90
  127. package/dist/testing/types.d.ts +0 -207
  128. package/dist/testing/websocket-testing.d.ts +0 -227
  129. package/dist/types/controller-types.d.ts +0 -208
  130. package/dist/types/core.d.ts +0 -543
  131. package/dist/types/middleware-types.d.ts +0 -227
  132. package/dist/types/request-response-augmentation.d.ts +0 -261
  133. package/dist/types/route-inference.d.ts +0 -168
  134. package/dist/types.d.ts +0 -1782
  135. package/dist/url.d.ts +0 -56
  136. package/dist/utils/index.d.ts +0 -1
  137. package/dist/utils/query-preservation.d.ts +0 -48
  138. package/dist/utils.d.ts +0 -69
  139. package/dist/validation/validator.d.ts +0 -140
  140. package/dist/websocket/clustering.d.ts +0 -185
  141. package/src/auth.ts +0 -469
  142. package/src/cache/lru-cache.ts +0 -457
  143. package/src/cache/middleware-memoization.ts +0 -531
  144. package/src/cache/route-cache-warmer.ts +0 -486
  145. package/src/cache/sqlite-cache.ts +0 -783
  146. package/src/cache/streaming-cache.ts +0 -572
  147. package/src/cli/colors.ts +0 -29
  148. package/src/cli/index.ts +0 -287
  149. package/src/cli/middleware.ts +0 -291
  150. package/src/cli/openapi.ts +0 -407
  151. package/src/cli/router.ts +0 -188
  152. package/src/cli/routes.ts +0 -265
  153. package/src/cli/utils.ts +0 -531
  154. package/src/cli.ts +0 -5
  155. package/src/config.ts +0 -322
  156. package/src/container/container.ts +0 -740
  157. package/src/container/contextual-binding.ts +0 -603
  158. package/src/container/decorators.ts +0 -359
  159. package/src/container/service-provider.ts +0 -596
  160. package/src/development/hot-reload.ts +0 -673
  161. package/src/development/index.ts +0 -499
  162. package/src/development/performance-profiler.ts +0 -717
  163. package/src/development/route-debugger.ts +0 -527
  164. package/src/development/route-inspector.ts +0 -749
  165. package/src/development/typescript-utilities.ts +0 -682
  166. package/src/docs.ts +0 -397
  167. package/src/errors/circuit-breaker.ts +0 -732
  168. package/src/errors/error-handler.ts +0 -569
  169. package/src/errors/error-reporting.ts +0 -672
  170. package/src/errors/exceptions.ts +0 -536
  171. package/src/errors/graceful-degradation.ts +0 -621
  172. package/src/errors/index.ts +0 -21
  173. package/src/errors/router-errors.ts +0 -632
  174. package/src/file-serving/static-files.ts +0 -581
  175. package/src/index.ts +0 -14
  176. package/src/middleware/auth.ts +0 -219
  177. package/src/middleware/content_security_policy.ts +0 -215
  178. package/src/middleware/cors.ts +0 -74
  179. package/src/middleware/csrf.ts +0 -108
  180. package/src/middleware/ddos_protection.ts +0 -255
  181. package/src/middleware/file_security.ts +0 -191
  182. package/src/middleware/file_upload.ts +0 -264
  183. package/src/middleware/helmet.ts +0 -268
  184. package/src/middleware/index.ts +0 -117
  185. package/src/middleware/input_validation.ts +0 -449
  186. package/src/middleware/json_body.ts +0 -37
  187. package/src/middleware/performance_alerting.ts +0 -538
  188. package/src/middleware/performance_dashboard.ts +0 -661
  189. package/src/middleware/performance_monitor.ts +0 -943
  190. package/src/middleware/pipeline.ts +0 -489
  191. package/src/middleware/rate_limit.ts +0 -245
  192. package/src/middleware/request_id.ts +0 -36
  193. package/src/middleware/request_signing.ts +0 -636
  194. package/src/middleware/request_tracer.ts +0 -636
  195. package/src/middleware/response_cache.ts +0 -743
  196. package/src/middleware/security.ts +0 -482
  197. package/src/middleware/security_suite.ts +0 -257
  198. package/src/middleware/session.ts +0 -91
  199. package/src/model-binding/index.ts +0 -18
  200. package/src/model-binding/model-middleware.ts +0 -425
  201. package/src/model-binding/model-registry.ts +0 -550
  202. package/src/model-binding.ts +0 -370
  203. package/src/model-resolver-factory.ts +0 -106
  204. package/src/observability/correlation.ts +0 -691
  205. package/src/observability/health-checks.ts +0 -729
  206. package/src/observability/index.ts +0 -184
  207. package/src/observability/integration.ts +0 -548
  208. package/src/observability/metrics.ts +0 -753
  209. package/src/observability/tracing.ts +0 -638
  210. package/src/optimization/bun-utilities.ts +0 -778
  211. package/src/query-builder-integration.ts +0 -137
  212. package/src/request/context.ts +0 -62
  213. package/src/request/enhanced-request.ts +0 -857
  214. package/src/request/macros.ts +0 -688
  215. package/src/response/macros.ts +0 -612
  216. package/src/response/response-factory.ts +0 -596
  217. package/src/router/api-routes.ts +0 -243
  218. package/src/router/file-based-routing.ts +0 -670
  219. package/src/router/file-streaming.ts +0 -372
  220. package/src/router/fluent-router.ts +0 -927
  221. package/src/router/fluent-routing.ts +0 -797
  222. package/src/router/group-organization.ts +0 -213
  223. package/src/router/handler-resolver.ts +0 -291
  224. package/src/router/http-methods.ts +0 -377
  225. package/src/router/index.ts +0 -187
  226. package/src/router/middleware-groups.ts +0 -222
  227. package/src/router/middleware-integration.ts +0 -399
  228. package/src/router/middleware.ts +0 -231
  229. package/src/router/model-binding.ts +0 -215
  230. package/src/router/optimized-route-matching.ts +0 -253
  231. package/src/router/route-building.ts +0 -212
  232. package/src/router/route-compiler.ts +0 -702
  233. package/src/router/route-matching.ts +0 -349
  234. package/src/router/route-trie.ts +0 -464
  235. package/src/router/router.ts +0 -1581
  236. package/src/router/server.ts +0 -462
  237. package/src/router/validation-integration.ts +0 -443
  238. package/src/router/view-rendering.ts +0 -233
  239. package/src/router/websocket.ts +0 -100
  240. package/src/routing/route-caching.ts +0 -402
  241. package/src/routing/route-throttling.ts +0 -469
  242. package/src/routing/subdomain-routing.ts +0 -492
  243. package/src/session/database-store.ts +0 -109
  244. package/src/session/file-store.ts +0 -148
  245. package/src/session/index.ts +0 -244
  246. package/src/session/memory-store.ts +0 -88
  247. package/src/session/redis-store.ts +0 -93
  248. package/src/streaming/index.ts +0 -17
  249. package/src/streaming/sse-handler.ts +0 -482
  250. package/src/streaming/stream-handler.ts +0 -552
  251. package/src/testing/auth-testing.ts +0 -446
  252. package/src/testing/file-upload-testing.ts +0 -543
  253. package/src/testing/index.ts +0 -10
  254. package/src/testing/middleware-testing.ts +0 -322
  255. package/src/testing/model-binding-testing.ts +0 -645
  256. package/src/testing/performance-testing.ts +0 -738
  257. package/src/testing/test-client.ts +0 -310
  258. package/src/testing/test-request.ts +0 -315
  259. package/src/testing/test-response.ts +0 -332
  260. package/src/testing/types.ts +0 -224
  261. package/src/testing/websocket-testing.ts +0 -590
  262. package/src/types/controller-types.ts +0 -385
  263. package/src/types/core.ts +0 -683
  264. package/src/types/middleware-types.ts +0 -419
  265. package/src/types/request-response-augmentation.ts +0 -489
  266. package/src/types/route-inference.ts +0 -357
  267. package/src/types.ts +0 -2055
  268. package/src/url.ts +0 -126
  269. package/src/utils/index.ts +0 -1
  270. package/src/utils/query-preservation.ts +0 -201
  271. package/src/utils.ts +0 -327
  272. package/src/validation/validator.ts +0 -685
  273. package/src/websocket/clustering.ts +0 -762
@@ -1,636 +0,0 @@
1
- import type { EnhancedRequest, NextFunction } from '../types'
2
- import { config } from '../config'
3
-
4
- export interface TraceSpan {
5
- traceId: string
6
- spanId: string
7
- parentSpanId?: string
8
- operationName: string
9
- startTime: number
10
- endTime?: number
11
- duration?: number
12
- tags: Record<string, any>
13
- logs: Array<{
14
- timestamp: number
15
- level: 'debug' | 'info' | 'warn' | 'error'
16
- message: string
17
- fields?: Record<string, any>
18
- }>
19
- status: 'ok' | 'error' | 'timeout'
20
- error?: string
21
- stackTrace?: string[]
22
- }
23
-
24
- export interface TracingOptions {
25
- enabled?: boolean
26
- sampleRate?: number
27
- maxSpans?: number
28
- includeHeaders?: boolean
29
- includeQueryParams?: boolean
30
- includeRequestBody?: boolean
31
- includeResponseBody?: boolean
32
- maxBodySize?: number
33
- exporters?: Array<{
34
- type: 'console' | 'jaeger' | 'zipkin' | 'otlp' | 'custom'
35
- endpoint?: string
36
- headers?: Record<string, string>
37
- customExporter?: (spans: TraceSpan[]) => Promise<void>
38
- }>
39
- propagation?: {
40
- enabled?: boolean
41
- headers?: string[]
42
- }
43
- }
44
-
45
- export default class RequestTracer {
46
- private options: TracingOptions
47
- private spans: Map<string, TraceSpan> = new Map()
48
- private activeSpans: Map<string, string> = new Map() // requestId -> spanId
49
- private exportQueue: TraceSpan[] = []
50
- private exportInterval?: ReturnType<typeof setInterval>
51
-
52
- constructor(options: TracingOptions = {}) {
53
- const tracingConfig = (config.server?.performance?.monitoring as any)?.tracing || {}
54
-
55
- this.options = {
56
- enabled: options.enabled ?? tracingConfig.enabled ?? false,
57
- sampleRate: options.sampleRate ?? tracingConfig.sampleRate ?? 1.0,
58
- maxSpans: options.maxSpans ?? 10000,
59
- includeHeaders: options.includeHeaders ?? false,
60
- includeQueryParams: options.includeQueryParams ?? true,
61
- includeRequestBody: options.includeRequestBody ?? false,
62
- includeResponseBody: options.includeResponseBody ?? false,
63
- maxBodySize: options.maxBodySize ?? 1024 * 1024, // 1MB
64
- exporters: options.exporters ?? [{ type: 'console' }],
65
- propagation: {
66
- enabled: true,
67
- headers: ['x-trace-id', 'x-span-id', 'x-parent-span-id'],
68
- ...options.propagation,
69
- },
70
- }
71
-
72
- if (this.options.enabled) {
73
- this.startExportInterval()
74
- }
75
- }
76
-
77
- private startExportInterval(): void {
78
- this.exportInterval = setInterval(async () => {
79
- try {
80
- await this.exportSpans()
81
- }
82
- catch (error) {
83
- console.warn('Error exporting spans:', error)
84
- }
85
- }, 100) // Export every 100ms for faster testing
86
- }
87
-
88
- private shouldSample(): boolean {
89
- return Math.random() < (this.options.sampleRate || 1.0)
90
- }
91
-
92
- private generateId(): string {
93
- return Math.random().toString(36).substring(2, 15)
94
- + Math.random().toString(36).substring(2, 15)
95
- }
96
-
97
- private extractPropagationHeaders(req: EnhancedRequest): {
98
- traceId?: string
99
- parentSpanId?: string
100
- } {
101
- if (!this.options.propagation?.enabled) {
102
- return {}
103
- }
104
-
105
- const headers = this.options.propagation.headers || []
106
- let traceId: string | undefined
107
-
108
- // Try to find trace ID from configured headers
109
- for (const header of headers) {
110
- const value = req.headers.get(header)
111
- if (value) {
112
- traceId = value
113
- break
114
- }
115
- }
116
-
117
- // Look for parent span ID
118
- const parentSpanId = req.headers.get('x-parent-span-id') || undefined
119
-
120
- return { traceId, parentSpanId }
121
- }
122
-
123
- private async captureRequestBody(req: EnhancedRequest): Promise<any> {
124
- if (!this.options.includeRequestBody)
125
- return undefined
126
-
127
- try {
128
- const contentType = req.headers.get('content-type') || ''
129
- const contentLength = Number.parseInt(req.headers.get('content-length') || '0', 10)
130
-
131
- if (contentLength > (this.options.maxBodySize || 1024 * 1024)) {
132
- return { truncated: true, reason: 'Body too large', size: contentLength }
133
- }
134
-
135
- if (contentType.includes('application/json')) {
136
- const cloned = req.clone()
137
- return await cloned.json()
138
- }
139
- else if (contentType.includes('application/x-www-form-urlencoded')) {
140
- const cloned = req.clone()
141
- const formData = await cloned.formData()
142
- const result: Record<string, any> = {}
143
- for (const [key, value] of (formData as any).entries()) {
144
- result[key] = value
145
- }
146
- return result
147
- }
148
- else if (contentType.includes('text/')) {
149
- const cloned = req.clone()
150
- return await cloned.text()
151
- }
152
- }
153
- catch (error) {
154
- return { error: 'Failed to capture body', message: error instanceof Error ? error.message : String(error) }
155
- }
156
-
157
- return undefined
158
- }
159
-
160
- private async captureResponseBody(response: Response): Promise<any> {
161
- if (!this.options.includeResponseBody)
162
- return undefined
163
-
164
- try {
165
- const contentType = response.headers.get('content-type') || ''
166
- const contentLength = Number.parseInt(response.headers.get('content-length') || '0', 10)
167
-
168
- if (contentLength > (this.options.maxBodySize || 1024 * 1024)) {
169
- return { truncated: true, reason: 'Body too large', size: contentLength }
170
- }
171
-
172
- if (contentType.includes('application/json')) {
173
- const cloned = response.clone()
174
- return await cloned.json()
175
- }
176
- else if (contentType.includes('text/')) {
177
- const cloned = response.clone()
178
- return await cloned.text()
179
- }
180
- }
181
- catch (error) {
182
- return { error: 'Failed to capture body', message: error instanceof Error ? error.message : String(error) }
183
- }
184
-
185
- return undefined
186
- }
187
-
188
- private createSpan(
189
- traceId: string,
190
- spanId: string,
191
- operationName: string,
192
- parentSpanId?: string,
193
- ): TraceSpan {
194
- return {
195
- traceId,
196
- spanId,
197
- parentSpanId,
198
- operationName,
199
- startTime: performance.now(),
200
- tags: {},
201
- logs: [],
202
- status: 'ok',
203
- }
204
- }
205
-
206
- private addSpanTag(spanId: string, key: string, value: any): void {
207
- const span = this.spans.get(spanId)
208
- if (span) {
209
- span.tags[key] = value
210
- }
211
- }
212
-
213
- private addSpanLog(
214
- spanId: string,
215
- level: 'debug' | 'info' | 'warn' | 'error',
216
- message: string,
217
- fields?: Record<string, any>,
218
- ): void {
219
- const span = this.spans.get(spanId)
220
- if (span) {
221
- span.logs.push({
222
- timestamp: performance.now(),
223
- level,
224
- message,
225
- fields,
226
- })
227
- }
228
- }
229
-
230
- private finishSpan(spanId: string, status: 'ok' | 'error' | 'timeout' = 'ok', error?: string): void {
231
- const span = this.spans.get(spanId)
232
- if (span) {
233
- span.endTime = performance.now()
234
- span.duration = span.endTime - span.startTime
235
- span.status = status
236
- if (error) {
237
- span.error = error
238
- if (this.options.includeHeaders) {
239
- span.stackTrace = new Error('Trace error stack').stack?.split('\n')
240
- }
241
- }
242
-
243
- // Move to export queue
244
- this.exportQueue.push(span)
245
- this.spans.delete(spanId)
246
- }
247
- }
248
-
249
- private async exportSpans(): Promise<void> {
250
- // For debugging
251
- console.warn(`[RequestTracer] Exporting spans, queue size: ${this.exportQueue.length}, active spans: ${this.spans.size}`)
252
-
253
- if (this.exportQueue.length === 0) {
254
- // Also check if there are any finished spans that need to be exported
255
- // This ensures spans are exported even if they weren't properly moved to the queue
256
- const finishedSpans = Array.from(this.spans.values()).filter(span => span.endTime !== undefined)
257
- if (finishedSpans.length > 0) {
258
- console.warn(`[RequestTracer] Found ${finishedSpans.length} finished spans to export`)
259
- // Move finished spans to export queue
260
- this.exportQueue.push(...finishedSpans)
261
- // Remove them from the spans map
262
- for (const span of finishedSpans) {
263
- this.spans.delete(span.spanId)
264
- }
265
- }
266
-
267
- // If still no spans to export, return
268
- if (this.exportQueue.length === 0) {
269
- return
270
- }
271
- }
272
-
273
- const spansToExport = [...this.exportQueue]
274
- this.exportQueue = []
275
-
276
- // Make sure we have exporters configured
277
- const exporters = this.options.exporters || []
278
- if (exporters.length === 0) {
279
- // Default to console if no exporters configured
280
- this.exportToConsole(spansToExport)
281
- return
282
- }
283
-
284
- for (const exporter of exporters) {
285
- try {
286
- switch (exporter.type) {
287
- case 'console':
288
- this.exportToConsole(spansToExport)
289
- break
290
- case 'jaeger':
291
- await this.exportToJaeger(spansToExport, exporter)
292
- break
293
- case 'zipkin':
294
- await this.exportToZipkin(spansToExport, exporter)
295
- break
296
- case 'custom':
297
- if (typeof exporter.customExporter === 'function') {
298
- await exporter.customExporter(spansToExport)
299
- }
300
- break
301
- }
302
- }
303
- catch (error) {
304
- // Use allowed console method
305
- console.warn(`Failed to export spans to ${exporter.type}:`, error)
306
- }
307
- }
308
- }
309
-
310
- private exportToConsole(spans: TraceSpan[]): void {
311
- for (const span of spans) {
312
- // Use allowed console method
313
- console.warn('Trace Span:', {
314
- traceId: span.traceId,
315
- spanId: span.spanId,
316
- operation: span.operationName,
317
- duration: `${Math.round((span.duration || 0) * 100) / 100}ms`,
318
- status: span.status,
319
- tags: span.tags,
320
- logs: span.logs.length,
321
- error: span.error,
322
- })
323
- }
324
- }
325
-
326
- private async exportToJaeger(spans: TraceSpan[], exporter: any): Promise<void> {
327
- if (!exporter.endpoint)
328
- return
329
-
330
- const jaegerSpans = spans.map(span => ({
331
- traceID: span.traceId,
332
- spanID: span.spanId,
333
- parentSpanID: span.parentSpanId,
334
- operationName: span.operationName,
335
- startTime: Math.floor(span.startTime * 1000), // microseconds
336
- duration: Math.floor((span.duration || 0) * 1000),
337
- tags: Object.entries(span.tags).map(([key, value]) => ({
338
- key,
339
- type: typeof value === 'string' ? 'string' : 'number',
340
- value: String(value),
341
- })),
342
- logs: span.logs.map(log => ({
343
- timestamp: Math.floor(log.timestamp * 1000),
344
- fields: [
345
- { key: 'level', value: log.level },
346
- { key: 'message', value: log.message },
347
- ...(log.fields ? Object.entries(log.fields).map(([k, v]) => ({ key: k, value: String(v) })) : []),
348
- ],
349
- })),
350
- process: {
351
- serviceName: 'bun-router',
352
- tags: [
353
- { key: 'hostname', value: Bun.env.HOSTNAME || 'localhost' },
354
- { key: 'pid', value: String(123) }, // Use a placeholder since Bun.pid is not available
355
- ],
356
- },
357
- }))
358
-
359
- await fetch(`${exporter.endpoint}/api/traces`, {
360
- method: 'POST',
361
- headers: {
362
- 'Content-Type': 'application/json',
363
- ...exporter.headers,
364
- },
365
- body: JSON.stringify({ data: [{ spans: jaegerSpans }] }),
366
- })
367
- }
368
-
369
- private async exportToZipkin(spans: TraceSpan[], exporter: any): Promise<void> {
370
- if (!exporter.endpoint)
371
- return
372
-
373
- const zipkinSpans = spans.map(span => ({
374
- traceId: span.traceId,
375
- id: span.spanId,
376
- parentId: span.parentSpanId,
377
- name: span.operationName,
378
- timestamp: Math.floor(span.startTime * 1000), // microseconds
379
- duration: Math.floor((span.duration || 0) * 1000),
380
- kind: 'SERVER',
381
- localEndpoint: {
382
- serviceName: 'bun-router',
383
- },
384
- tags: span.tags,
385
- annotations: span.logs.map(log => ({
386
- timestamp: Math.floor(log.timestamp * 1000),
387
- value: `${log.level}: ${log.message}`,
388
- })),
389
- }))
390
-
391
- await fetch(`${exporter.endpoint}/api/v2/spans`, {
392
- method: 'POST',
393
- headers: {
394
- 'Content-Type': 'application/json',
395
- ...exporter.headers,
396
- },
397
- body: JSON.stringify(zipkinSpans),
398
- })
399
- }
400
-
401
- async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
402
- if (!this.options.enabled || !this.shouldSample()) {
403
- const response = await next()
404
- return response || new Response('Internal Server Error', { status: 500 })
405
- }
406
-
407
- const requestId = req.requestId || this.generateId()
408
- const propagation = this.extractPropagationHeaders(req)
409
- const traceId = propagation.traceId || this.generateId()
410
- const spanId = this.generateId()
411
- const url = new URL(req.url)
412
-
413
- // For debugging
414
- console.warn(`[RequestTracer] Creating span for ${req.method} ${url.pathname}, traceId=${traceId}, spanId=${spanId}`)
415
-
416
- // Create main request span
417
- const span = this.createSpan(
418
- traceId,
419
- spanId,
420
- `${req.method} ${url.pathname}`,
421
- propagation.parentSpanId,
422
- )
423
-
424
- this.spans.set(spanId, span)
425
- this.activeSpans.set(requestId, spanId)
426
-
427
- // Add trace info to request
428
- req.traceId = traceId
429
- req.spanId = spanId
430
-
431
- // Ensure these properties are accessible
432
- Object.defineProperties(req, {
433
- traceId: {
434
- value: traceId,
435
- writable: true,
436
- enumerable: true,
437
- configurable: true,
438
- },
439
- spanId: {
440
- value: spanId,
441
- writable: true,
442
- enumerable: true,
443
- configurable: true,
444
- },
445
- })
446
-
447
- // Add basic tags
448
- this.addSpanTag(spanId, 'http.method', req.method)
449
- this.addSpanTag(spanId, 'http.url', req.url)
450
- this.addSpanTag(spanId, 'http.path', url.pathname)
451
- this.addSpanTag(spanId, 'user_agent', req.headers.get('user-agent'))
452
-
453
- if (this.options.includeHeaders) {
454
- const headers: Record<string, string> = {}
455
- for (const [key, value] of req.headers.entries()) {
456
- headers[key] = value
457
- }
458
- this.addSpanTag(spanId, 'http.headers', headers)
459
- }
460
-
461
- if (this.options.includeQueryParams && url.searchParams.size > 0) {
462
- const params: Record<string, string> = {}
463
- for (const [key, value] of url.searchParams.entries()) {
464
- params[key] = value
465
- }
466
- this.addSpanTag(spanId, 'http.query_params', params)
467
- }
468
-
469
- // Capture request body if enabled
470
- if (this.options.includeRequestBody && req.method !== 'GET' && req.method !== 'HEAD') {
471
- try {
472
- const body = await this.captureRequestBody(req)
473
- if (body !== undefined) {
474
- this.addSpanTag(spanId, 'http.request_body', body)
475
- }
476
- }
477
- catch (error) {
478
- this.addSpanLog(spanId, 'warn', 'Failed to capture request body', { error: String(error) })
479
- }
480
- }
481
-
482
- this.addSpanLog(spanId, 'info', 'Request started')
483
-
484
- let response: Response
485
- let error: string | undefined
486
-
487
- try {
488
- const nextResponse = await next()
489
- response = nextResponse || new Response('Internal Server Error', { status: 500 })
490
-
491
- // Add response tags
492
- this.addSpanTag(spanId, 'http.status_code', response.status)
493
- this.addSpanTag(spanId, 'http.status_text', response.statusText)
494
-
495
- if (this.options.includeResponseBody) {
496
- try {
497
- const body = await this.captureResponseBody(response)
498
- if (body !== undefined) {
499
- this.addSpanTag(spanId, 'http.response_body', body)
500
- }
501
- }
502
- catch (err) {
503
- this.addSpanLog(spanId, 'warn', 'Failed to capture response body', { error: String(err) })
504
- }
505
- }
506
-
507
- this.addSpanLog(spanId, 'info', 'Request completed', {
508
- status: response.status,
509
- statusText: response.statusText,
510
- })
511
-
512
- // Mark as error if status code is 4xx or 5xx
513
- const isError = response.status >= 400
514
- if (isError) {
515
- this.addSpanTag(spanId, 'error', true)
516
- this.addSpanTag(spanId, 'error.status_code', response.status)
517
- }
518
-
519
- this.finishSpan(spanId, isError ? 'error' : 'ok', isError ? `HTTP ${response.status}` : undefined)
520
- }
521
- catch (err) {
522
- error = err instanceof Error ? err.message : String(err)
523
- this.addSpanTag(spanId, 'error', true)
524
- this.addSpanTag(spanId, 'error.message', error)
525
- this.addSpanTag(spanId, 'error.type', err instanceof Error ? err.constructor.name : 'Unknown')
526
- this.addSpanLog(spanId, 'error', 'Request failed', { error })
527
-
528
- // Ensure the span is properly finished with error status
529
- this.finishSpan(spanId, 'error', error)
530
-
531
- // Force immediate export of this error span
532
- const errorSpan = this.spans.get(spanId)
533
- if (errorSpan) {
534
- // Make sure it's finished
535
- if (errorSpan.endTime === undefined) {
536
- errorSpan.endTime = performance.now()
537
- errorSpan.duration = errorSpan.endTime - errorSpan.startTime
538
- errorSpan.status = 'error'
539
- errorSpan.error = error
540
- }
541
-
542
- // Add to export queue and remove from spans
543
- this.exportQueue.push(errorSpan)
544
- this.spans.delete(spanId)
545
-
546
- // Force immediate export
547
- this.exportSpans().catch((exportErr) => {
548
- console.warn('Failed to export error span:', exportErr)
549
- })
550
- }
551
-
552
- response = new Response('Internal Server Error', { status: 500 })
553
- }
554
-
555
- // Cleanup
556
- this.activeSpans.delete(requestId)
557
-
558
- // Add trace headers to response for propagation
559
- if (this.options.propagation?.enabled) {
560
- response.headers.set('x-trace-id', traceId)
561
- response.headers.set('x-span-id', spanId)
562
- }
563
-
564
- return response
565
- }
566
-
567
- // Public API methods
568
- getActiveSpans(): TraceSpan[] {
569
- return Array.from(this.spans.values())
570
- }
571
-
572
- getSpanById(spanId: string): TraceSpan | undefined {
573
- return this.spans.get(spanId)
574
- }
575
-
576
- createChildSpan(parentSpanId: string, operationName: string): string | null {
577
- const parentSpan = this.spans.get(parentSpanId)
578
- if (!parentSpan)
579
- return null
580
-
581
- const childSpanId = this.generateId()
582
- const childSpan = this.createSpan(
583
- parentSpan.traceId,
584
- childSpanId,
585
- operationName,
586
- parentSpanId,
587
- )
588
-
589
- this.spans.set(childSpanId, childSpan)
590
- return childSpanId
591
- }
592
-
593
- addTag(spanId: string, key: string, value: any): void {
594
- this.addSpanTag(spanId, key, value)
595
- }
596
-
597
- addLog(spanId: string, level: 'debug' | 'info' | 'warn' | 'error', message: string, fields?: Record<string, any>): void {
598
- this.addSpanLog(spanId, level, message, fields)
599
- }
600
-
601
- finish(spanId: string, status: 'ok' | 'error' | 'timeout' = 'ok', error?: string): void {
602
- this.finishSpan(spanId, status, error)
603
- }
604
-
605
- async flush(): Promise<void> {
606
- // Force all active spans to be finished and exported
607
- const activeSpanIds = Array.from(this.spans.keys())
608
- console.warn(`[RequestTracer] Flushing ${activeSpanIds.length} active spans`)
609
-
610
- // Finish any active spans
611
- for (const spanId of activeSpanIds) {
612
- const span = this.spans.get(spanId)
613
- if (span && !span.endTime) {
614
- this.finishSpan(spanId, 'ok')
615
- }
616
- }
617
-
618
- // Export all spans in the queue
619
- await this.exportSpans()
620
- }
621
-
622
- destroy(): void {
623
- if (this.exportInterval) {
624
- clearInterval(this.exportInterval)
625
- }
626
- this.spans.clear()
627
- this.activeSpans.clear()
628
- this.exportQueue = []
629
- }
630
- }
631
-
632
- // Factory function for easy use
633
- export function requestTracer(options: TracingOptions = {}): (req: EnhancedRequest, next: NextFunction) => Promise<Response> {
634
- const instance = new RequestTracer(options)
635
- return async (req: EnhancedRequest, next: NextFunction) => instance.handle(req, next)
636
- }