@stacksjs/bun-router 0.0.16 → 0.0.18

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 (176) hide show
  1. package/dist/auth.d.ts +22 -8
  2. package/dist/chunk-1ahs68ys.js +18 -0
  3. package/dist/{chunk-0145g1me.js → chunk-cgptvjdf.js} +147 -75
  4. package/dist/chunk-g3ybefhg.js +1923 -0
  5. package/dist/cli.js +3 -2
  6. package/dist/container/container.d.ts +1 -0
  7. package/dist/container/contextual-binding.d.ts +0 -1
  8. package/dist/container/decorators.d.ts +2 -5
  9. package/dist/container/index.d.ts +16 -0
  10. package/dist/container/index.js +322 -0
  11. package/dist/container/service-provider.d.ts +3 -3
  12. package/dist/development/performance-profiler.d.ts +3 -3
  13. package/dist/development/route-debugger.d.ts +1 -1
  14. package/dist/development/route-inspector.d.ts +2 -2
  15. package/dist/file-serving/static-files.d.ts +16 -0
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +1159 -1380
  18. package/dist/middleware/cors.d.ts +9 -0
  19. package/dist/middleware/csrf.d.ts +7 -0
  20. package/dist/middleware/ddos_protection.d.ts +16 -1
  21. package/dist/middleware/rate_limit.d.ts +7 -1
  22. package/dist/middleware/request_tracer.d.ts +15 -9
  23. package/dist/middleware/response_cache.d.ts +2 -1
  24. package/dist/observability/integration.d.ts +1 -1
  25. package/dist/request/context.d.ts +12 -1
  26. package/dist/request/macros.d.ts +40 -2
  27. package/dist/response/macros.d.ts +4 -4
  28. package/dist/router/fluent-routing.d.ts +50 -13
  29. package/dist/router/handler-resolver.d.ts +8 -0
  30. package/dist/router/index.d.ts +9 -7
  31. package/dist/router/route-compiler.d.ts +8 -10
  32. package/dist/router/route-trie.d.ts +7 -1
  33. package/dist/router/router.d.ts +13 -34
  34. package/dist/router/validation-integration.d.ts +10 -4
  35. package/dist/testing/performance-testing.d.ts +2 -2
  36. package/dist/testing/test-client.d.ts +1 -1
  37. package/dist/testing/websocket-testing.d.ts +1 -1
  38. package/dist/types/middleware-types.d.ts +1 -1
  39. package/dist/types/route-inference.d.ts +9 -2
  40. package/dist/types.d.ts +62 -9
  41. package/dist/utils.d.ts +1 -1
  42. package/package.json +12 -3
  43. package/dist/router/fluent-router.d.ts +0 -315
  44. package/src/auth.ts +0 -469
  45. package/src/cache/lru-cache.ts +0 -457
  46. package/src/cache/middleware-memoization.ts +0 -531
  47. package/src/cache/route-cache-warmer.ts +0 -486
  48. package/src/cache/sqlite-cache.ts +0 -783
  49. package/src/cache/streaming-cache.ts +0 -572
  50. package/src/cli/colors.ts +0 -29
  51. package/src/cli/index.ts +0 -287
  52. package/src/cli/middleware.ts +0 -291
  53. package/src/cli/openapi.ts +0 -407
  54. package/src/cli/router.ts +0 -188
  55. package/src/cli/routes.ts +0 -265
  56. package/src/cli/utils.ts +0 -531
  57. package/src/cli.ts +0 -5
  58. package/src/config.ts +0 -322
  59. package/src/container/container.ts +0 -740
  60. package/src/container/contextual-binding.ts +0 -603
  61. package/src/container/decorators.ts +0 -359
  62. package/src/container/service-provider.ts +0 -596
  63. package/src/development/hot-reload.ts +0 -673
  64. package/src/development/index.ts +0 -499
  65. package/src/development/performance-profiler.ts +0 -717
  66. package/src/development/route-debugger.ts +0 -527
  67. package/src/development/route-inspector.ts +0 -749
  68. package/src/development/typescript-utilities.ts +0 -682
  69. package/src/docs.ts +0 -397
  70. package/src/errors/circuit-breaker.ts +0 -732
  71. package/src/errors/error-handler.ts +0 -569
  72. package/src/errors/error-reporting.ts +0 -672
  73. package/src/errors/exceptions.ts +0 -536
  74. package/src/errors/graceful-degradation.ts +0 -621
  75. package/src/errors/index.ts +0 -21
  76. package/src/errors/router-errors.ts +0 -632
  77. package/src/file-serving/static-files.ts +0 -581
  78. package/src/index.ts +0 -14
  79. package/src/middleware/auth.ts +0 -220
  80. package/src/middleware/content_security_policy.ts +0 -215
  81. package/src/middleware/cors.ts +0 -74
  82. package/src/middleware/csrf.ts +0 -118
  83. package/src/middleware/ddos_protection.ts +0 -255
  84. package/src/middleware/file_security.ts +0 -191
  85. package/src/middleware/file_upload.ts +0 -275
  86. package/src/middleware/helmet.ts +0 -268
  87. package/src/middleware/index.ts +0 -117
  88. package/src/middleware/input_validation.ts +0 -449
  89. package/src/middleware/json_body.ts +0 -37
  90. package/src/middleware/performance_alerting.ts +0 -538
  91. package/src/middleware/performance_dashboard.ts +0 -661
  92. package/src/middleware/performance_monitor.ts +0 -943
  93. package/src/middleware/pipeline.ts +0 -489
  94. package/src/middleware/rate_limit.ts +0 -245
  95. package/src/middleware/request_id.ts +0 -36
  96. package/src/middleware/request_signing.ts +0 -636
  97. package/src/middleware/request_tracer.ts +0 -636
  98. package/src/middleware/response_cache.ts +0 -743
  99. package/src/middleware/security.ts +0 -482
  100. package/src/middleware/security_suite.ts +0 -257
  101. package/src/middleware/session.ts +0 -91
  102. package/src/model-binding/index.ts +0 -18
  103. package/src/model-binding/model-middleware.ts +0 -425
  104. package/src/model-binding/model-registry.ts +0 -550
  105. package/src/model-binding.ts +0 -370
  106. package/src/model-resolver-factory.ts +0 -106
  107. package/src/observability/correlation.ts +0 -691
  108. package/src/observability/health-checks.ts +0 -729
  109. package/src/observability/index.ts +0 -184
  110. package/src/observability/integration.ts +0 -548
  111. package/src/observability/metrics.ts +0 -753
  112. package/src/observability/tracing.ts +0 -638
  113. package/src/optimization/bun-utilities.ts +0 -778
  114. package/src/query-builder-integration.ts +0 -137
  115. package/src/request/context.ts +0 -62
  116. package/src/request/enhanced-request.ts +0 -857
  117. package/src/request/macros.ts +0 -688
  118. package/src/response/macros.ts +0 -665
  119. package/src/response/response-factory.ts +0 -596
  120. package/src/router/api-routes.ts +0 -243
  121. package/src/router/file-based-routing.ts +0 -690
  122. package/src/router/file-streaming.ts +0 -383
  123. package/src/router/fluent-router.ts +0 -927
  124. package/src/router/fluent-routing.ts +0 -797
  125. package/src/router/group-organization.ts +0 -213
  126. package/src/router/handler-resolver.ts +0 -291
  127. package/src/router/http-methods.ts +0 -377
  128. package/src/router/index.ts +0 -187
  129. package/src/router/middleware-groups.ts +0 -222
  130. package/src/router/middleware-integration.ts +0 -399
  131. package/src/router/middleware.ts +0 -231
  132. package/src/router/model-binding.ts +0 -215
  133. package/src/router/optimized-route-matching.ts +0 -253
  134. package/src/router/route-building.ts +0 -221
  135. package/src/router/route-compiler.ts +0 -702
  136. package/src/router/route-matching.ts +0 -349
  137. package/src/router/route-trie.ts +0 -464
  138. package/src/router/router.ts +0 -1604
  139. package/src/router/server.ts +0 -462
  140. package/src/router/validation-integration.ts +0 -443
  141. package/src/router/view-rendering.ts +0 -233
  142. package/src/router/websocket.ts +0 -100
  143. package/src/routing/route-caching.ts +0 -402
  144. package/src/routing/route-throttling.ts +0 -469
  145. package/src/routing/subdomain-routing.ts +0 -492
  146. package/src/session/database-store.ts +0 -109
  147. package/src/session/file-store.ts +0 -148
  148. package/src/session/index.ts +0 -244
  149. package/src/session/memory-store.ts +0 -88
  150. package/src/session/redis-store.ts +0 -93
  151. package/src/streaming/index.ts +0 -17
  152. package/src/streaming/sse-handler.ts +0 -482
  153. package/src/streaming/stream-handler.ts +0 -552
  154. package/src/testing/auth-testing.ts +0 -446
  155. package/src/testing/file-upload-testing.ts +0 -543
  156. package/src/testing/index.ts +0 -10
  157. package/src/testing/middleware-testing.ts +0 -322
  158. package/src/testing/model-binding-testing.ts +0 -645
  159. package/src/testing/performance-testing.ts +0 -738
  160. package/src/testing/test-client.ts +0 -310
  161. package/src/testing/test-request.ts +0 -315
  162. package/src/testing/test-response.ts +0 -332
  163. package/src/testing/types.ts +0 -224
  164. package/src/testing/websocket-testing.ts +0 -590
  165. package/src/types/controller-types.ts +0 -385
  166. package/src/types/core.ts +0 -683
  167. package/src/types/middleware-types.ts +0 -419
  168. package/src/types/request-response-augmentation.ts +0 -489
  169. package/src/types/route-inference.ts +0 -357
  170. package/src/types.ts +0 -2067
  171. package/src/url.ts +0 -126
  172. package/src/utils/index.ts +0 -1
  173. package/src/utils/query-preservation.ts +0 -201
  174. package/src/utils.ts +0 -392
  175. package/src/validation/validator.ts +0 -685
  176. package/src/websocket/clustering.ts +0 -762
@@ -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()