@stacksjs/bun-router 0.0.17 → 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 (146) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/container/service-provider.d.ts +3 -3
  3. package/dist/development/performance-profiler.d.ts +3 -3
  4. package/dist/development/route-debugger.d.ts +1 -1
  5. package/dist/development/route-inspector.d.ts +2 -2
  6. package/dist/observability/integration.d.ts +1 -1
  7. package/dist/response/macros.d.ts +1 -1
  8. package/dist/router/index.d.ts +7 -7
  9. package/dist/router/router.d.ts +0 -32
  10. package/dist/testing/performance-testing.d.ts +2 -2
  11. package/dist/testing/test-client.d.ts +1 -1
  12. package/dist/testing/websocket-testing.d.ts +1 -1
  13. package/package.json +2 -3
  14. package/src/auth.ts +0 -489
  15. package/src/cache/lru-cache.ts +0 -457
  16. package/src/cache/middleware-memoization.ts +0 -531
  17. package/src/cache/route-cache-warmer.ts +0 -486
  18. package/src/cache/sqlite-cache.ts +0 -783
  19. package/src/cache/streaming-cache.ts +0 -572
  20. package/src/cli/colors.ts +0 -29
  21. package/src/cli/index.ts +0 -287
  22. package/src/cli/middleware.ts +0 -291
  23. package/src/cli/openapi.ts +0 -407
  24. package/src/cli/router.ts +0 -188
  25. package/src/cli/routes.ts +0 -265
  26. package/src/cli/utils.ts +0 -531
  27. package/src/cli.ts +0 -5
  28. package/src/config.ts +0 -322
  29. package/src/container/container.ts +0 -786
  30. package/src/container/contextual-binding.ts +0 -606
  31. package/src/container/decorators.ts +0 -368
  32. package/src/container/index.ts +0 -49
  33. package/src/container/service-provider.ts +0 -596
  34. package/src/development/hot-reload.ts +0 -673
  35. package/src/development/index.ts +0 -499
  36. package/src/development/performance-profiler.ts +0 -717
  37. package/src/development/route-debugger.ts +0 -527
  38. package/src/development/route-inspector.ts +0 -749
  39. package/src/development/typescript-utilities.ts +0 -682
  40. package/src/docs.ts +0 -397
  41. package/src/errors/circuit-breaker.ts +0 -733
  42. package/src/errors/error-handler.ts +0 -569
  43. package/src/errors/error-reporting.ts +0 -672
  44. package/src/errors/exceptions.ts +0 -536
  45. package/src/errors/graceful-degradation.ts +0 -623
  46. package/src/errors/index.ts +0 -21
  47. package/src/errors/router-errors.ts +0 -632
  48. package/src/file-serving/static-files.ts +0 -718
  49. package/src/index.ts +0 -66
  50. package/src/middleware/auth.ts +0 -220
  51. package/src/middleware/content_security_policy.ts +0 -215
  52. package/src/middleware/cors.ts +0 -142
  53. package/src/middleware/csrf.ts +0 -166
  54. package/src/middleware/ddos_protection.ts +0 -279
  55. package/src/middleware/file_security.ts +0 -191
  56. package/src/middleware/file_upload.ts +0 -275
  57. package/src/middleware/helmet.ts +0 -268
  58. package/src/middleware/index.ts +0 -117
  59. package/src/middleware/input_validation.ts +0 -453
  60. package/src/middleware/json_body.ts +0 -37
  61. package/src/middleware/performance_alerting.ts +0 -540
  62. package/src/middleware/performance_dashboard.ts +0 -661
  63. package/src/middleware/performance_monitor.ts +0 -945
  64. package/src/middleware/pipeline.ts +0 -489
  65. package/src/middleware/rate_limit.ts +0 -251
  66. package/src/middleware/request_id.ts +0 -36
  67. package/src/middleware/request_signing.ts +0 -638
  68. package/src/middleware/request_tracer.ts +0 -653
  69. package/src/middleware/response_cache.ts +0 -778
  70. package/src/middleware/security.ts +0 -482
  71. package/src/middleware/security_suite.ts +0 -257
  72. package/src/middleware/session.ts +0 -91
  73. package/src/model-binding/index.ts +0 -18
  74. package/src/model-binding/model-middleware.ts +0 -425
  75. package/src/model-binding/model-registry.ts +0 -550
  76. package/src/model-binding.ts +0 -370
  77. package/src/model-resolver-factory.ts +0 -106
  78. package/src/observability/correlation.ts +0 -691
  79. package/src/observability/health-checks.ts +0 -729
  80. package/src/observability/index.ts +0 -184
  81. package/src/observability/integration.ts +0 -548
  82. package/src/observability/metrics.ts +0 -753
  83. package/src/observability/tracing.ts +0 -638
  84. package/src/optimization/bun-utilities.ts +0 -778
  85. package/src/query-builder-integration.ts +0 -137
  86. package/src/request/context.ts +0 -109
  87. package/src/request/enhanced-request.ts +0 -876
  88. package/src/request/macros.ts +0 -822
  89. package/src/response/macros.ts +0 -665
  90. package/src/response/response-factory.ts +0 -596
  91. package/src/router/api-routes.ts +0 -243
  92. package/src/router/file-based-routing.ts +0 -697
  93. package/src/router/file-streaming.ts +0 -383
  94. package/src/router/fluent-routing.ts +0 -866
  95. package/src/router/group-organization.ts +0 -229
  96. package/src/router/handler-resolver.ts +0 -327
  97. package/src/router/http-methods.ts +0 -407
  98. package/src/router/index.ts +0 -193
  99. package/src/router/middleware-groups.ts +0 -222
  100. package/src/router/middleware-integration.ts +0 -399
  101. package/src/router/middleware.ts +0 -234
  102. package/src/router/model-binding.ts +0 -215
  103. package/src/router/optimized-route-matching.ts +0 -302
  104. package/src/router/route-building.ts +0 -221
  105. package/src/router/route-compiler.ts +0 -691
  106. package/src/router/route-matching.ts +0 -368
  107. package/src/router/route-trie.ts +0 -450
  108. package/src/router/router.ts +0 -1616
  109. package/src/router/server.ts +0 -684
  110. package/src/router/validation-integration.ts +0 -449
  111. package/src/router/view-rendering.ts +0 -233
  112. package/src/router/websocket.ts +0 -100
  113. package/src/routing/route-caching.ts +0 -402
  114. package/src/routing/route-throttling.ts +0 -469
  115. package/src/routing/subdomain-routing.ts +0 -492
  116. package/src/session/database-store.ts +0 -109
  117. package/src/session/file-store.ts +0 -148
  118. package/src/session/index.ts +0 -244
  119. package/src/session/memory-store.ts +0 -88
  120. package/src/session/redis-store.ts +0 -93
  121. package/src/streaming/index.ts +0 -17
  122. package/src/streaming/sse-handler.ts +0 -482
  123. package/src/streaming/stream-handler.ts +0 -552
  124. package/src/testing/auth-testing.ts +0 -448
  125. package/src/testing/file-upload-testing.ts +0 -543
  126. package/src/testing/index.ts +0 -10
  127. package/src/testing/middleware-testing.ts +0 -322
  128. package/src/testing/model-binding-testing.ts +0 -645
  129. package/src/testing/performance-testing.ts +0 -738
  130. package/src/testing/test-client.ts +0 -310
  131. package/src/testing/test-request.ts +0 -315
  132. package/src/testing/test-response.ts +0 -332
  133. package/src/testing/types.ts +0 -224
  134. package/src/testing/websocket-testing.ts +0 -590
  135. package/src/types/controller-types.ts +0 -385
  136. package/src/types/core.ts +0 -683
  137. package/src/types/middleware-types.ts +0 -422
  138. package/src/types/request-response-augmentation.ts +0 -489
  139. package/src/types/route-inference.ts +0 -372
  140. package/src/types.ts +0 -2123
  141. package/src/url.ts +0 -131
  142. package/src/utils/index.ts +0 -1
  143. package/src/utils/query-preservation.ts +0 -201
  144. package/src/utils.ts +0 -395
  145. package/src/validation/validator.ts +0 -688
  146. package/src/websocket/clustering.ts +0 -769
