@stacksjs/bun-router 0.0.14 → 0.0.15
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.
- package/README.md +261 -584
- package/bin/cli.ts +9 -0
- package/dist/auth.d.ts +134 -0
- package/dist/cache/lru-cache.d.ts +139 -0
- package/dist/cache/middleware-memoization.d.ts +151 -0
- package/dist/cache/route-cache-warmer.d.ts +161 -0
- package/dist/cache/sqlite-cache.d.ts +209 -0
- package/dist/cache/streaming-cache.d.ts +132 -0
- package/dist/chunk-j0e7z7hd.js +18053 -0
- package/dist/cli/colors.d.ts +15 -0
- package/dist/cli/index.d.ts +10 -0
- package/dist/cli/middleware.d.ts +31 -0
- package/dist/cli/openapi.d.ts +17 -0
- package/dist/cli/router.d.ts +15 -0
- package/dist/cli/routes.d.ts +29 -0
- package/dist/cli/utils.d.ts +74 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +3360 -0
- package/dist/config.d.ts +7 -0
- package/dist/container/container.d.ts +273 -0
- package/dist/container/contextual-binding.d.ts +240 -0
- package/dist/container/decorators.d.ts +141 -0
- package/dist/container/service-provider.d.ts +285 -0
- package/dist/development/hot-reload.d.ts +187 -0
- package/dist/development/index.d.ts +167 -0
- package/dist/development/performance-profiler.d.ts +217 -0
- package/dist/development/route-debugger.d.ts +154 -0
- package/dist/development/route-inspector.d.ts +211 -0
- package/dist/development/typescript-utilities.d.ts +209 -0
- package/dist/docs.d.ts +11 -0
- package/dist/errors/circuit-breaker.d.ts +195 -0
- package/dist/errors/error-handler.d.ts +88 -0
- package/dist/errors/error-reporting.d.ts +144 -0
- package/dist/errors/exceptions.d.ts +184 -0
- package/dist/errors/graceful-degradation.d.ts +154 -0
- package/dist/errors/index.d.ts +9 -0
- package/dist/errors/router-errors.d.ts +110 -0
- package/dist/file-serving/static-files.d.ts +143 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +13968 -0
- package/dist/middleware/auth.d.ts +63 -0
- package/dist/middleware/content_security_policy.d.ts +53 -0
- package/dist/middleware/cors.d.ts +5 -0
- package/dist/middleware/csrf.d.ts +7 -0
- package/dist/middleware/ddos_protection.d.ts +39 -0
- package/dist/middleware/file_security.d.ts +26 -0
- package/dist/middleware/file_upload.d.ts +38 -0
- package/dist/middleware/helmet.d.ts +54 -0
- package/dist/middleware/index.d.ts +44 -0
- package/dist/middleware/input_validation.d.ts +45 -0
- package/dist/middleware/json_body.d.ts +4 -0
- package/dist/middleware/performance_alerting.d.ts +87 -0
- package/dist/middleware/performance_dashboard.d.ts +87 -0
- package/dist/middleware/performance_monitor.d.ts +209 -0
- package/dist/middleware/pipeline.d.ts +131 -0
- package/dist/middleware/rate_limit.d.ts +36 -0
- package/dist/middleware/request_id.d.ts +4 -0
- package/dist/middleware/request_signing.d.ts +153 -0
- package/dist/middleware/request_tracer.d.ts +72 -0
- package/dist/middleware/response_cache.d.ts +97 -0
- package/dist/middleware/security.d.ts +69 -0
- package/dist/middleware/security_suite.d.ts +46 -0
- package/dist/middleware/session.d.ts +23 -0
- package/dist/model-binding/index.d.ts +2 -0
- package/dist/model-binding/model-middleware.d.ts +118 -0
- package/dist/model-binding/model-registry.d.ts +164 -0
- package/dist/model-binding.d.ts +185 -0
- package/dist/model-resolver-factory.d.ts +31 -0
- package/dist/observability/correlation.d.ts +187 -0
- package/dist/observability/health-checks.d.ts +186 -0
- package/dist/observability/index.d.ts +60 -0
- package/dist/observability/integration.d.ts +147 -0
- package/dist/observability/metrics.d.ts +184 -0
- package/dist/observability/tracing.d.ts +187 -0
- package/dist/optimization/bun-utilities.d.ts +224 -0
- package/dist/query-builder-integration.d.ts +36 -0
- package/dist/request/context.d.ts +34 -0
- package/dist/request/enhanced-request.d.ts +213 -0
- package/dist/request/macros.d.ts +300 -0
- package/dist/response/macros.d.ts +256 -0
- package/dist/response/response-factory.d.ts +133 -0
- package/dist/router/api-routes.d.ts +5 -0
- package/dist/router/file-based-routing.d.ts +118 -0
- package/dist/router/file-streaming.d.ts +5 -0
- package/dist/router/fluent-router.d.ts +315 -0
- package/dist/router/fluent-routing.d.ts +271 -0
- package/dist/router/group-organization.d.ts +5 -0
- package/dist/router/handler-resolver.d.ts +24 -0
- package/dist/router/http-methods.d.ts +10 -0
- package/dist/router/index.d.ts +114 -0
- package/dist/router/middleware-groups.d.ts +94 -0
- package/dist/router/middleware-integration.d.ts +112 -0
- package/dist/router/middleware.d.ts +5 -0
- package/dist/router/model-binding.d.ts +5 -0
- package/dist/router/optimized-route-matching.d.ts +6 -0
- package/dist/router/route-building.d.ts +5 -0
- package/dist/router/route-compiler.d.ts +153 -0
- package/dist/router/route-matching.d.ts +5 -0
- package/dist/router/route-trie.d.ts +114 -0
- package/dist/router/router.d.ts +317 -0
- package/dist/router/server.d.ts +5 -0
- package/dist/router/validation-integration.d.ts +170 -0
- package/dist/router/view-rendering.d.ts +5 -0
- package/dist/router/websocket.d.ts +5 -0
- package/dist/routing/route-caching.d.ts +129 -0
- package/dist/routing/route-throttling.d.ts +150 -0
- package/dist/routing/subdomain-routing.d.ts +206 -0
- package/dist/session/database-store.d.ts +51 -0
- package/dist/session/file-store.d.ts +22 -0
- package/dist/session/index.d.ts +106 -0
- package/dist/session/memory-store.d.ts +21 -0
- package/dist/session/redis-store.d.ts +31 -0
- package/dist/streaming/index.d.ts +3 -0
- package/dist/streaming/sse-handler.d.ts +138 -0
- package/dist/streaming/stream-handler.d.ts +114 -0
- package/dist/testing/auth-testing.d.ts +156 -0
- package/dist/testing/file-upload-testing.d.ts +190 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/middleware-testing.d.ts +138 -0
- package/dist/testing/model-binding-testing.d.ts +186 -0
- package/dist/testing/performance-testing.d.ts +235 -0
- package/dist/testing/test-client.d.ts +117 -0
- package/dist/testing/test-request.d.ts +85 -0
- package/dist/testing/test-response.d.ts +90 -0
- package/dist/testing/types.d.ts +207 -0
- package/dist/testing/websocket-testing.d.ts +227 -0
- package/dist/types/controller-types.d.ts +208 -0
- package/dist/types/core.d.ts +543 -0
- package/dist/types/middleware-types.d.ts +227 -0
- package/dist/types/request-response-augmentation.d.ts +261 -0
- package/dist/types/route-inference.d.ts +168 -0
- package/dist/types.d.ts +1794 -0
- package/dist/url.d.ts +56 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/query-preservation.d.ts +48 -0
- package/dist/utils.d.ts +69 -0
- package/dist/validation/validator.d.ts +140 -0
- package/dist/websocket/clustering.d.ts +185 -0
- package/package.json +45 -44
- package/src/auth.ts +469 -0
- package/src/cache/lru-cache.ts +457 -0
- package/src/cache/middleware-memoization.ts +531 -0
- package/src/cache/route-cache-warmer.ts +486 -0
- package/src/cache/sqlite-cache.ts +783 -0
- package/src/cache/streaming-cache.ts +572 -0
- package/src/cli/colors.ts +29 -0
- package/src/cli/index.ts +287 -0
- package/src/cli/middleware.ts +291 -0
- package/src/cli/openapi.ts +407 -0
- package/src/cli/router.ts +188 -0
- package/src/cli/routes.ts +265 -0
- package/src/cli/utils.ts +531 -0
- package/src/cli.ts +5 -0
- package/src/config.ts +322 -0
- package/src/container/container.ts +740 -0
- package/src/container/contextual-binding.ts +603 -0
- package/src/container/decorators.ts +359 -0
- package/src/container/service-provider.ts +596 -0
- package/src/development/hot-reload.ts +673 -0
- package/src/development/index.ts +499 -0
- package/src/development/performance-profiler.ts +717 -0
- package/src/development/route-debugger.ts +527 -0
- package/src/development/route-inspector.ts +749 -0
- package/src/development/typescript-utilities.ts +682 -0
- package/src/docs.ts +397 -0
- package/src/errors/circuit-breaker.ts +732 -0
- package/src/errors/error-handler.ts +569 -0
- package/src/errors/error-reporting.ts +672 -0
- package/src/errors/exceptions.ts +536 -0
- package/src/errors/graceful-degradation.ts +621 -0
- package/src/errors/index.ts +21 -0
- package/src/errors/router-errors.ts +632 -0
- package/src/file-serving/static-files.ts +581 -0
- package/src/index.ts +14 -0
- package/src/middleware/auth.ts +220 -0
- package/src/middleware/content_security_policy.ts +215 -0
- package/src/middleware/cors.ts +74 -0
- package/src/middleware/csrf.ts +108 -0
- package/src/middleware/ddos_protection.ts +255 -0
- package/src/middleware/file_security.ts +191 -0
- package/src/middleware/file_upload.ts +275 -0
- package/src/middleware/helmet.ts +268 -0
- package/src/middleware/index.ts +117 -0
- package/src/middleware/input_validation.ts +449 -0
- package/src/middleware/json_body.ts +37 -0
- package/src/middleware/performance_alerting.ts +538 -0
- package/src/middleware/performance_dashboard.ts +661 -0
- package/src/middleware/performance_monitor.ts +943 -0
- package/src/middleware/pipeline.ts +489 -0
- package/src/middleware/rate_limit.ts +245 -0
- package/src/middleware/request_id.ts +36 -0
- package/src/middleware/request_signing.ts +636 -0
- package/src/middleware/request_tracer.ts +636 -0
- package/src/middleware/response_cache.ts +743 -0
- package/src/middleware/security.ts +482 -0
- package/src/middleware/security_suite.ts +257 -0
- package/src/middleware/session.ts +91 -0
- package/src/model-binding/index.ts +18 -0
- package/src/model-binding/model-middleware.ts +425 -0
- package/src/model-binding/model-registry.ts +550 -0
- package/src/model-binding.ts +370 -0
- package/src/model-resolver-factory.ts +106 -0
- package/src/observability/correlation.ts +691 -0
- package/src/observability/health-checks.ts +729 -0
- package/src/observability/index.ts +184 -0
- package/src/observability/integration.ts +548 -0
- package/src/observability/metrics.ts +753 -0
- package/src/observability/tracing.ts +638 -0
- package/src/optimization/bun-utilities.ts +778 -0
- package/src/query-builder-integration.ts +137 -0
- package/src/request/context.ts +62 -0
- package/src/request/enhanced-request.ts +857 -0
- package/src/request/macros.ts +688 -0
- package/src/response/macros.ts +665 -0
- package/src/response/response-factory.ts +596 -0
- package/src/router/api-routes.ts +243 -0
- package/src/router/file-based-routing.ts +690 -0
- package/src/router/file-streaming.ts +383 -0
- package/src/router/fluent-router.ts +927 -0
- package/src/router/fluent-routing.ts +797 -0
- package/src/router/group-organization.ts +213 -0
- package/src/router/handler-resolver.ts +291 -0
- package/src/router/http-methods.ts +377 -0
- package/src/router/index.ts +187 -0
- package/src/router/middleware-groups.ts +222 -0
- package/src/router/middleware-integration.ts +399 -0
- package/src/router/middleware.ts +231 -0
- package/src/router/model-binding.ts +215 -0
- package/src/router/optimized-route-matching.ts +253 -0
- package/src/router/route-building.ts +221 -0
- package/src/router/route-compiler.ts +702 -0
- package/src/router/route-matching.ts +349 -0
- package/src/router/route-trie.ts +464 -0
- package/src/router/router.ts +1604 -0
- package/src/router/server.ts +462 -0
- package/src/router/validation-integration.ts +443 -0
- package/src/router/view-rendering.ts +233 -0
- package/src/router/websocket.ts +100 -0
- package/src/routing/route-caching.ts +402 -0
- package/src/routing/route-throttling.ts +469 -0
- package/src/routing/subdomain-routing.ts +492 -0
- package/src/session/database-store.ts +109 -0
- package/src/session/file-store.ts +148 -0
- package/src/session/index.ts +244 -0
- package/src/session/memory-store.ts +88 -0
- package/src/session/redis-store.ts +93 -0
- package/src/streaming/index.ts +17 -0
- package/src/streaming/sse-handler.ts +482 -0
- package/src/streaming/stream-handler.ts +552 -0
- package/src/testing/auth-testing.ts +446 -0
- package/src/testing/file-upload-testing.ts +543 -0
- package/src/testing/index.ts +10 -0
- package/src/testing/middleware-testing.ts +322 -0
- package/src/testing/model-binding-testing.ts +645 -0
- package/src/testing/performance-testing.ts +738 -0
- package/src/testing/test-client.ts +310 -0
- package/src/testing/test-request.ts +315 -0
- package/src/testing/test-response.ts +332 -0
- package/src/testing/types.ts +224 -0
- package/src/testing/websocket-testing.ts +590 -0
- package/src/types/controller-types.ts +385 -0
- package/src/types/core.ts +683 -0
- package/src/types/middleware-types.ts +419 -0
- package/src/types/request-response-augmentation.ts +489 -0
- package/src/types/route-inference.ts +357 -0
- package/src/types.ts +2067 -0
- package/src/url.ts +126 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/query-preservation.ts +201 -0
- package/src/utils.ts +327 -0
- package/src/validation/validator.ts +685 -0
- package/src/websocket/clustering.ts +762 -0
- package/CHANGELOG.md +0 -770
|
@@ -0,0 +1,489 @@
|
|
|
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()
|