@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
@@ -1,453 +0,0 @@
1
- import type { EnhancedRequest, NextFunction } from '../types'
2
- import { config } from '../config'
3
-
4
- // Hoisted format regexes — previously compiled on every validation call
5
- const EMAIL_REGEX = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
6
- const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
7
-
8
- export interface ValidationRule {
9
- type: 'string' | 'number' | 'boolean' | 'email' | 'url' | 'uuid' | 'date' | 'regex' | 'custom'
10
- required?: boolean
11
- min?: number
12
- max?: number
13
- pattern?: RegExp
14
- enum?: unknown[]
15
- custom?: (value: unknown) => boolean | string
16
- sanitize?: boolean
17
- transform?: (value: unknown) => unknown
18
- }
19
-
20
- export interface ValidationSchema {
21
- [key: string]: ValidationRule | ValidationSchema
22
- }
23
-
24
- export interface InputValidationOptions {
25
- enabled?: boolean
26
- schemas?: {
27
- query?: ValidationSchema
28
- body?: ValidationSchema
29
- headers?: ValidationSchema
30
- params?: ValidationSchema
31
- }
32
- sanitizeByDefault?: boolean
33
- strictMode?: boolean
34
- allowUnknownFields?: boolean
35
- maxDepth?: number
36
- onValidationError?: (errors: ValidationError[]) => Response
37
- }
38
-
39
- export interface ValidationError {
40
- field: string
41
- message: string
42
- value: any
43
- rule: string
44
- }
45
-
46
- export default class InputValidation {
47
- private options: InputValidationOptions
48
-
49
- constructor(options: InputValidationOptions = {}) {
50
- const validationConfig = config.server?.security?.inputValidation || {}
51
-
52
- this.options = {
53
- enabled: options.enabled ?? validationConfig.enabled ?? true,
54
- schemas: (options.schemas ?? validationConfig.schemas ?? {}) as InputValidationOptions['schemas'],
55
- sanitizeByDefault: options.sanitizeByDefault ?? validationConfig.sanitizeByDefault ?? true,
56
- strictMode: options.strictMode ?? validationConfig.strictMode ?? false,
57
- allowUnknownFields: options.allowUnknownFields ?? validationConfig.allowUnknownFields ?? true,
58
- maxDepth: options.maxDepth ?? validationConfig.maxDepth ?? 10,
59
- onValidationError: options.onValidationError,
60
- }
61
- }
62
-
63
- private validateValue(value: any, rule: ValidationRule, fieldPath: string): ValidationError[] {
64
- const errors: ValidationError[] = []
65
-
66
- // Check required
67
- if (rule.required && (value === undefined || value === null || value === '')) {
68
- errors.push({
69
- field: fieldPath,
70
- message: 'Field is required',
71
- value,
72
- rule: 'required',
73
- })
74
- return errors
75
- }
76
-
77
- // Skip validation if value is undefined/null and not required
78
- if (value === undefined || value === null) {
79
- return errors
80
- }
81
-
82
- // Type validation
83
- switch (rule.type) {
84
- case 'string':
85
- if (typeof value !== 'string') {
86
- errors.push({
87
- field: fieldPath,
88
- message: 'Must be a string',
89
- value,
90
- rule: 'type',
91
- })
92
- }
93
- else {
94
- if (rule.min !== undefined && value.length < rule.min) {
95
- errors.push({
96
- field: fieldPath,
97
- message: `Must be at least ${rule.min} characters`,
98
- value,
99
- rule: 'min',
100
- })
101
- }
102
- if (rule.max !== undefined && value.length > rule.max) {
103
- errors.push({
104
- field: fieldPath,
105
- message: `Must be at most ${rule.max} characters`,
106
- value,
107
- rule: 'max',
108
- })
109
- }
110
- }
111
- break
112
-
113
- case 'number': {
114
- const num = Number(value)
115
- if (Number.isNaN(num)) {
116
- errors.push({
117
- field: fieldPath,
118
- message: 'Must be a number',
119
- value,
120
- rule: 'type',
121
- })
122
- }
123
- else {
124
- if (rule.min !== undefined && num < rule.min) {
125
- errors.push({
126
- field: fieldPath,
127
- message: `Must be at least ${rule.min}`,
128
- value,
129
- rule: 'min',
130
- })
131
- }
132
- if (rule.max !== undefined && num > rule.max) {
133
- errors.push({
134
- field: fieldPath,
135
- message: `Must be at most ${rule.max}`,
136
- value,
137
- rule: 'max',
138
- })
139
- }
140
- }
141
- break
142
- }
143
- case 'boolean':
144
- if (typeof value !== 'boolean' && value !== 'true' && value !== 'false') {
145
- errors.push({
146
- field: fieldPath,
147
- message: 'Must be a boolean',
148
- value,
149
- rule: 'type',
150
- })
151
- }
152
- break
153
-
154
- case 'email': {
155
- if (typeof value === 'string' && !EMAIL_REGEX.test(value)) {
156
- errors.push({
157
- field: fieldPath,
158
- message: 'Must be a valid email address',
159
- value,
160
- rule: 'format',
161
- })
162
- }
163
- break
164
- }
165
- case 'url':
166
- try {
167
- void new URL(value)
168
- }
169
- catch {
170
- errors.push({
171
- field: fieldPath,
172
- message: 'Must be a valid URL',
173
- value,
174
- rule: 'format',
175
- })
176
- }
177
- break
178
-
179
- case 'uuid': {
180
- if (typeof value === 'string' && !UUID_REGEX.test(value)) {
181
- errors.push({
182
- field: fieldPath,
183
- message: 'Must be a valid UUID',
184
- value,
185
- rule: 'format',
186
- })
187
- }
188
- break
189
- }
190
- case 'date': {
191
- const date = new Date(value)
192
- if (Number.isNaN(date.getTime())) {
193
- errors.push({
194
- field: fieldPath,
195
- message: 'Must be a valid date',
196
- value,
197
- rule: 'format',
198
- })
199
- }
200
- break
201
- }
202
- case 'regex':
203
- if (rule.pattern && typeof value === 'string' && !rule.pattern.test(value)) {
204
- errors.push({
205
- field: fieldPath,
206
- message: 'Does not match required pattern',
207
- value,
208
- rule: 'pattern',
209
- })
210
- }
211
- break
212
-
213
- case 'custom':
214
- if (rule.custom) {
215
- const result = rule.custom(value)
216
- if (result !== true) {
217
- errors.push({
218
- field: fieldPath,
219
- message: typeof result === 'string' ? result : 'Custom validation failed',
220
- value,
221
- rule: 'custom',
222
- })
223
- }
224
- }
225
- break
226
- }
227
-
228
- // Enum validation
229
- if (rule.enum && !rule.enum.includes(value)) {
230
- errors.push({
231
- field: fieldPath,
232
- message: `Must be one of: ${rule.enum.join(', ')}`,
233
- value,
234
- rule: 'enum',
235
- })
236
- }
237
-
238
- // Pattern validation — skipped for type 'regex', which already
239
- // validated the pattern above (running it twice produced duplicate
240
- // errors for the same field)
241
- if (rule.type !== 'regex' && rule.pattern && typeof value === 'string' && !rule.pattern.test(value)) {
242
- errors.push({
243
- field: fieldPath,
244
- message: 'Does not match required pattern',
245
- value,
246
- rule: 'pattern',
247
- })
248
- }
249
-
250
- return errors
251
- }
252
-
253
- private sanitizeValue(value: any, rule: ValidationRule): any {
254
- if (!rule.sanitize && !this.options.sanitizeByDefault) {
255
- return value
256
- }
257
-
258
- if (typeof value === 'string') {
259
- // Basic HTML sanitization
260
- value = value
261
- .replace(/[<>'"&]/g, (match) => {
262
- const entities: Record<string, string> = {
263
- '<': '&lt;',
264
- '>': '&gt;',
265
- '"': '&quot;',
266
- '\'': '&#x27;',
267
- '&': '&amp;',
268
- }
269
- return entities[match] || match
270
- })
271
- .trim()
272
- }
273
-
274
- // Apply transformation if provided
275
- if (rule.transform) {
276
- value = rule.transform(value)
277
- }
278
-
279
- return value
280
- }
281
-
282
- private validateObject(obj: any, schema: ValidationSchema, basePath = '', depth = 0): ValidationError[] {
283
- const errors: ValidationError[] = []
284
-
285
- if (depth > this.options.maxDepth!) {
286
- errors.push({
287
- field: basePath,
288
- message: 'Maximum nesting depth exceeded',
289
- value: obj,
290
- rule: 'depth',
291
- })
292
- return errors
293
- }
294
-
295
- // Check for unknown fields in strict mode
296
- if (this.options.strictMode && !this.options.allowUnknownFields) {
297
- for (const key in obj) {
298
- if (!(key in schema)) {
299
- errors.push({
300
- field: basePath ? `${basePath}.${key}` : key,
301
- message: 'Unknown field',
302
- value: obj[key],
303
- rule: 'unknown',
304
- })
305
- }
306
- }
307
- }
308
-
309
- // Validate known fields
310
- for (const [key, rule] of Object.entries(schema)) {
311
- const fieldPath = basePath ? `${basePath}.${key}` : key
312
- const value = obj?.[key]
313
-
314
- if (typeof rule === 'object' && !('type' in rule)) {
315
- // Nested schema
316
- if (value && typeof value === 'object') {
317
- errors.push(...this.validateObject(value, rule as ValidationSchema, fieldPath, depth + 1))
318
- }
319
- }
320
- else {
321
- // Validation rule
322
- const validationRule = rule as ValidationRule
323
- errors.push(...this.validateValue(value, validationRule, fieldPath))
324
-
325
- // Sanitize if needed
326
- if (obj && (validationRule.sanitize || this.options.sanitizeByDefault)) {
327
- obj[key] = this.sanitizeValue(value, validationRule)
328
- }
329
- }
330
- }
331
-
332
- return errors
333
- }
334
-
335
- private async parseRequestBody(req: EnhancedRequest): Promise<any> {
336
- const contentType = req.headers.get('content-type') || ''
337
-
338
- try {
339
- if (contentType.includes('application/json')) {
340
- return await req.json()
341
- }
342
- else if (contentType.includes('application/x-www-form-urlencoded')) {
343
- const formData = await req.formData()
344
- const result: Record<string, any> = {}
345
- for (const [key, value] of (formData as any).entries()) {
346
- result[key] = value
347
- }
348
- return result
349
- }
350
- else if (contentType.includes('multipart/form-data')) {
351
- const formData = await req.formData()
352
- const result: Record<string, any> = {}
353
- for (const [key, value] of (formData as any).entries()) {
354
- result[key] = value
355
- }
356
- return result
357
- }
358
- }
359
- catch (error) {
360
- console.error(error)
361
- throw new Error('Invalid request body format')
362
- }
363
-
364
- return {}
365
- }
366
-
367
- async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
368
- if (!this.options.enabled) {
369
- const response = await next()
370
- return response || new Response('Not Found', { status: 404 })
371
- }
372
-
373
- const allErrors: ValidationError[] = []
374
- const url = new URL(req.url)
375
-
376
- try {
377
- // Validate query parameters
378
- if (this.options.schemas?.query) {
379
- const queryParams: Record<string, any> = {}
380
- for (const [key, value] of url.searchParams.entries()) {
381
- queryParams[key] = value
382
- }
383
- const queryErrors = this.validateObject(queryParams, this.options.schemas.query)
384
- allErrors.push(...queryErrors)
385
- }
386
-
387
- // Validate request body
388
- if (this.options.schemas?.body && req.method !== 'GET' && req.method !== 'HEAD') {
389
- try {
390
- const body = await this.parseRequestBody(req)
391
- const bodyErrors = this.validateObject(body, this.options.schemas.body)
392
- allErrors.push(...bodyErrors)
393
-
394
- // Attach validated body to request
395
- req.validatedBody = body
396
- }
397
- catch (error) {
398
- allErrors.push({
399
- field: 'body',
400
- message: error instanceof Error ? error.message : 'Invalid request body',
401
- value: null,
402
- rule: 'parse',
403
- })
404
- }
405
- }
406
-
407
- // Validate headers
408
- if (this.options.schemas?.headers) {
409
- const headers: Record<string, any> = {}
410
- for (const [key, value] of req.headers.entries()) {
411
- headers[key] = value
412
- }
413
- const headerErrors = this.validateObject(headers, this.options.schemas.headers)
414
- allErrors.push(...headerErrors)
415
- }
416
-
417
- // Validate route parameters
418
- if (this.options.schemas?.params && req.params) {
419
- const paramErrors = this.validateObject(req.params, this.options.schemas.params)
420
- allErrors.push(...paramErrors)
421
- }
422
-
423
- // Return validation errors if any
424
- if (allErrors.length > 0) {
425
- if (this.options.onValidationError) {
426
- return this.options.onValidationError(allErrors)
427
- }
428
-
429
- return new Response(JSON.stringify({
430
- error: 'Validation Error',
431
- message: 'Request validation failed',
432
- errors: allErrors,
433
- }), {
434
- status: 400,
435
- headers: { 'Content-Type': 'application/json' },
436
- })
437
- }
438
-
439
- const response = await next()
440
- return response || new Response('Not Found', { status: 404 })
441
- }
442
- catch (error) {
443
- console.error('Input validation error:', error)
444
- return new Response('Internal Server Error', { status: 500 })
445
- }
446
- }
447
- }
448
-
449
- // Factory function for easy use
450
- export function inputValidation(options: InputValidationOptions = {}): (req: EnhancedRequest, next: NextFunction) => Promise<Response> {
451
- const instance = new InputValidation(options)
452
- return async (req: EnhancedRequest, next: NextFunction) => instance.handle(req, next)
453
- }
@@ -1,37 +0,0 @@
1
- import type { EnhancedRequest, NextFunction } from '../types'
2
-
3
- export default class JsonBody {
4
- async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
5
- // Only process requests with application/json content type
6
- const contentType = req.headers.get('content-type')
7
- if (contentType && contentType.includes('application/json')) {
8
- try {
9
- // Clone the request since it can only be used once
10
- const clonedReq = req.clone()
11
- const body = await clonedReq.json()
12
-
13
- // Attach the parsed body to the request object
14
- Object.defineProperty(req, 'jsonBody', {
15
- value: body,
16
- writable: true,
17
- enumerable: true,
18
- configurable: true,
19
- })
20
- }
21
- catch {
22
- // If JSON parsing fails, return a 400 Bad Request
23
- return new Response(
24
- JSON.stringify({ error: 'Invalid JSON payload' }),
25
- {
26
- status: 400,
27
- headers: { 'Content-Type': 'application/json' },
28
- },
29
- )
30
- }
31
- }
32
-
33
- // Continue to next middleware
34
- const response = await next()
35
- return response || new Response('Not Found', { status: 404 })
36
- }
37
- }