@stacksjs/bun-router 0.0.17 → 0.0.19

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 (153) hide show
  1. package/dist/chunk-2mx7fq49.js +4 -0
  2. package/dist/chunk-a8p83068.js +103 -0
  3. package/dist/{chunk-cgptvjdf.js → chunk-y3xq6wq6.js} +1 -1
  4. package/dist/cli.js +4 -3
  5. package/dist/container/index.js +1149 -211
  6. package/dist/container/service-provider.d.ts +3 -3
  7. package/dist/development/performance-profiler.d.ts +3 -3
  8. package/dist/development/route-debugger.d.ts +1 -1
  9. package/dist/development/route-inspector.d.ts +2 -2
  10. package/dist/index.js +369 -2209
  11. package/dist/observability/integration.d.ts +1 -1
  12. package/dist/response/macros.d.ts +1 -1
  13. package/dist/router/index.d.ts +7 -7
  14. package/dist/router/router.d.ts +0 -32
  15. package/dist/testing/performance-testing.d.ts +2 -2
  16. package/dist/testing/test-client.d.ts +1 -1
  17. package/dist/testing/websocket-testing.d.ts +1 -1
  18. package/package.json +7 -7
  19. package/dist/chunk-1ahs68ys.js +0 -18
  20. package/dist/chunk-g3ybefhg.js +0 -1923
  21. package/src/auth.ts +0 -489
  22. package/src/cache/lru-cache.ts +0 -457
  23. package/src/cache/middleware-memoization.ts +0 -531
  24. package/src/cache/route-cache-warmer.ts +0 -486
  25. package/src/cache/sqlite-cache.ts +0 -783
  26. package/src/cache/streaming-cache.ts +0 -572
  27. package/src/cli/colors.ts +0 -29
  28. package/src/cli/index.ts +0 -287
  29. package/src/cli/middleware.ts +0 -291
  30. package/src/cli/openapi.ts +0 -407
  31. package/src/cli/router.ts +0 -188
  32. package/src/cli/routes.ts +0 -265
  33. package/src/cli/utils.ts +0 -531
  34. package/src/cli.ts +0 -5
  35. package/src/config.ts +0 -322
  36. package/src/container/container.ts +0 -786
  37. package/src/container/contextual-binding.ts +0 -606
  38. package/src/container/decorators.ts +0 -368
  39. package/src/container/index.ts +0 -49
  40. package/src/container/service-provider.ts +0 -596
  41. package/src/development/hot-reload.ts +0 -673
  42. package/src/development/index.ts +0 -499
  43. package/src/development/performance-profiler.ts +0 -717
  44. package/src/development/route-debugger.ts +0 -527
  45. package/src/development/route-inspector.ts +0 -749
  46. package/src/development/typescript-utilities.ts +0 -682
  47. package/src/docs.ts +0 -397
  48. package/src/errors/circuit-breaker.ts +0 -733
  49. package/src/errors/error-handler.ts +0 -569
  50. package/src/errors/error-reporting.ts +0 -672
  51. package/src/errors/exceptions.ts +0 -536
  52. package/src/errors/graceful-degradation.ts +0 -623
  53. package/src/errors/index.ts +0 -21
  54. package/src/errors/router-errors.ts +0 -632
  55. package/src/file-serving/static-files.ts +0 -718
  56. package/src/index.ts +0 -66
  57. package/src/middleware/auth.ts +0 -220
  58. package/src/middleware/content_security_policy.ts +0 -215
  59. package/src/middleware/cors.ts +0 -142
  60. package/src/middleware/csrf.ts +0 -166
  61. package/src/middleware/ddos_protection.ts +0 -279
  62. package/src/middleware/file_security.ts +0 -191
  63. package/src/middleware/file_upload.ts +0 -275
  64. package/src/middleware/helmet.ts +0 -268
  65. package/src/middleware/index.ts +0 -117
  66. package/src/middleware/input_validation.ts +0 -453
  67. package/src/middleware/json_body.ts +0 -37
  68. package/src/middleware/performance_alerting.ts +0 -540
  69. package/src/middleware/performance_dashboard.ts +0 -661
  70. package/src/middleware/performance_monitor.ts +0 -945
  71. package/src/middleware/pipeline.ts +0 -489
  72. package/src/middleware/rate_limit.ts +0 -251
  73. package/src/middleware/request_id.ts +0 -36
  74. package/src/middleware/request_signing.ts +0 -638
  75. package/src/middleware/request_tracer.ts +0 -653
  76. package/src/middleware/response_cache.ts +0 -778
  77. package/src/middleware/security.ts +0 -482
  78. package/src/middleware/security_suite.ts +0 -257
  79. package/src/middleware/session.ts +0 -91
  80. package/src/model-binding/index.ts +0 -18
  81. package/src/model-binding/model-middleware.ts +0 -425
  82. package/src/model-binding/model-registry.ts +0 -550
  83. package/src/model-binding.ts +0 -370
  84. package/src/model-resolver-factory.ts +0 -106
  85. package/src/observability/correlation.ts +0 -691
  86. package/src/observability/health-checks.ts +0 -729
  87. package/src/observability/index.ts +0 -184
  88. package/src/observability/integration.ts +0 -548
  89. package/src/observability/metrics.ts +0 -753
  90. package/src/observability/tracing.ts +0 -638
  91. package/src/optimization/bun-utilities.ts +0 -778
  92. package/src/query-builder-integration.ts +0 -137
  93. package/src/request/context.ts +0 -109
  94. package/src/request/enhanced-request.ts +0 -876
  95. package/src/request/macros.ts +0 -822
  96. package/src/response/macros.ts +0 -665
  97. package/src/response/response-factory.ts +0 -596
  98. package/src/router/api-routes.ts +0 -243
  99. package/src/router/file-based-routing.ts +0 -697
  100. package/src/router/file-streaming.ts +0 -383
  101. package/src/router/fluent-routing.ts +0 -866
  102. package/src/router/group-organization.ts +0 -229
  103. package/src/router/handler-resolver.ts +0 -327
  104. package/src/router/http-methods.ts +0 -407
  105. package/src/router/index.ts +0 -193
  106. package/src/router/middleware-groups.ts +0 -222
  107. package/src/router/middleware-integration.ts +0 -399
  108. package/src/router/middleware.ts +0 -234
  109. package/src/router/model-binding.ts +0 -215
  110. package/src/router/optimized-route-matching.ts +0 -302
  111. package/src/router/route-building.ts +0 -221
  112. package/src/router/route-compiler.ts +0 -691
  113. package/src/router/route-matching.ts +0 -368
  114. package/src/router/route-trie.ts +0 -450
  115. package/src/router/router.ts +0 -1616
  116. package/src/router/server.ts +0 -684
  117. package/src/router/validation-integration.ts +0 -449
  118. package/src/router/view-rendering.ts +0 -233
  119. package/src/router/websocket.ts +0 -100
  120. package/src/routing/route-caching.ts +0 -402
  121. package/src/routing/route-throttling.ts +0 -469
  122. package/src/routing/subdomain-routing.ts +0 -492
  123. package/src/session/database-store.ts +0 -109
  124. package/src/session/file-store.ts +0 -148
  125. package/src/session/index.ts +0 -244
  126. package/src/session/memory-store.ts +0 -88
  127. package/src/session/redis-store.ts +0 -93
  128. package/src/streaming/index.ts +0 -17
  129. package/src/streaming/sse-handler.ts +0 -482
  130. package/src/streaming/stream-handler.ts +0 -552
  131. package/src/testing/auth-testing.ts +0 -448
  132. package/src/testing/file-upload-testing.ts +0 -543
  133. package/src/testing/index.ts +0 -10
  134. package/src/testing/middleware-testing.ts +0 -322
  135. package/src/testing/model-binding-testing.ts +0 -645
  136. package/src/testing/performance-testing.ts +0 -738
  137. package/src/testing/test-client.ts +0 -310
  138. package/src/testing/test-request.ts +0 -315
  139. package/src/testing/test-response.ts +0 -332
  140. package/src/testing/types.ts +0 -224
  141. package/src/testing/websocket-testing.ts +0 -590
  142. package/src/types/controller-types.ts +0 -385
  143. package/src/types/core.ts +0 -683
  144. package/src/types/middleware-types.ts +0 -422
  145. package/src/types/request-response-augmentation.ts +0 -489
  146. package/src/types/route-inference.ts +0 -372
  147. package/src/types.ts +0 -2123
  148. package/src/url.ts +0 -131
  149. package/src/utils/index.ts +0 -1
  150. package/src/utils/query-preservation.ts +0 -201
  151. package/src/utils.ts +0 -395
  152. package/src/validation/validator.ts +0 -688
  153. package/src/websocket/clustering.ts +0 -769