package/src/types.ts DELETED
@@ -1,2123 +0,0 @@
1
- import type { Server } from 'bun'
2
- import type { Router } from './router/router'
3
- import type { SessionManager } from './session/index'
4
- import type { QueryPreservationConfig } from './utils/query-preservation'
5
- import type {
6
- AuthContext,
7
- AuthenticatedUser,
8
- BoundModels,
9
- CacheAdapter,
10
- CacheStats,
11
- CookieToDelete,
12
- CookieToSet,
13
- ErrorMetadata,
14
- FallbackError,
15
- FileInfo,
16
- FlashMessages,
17
- FormBody,
18
- InputValidationSchemas,
19
- InputValue,
20
- JsonBodyData,
21
- JwtHeader,
22
- JwtPayload,
23
- MetricEntry,
24
- MiddlewareParams,
25
- OAuth2Flows,
26
- OAuth2Profile,
27
- RequestContext,
28
- RequestInput,
29
- RouteMetadata,
30
- SanitizationOptions,
31
- SanitizationRule,
32
- SessionData,
33
- SessionSerializer,
34
- SessionStore,
35
- SSEConnection,
36
- StaticResponseBody,
37
- TemplateHelper,
38
- TemplateHelpers,
39
- TraceAttributes,
40
- TraceSpan,
41
- TypedServerWebSocket,
42
- User,
43
- ValidatedBody,
44
- ValidatedData,
45
- ValidationSchema,
46
- WebSocketData,
47
- } from './types/core'
48
-
49
- // Re-export query preservation types
50
- export type { QueryPreservationConfig } from './utils/query-preservation'
51
-
52
- // Re-export core types
53
- export type {
54
- AuthContext,
55
- AuthenticatedUser,
56
- BoundModels,
57
- CacheAdapter,
58
- CacheStats,
59
- CookieToDelete,
60
- CookieToSet,
61
- ErrorMetadata,
62
- FallbackError,
63
- FileInfo,
64
- FlashMessages,
65
- FormBody,
66
- InputValidationSchemas,
67
- InputValue,
68
- JsonBodyData,
69
- JwtHeader,
70
- JwtPayload,
71
- MetricEntry,
72
- MiddlewareParams,
73
- OAuth2Flows,
74
- OAuth2Profile,
75
- RequestContext,
76
- RequestInput,
77
- RouteMetadata,
78
- SanitizationOptions,
79
- SanitizationRule,
80
- SessionData,
81
- SessionSerializer,
82
- SessionStore,
83
- SSEConnection,
84
- StaticResponseBody,
85
- TemplateHelper,
86
- TemplateHelpers,
87
- TraceAttributes,
88
- TraceSpan,
89
- TypedServerWebSocket,
90
- User,
91
- ValidatedBody,
92
- ValidatedData,
93
- ValidationSchema,
94
- WebSocketData,
95
- }
96
-
97
- export interface Contact {
98
- name?: string
99
- email?: string
100
- url?: string
101
- }
102
-
103
- export interface SecurityScheme {
104
- type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect'
105
- scheme?: string
106
- bearerFormat?: string
107
- name?: string
108
- in?: 'header' | 'query' | 'cookie'
109
- flows?: OAuth2Flows
110
- }
111
-
112
- export interface DocsConfig {
113
- output: string
114
- groupBy: 'path' | 'method' | 'tag'
115
- includeExamples: boolean
116
- title: string
117
- description: string
118
- version: string
119
- baseUrl: string
120
- contact?: Contact
121
- security?: Record<string, SecurityScheme>
122
- }
123
-
124
- export interface CorsConfig {
125
- enabled?: boolean
126
- origin?: string | string[]
127
- methods?: string[]
128
- allowedHeaders?: string[]
129
- exposedHeaders?: string[]
130
- credentials?: boolean
131
- maxAge?: number
132
- preflightContinue?: boolean
133
- optionsSuccessStatus?: number
134
- privateNetworkAccess?: boolean
135
- }
136
-
137
- export interface RateLimitConfig {
138
- enabled?: boolean
139
- max?: number
140
- timeWindow?: number
141
- message?: string
142
- draftMode?: boolean
143
- advanced?: {
144
- tokensPerInterval?: number
145
- interval?: number
146
- burst?: number
147
- skipFailedRequests?: boolean
148
- keyGenerator?: (req: Request) => string
149
- algorithm?: 'fixed-window' | 'sliding-window' | 'token-bucket'
150
- }
151
- stores?: {
152
- type: 'memory' | 'redis'
153
- redis?: {
154
- url: string
155
- prefix?: string
156
- }
157
- }
158
- }
159
-
160
- export interface CompressionConfig {
161
- enabled: boolean
162
- level: number
163
- threshold: number
164
- }
165
-
166
- export interface StaticConfig {
167
- enabled: boolean
168
- dir: string
169
- maxAge: number
170
- }
171
-
172
- export interface CacheConfig {
173
- enabled: boolean
174
- type: CacheType
175
- ttl: number
176
- max?: number
177
- redis?: {
178
- url: string
179
- prefix: string
180
- maxRetries: number
181
- connectTimeout: number
182
- cluster?: {
183
- nodes: string[]
184
- options?: {
185
- scaleReads: 'master' | 'slave' | 'all'
186
- maxRedirections: number
187
- }
188
- }
189
- }
190
- customAdapter?: CacheAdapter<unknown>
191
- routeCache?: {
192
- enabled: boolean
193
- ttl: number
194
- methods: string[]
195
- excludePaths: string[]
196
- varyByHeaders: string[]
197
- varyByQuery: string[]
198
- maxSize?: number
199
- purgeConditions?: {
200
- maxAge: number
201
- maxItems: number
202
- lowMemory: boolean
203
- }
204
- }
205
- strategies?: {
206
- [key: string]: {
207
- type: CacheStrategy
208
- ttl: number
209
- staleWhileRevalidateTtl?: number
210
- }
211
- }
212
- }
213
-
214
- export interface PerformanceConfig {
215
- cache: CacheConfig
216
- prefetch: {
217
- enabled: boolean
218
- paths: string[]
219
- maxConcurrent: number
220
- preloadPatterns?: string[]
221
- warmupStrategy?: 'gradual' | 'aggressive'
222
- prefetchHeaders?: Record<string, string>
223
- }
224
- optimization: {
225
- minify: boolean
226
- compress: boolean
227
- treeshake: boolean
228
- lazyLoad: boolean
229
- chunkSize: number
230
- imageOptimization?: {
231
- enabled: boolean
232
- quality: number
233
- formats: ('webp' | 'avif' | 'jpeg' | 'png')[]
234
- maxWidth: number
235
- responsive: boolean
236
- }
237
- fontOptimization?: {
238
- enabled: boolean
239
- inlineSize: number
240
- preload: boolean
241
- formats: ('woff2' | 'woff')[]
242
- }
243
- cssOptimization?: {
244
- minify: boolean
245
- purge: boolean
246
- splitChunks: boolean
247
- criticalPath: boolean
248
- }
249
- }
250
- monitoring?: {
251
- enabled?: boolean
252
- sampleRate?: number
253
- metrics?: {
254
- responseTime?: boolean
255
- memoryUsage?: boolean
256
- cpuUsage?: boolean
257
- errorRate?: boolean
258
- requestRate?: boolean
259
- cacheStats?: boolean
260
- }
261
- tracing?: {
262
- enabled?: boolean
263
- sampleRate?: number
264
- serviceName?: string
265
- serviceVersion?: string
266
- environment?: string
267
- jaegerEndpoint?: string
268
- zipkinEndpoint?: string
269
- }
270
- storage?: {
271
- type?: CacheType
272
- maxEntries?: number
273
- filePath?: string
274
- customHandler?: (metrics: MetricEntry[]) => Promise<void>
275
- }
276
- alerting?: {
277
- enabled?: boolean
278
- thresholds?: {
279
- responseTime?: number
280
- errorRate?: number
281
- memoryUsage?: number
282
- }
283
- webhookUrl?: string
284
- slackWebhook?: string
285
- emailConfig?: {
286
- smtp?: {
287
- host?: string
288
- port?: number
289
- secure?: boolean
290
- auth?: {
291
- user?: string
292
- pass?: string
293
- }
294
- }
295
- to?: string[]
296
- from?: string
297
- cache: boolean
298
- queue: boolean
299
- }
300
- }
301
- profiling?: {
302
- enabled: boolean
303
- sampleRate: number
304
- includeHeapSnapshot: boolean
305
- gcStats: boolean
306
- }
307
- logging: {
308
- level: 'debug' | 'info' | 'warn' | 'error'
309
- format: 'json' | 'pretty'
310
- destination: 'console' | 'file'
311
- rotation?: {
312
- size: string
313
- interval: string
314
- maxFiles: number
315
- }
316
- }
317
- }
318
- }
319
-
320
- export interface LoadBalancerConfig {
321
- enabled: boolean
322
- strategy: 'round-robin' | 'least-connections' | 'ip-hash' | 'weighted-round-robin' | 'fastest-response'
323
- healthCheck: {
324
- enabled: boolean
325
- interval: number
326
- timeout: number
327
- unhealthyThreshold: number
328
- healthyThreshold: number
329
- path: string
330
- expectedStatus?: number
331
- expectedBody?: string
332
- headers?: Record<string, string>
333
- }
334
- sticky: {
335
- enabled: boolean
336
- cookieName: string
337
- ttl: number
338
- secret?: string
339
- path?: string
340
- domain?: string
341
- }
342
- retries: {
343
- attempts: number
344
- timeout: number
345
- codes: number[]
346
- backoff?: {
347
- type: 'fixed' | 'exponential' | 'fibonacci'
348
- initialDelay: number
349
- maxDelay: number
350
- factor: number
351
- }
352
- }
353
- nodes?: {
354
- [key: string]: {
355
- url: string
356
- weight?: number
357
- backup?: boolean
358
- maxFails?: number
359
- failTimeout?: number
360
- }
361
- }
362
- }
363
-
364
- export interface SecurityConfig {
365
- schemes: Record<string, SecurityScheme>
366
- rateLimit: RateLimitConfig & {
367
- advanced?: {
368
- tokensPerInterval: number
369
- interval: number
370
- burst?: number
371
- skipFailedRequests?: boolean
372
- keyGenerator?: (req: Request) => string
373
- }
374
- stores?: {
375
- type: 'memory' | 'redis'
376
- redis?: {
377
- url: string
378
- prefix: string
379
- }
380
- }
381
- }
382
- cors: CorsConfig & {
383
- preflightContinue?: boolean
384
- optionsSuccessStatus?: number
385
- privateNetworkAccess?: boolean
386
- exposedHeaders?: string[]
387
- }
388
- csrf: {
389
- enabled: boolean
390
- secret: string
391
- cookie: {
392
- name: string
393
- options: {
394
- httpOnly: boolean
395
- secure: boolean
396
- sameSite: 'strict' | 'lax' | 'none'
397
- }
398
- }
399
- ignoreMethods?: string[]
400
- ignorePaths?: string[]
401
- tokenLength?: number
402
- }
403
- helmet: {
404
- enabled: boolean
405
- contentSecurityPolicy: boolean | {
406
- directives: Record<string, string[]>
407
- reportOnly?: boolean
408
- reportUri?: string
409
- upgradeInsecureRequests?: boolean
410
- blockAllMixedContent?: boolean
411
- }
412
- crossOriginEmbedderPolicy?: boolean | {
413
- policy?: 'require-corp' | 'credentialless'
414
- }
415
- crossOriginOpenerPolicy?: boolean | {
416
- policy?: 'same-origin' | 'same-origin-allow-popups' | 'unsafe-none'
417
- }
418
- crossOriginResourcePolicy?: boolean | {
419
- policy?: 'same-site' | 'same-origin' | 'cross-origin'
420
- }
421
- dnsPrefetchControl?: boolean | {
422
- allow?: boolean
423
- }
424
- xssFilter: boolean | {
425
- setOnOldIE?: boolean
426
- }
427
- noSniff: boolean
428
- frameOptions: 'DENY' | 'SAMEORIGIN'
429
- hidePoweredBy: boolean
430
- hsts?: {
431
- maxAge: number
432
- includeSubDomains: boolean
433
- preload: boolean
434
- }
435
- referrerPolicy?: string | {
436
- policy?: string | string[]
437
- }
438
- expectCt?: {
439
- enforce: boolean
440
- maxAge: number
441
- reportUri?: string
442
- }
443
- ieNoOpen?: boolean
444
- originAgentCluster?: boolean
445
- permittedCrossDomainPolicies?: boolean | {
446
- permittedPolicies?: 'none' | 'master-only' | 'by-content-type' | 'all'
447
- }
448
- }
449
- ddos?: {
450
- enabled?: boolean
451
- maxRequestsPerSecond?: number
452
- maxRequestsPerMinute?: number
453
- maxRequestsPerHour?: number
454
- burstLimit?: number
455
- windowSize?: number
456
- blockDuration?: number
457
- whitelistedIPs?: string[]
458
- blacklistedIPs?: string[]
459
- trustProxy?: boolean
460
- skipSuccessfulRequests?: boolean
461
- skipFailedRequests?: boolean
462
- keyGenerator?: (req: Request) => string
463
- store?: Extract<CacheType, 'memory' | 'redis'>
464
- redis?: {
465
- url: string
466
- prefix?: string
467
- }
468
- }
469
- inputValidation?: {
470
- enabled?: boolean
471
- sanitizeByDefault?: boolean
472
- strictMode?: boolean
473
- allowUnknownFields?: boolean
474
- maxDepth?: number
475
- schemas?: InputValidationSchemas
476
- }
477
- attackPrevention?: {
478
- enabled?: boolean
479
- sqlInjection?: boolean
480
- xss?: boolean
481
- pathTraversal?: boolean
482
- commandInjection?: boolean
483
- ldapInjection?: boolean
484
- xxe?: boolean
485
- customPatterns?: {
486
- name: string
487
- pattern: RegExp
488
- action: 'block' | 'log' | 'sanitize'
489
- }[]
490
- }
491
- requestFiltering?: {
492
- enabled?: boolean
493
- blockSuspiciousPatterns?: boolean
494
- maxRequestsPerMinute?: number
495
- blockUserAgents?: string[]
496
- allowedMethods?: string[]
497
- requireUserAgent?: boolean
498
- maxBodySize?: number
499
- maxUrlLength?: number
500
- maxHeaderSize?: number
501
- allowedContentTypes?: string[]
502
- }
503
- ipFiltering?: {
504
- enabled?: boolean
505
- whitelist?: string[]
506
- blacklist?: string[]
507
- blockPrivateIPs?: boolean
508
- blockCloudProviders?: boolean
509
- geoBlocking?: {
510
- enabled?: boolean
511
- allowedCountries?: string[]
512
- blockedCountries?: string[]
513
- }
514
- }
515
- responseSecurity?: {
516
- enabled?: boolean
517
- removeServerHeaders?: boolean
518
- addSecurityHeaders?: boolean
519
- sanitizeErrors?: boolean
520
- preventInfoDisclosure?: boolean
521
- }
522
- auth: {
523
- jwt: {
524
- secret: string
525
- expiresIn: string
526
- algorithm: 'HS256' | 'HS384' | 'HS512' | 'RS256'
527
- issuer?: string
528
- audience?: string
529
- refreshToken?: {
530
- enabled: boolean
531
- expiresIn: string
532
- renewBeforeExpiry?: number
533
- }
534
- rotation?: {
535
- enabled: boolean
536
- interval: number
537
- maxAge: number
538
- }
539
- }
540
- session: {
541
- enabled: boolean
542
- secret: string
543
- name: string
544
- resave: boolean
545
- rolling: boolean
546
- saveUninitialized: boolean
547
- cookie: {
548
- maxAge: number
549
- secure: boolean
550
- httpOnly: boolean
551
- sameSite: 'strict' | 'lax' | 'none'
552
- domain?: string
553
- path?: string
554
- }
555
- store?: {
556
- type: CacheType
557
- redis?: {
558
- url: string
559
- prefix: string
560
- ttl?: number
561
- scanCount?: number
562
- serializer?: SessionSerializer
563
- }
564
- custom?: SessionStore
565
- }
566
- }
567
- oauth2?: {
568
- enabled: boolean
569
- providers: {
570
- [key: string]: {
571
- clientId: string
572
- clientSecret: string
573
- callbackURL: string
574
- scope: string[]
575
- authorizationURL?: string
576
- tokenURL?: string
577
- profileURL?: string
578
- validateProfile?: (profile: OAuth2Profile) => Promise<boolean>
579
- }
580
- }
581
- }
582
- }
583
- encryption?: {
584
- enabled: boolean
585
- algorithm: string
586
- key: string
587
- iv?: string
588
- encoding: 'hex' | 'base64'
589
- }
590
- sanitization?: {
591
- enabled: boolean
592
- rules: {
593
- [key: string]: {
594
- type: 'escape' | 'strip' | 'validate'
595
- options?: SanitizationOptions
596
- }
597
- }
598
- }
599
- }
600
-
601
- export interface ServerConfig {
602
- port: number
603
- hostname: string
604
- development: boolean
605
- cors: CorsConfig
606
- rateLimit: RateLimitConfig
607
- compression: CompressionConfig
608
- static: StaticConfig
609
- performance: PerformanceConfig
610
- loadBalancer?: LoadBalancerConfig
611
- security: SecurityConfig
612
- cluster: {
613
- enabled: boolean
614
- workers: number | 'auto'
615
- sticky: boolean
616
- strategy?: 'rr' | 'lc'
617
- maxMemory?: number
618
- restartOnMemory?: boolean
619
- ipcTimeout?: number
620
- }
621
- gracefulShutdown: {
622
- enabled: boolean
623
- timeout: number
624
- signals: string[]
625
- forceTimeout: number
626
- preShutdown?: () => Promise<void>
627
- drain?: {
628
- enabled: boolean
629
- timeout: number
630
- waitForStreams: boolean
631
- }
632
- }
633
- middleware: {
634
- errorHandler?: (error: Error, req: Request) => Promise<Response>
635
- notFound?: (req: Request) => Promise<Response>
636
- timeout?: number
637
- order?: string[]
638
- global?: MiddlewareHandler[]
639
- }
640
- hooks: {
641
- onStart?: () => Promise<void>
642
- onStop?: () => Promise<void>
643
- onRequest?: (req: Request) => Promise<Request | Response>
644
- onResponse?: (res: Response) => Promise<Response>
645
- onError?: (error: Error) => Promise<void>
646
- onMetric?: (metric: { name: string, value: number, tags?: Record<string, string> }) => Promise<void>
647
- onTrace?: (span: TraceSpan) => Promise<void>
648
- }
649
- experimental?: {
650
- http3: boolean
651
- webTransport: boolean
652
- earlyHints: boolean
653
- webSocket: {
654
- enabled: boolean
655
- compression?: boolean
656
- maxPayload?: number
657
- }
658
- }
659
- }
660
-
661
- export interface ViewEngineConfig {
662
- /**
663
- * The path to view files
664
- */
665
- viewsPath: string
666
- /**
667
- * File extensions to look for when resolving views
668
- */
669
- extensions: string[]
670
- /**
671
- * Default layout to use for views
672
- */
673
- defaultLayout?: string
674
- /**
675
- * Whether to cache compiled templates
676
- */
677
- cache: boolean
678
- /**
679
- * Template engine to use
680
- */
681
- engine: TemplateEngine
682
- /**
683
- * Custom render function for template processing
684
- */
685
- customRenderer?: (template: string, data: Record<string, any>, options: ViewRenderOptions) => Promise<string>
686
- /**
687
- * HTML minification options
688
- */
689
- minify?: {
690
- enabled: boolean
691
- options?: {
692
- removeComments?: boolean
693
- collapseWhitespace?: boolean
694
- conservativeCollapse?: boolean
695
- minifyJS?: boolean
696
- minifyCSS?: boolean
697
- }
698
- }
699
- /**
700
- * Template helpers
701
- */
702
- helpers?: TemplateHelpers
703
- }
704
-
705
- export interface ViewRenderOptions {
706
- layout?: string
707
- partials?: Record<string, string>
708
- components?: Record<string, string>
709
- helpers?: TemplateHelpers
710
- sections?: Record<string, string>
711
- }
712
-
713
- export interface RouterConfig {
714
- verbose: boolean
715
- routesPath?: string
716
- apiRoutesPath?: string
717
- webRoutesPath?: string
718
- apiPrefix?: string
719
- webPrefix?: string
720
- /**
721
- * Base path for action handlers (default: 'actions')
722
- * Used when resolving string-based handlers like 'UserAction.ts'
723
- */
724
- actionsPath?: string
725
- /**
726
- * Base path for controllers (default: 'controllers')
727
- * Used when resolving Controller@method patterns
728
- */
729
- controllersPath?: string
730
- defaultMiddleware?: {
731
- api?: (string | MiddlewareHandler)[]
732
- web?: (string | MiddlewareHandler)[]
733
- }
734
- /**
735
- * View engine configuration
736
- */
737
- views?: ViewEngineConfig
738
- docs?: DocsConfig
739
- server?: ServerConfig
740
- /**
741
- * Query parameter preservation configuration
742
- * Automatically preserves specified query parameters across navigation
743
- * @example
744
- * queryPreservation: {
745
- * preserve: ['siteId', 'theme', 'locale'],
746
- * exclude: ['_t', 'utm_source'],
747
- * routes: ['/dashboard/*', '/admin/*']
748
- * }
749
- */
750
- queryPreservation?: QueryPreservationConfig
751
- }
752
-
753
- export type RouterOptions = Partial<RouterConfig>
754
-
755
- export interface RouteParams {
756
- [key: string]: string
757
- }
758
-
759
- /**
760
- * Cookie map interface for working with cookies
761
- */
762
- export interface CookieMap {
763
- get: (name: string) => string | undefined
764
- set: (name: string, value: string, options?: CookieOptions) => void
765
- delete: (name: string, options?: Pick<CookieOptions, 'path' | 'domain'>) => void
766
- getAll: () => Record<string, string>
767
- }
768
-
769
- /**
770
- * Cookie options interface
771
- */
772
- export interface CookieOptions {
773
- maxAge?: number
774
- expires?: Date
775
- httpOnly?: boolean
776
- secure?: boolean
777
- path?: string
778
- domain?: string
779
- sameSite?: 'strict' | 'lax' | 'none'
780
- }
781
-
782
- /**
783
- * Cookie accessor interface with utility methods
784
- */
785
- export interface CookieAccessor {
786
- get: (name: string) => string | undefined
787
- set: (name: string, value: string, options?: CookieOptions) => void
788
- delete: (name: string, options?: CookieOptions) => void
789
- getAll: () => Record<string, string>
790
- }
791
-
792
- export interface EnhancedRequest extends Request, Omit<RequestMacroMethods, 'ip' | 'cookies' | 'route'> {
793
- /**
794
- * Route parameters extracted from the URL
795
- */
796
- params: Record<string, string>
797
- /**
798
- * Lookup a single route param. Equivalent to `request.params[name]` but
799
- * with optional default-value handling, matching the Laravel-style
800
- * `$request->route('name')` ergonomics.
801
- */
802
- getParam: <T = string>(name: string, defaultValue?: T) => T | undefined
803
- /**
804
- * Query parameters from the URL
805
- */
806
- query: Record<string, string | string[]>
807
- /**
808
- * Parsed JSON body (if Content-Type is application/json)
809
- */
810
- jsonBody?: Record<string, unknown>
811
- /**
812
- * Raw unparsed request body cache, populated on first `rawBody()` read (or up
813
- * front by a framework body parser). Kept so webhook signature checks get the
814
- * exact bytes the client sent.
815
- */
816
- _rawBody?: string
817
- /**
818
- * Form body data (if Content-Type is multipart/form-data or application/x-www-form-urlencoded)
819
- */
820
- formBody?: FormBody
821
- /**
822
- * Uploaded files (if Content-Type is multipart/form-data)
823
- */
824
- files?: UploadedFile[]
825
- /**
826
- * Session for the current request. The built-in session middleware
827
- * attaches a `SessionManager` (with `get`/`set`/`flash`/… methods);
828
- * testing utilities may attach plain `SessionData`.
829
- */
830
- session?: SessionManager | SessionData
831
- /**
832
- * User data (if authentication middleware is used)
833
- */
834
- user?: User
835
- /**
836
- * Additional context data that can be set by middleware
837
- */
838
- context?: RequestContext
839
- /**
840
- * Validated data from validation middleware
841
- */
842
- validated?: ValidatedData
843
- /**
844
- * Model binding data
845
- */
846
- models?: BoundModels
847
- /**
848
- * Model binding errors
849
- */
850
- modelErrors?: Record<string, string>
851
- /**
852
- * Authenticated user from auth middleware
853
- */
854
- auth?: AuthContext
855
- /**
856
- * Rate limiting information
857
- */
858
- rateLimitRemaining?: number
859
- /**
860
- * Request ID for tracing
861
- */
862
- requestId?: string
863
- /**
864
- * IP address of the client (string property, not function from RequestMacroMethods)
865
- */
866
- ip?: string
867
- /**
868
- * Cookies parsed from the request with utility methods
869
- */
870
- cookies?: CookieAccessor
871
- /**
872
- * Flash messages (temporary messages for the next request)
873
- */
874
- flash?: FlashMessages
875
- /**
876
- * CSRF token
877
- */
878
- csrfToken?: string
879
- /**
880
- * Request start time for performance monitoring
881
- */
882
- startTime?: number
883
- /**
884
- * Trace ID for distributed tracing
885
- */
886
- traceId?: string
887
- /**
888
- * Span ID for distributed tracing
889
- */
890
- spanId?: string
891
- /**
892
- * Security middleware additions
893
- */
894
- nonce?: string
895
- validatedBody?: ValidatedBody
896
- /**
897
- * Internal cookies to set in response (used by cookie utilities)
898
- */
899
- _cookiesToSet?: CookieToSet[]
900
- /**
901
- * Internal cookies to delete in response (used by cookie utilities)
902
- */
903
- _cookiesToDelete?: CookieToDelete[]
904
- /**
905
- * SSE connection information
906
- */
907
- sse?: SSEConnection
908
- /**
909
- * The matched route object
910
- */
911
- route?: Route
912
- }
913
-
914
- export interface UploadedFile {
915
- fieldName: string
916
- originalName: string
917
- filename: string
918
- path: string
919
- size: number
920
- mimetype: string
921
- buffer: ArrayBuffer
922
- }
923
-
924
- export type RouteHandler = (_req: EnhancedRequest) => Response | Promise<Response>
925
-
926
- /**
927
- * Interface for handling route actions.
928
- * All action handlers must implement this interface.
929
- */
930
- export interface ActionHandlerClass {
931
- /**
932
- * Handles an incoming HTTP request and returns a response.
933
- * @param request The incoming HTTP request
934
- * @returns A Promise that resolves to a Response object
935
- */
936
- handle: (request: EnhancedRequest) => Promise<Response>
937
- }
938
-
939
- /**
940
- * Action handler path with strict pattern validation
941
- */
942
- export type ActionPath = `Actions/${string}Action` | `actions/${string}Action` | `${string}Controller@${string}`
943
-
944
- /**
945
- * Strongly typed action handler with better type safety
946
- */
947
- export type ActionHandler<TPath extends string = string> =
948
- | ActionPath
949
- | TypedRouteHandler<TPath>
950
- | RouteHandler
951
- | (new () => ActionHandlerClass)
952
- | Response
953
-
954
- /**
955
- * Controller method reference with strict typing
956
- */
957
- export type ControllerMethod<
958
- TController extends string = string,
959
- TMethod extends string = string,
960
- > = `${TController}@${TMethod}`
961
-
962
- /**
963
- * Action class constructor with typed handle method
964
- */
965
- export interface TypedActionHandlerClass<TPath extends string = string> {
966
- handle: (request: EnhancedRequest & { params: ExtractRouteParams<TPath> }) => Promise<Response>
967
- }
968
-
969
- /**
970
- * Discriminated union for different action handler types
971
- */
972
- export type ActionHandlerVariant<TPath extends string = string> =
973
- | { type: 'path', value: ActionPath }
974
- | { type: 'function', value: TypedRouteHandler<TPath> }
975
- | { type: 'class', value: new () => TypedActionHandlerClass<TPath> }
976
- | { type: 'controller', value: ControllerMethod }
977
-
978
- export type NextFunction = () => Promise<Response | null> | Response | null
979
- export type MiddlewareHandler = (_req: EnhancedRequest, _next: NextFunction) => Promise<Response | null> | Response | null
980
-
981
- export interface Middleware {
982
- handle: MiddlewareHandler
983
- }
984
-
985
- /**
986
- * Strict middleware configuration with narrow types
987
- */
988
- export interface StrictMiddlewareConfig {
989
- name: BuiltInMiddleware
990
- enabled: boolean
991
- priority: number
992
- timing: MiddlewareTiming
993
- params?: Record<string, string | number | boolean>
994
- }
995
-
996
- /**
997
- * Conditional middleware with narrow type constraints
998
- */
999
- export interface ConditionalMiddleware<T extends BuiltInMiddleware = BuiltInMiddleware> {
1000
- name: T
1001
- condition: (req: EnhancedRequest) => boolean
1002
- handler: MiddlewareHandler
1003
- priority?: number
1004
- }
1005
-
1006
- /**
1007
- * Middleware group configuration with strict typing
1008
- */
1009
- export interface MiddlewareGroup {
1010
- name: string
1011
- middleware: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[]
1012
- priority: number
1013
- description?: string
1014
- }
1015
-
1016
- /**
1017
- * Throttle middleware parameters with narrow types
1018
- */
1019
- export interface ThrottleMiddlewareParams {
1020
- pattern: ThrottlePattern
1021
- name?: string
1022
- keyGenerator?: (req: EnhancedRequest) => string
1023
- skipIf?: (req: EnhancedRequest) => boolean
1024
- }
1025
-
1026
- /**
1027
- * CORS middleware configuration with strict options
1028
- */
1029
- export interface CorsMiddlewareConfig {
1030
- origin: string | string[] | boolean | ((_origin: string) => boolean)
1031
- methods: HTTPMethod[]
1032
- allowedHeaders: string[]
1033
- exposedHeaders?: string[]
1034
- credentials: boolean
1035
- maxAge: number
1036
- preflightContinue: boolean
1037
- optionsSuccessStatus: ResponseStatus
1038
- }
1039
-
1040
- /**
1041
- * Auth middleware configuration with narrow types
1042
- */
1043
- export interface AuthMiddlewareConfig {
1044
- type: 'jwt' | 'session' | 'apikey' | 'basic' | 'bearer'
1045
- required: boolean
1046
- realm?: string
1047
- validateUser?: (user: User) => boolean
1048
- onUnauthorized?: (req: EnhancedRequest) => Response
1049
- }
1050
-
1051
- export interface RouteGroup {
1052
- prefix?: string
1053
- middleware?: (string | MiddlewareHandler)[]
1054
- }
1055
-
1056
- export interface Route {
1057
- path: string
1058
- handler: ActionHandler
1059
- method: string
1060
- middleware: MiddlewareHandler[]
1061
- type?: 'api' | 'web'
1062
- name?: string
1063
- constraints?: Record<string, string> | ((_params: Record<string, string>) => boolean)[]
1064
- domain?: string
1065
- params?: Record<string, string>
1066
- pattern?: {
1067
- exec: (url: URL) => PatternMatchResult | null
1068
- }
1069
- /**
1070
- * Set to `false` (via `router.withoutNativeDispatch()`) to keep this
1071
- * route on the fetch-handler matcher even when the server runs with
1072
- * `nativeRoutes: true` — e.g. when it must respect registration-order
1073
- * precedence against an overlapping pattern.
1074
- */
1075
- nativeDispatch?: boolean
1076
- }
1077
-
1078
- /**
1079
- * WebSocket handler configuration
1080
- */
1081
- export interface WebSocketConfig<T extends WebSocketData = WebSocketData> {
1082
- open?: (ws: TypedServerWebSocket<T>) => void | Promise<void>
1083
- message: (ws: TypedServerWebSocket<T>, message: string | Uint8Array | ArrayBuffer) => void | Promise<void>
1084
- close?: (ws: TypedServerWebSocket<T>, code: number, reason: string) => void | Promise<void>
1085
- ping?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>
1086
- pong?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>
1087
- drain?: (ws: TypedServerWebSocket<T>) => void | Promise<void>
1088
- error?: (ws: TypedServerWebSocket<T>, error: Error) => void | Promise<void>
1089
- maxPayloadLength?: number
1090
- backpressureLimit?: number
1091
- closeOnBackpressureLimit?: boolean
1092
- idleTimeout?: number
1093
- perMessageDeflate?: boolean | {
1094
- compress?: boolean | Compressor
1095
- decompress?: boolean | Compressor
1096
- }
1097
- sendPings?: boolean
1098
- publishToSelf?: boolean
1099
- }
1100
-
1101
- export type Compressor =
1102
- | 'disable'
1103
- | 'shared'
1104
- | 'dedicated'
1105
- | '3KB'
1106
- | '4KB'
1107
- | '8KB'
1108
- | '16KB'
1109
- | '32KB'
1110
- | '64KB'
1111
- | '128KB'
1112
- | '256KB'
1113
-
1114
- export interface ServerOptions<T extends WebSocketData = WebSocketData> extends Partial<Omit<Server<T>, 'websocket' | 'development'>> {
1115
- websocket?: WebSocketConfig<T>
1116
- /**
1117
- * Pre-computed static responses served by Bun's native static dispatch.
1118
- * These bypass the fetch handler entirely for zero-allocation serving (~15% faster).
1119
- */
1120
- static?: Record<string, Response>
1121
- /**
1122
- * Opt-in: register compatible routes with `Bun.serve`'s native router
1123
- * (`routes`), skipping the fetch handler's URL parsing and route
1124
- * matching for them. Compatible means: standard HTTP method, no
1125
- * domain scoping, no `where()`/inline constraints, no optional
1126
- * params, and `{param}`s spanning whole segments. Everything else —
1127
- * incompatible routes, 404/405 handling, HEAD fallback, the generic
1128
- * OPTIONS preflight — still flows through the fetch handler with
1129
- * identical semantics.
1130
- *
1131
- * Caveat: Bun matches by specificity (exact > param > wildcard).
1132
- * Apps that rely on registration order between same-shape overlapping
1133
- * patterns should leave this off. Routes registered after `serve()`
1134
- * only join the native table after `reload()`.
1135
- */
1136
- nativeRoutes?: boolean
1137
- /**
1138
- * Development mode options for Bun's dev server.
1139
- * When true, enables HMR and development features.
1140
- * When an object, allows fine-grained control over HMR and console streaming.
1141
- *
1142
- * @example
1143
- * // Stream browser console.log/console.error to terminal
1144
- * development: { console: true }
1145
- *
1146
- * // Enable HMR + console streaming
1147
- * development: { hmr: true, console: true }
1148
- */
1149
- development?: boolean | {
1150
- hmr?: boolean
1151
- console?: boolean
1152
- }
1153
- }
1154
-
1155
- /**
1156
- * Type definition for route configuration with strict typing.
1157
- */
1158
- export interface RouteDefinition<
1159
- TPath extends string = string,
1160
- TMethod extends HTTPMethod = HTTPMethod,
1161
- THandler extends ActionHandler = ActionHandler,
1162
- > {
1163
- /**
1164
- * The path pattern for the route
1165
- */
1166
- path: TPath
1167
- /**
1168
- * The HTTP method for the route
1169
- */
1170
- method: TMethod
1171
- /**
1172
- * The action handler for the route - can be a string path, function, or class
1173
- */
1174
- handler: THandler
1175
- /**
1176
- * Optional array of middleware to be executed before the handler
1177
- */
1178
- middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware> | MiddlewareHandler)[]
1179
- /**
1180
- * Optional route type to distinguish between API and web routes
1181
- */
1182
- type?: 'api' | 'web'
1183
- /**
1184
- * Optional route name for reverse routing
1185
- */
1186
- name?: string
1187
- /**
1188
- * Route parameter constraints
1189
- */
1190
- constraints?: {
1191
- [K in keyof ExtractRouteParams<TPath>]: RouteConstraint
1192
- }
1193
- /**
1194
- * Optional route metadata for documentation or other purposes
1195
- */
1196
- meta?: RouteMetadata
1197
- /**
1198
- * Cache configuration for this specific route
1199
- */
1200
- cache?: {
1201
- enabled: boolean
1202
- ttl: number
1203
- tags?: string[]
1204
- strategy?: CacheStrategy
1205
- }
1206
- /**
1207
- * Rate limiting configuration for this route
1208
- */
1209
- throttle?: ThrottlePattern | ThrottleMiddlewareParams
1210
- }
1211
-
1212
- /**
1213
- * HTTP Methods type - extremely narrow
1214
- */
1215
- export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE' | 'CONNECT'
1216
-
1217
- /**
1218
- * Narrow throttle pattern types
1219
- */
1220
- export type ThrottlePattern =
1221
- | `${number}` // e.g., "60" (60 requests per 1 minute)
1222
- | `${number},${number}` // e.g., "60,1" (60 requests per 1 minute)
1223
- | `${number},${number}min` // e.g., "60,5min" (60 requests per 5 minutes)
1224
- | `${number},${number}m` // e.g., "60,5m" (60 requests per 5 minutes)
1225
- | `${number},${number}sec` // e.g., "100,30sec" (100 requests per 30 seconds)
1226
- | `${number},${number}s` // e.g., "100,30s" (100 requests per 30 seconds)
1227
- | `${number},${number}hour` // e.g., "1000,1hour" (1000 requests per 1 hour)
1228
- | `${number},${number}h` // e.g., "1000,1h" (1000 requests per 1 hour)
1229
-
1230
- /**
1231
- * Cache strategy types - narrow and specific
1232
- */
1233
- export type CacheStrategy = 'stale-while-revalidate' | 'cache-first' | 'network-first'
1234
-
1235
- /**
1236
- * Cache type narrow definition
1237
- */
1238
- export type CacheType = 'memory' | 'redis' | 'custom'
1239
-
1240
- /**
1241
- * File extension types for views
1242
- */
1243
- export type ViewExtension = '.html' | '.stx' | '.hbs' | '.ejs' | '.pug' | '.mustache'
1244
-
1245
- /**
1246
- * Template engine types
1247
- */
1248
- export type TemplateEngine = 'auto' | 'stx' | 'html' | 'handlebars' | 'ejs' | 'pug' | 'mustache' | 'custom'
1249
-
1250
- /**
1251
- * Route parameter constraint patterns
1252
- */
1253
- export type RouteConstraint =
1254
- | 'number' // Only numbers
1255
- | 'alpha' // Only letters
1256
- | 'alphanumeric' // Letters and numbers
1257
- | 'uuid' // UUID format
1258
- | 'slug' // URL-friendly slug
1259
- | RegExp // Custom regex
1260
- | string // Custom pattern string
1261
-
1262
- /**
1263
- * Middleware execution timing
1264
- */
1265
- export type MiddlewareTiming = 'before' | 'after' | 'around'
1266
-
1267
- /**
1268
- * Security header types
1269
- */
1270
- export type SecurityHeader =
1271
- | 'Content-Security-Policy'
1272
- | 'X-Frame-Options'
1273
- | 'X-Content-Type-Options'
1274
- | 'Referrer-Policy'
1275
- | 'Permissions-Policy'
1276
- | 'Strict-Transport-Security'
1277
-
1278
- /**
1279
- * Built-in middleware names - extremely narrow
1280
- */
1281
- export type BuiltInMiddleware =
1282
- | 'auth'
1283
- | 'cors'
1284
- | 'csrf'
1285
- | 'helmet'
1286
- | 'json'
1287
- | 'compress'
1288
- | 'static'
1289
- | 'session'
1290
- | 'rateLimiter'
1291
- | 'requestId'
1292
- | 'logger'
1293
- | 'throttle'
1294
-
1295
- /**
1296
- * Middleware with parameters
1297
- */
1298
- export type MiddlewareWithParams<T extends string = string> =
1299
- | T
1300
- | `${T}:${string}`
1301
-
1302
- /**
1303
- * Route path parameter types - narrow template literals
1304
- */
1305
- export type RouteParam<T extends string> = T extends `{${infer P}}` ? P : never
1306
-
1307
- /**
1308
- * Strip an inline constraint from a parameter token:
1309
- * `id:[0-9]+` → `id`, `slug` → `slug`
1310
- */
1311
- export type ExtractParamName<T extends string> =
1312
- T extends `${infer Name}:${string}` ? Name : T
1313
-
1314
- /**
1315
- * Extract parameters from a route path into a narrowly-typed object.
1316
- *
1317
- * Handles the full parameter grammar:
1318
- * - `{id}` → `{ id: string }`
1319
- * - `{id?}` (optional) → `{ id?: string }`
1320
- * - `{id:[0-9]+}` (inline constraint) → `{ id: string }`
1321
- * - trailing `*` wildcard → `{ wildcard: string }`
1322
- *
1323
- * @example
1324
- * type P = ExtractRouteParams<'/users/{userId}/posts/{slug?}'>
1325
- * // ^? { userId: string } & { slug?: string }
1326
- */
1327
- export type ExtractRouteParams<T extends string> =
1328
- T extends `${string}{${infer Param}}${infer Rest}`
1329
- ? (Param extends `${infer Inner}?`
1330
- ? { [K in ExtractParamName<Inner>]?: string }
1331
- : { [K in ExtractParamName<Param>]: string }) & ExtractRouteParams<Rest>
1332
- : T extends `${string}*${string}`
1333
- ? { wildcard: string }
1334
- : object
1335
-
1336
- /**
1337
- * Route method constraints
1338
- */
1339
- export type RouteMethodConstraint<M extends HTTPMethod = HTTPMethod> = M
1340
-
1341
- /**
1342
- * File MIME types for uploads
1343
- */
1344
- export type AllowedMimeType =
1345
- | 'image/jpeg'
1346
- | 'image/png'
1347
- | 'image/gif'
1348
- | 'image/webp'
1349
- | 'image/svg+xml'
1350
- | 'application/pdf'
1351
- | 'application/json'
1352
- | 'text/plain'
1353
- | 'text/csv'
1354
- | 'application/octet-stream'
1355
-
1356
- /**
1357
- * Response status codes - narrow and specific
1358
- */
1359
- export type ResponseStatus =
1360
- | 200 | 201 | 202 | 204 // Success
1361
- | 301 | 302 | 304 // Redirects
1362
- | 400 | 401 | 403 | 404 | 405 | 409 | 422 | 429 // Client errors
1363
- | 500 | 502 | 503 | 504 // Server errors
1364
-
1365
- /**
1366
- * Content types - narrow
1367
- */
1368
- export type ContentType =
1369
- | 'application/json'
1370
- | 'application/xml'
1371
- | 'text/html'
1372
- | 'text/plain'
1373
- | 'text/csv'
1374
- | 'application/pdf'
1375
- | 'application/octet-stream'
1376
- | 'multipart/form-data'
1377
- | 'application/x-www-form-urlencoded'
1378
-
1379
- /**
1380
- * Strongly typed route method signatures
1381
- */
1382
- export interface TypedRouteHandler<TPath extends string> {
1383
- (req: EnhancedRequest & { params: ExtractRouteParams<TPath> }): Response | Promise<Response>
1384
- }
1385
-
1386
- /**
1387
- * Strongly typed route definition for specific HTTP methods
1388
- */
1389
- export interface GetRoute<TPath extends string> extends RouteDefinition<TPath, 'GET'> {
1390
- method: 'GET'
1391
- handler: TypedRouteHandler<TPath> | ActionHandler
1392
- }
1393
-
1394
- export interface PostRoute<TPath extends string> extends RouteDefinition<TPath, 'POST'> {
1395
- method: 'POST'
1396
- handler: TypedRouteHandler<TPath> | ActionHandler
1397
- }
1398
-
1399
- export interface PutRoute<TPath extends string> extends RouteDefinition<TPath, 'PUT'> {
1400
- method: 'PUT'
1401
- handler: TypedRouteHandler<TPath> | ActionHandler
1402
- }
1403
-
1404
- export interface DeleteRoute<TPath extends string> extends RouteDefinition<TPath, 'DELETE'> {
1405
- method: 'DELETE'
1406
- handler: TypedRouteHandler<TPath> | ActionHandler
1407
- }
1408
-
1409
- export interface PatchRoute<TPath extends string> extends RouteDefinition<TPath, 'PATCH'> {
1410
- method: 'PATCH'
1411
- handler: TypedRouteHandler<TPath> | ActionHandler
1412
- }
1413
-
1414
- /**
1415
- * Union of all typed route definitions
1416
- */
1417
- export type TypedRouteDefinition<TPath extends string = string> =
1418
- | GetRoute<TPath>
1419
- | PostRoute<TPath>
1420
- | PutRoute<TPath>
1421
- | DeleteRoute<TPath>
1422
- | PatchRoute<TPath>
1423
-
1424
- /**
1425
- * Route validation helpers
1426
- */
1427
- export interface RouteValidation<TPath extends string> {
1428
- path: TPath
1429
- params: ExtractRouteParams<TPath>
1430
- validate: (req: EnhancedRequest) => req is EnhancedRequest & { params: ExtractRouteParams<TPath> }
1431
- }
1432
-
1433
- /**
1434
- * Common route patterns with strict template literal types
1435
- */
1436
- export type CommonRoutePatterns =
1437
- | '/' // Root
1438
- | '/health' // Health check
1439
- | '/api' // API root
1440
- | '/api/v1' // Versioned API
1441
- | '/api/v1/users' // User collection
1442
- | '/api/v1/users/{id}' // User resource
1443
- | '/api/v1/users/{userId}/posts' // Nested resource
1444
- | '/api/v1/users/{userId}/posts/{postId}' // Nested resource item
1445
- | '/admin' // Admin panel
1446
- | '/admin/{section}' // Admin section
1447
- | '/auth/login' // Authentication
1448
- | '/auth/logout' // Logout
1449
- | '/auth/register' // Registration
1450
- | '/auth/forgot-password' // Password reset
1451
- | '/uploads/{filename}' // File uploads
1452
- | '/assets/{path}' // Static assets
1453
-
1454
- /**
1455
- * RESTful resource route patterns
1456
- */
1457
- export type ResourceRoutePatterns<T extends string> =
1458
- | `/${T}` // Collection: GET /users
1459
- | `/${T}/{id}` // Item: GET /users/123
1460
- | `/${T}/create` // Create form: GET /users/create
1461
- | `/${T}/{id}/edit` // Edit form: GET /users/123/edit
1462
- | `/${T}/{id}/show` // Show item: GET /users/123/show
1463
-
1464
- /**
1465
- * API versioning patterns
1466
- */
1467
- export type ApiVersionPattern<V extends string, Path extends string> = `/api/${V}${Path}`
1468
-
1469
- /**
1470
- * Nested resource patterns
1471
- */
1472
- export type NestedResourcePattern<
1473
- Parent extends string,
1474
- Child extends string,
1475
- ParentId extends string = 'id',
1476
- ChildId extends string = 'id',
1477
- > = `/${Parent}/{${ParentId}}/${Child}` | `/${Parent}/{${ParentId}}/${Child}/{${ChildId}}`
1478
-
1479
- /**
1480
- * Route parameter patterns with constraints
1481
- */
1482
- export type IdPattern = '{id}'
1483
- export type UuidPattern = '{uuid}'
1484
- export type SlugPattern = '{slug}'
1485
- export type NumberPattern = '{number}'
1486
-
1487
- /**
1488
- * File path patterns
1489
- */
1490
- export type FilePathPattern = '{filepath}' | '{*filepath}' | '{path...}'
1491
-
1492
- /**
1493
- * Discriminated union for cache configurations
1494
- */
1495
- export type CacheConfigVariant =
1496
- | { type: 'memory', maxSize: number, ttl: number }
1497
- | { type: 'redis', url: string, prefix: string, ttl: number, maxRetries: number }
1498
- | { type: 'custom', adapter: CacheConfig['customAdapter'], ttl: number }
1499
-
1500
- /**
1501
- * Discriminated union for authentication configurations
1502
- */
1503
- export type AuthConfigVariant =
1504
- | { type: 'jwt', secret: string, expiresIn: string, algorithm: 'HS256' | 'HS384' | 'HS512' | 'RS256' }
1505
- | { type: 'session', secret: string, store: CacheType, maxAge: number }
1506
- | { type: 'apikey', keyName: string, location: 'header' | 'query' | 'cookie' }
1507
- | { type: 'basic', realm: string, users: Record<string, string> }
1508
- | { type: 'bearer', validate: (token: string) => Promise<boolean> }
1509
-
1510
- /**
1511
- * Discriminated union for rate limiting configurations
1512
- */
1513
- export type RateLimitConfigVariant =
1514
- | { type: 'memory', maxAttempts: number, windowMs: number, keyGenerator?: (req: EnhancedRequest) => string }
1515
- | { type: 'redis', maxAttempts: number, windowMs: number, redisUrl: string, keyPrefix: string }
1516
- | { type: 'pattern', pattern: ThrottlePattern, name?: string }
1517
-
1518
- /**
1519
- * Discriminated union for middleware configurations
1520
- */
1521
- export type MiddlewareConfigVariant =
1522
- | { type: 'throttle', config: RateLimitConfigVariant }
1523
- | { type: 'cors', config: CorsMiddlewareConfig }
1524
- | { type: 'auth', config: AuthConfigVariant }
1525
- | { type: 'cache', config: CacheConfigVariant }
1526
- | { type: 'custom', name: string, handler: MiddlewareHandler, params?: MiddlewareParams }
1527
-
1528
- /**
1529
- * Discriminated union for route handlers
1530
- */
1531
- export type RouteHandlerVariant<TPath extends string = string> =
1532
- | { type: 'action', path: ActionPath }
1533
- | { type: 'function', handler: TypedRouteHandler<TPath> }
1534
- | { type: 'class', constructor: new () => TypedActionHandlerClass<TPath> }
1535
- | { type: 'controller', method: ControllerMethod }
1536
-
1537
- /**
1538
- * Discriminated union for validation rules
1539
- */
1540
- export type ValidationRuleVariant =
1541
- | { type: 'required', message?: string }
1542
- | { type: 'string', minLength?: number, maxLength?: number, pattern?: RegExp }
1543
- | { type: 'number', min?: number, max?: number, integer?: boolean }
1544
- | { type: 'email', message?: string }
1545
- | { type: 'url', protocols?: string[] }
1546
- | { type: 'custom', validate: (value: unknown) => boolean | Promise<boolean>, message: string }
1547
-
1548
- /**
1549
- * Streaming configuration types with extreme narrowing
1550
- */
1551
- export type StreamingFormat = 'json' | 'ndjson' | 'csv' | 'xml' | 'text' | 'binary'
1552
- export type StreamingCompression = 'gzip' | 'deflate' | 'br' | 'none'
1553
- export type StreamingMode = 'chunked' | 'buffered' | 'direct'
1554
-
1555
- /**
1556
- * Server-Sent Events configuration
1557
- */
1558
- export interface SSEConfig {
1559
- retryInterval?: number
1560
- keepAlive?: number
1561
- compression?: StreamingCompression
1562
- maxConnections?: number
1563
- heartbeatInterval?: number
1564
- headers?: Record<string, string>
1565
- enableHeartbeat?: boolean
1566
- connectionTimeout?: number
1567
- retryDelay?: number
1568
- }
1569
-
1570
- /**
1571
- * SSE Event data structure with strict typing
1572
- */
1573
- export interface SSEEvent<T = unknown> {
1574
- data: T
1575
- event?: string
1576
- id?: string | number
1577
- retry?: number
1578
- comment?: string
1579
- }
1580
-
1581
- /**
1582
- * Stream generator function types
1583
- */
1584
- export type SSEGenerator<T = unknown> = () => AsyncGenerator<SSEEvent<T>, void, unknown>
1585
-
1586
- /**
1587
- * Direct streaming configuration
1588
- */
1589
- export interface DirectStreamConfig {
1590
- headers?: Record<string, string>
1591
- status?: ResponseStatus
1592
- compression?: StreamingCompression
1593
- format?: StreamingFormat
1594
- bufferSize?: number
1595
- delimiter?: string
1596
- contentType?: ContentType
1597
- enableCompression?: boolean
1598
- compressionType?: StreamingCompression
1599
- }
1600
-
1601
- /**
1602
- * Buffered streaming configuration
1603
- */
1604
- export interface BufferedStreamConfig extends DirectStreamConfig {
1605
- highWaterMark?: number
1606
- maxBuffer?: number
1607
- flushInterval?: number
1608
- autoFlush?: boolean
1609
- contentType?: ContentType
1610
- }
1611
-
1612
- /**
1613
- * File streaming configuration with strict types
1614
- */
1615
- export interface FileStreamConfig {
1616
- headers?: Record<string, string>
1617
- status?: ResponseStatus
1618
- mimeType?: AllowedMimeType
1619
- disposition?: 'inline' | 'attachment'
1620
- filename?: string
1621
- maxAge?: number
1622
- etag?: boolean
1623
- lastModified?: boolean
1624
- compression?: StreamingCompression
1625
- }
1626
-
1627
- /**
1628
- * Range request configuration for file streaming
1629
- */
1630
- export interface RangeStreamConfig extends FileStreamConfig {
1631
- unit?: 'bytes'
1632
- maxRanges?: number
1633
- enableMultipart?: boolean
1634
- }
1635
-
1636
- /**
1637
- * Transform stream configuration
1638
- */
1639
- export interface TransformStreamConfig<TInput = any, TOutput = any> {
1640
- transform: (chunk: TInput) => TOutput | Promise<TOutput>
1641
- flush?: () => TOutput[] | Promise<TOutput[]>
1642
- objectMode?: boolean
1643
- highWaterMark?: number
1644
- format?: StreamingFormat
1645
- headers?: Record<string, string>
1646
- }
1647
-
1648
- /**
1649
- * Streaming response writer interfaces
1650
- */
1651
- export interface StreamWriter<T = any> {
1652
- write: (chunk: T) => void | Promise<void>
1653
- end: () => void | Promise<void>
1654
- close: () => void
1655
- }
1656
-
1657
- export interface BufferedStreamWriterGeneric<T = any> extends StreamWriter<T> {
1658
- flush: () => void | Promise<void>
1659
- cork: () => void
1660
- uncork: () => void
1661
- }
1662
-
1663
- /**
1664
- * Model binding configuration with strict types
1665
- */
1666
- export interface ModelBinding<T = any> {
1667
- name: string
1668
- model: string // Model name
1669
- parameter: string // Parameter name
1670
- required?: boolean
1671
- as?: string // Alias for the bound model
1672
- resolver: ModelResolver<T>
1673
- cache?: {
1674
- enabled: boolean
1675
- ttl: number
1676
- key?: (params: Record<string, string>) => string
1677
- }
1678
- validation?: {
1679
- required?: boolean
1680
- validator?: (model: T) => boolean | Promise<boolean>
1681
- }
1682
- errorHandler?: (error: Error, params: Record<string, string>) => Response
1683
- }
1684
-
1685
- /**
1686
- * Model resolver function type
1687
- */
1688
- export type ModelResolver<T = any> = (
1689
- params: Record<string, string>,
1690
- req: EnhancedRequest
1691
- ) => T | Promise<T> | null
1692
-
1693
- /**
1694
- * Model validator function type
1695
- */
1696
- export type ModelValidatorFn<T = any> = (
1697
- model: T,
1698
- params: Record<string, string>,
1699
- req?: EnhancedRequest
1700
- ) => Promise<{ valid: boolean, error?: string, status?: number }> | { valid: boolean, error?: string, status?: number }
1701
-
1702
- /**
1703
- * Model transformer function type
1704
- */
1705
- export type ModelTransformerFn<T = any> = (
1706
- model: T,
1707
- params?: Record<string, string>,
1708
- req?: EnhancedRequest
1709
- ) => any | Promise<any>
1710
-
1711
- /**
1712
- * Model registry interface
1713
- */
1714
- export interface ModelRegistry {
1715
- register: <T>(binding: ModelBinding<T>) => void
1716
- resolve: <T>(name: string, params: Record<string, string>, req: EnhancedRequest) => Promise<T | null>
1717
- has: (name: string) => boolean
1718
- clear: () => void
1719
- getAll: () => ModelBinding[]
1720
- }
1721
-
1722
- /**
1723
- * Model binding middleware configuration
1724
- */
1725
- export interface ModelBindingConfig {
1726
- parameterName: string
1727
- modelName: string
1728
- required?: boolean
1729
- cacheKey?: (params: Record<string, string>) => string
1730
- }
1731
-
1732
- /**
1733
- * Resource route configuration with model binding
1734
- */
1735
- export interface ResourceConfig {
1736
- controller: string
1737
- only?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[]
1738
- except?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[]
1739
- middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[]
1740
- bindings?: Record<string, string>
1741
- names?: Partial<Record<'index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy', string>>
1742
- }
1743
-
1744
- /**
1745
- * Stream route handler with typed path parameters
1746
- */
1747
- export interface StreamRouteHandler<TPath extends string = string> {
1748
- (
1749
- req: EnhancedRequest & { params: ExtractRouteParams<TPath> },
1750
- writer: StreamWriter
1751
- ): Promise<void> | void
1752
- }
1753
-
1754
- /**
1755
- * SSE route handler with typed path parameters
1756
- */
1757
- export interface SSERouteHandler<TPath extends string = string> {
1758
- (
1759
- req: EnhancedRequest & { params: ExtractRouteParams<TPath> }
1760
- ): SSEGenerator | AsyncGenerator<SSEEvent, void, unknown>
1761
- }
1762
-
1763
- /**
1764
- * Route matching result
1765
- */
1766
- export interface MatchResult {
1767
- route: Route
1768
- params: Record<string, string>
1769
- }
1770
-
1771
- /**
1772
- * URL pattern match result
1773
- */
1774
- export interface PatternMatchResult {
1775
- pathname: {
1776
- groups: Record<string, string>
1777
- }
1778
- }
1779
-
1780
- /**
1781
- * Streaming response options
1782
- */
1783
- export interface StreamingOptions {
1784
- headers?: Record<string, string>
1785
- status?: number
1786
- }
1787
-
1788
- /**
1789
- * SSE (Server-Sent Events) data structure
1790
- */
1791
- export interface SSEData<T = unknown> {
1792
- data: T
1793
- event?: string
1794
- id?: string
1795
- retry?: number
1796
- }
1797
-
1798
- /**
1799
- * Direct streaming writer interface
1800
- */
1801
- export interface DirectStreamWriter {
1802
- write: (chunk: string | Uint8Array) => void
1803
- close: () => void
1804
- }
1805
-
1806
- /**
1807
- * Buffered streaming writer interface
1808
- */
1809
- export interface BufferedStreamWriter {
1810
- write: (chunk: string | Uint8Array) => void
1811
- flush: () => void
1812
- end: () => void
1813
- }
1814
-
1815
- /**
1816
- * Buffered streaming options
1817
- */
1818
- export interface BufferedStreamOptions {
1819
- highWaterMark?: number
1820
- asUint8Array?: boolean
1821
- }
1822
-
1823
- /**
1824
- * Async generator function type for streaming
1825
- */
1826
- export type StreamGenerator<T = unknown> = () => AsyncGenerator<T, void, unknown>
1827
-
1828
- /**
1829
- * Direct stream handler function type
1830
- */
1831
- export type DirectStreamHandler = (_writer: DirectStreamWriter) => Promise<void>
1832
-
1833
- /**
1834
- * Buffered stream handler function type
1835
- */
1836
- export type BufferedStreamHandler = (_writer: BufferedStreamWriter) => Promise<void>
1837
-
1838
- /**
1839
- * Transform function type for stream transformation
1840
- */
1841
- export type TransformFunction<T = Uint8Array, R = string | Uint8Array> = (_chunk: T) => R | Promise<R>
1842
-
1843
- /**
1844
- * Advanced Error Handling Types
1845
- */
1846
- export interface ErrorContext {
1847
- requestId?: string
1848
- userId?: string | number
1849
- traceId?: string
1850
- spanId?: string
1851
- route?: string
1852
- method?: string
1853
- url?: string
1854
- userAgent?: string
1855
- ip?: string
1856
- timestamp?: Date
1857
- metadata?: ErrorMetadata
1858
- }
1859
-
1860
- export interface ErrorReportingConfig {
1861
- enabled: boolean
1862
- service: 'sentry' | 'bugsnag' | 'custom'
1863
- dsn?: string
1864
- apiKey?: string
1865
- environment?: string
1866
- release?: string
1867
- sampleRate?: number
1868
- beforeSend?: (error: Error, context: ErrorContext) => Error | null
1869
- filters?: {
1870
- ignoreErrors?: (string | RegExp)[]
1871
- ignoreCodes?: string[]
1872
- ignoreUrls?: (string | RegExp)[]
1873
- allowUrls?: (string | RegExp)[]
1874
- }
1875
- tags?: Record<string, string>
1876
- user?: {
1877
- id?: string
1878
- email?: string
1879
- username?: string
1880
- }
1881
- extra?: Record<string, unknown>
1882
- breadcrumbs?: {
1883
- enabled: boolean
1884
- maxBreadcrumbs: number
1885
- }
1886
- performance?: {
1887
- enabled: boolean
1888
- tracesSampleRate: number
1889
- }
1890
- }
1891
-
1892
- export interface CircuitBreakerConfig {
1893
- name: string
1894
- failureThreshold: number
1895
- recoveryTimeout: number
1896
- timeout: number
1897
- monitoringPeriod: number
1898
- minimumRequests: number
1899
- errorThresholdPercentage: number
1900
- halfOpenMaxCalls: number
1901
- resetTimeout: number
1902
- onStateChange?: (state: 'CLOSED' | 'OPEN' | 'HALF_OPEN', name: string) => void
1903
- onFailure?: (error: Error, name: string) => void
1904
- onSuccess?: (name: string) => void
1905
- shouldTripOnError?: (error: Error) => boolean
1906
- }
1907
-
1908
- export interface DegradationConfig {
1909
- enabled: boolean
1910
- fallbackStrategies: {
1911
- [serviceName: string]: {
1912
- type: 'cache' | 'static' | 'simplified' | 'redirect' | 'custom'
1913
- priority: number
1914
- timeout: number
1915
- retries: number
1916
- backoff: {
1917
- type: 'fixed' | 'exponential'
1918
- delay: number
1919
- maxDelay?: number
1920
- }
1921
- fallbackHandler?: (error: FallbackError, context: ErrorContext) => Promise<Response>
1922
- cacheConfig?: {
1923
- key: string
1924
- ttl: number
1925
- staleWhileRevalidate: boolean
1926
- }
1927
- staticResponse?: {
1928
- status: number
1929
- body: StaticResponseBody
1930
- headers?: Record<string, string>
1931
- }
1932
- redirectConfig?: {
1933
- url: string
1934
- permanent: boolean
1935
- }
1936
- }
1937
- }
1938
- healthChecks: {
1939
- [serviceName: string]: {
1940
- enabled: boolean
1941
- endpoint: string
1942
- interval: number
1943
- timeout: number
1944
- retries: number
1945
- expectedStatus: number[]
1946
- expectedBody?: string | RegExp
1947
- headers?: Record<string, string>
1948
- onHealthy?: () => void
1949
- onUnhealthy?: (error: Error) => void
1950
- }
1951
- }
1952
- monitoring: {
1953
- enabled: boolean
1954
- alertThresholds: {
1955
- errorRate: number
1956
- responseTime: number
1957
- availability: number
1958
- }
1959
- }
1960
- }
1961
-
1962
- /**
1963
- * Request/Response Enhancement Types
1964
- */
1965
- export interface RequestMacroMethods {
1966
- // Content type detection
1967
- wantsJson: () => boolean
1968
- wantsHtml: () => boolean
1969
- wantsXml: () => boolean
1970
- expectsJson: () => boolean
1971
-
1972
- // Request information
1973
- isAjax: () => boolean
1974
- isPjax: () => boolean
1975
- isMobile: () => boolean
1976
- isBot: () => boolean
1977
- isSecure: () => boolean
1978
-
1979
- // Client information
1980
- ip: () => string
1981
- ips: () => string[]
1982
- userAgent: () => string
1983
- referer: () => string | null
1984
-
1985
- // Authentication
1986
- bearerToken: () => string | null
1987
- basicAuth: () => { username: string, password: string } | null
1988
-
1989
- /** Raw unparsed request body as a string (cached). Needed for webhook signature verification (Stripe/GitHub/Slack), where a re-serialized jsonBody won't match the HMAC. */
1990
- rawBody: () => Promise<string>
1991
-
1992
- // Headers
1993
- hasHeader: (name: string) => boolean
1994
- header: (name: string, defaultValue?: string) => string | null
1995
- allHeaders: () => Record<string, string>
1996
-
1997
- // Input handling
1998
- input: <T = InputValue>(key: string, defaultValue?: T) => T
1999
- all: () => RequestInput
2000
- only: (keys: string[]) => RequestInput
2001
- except: (keys: string[]) => RequestInput
2002
-
2003
- // Validation checks
2004
- has: (key: string) => boolean
2005
- hasAny: (keys: string[]) => boolean
2006
- missing: (key: string) => boolean
2007
- filled: (key: string) => boolean
2008
-
2009
- // Query and params
2010
- getQuery: <T = InputValue>(key?: string, defaultValue?: T) => T
2011
- param: <T = InputValue>(key: string, defaultValue?: T) => T
2012
-
2013
- // Cookies
2014
- cookie: (name: string, defaultValue?: string) => string | null
2015
- cookies: () => Record<string, string>
2016
-
2017
- // Files
2018
- /**
2019
- * Lookup a single uploaded file by form field name. Returns the
2020
- * matching `FileInfo` (structurally an `UploadedFile`) or `null` when
2021
- * no field with that name was uploaded. Populated by the multipart
2022
- * file-upload middleware alongside `files: UploadedFile[]`. Mirrors
2023
- * Laravel's `$request->file('avatar')`:
2024
- *
2025
- * ```ts
2026
- * const avatar = req.file('avatar')
2027
- * if (!avatar) return new Response('Missing avatar', { status: 400 })
2028
- * ```
2029
- */
2030
- file: (name: string) => FileInfo | null
2031
- hasFile: (name: string) => boolean
2032
-
2033
- // URL utilities
2034
- path: () => string
2035
- fullUrl: () => string
2036
- root: () => string
2037
- is: (pattern: string) => boolean
2038
- route: () => string | null
2039
-
2040
- // Utilities
2041
- fingerprint: () => string
2042
- signature: (secret: string) => string
2043
- merge: (data: RequestInput) => void
2044
- replace: (data: RequestInput) => void
2045
- age: () => number
2046
- isFromTrustedProxy: (trustedProxies?: string[]) => boolean
2047
- contentLength: () => number
2048
- contentType: () => string | null
2049
- isContentType: (type: string) => boolean
2050
- }
2051
-
2052
- /**
2053
- * Enhanced streaming generator types with extreme narrowing
2054
- */
2055
- export type StreamGeneratorSync<T = string | Uint8Array> = () => Generator<T, void, unknown>
2056
- export type AsyncStreamGenerator<T = string | Uint8Array> = () => AsyncGenerator<T, void, unknown>
2057
- export type StreamCallbackGenerator<T = string | Uint8Array> = StreamGenerator<T> | AsyncStreamGenerator<T>
2058
-
2059
- /**
2060
- * SSE Event generator with strict typing
2061
- */
2062
- export type SSEEventGenerator<T = unknown> = () => Generator<SSEEvent<T>, void, unknown> | AsyncGenerator<SSEEvent<T>, void, unknown>
2063
-
2064
- /**
2065
- * Extreme narrow types for Laravel-style methods with template literal patterns
2066
- */
2067
- export interface EnhancedLaravelStreamingMethods {
2068
- /**
2069
- * Laravel-style response()->stream() with extreme type narrowing
2070
- */
2071
- stream: <T extends string | Uint8Array = string>(
2072
- callback: StreamCallbackGenerator<T>,
2073
- status?: ResponseStatus,
2074
- headers?: Record<string, string>
2075
- ) => Response
2076
-
2077
- /**
2078
- * Laravel-style response()->streamJson() with strict object key typing
2079
- */
2080
- streamJson: <T, K extends string = string>(
2081
- data: Record<K, Iterable<T> | AsyncIterable<T>>,
2082
- status?: ResponseStatus,
2083
- headers?: Record<string, string>
2084
- ) => Response
2085
-
2086
- /**
2087
- * Laravel-style response()->eventStream() with strict SSE typing
2088
- */
2089
- eventStream: <T = unknown>(
2090
- callback: SSEEventGenerator<T>,
2091
- headers?: Record<string, string>
2092
- ) => Response
2093
-
2094
- /**
2095
- * Laravel-style response()->streamDownload() with filename validation
2096
- */
2097
- streamDownload: <T extends string | Uint8Array = string>(
2098
- callback: StreamCallbackGenerator<T>,
2099
- filename: `${string}.${string}`, // Must have extension
2100
- headers?: Record<string, string>
2101
- ) => Response
2102
- }
2103
-
2104
- /**
2105
- * Enhanced model binding with strict key typing
2106
- */
2107
- export interface EnhancedLaravelModelBindingMethods {
2108
- /**
2109
- * Laravel-style Route::model() with key validation
2110
- */
2111
- model: <T, K extends string>(
2112
- key: K,
2113
- modelClass: string | ((_value: string) => Promise<T | null>),
2114
- callback?: (model: T | null) => Response | null
2115
- ) => Router & { [P in K]: T }
2116
-
2117
- /**
2118
- * Scoped bindings with relationship validation
2119
- */
2120
- scopedBindings: <Parent extends string, Child extends string>(
2121
- bindings: Record<Child, Parent>
2122
- ) => MiddlewareHandler
2123
- }