@@ -1,489 +0,0 @@
1
- import type { EnhancedRequest, MiddlewareHandler, NextFunction } from '../types'
2
- import process from 'node:process'
3
-
4
- /**
5
- * Middleware pipeline with composition caching, conditional execution,
6
- * dependency injection, and short-circuiting capabilities
7
- */
8
-
9
- export interface MiddlewareContext {
10
- request: EnhancedRequest
11
- route?: any
12
- skipConditions?: MiddlewareSkipCondition[]
13
- dependencies?: Map<string, any>
14
- metadata?: Record<string, any>
15
- }
16
-
17
- export interface MiddlewareSkipCondition {
18
- name: string
19
- condition: (context: MiddlewareContext) => boolean | Promise<boolean>
20
- }
21
-
22
- export interface MiddlewareDependency {
23
- name: string
24
- factory: (context: MiddlewareContext) => any | Promise<any>
25
- singleton?: boolean
26
- dependencies?: string[]
27
- }
28
-
29
- export interface CompiledMiddleware {
30
- handler: MiddlewareHandler
31
- name: string
32
- skipConditions: MiddlewareSkipCondition[]
33
- dependencies: string[]
34
- canShortCircuit: boolean
35
- priority: number
36
- }
37
-
38
- export interface MiddlewarePipelineStats {
39
- totalExecutions: number
40
- cacheHits: number
41
- cacheMisses: number
42
- shortCircuits: number
43
- skippedMiddleware: number
44
- averageExecutionTime: number
45
- dependencyResolutions: number
46
- }
47
-
48
- /**
49
- * Middleware pipeline with advanced optimization features
50
- */
51
- export class MiddlewarePipeline {
52
- private compiledPipelines = new Map<string, CompiledMiddleware[]>()
53
- private dependencyRegistry = new Map<string, MiddlewareDependency>()
54
- private singletonInstances = new Map<string, any>()
55
- private stats: MiddlewarePipelineStats = {
56
- totalExecutions: 0,
57
- cacheHits: 0,
58
- cacheMisses: 0,
59
- shortCircuits: 0,
60
- skippedMiddleware: 0,
61
- averageExecutionTime: 0,
62
- dependencyResolutions: 0,
63
- }
64
-
65
- /**
66
- * Register a dependency for injection into middleware
67
- */
68
- registerDependency(dependency: MiddlewareDependency): void {
69
- this.dependencyRegistry.set(dependency.name, dependency)
70
- }
71
-
72
- /**
73
- * Compile middleware chain for a specific route
74
- */
75
- compileMiddleware(
76
- routeKey: string,
77
- middleware: MiddlewareHandler[],
78
- skipConditions: MiddlewareSkipCondition[] = [],
79
- ): void {
80
- const compiled: CompiledMiddleware[] = []
81
-
82
- for (let i = 0; i < middleware.length; i++) {
83
- const handler = middleware[i]
84
- const name = handler.name || `middleware_${i}`
85
-
86
- compiled.push({
87
- handler,
88
- name,
89
- skipConditions: skipConditions.filter(condition =>
90
- condition.name.includes(name) || condition.name === 'global',
91
- ),
92
- dependencies: this.extractDependencies(handler),
93
- canShortCircuit: this.canShortCircuit(handler),
94
- priority: i,
95
- })
96
- }
97
-
98
- this.compiledPipelines.set(routeKey, compiled)
99
- }
100
-
101
- /**
102
- * Execute compiled middleware pipeline
103
- */
104
- async execute(
105
- routeKey: string,
106
- request: EnhancedRequest,
107
- finalHandler: () => Promise<Response>,
108
- ): Promise<Response> {
109
- const startTime = performance.now()
110
- this.stats.totalExecutions++
111
-
112
- const pipeline = this.compiledPipelines.get(routeKey)
113
- if (!pipeline) {
114
- this.stats.cacheMisses++
115
- return await finalHandler()
116
- }
117
-
118
- this.stats.cacheHits++
119
-
120
- const context: MiddlewareContext = {
121
- request,
122
- dependencies: new Map(),
123
- metadata: {},
124
- }
125
-
126
- // Resolve dependencies
127
- await this.resolveDependencies(context, pipeline)
128
-
129
- // Execute middleware chain
130
- let currentIndex = 0
131
-
132
- const next: NextFunction = async (): Promise<Response | null> => {
133
- if (currentIndex >= pipeline.length) {
134
- return await finalHandler()
135
- }
136
-
137
- const middleware = pipeline[currentIndex++]
138
-
139
- // Check skip conditions
140
- if (await this.shouldSkip(middleware, context)) {
141
- this.stats.skippedMiddleware++
142
- return await next()
143
- }
144
-
145
- // Execute middleware
146
- const result = await middleware.handler(request, next)
147
-
148
- // Handle short-circuiting
149
- if (result instanceof Response && middleware.canShortCircuit) {
150
- this.stats.shortCircuits++
151
- return result
152
- }
153
-
154
- return result
155
- }
156
-
157
- const result = await next()
158
- const executionTime = performance.now() - startTime
159
- this.updateAverageExecutionTime(executionTime)
160
-
161
- return result || new Response('Internal Server Error', { status: 500 })
162
- }
163
-
164
- /**
165
- * Check if middleware should be skipped
166
- */
167
- private async shouldSkip(
168
- middleware: CompiledMiddleware,
169
- context: MiddlewareContext,
170
- ): Promise<boolean> {
171
- for (const skipCondition of middleware.skipConditions) {
172
- if (await skipCondition.condition(context)) {
173
- return true
174
- }
175
- }
176
- return false
177
- }
178
-
179
- /**
180
- * Resolve dependencies for middleware
181
- */
182
- private async resolveDependencies(
183
- context: MiddlewareContext,
184
- pipeline: CompiledMiddleware[],
185
- ): Promise<void> {
186
- const allDependencies = new Set<string>()
187
-
188
- for (const middleware of pipeline) {
189
- for (const dep of middleware.dependencies) {
190
- allDependencies.add(dep)
191
- }
192
- }
193
-
194
- for (const depName of allDependencies) {
195
- const dependency = this.dependencyRegistry.get(depName)
196
- if (!dependency)
197
- continue
198
-
199
- this.stats.dependencyResolutions++
200
-
201
- if (dependency.singleton && this.singletonInstances.has(depName)) {
202
- context.dependencies!.set(depName, this.singletonInstances.get(depName))
203
- }
204
- else {
205
- const instance = await dependency.factory(context)
206
- context.dependencies!.set(depName, instance)
207
-
208
- if (dependency.singleton) {
209
- this.singletonInstances.set(depName, instance)
210
- }
211
- }
212
- }
213
- }
214
-
215
- /**
216
- * Extract dependency names from middleware function
217
- */
218
- private extractDependencies(handler: MiddlewareHandler): string[] {
219
- // Simple dependency extraction based on function parameters
220
- const funcStr = handler.toString()
221
- const dependencies: string[] = []
222
-
223
- // Look for common dependency patterns
224
- if (funcStr.includes('database') || funcStr.includes('db'))
225
- dependencies.push('database')
226
- if (funcStr.includes('logger') || funcStr.includes('log'))
227
- dependencies.push('logger')
228
- if (funcStr.includes('cache'))
229
- dependencies.push('cache')
230
- if (funcStr.includes('httpClient') || funcStr.includes('http'))
231
- dependencies.push('httpClient')
232
-
233
- return dependencies
234
- }
235
-
236
- /**
237
- * Check if middleware can short-circuit the pipeline
238
- */
239
- private canShortCircuit(handler: MiddlewareHandler): boolean {
240
- const funcStr = handler.toString()
241
- return funcStr.includes('return') && funcStr.includes('Response')
242
- }
243
-
244
- /**
245
- * Update average execution time
246
- */
247
- private updateAverageExecutionTime(executionTime: number): void {
248
- const totalTime = this.stats.averageExecutionTime * (this.stats.totalExecutions - 1)
249
- this.stats.averageExecutionTime = (totalTime + executionTime) / this.stats.totalExecutions
250
- }
251
-
252
- /**
253
- * Get pipeline statistics
254
- */
255
- getStats(): MiddlewarePipelineStats {
256
- return { ...this.stats }
257
- }
258
-
259
- /**
260
- * Clear compiled pipelines and reset stats
261
- */
262
- clear(): void {
263
- this.compiledPipelines.clear()
264
- this.singletonInstances.clear()
265
- this.stats = {
266
- totalExecutions: 0,
267
- cacheHits: 0,
268
- cacheMisses: 0,
269
- shortCircuits: 0,
270
- skippedMiddleware: 0,
271
- averageExecutionTime: 0,
272
- dependencyResolutions: 0,
273
- }
274
- }
275
- }
276
-
277
- /**
278
- * Skip condition factory functions
279
- */
280
- export const SkipConditions = {
281
- skipForMethods: (methods: string[]): MiddlewareSkipCondition => ({
282
- name: `skip_for_methods_${methods.join('_')}`,
283
- condition: context => methods.includes(context.request.method),
284
- }),
285
-
286
- skipForPaths: (paths: string[]): MiddlewareSkipCondition => ({
287
- name: `skip_for_paths_${paths.join('_').replace(/\//g, '_')}`,
288
- condition: (context) => {
289
- const url = new URL(context.request.url)
290
- return paths.some(path => url.pathname.startsWith(path))
291
- },
292
- }),
293
-
294
- skipForHeaders: (headers: Record<string, string>): MiddlewareSkipCondition => ({
295
- name: `skip_for_headers_${Object.keys(headers).join('_')}`,
296
- condition: (context) => {
297
- return Object.entries(headers).some(([key, value]) =>
298
- context.request.headers.get(key) === value,
299
- )
300
- },
301
- }),
302
-
303
- skipForRoles: (roles: string[]): MiddlewareSkipCondition => ({
304
- name: `skip_for_roles_${roles.join('_')}`,
305
- condition: (context) => {
306
- const userRoles = context.request.user?.roles || []
307
- return !roles.some(role => userRoles.includes(role))
308
- },
309
- }),
310
-
311
- skipForEnvironment: (environments: string[]): MiddlewareSkipCondition => ({
312
- name: `skip_for_env_${environments.join('_')}`,
313
- condition: () => {
314
- const env = process.env.NODE_ENV || 'development'
315
- return environments.includes(env)
316
- },
317
- }),
318
- }
319
-
320
- /**
321
- * Dependency factory functions
322
- */
323
- export const Dependencies = {
324
- database: (connectionString?: string): MiddlewareDependency => ({
325
- name: 'database',
326
- factory: async () => {
327
- // Mock database connection
328
- return {
329
- query: async (_sql: string) => ({ rows: [] }),
330
- close: async () => {},
331
- connectionString: connectionString || 'mock://database',
332
- }
333
- },
334
- singleton: true,
335
- }),
336
-
337
- logger: (level: string = 'info'): MiddlewareDependency => ({
338
- name: 'logger',
339
- factory: () => ({
340
- info: (msg: string) => console.log(`[INFO] ${msg}`),
341
- error: (msg: string) => console.error(`[ERROR] ${msg}`),
342
- warn: (msg: string) => console.warn(`[WARN] ${msg}`),
343
- debug: (msg: string) => console.debug(`[DEBUG] ${msg}`),
344
- level,
345
- }),
346
- singleton: true,
347
- }),
348
-
349
- cache: (maxSize: number = 1000): MiddlewareDependency => ({
350
- name: 'cache',
351
- factory: () => {
352
- const cache = new Map()
353
- return {
354
- get: (key: string) => cache.get(key),
355
- set: (key: string, value: any) => {
356
- if (cache.size >= maxSize) {
357
- const firstKey = cache.keys().next().value
358
- cache.delete(firstKey)
359
- }
360
- cache.set(key, value)
361
- },
362
- delete: (key: string) => cache.delete(key),
363
- clear: () => cache.clear(),
364
- size: () => cache.size,
365
- }
366
- },
367
- singleton: true,
368
- }),
369
-
370
- httpClient: (baseURL?: string): MiddlewareDependency => ({
371
- name: 'httpClient',
372
- factory: () => ({
373
- get: async (url: string) => fetch(baseURL ? `${baseURL}${url}` : url),
374
- post: async (url: string, _data: any) =>
375
- fetch(baseURL ? `${baseURL}${url}` : url, {
376
- method: 'POST',
377
- headers: { 'Content-Type': 'application/json' },
378
- body: JSON.stringify(_data),
379
- }),
380
- put: async (url: string, _data: any) =>
381
- fetch(baseURL ? `${baseURL}${url}` : url, {
382
- method: 'PUT',
383
- headers: { 'Content-Type': 'application/json' },
384
- body: JSON.stringify(_data),
385
- }),
386
- delete: async (url: string) =>
387
- fetch(baseURL ? `${baseURL}${url}` : url, { method: 'DELETE' }),
388
- }),
389
- singleton: true,
390
- }),
391
- }
392
-
393
- /**
394
- * Middleware factory functions
395
- */
396
- export const MiddlewareFactory = {
397
- auth: (options: { secret?: string, skipPaths?: string[] } = {}): MiddlewareHandler => {
398
- return async (req, next) => {
399
- const url = new URL(req.url)
400
- if (options.skipPaths?.some(path => url.pathname.startsWith(path))) {
401
- return await next()
402
- }
403
-
404
- const token = req.headers.get('Authorization')?.replace('Bearer ', '')
405
- if (!token) {
406
- return new Response('Unauthorized', { status: 401 })
407
- }
408
-
409
- // Mock JWT verification
410
- try {
411
- ;(req as any).user = { id: '123', roles: ['user'] }
412
- return await next()
413
- }
414
- catch {
415
- return new Response('Invalid token', { status: 401 })
416
- }
417
- }
418
- },
419
-
420
- rateLimit: (options: { maxRequests: number, windowMs: number }): MiddlewareHandler => {
421
- const requests = new Map<string, number[]>()
422
-
423
- return async (req, next) => {
424
- const ip = req.headers.get('x-forwarded-for') || 'unknown'
425
- const now = Date.now()
426
- const windowStart = now - options.windowMs
427
-
428
- if (!requests.has(ip)) {
429
- requests.set(ip, [])
430
- }
431
-
432
- const userRequests = requests.get(ip)!
433
- const recentRequests = userRequests.filter(time => time > windowStart)
434
-
435
- if (recentRequests.length >= options.maxRequests) {
436
- return new Response('Too Many Requests', { status: 429 })
437
- }
438
-
439
- recentRequests.push(now)
440
- requests.set(ip, recentRequests)
441
-
442
- return await next()
443
- }
444
- },
445
-
446
- cors: (options: { origin?: string, methods?: string[] } = {}): MiddlewareHandler => {
447
- return async (_req, next) => {
448
- const response = await next()
449
-
450
- if (response) {
451
- const headers = new Headers(response.headers)
452
- headers.set('Access-Control-Allow-Origin', options.origin || '*')
453
- headers.set('Access-Control-Allow-Methods', options.methods?.join(', ') || 'GET, POST, PUT, DELETE')
454
- headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
455
-
456
- return new Response(response.body, {
457
- status: response.status,
458
- statusText: response.statusText,
459
- headers,
460
- })
461
- }
462
-
463
- return response
464
- }
465
- },
466
-
467
- logging: (_options: { level?: string } = {}): MiddlewareHandler => {
468
- return async (req, next) => {
469
- const start = performance.now()
470
- const url = new URL(req.url)
471
-
472
- console.log(`[${new Date().toISOString()}] ${req.method} ${url.pathname}`)
473
-
474
- const response = await next()
475
- const duration = performance.now() - start
476
-
477
- if (response) {
478
- console.log(`[${new Date().toISOString()}] ${req.method} ${url.pathname} - ${response.status} (${duration.toFixed(2)}ms)`)
479
- }
480
-
481
- return response
482
- }
483
- },
484
- }
485
-
486
- /**
487
- * Global middleware pipeline instance
488
- */
489
- export const globalMiddlewarePipeline: MiddlewarePipeline = new MiddlewarePipeline()