@stacksjs/bun-router 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/dist/chunk-2mx7fq49.js +4 -0
  2. package/dist/chunk-a8p83068.js +103 -0
  3. package/dist/{chunk-cgptvjdf.js → chunk-y3xq6wq6.js} +1 -1
  4. package/dist/cli.js +4 -3
  5. package/dist/container/index.js +1149 -211
  6. package/dist/container/service-provider.d.ts +3 -3
  7. package/dist/development/performance-profiler.d.ts +3 -3
  8. package/dist/development/route-debugger.d.ts +1 -1
  9. package/dist/development/route-inspector.d.ts +2 -2
  10. package/dist/index.js +369 -2209
  11. package/dist/observability/integration.d.ts +1 -1
  12. package/dist/response/macros.d.ts +1 -1
  13. package/dist/router/index.d.ts +7 -7
  14. package/dist/router/router.d.ts +0 -32
  15. package/dist/testing/performance-testing.d.ts +2 -2
  16. package/dist/testing/test-client.d.ts +1 -1
  17. package/dist/testing/websocket-testing.d.ts +1 -1
  18. package/package.json +7 -7
  19. package/dist/chunk-1ahs68ys.js +0 -18
  20. package/dist/chunk-g3ybefhg.js +0 -1923
  21. package/src/auth.ts +0 -489
  22. package/src/cache/lru-cache.ts +0 -457
  23. package/src/cache/middleware-memoization.ts +0 -531
  24. package/src/cache/route-cache-warmer.ts +0 -486
  25. package/src/cache/sqlite-cache.ts +0 -783
  26. package/src/cache/streaming-cache.ts +0 -572
  27. package/src/cli/colors.ts +0 -29
  28. package/src/cli/index.ts +0 -287
  29. package/src/cli/middleware.ts +0 -291
  30. package/src/cli/openapi.ts +0 -407
  31. package/src/cli/router.ts +0 -188
  32. package/src/cli/routes.ts +0 -265
  33. package/src/cli/utils.ts +0 -531
  34. package/src/cli.ts +0 -5
  35. package/src/config.ts +0 -322
  36. package/src/container/container.ts +0 -786
  37. package/src/container/contextual-binding.ts +0 -606
  38. package/src/container/decorators.ts +0 -368
  39. package/src/container/index.ts +0 -49
  40. package/src/container/service-provider.ts +0 -596
  41. package/src/development/hot-reload.ts +0 -673
  42. package/src/development/index.ts +0 -499
  43. package/src/development/performance-profiler.ts +0 -717
  44. package/src/development/route-debugger.ts +0 -527
  45. package/src/development/route-inspector.ts +0 -749
  46. package/src/development/typescript-utilities.ts +0 -682
  47. package/src/docs.ts +0 -397
  48. package/src/errors/circuit-breaker.ts +0 -733
  49. package/src/errors/error-handler.ts +0 -569
  50. package/src/errors/error-reporting.ts +0 -672
  51. package/src/errors/exceptions.ts +0 -536
  52. package/src/errors/graceful-degradation.ts +0 -623
  53. package/src/errors/index.ts +0 -21
  54. package/src/errors/router-errors.ts +0 -632
  55. package/src/file-serving/static-files.ts +0 -718
  56. package/src/index.ts +0 -66
  57. package/src/middleware/auth.ts +0 -220
  58. package/src/middleware/content_security_policy.ts +0 -215
  59. package/src/middleware/cors.ts +0 -142
  60. package/src/middleware/csrf.ts +0 -166
  61. package/src/middleware/ddos_protection.ts +0 -279
  62. package/src/middleware/file_security.ts +0 -191
  63. package/src/middleware/file_upload.ts +0 -275
  64. package/src/middleware/helmet.ts +0 -268
  65. package/src/middleware/index.ts +0 -117
  66. package/src/middleware/input_validation.ts +0 -453
  67. package/src/middleware/json_body.ts +0 -37
  68. package/src/middleware/performance_alerting.ts +0 -540
  69. package/src/middleware/performance_dashboard.ts +0 -661
  70. package/src/middleware/performance_monitor.ts +0 -945
  71. package/src/middleware/pipeline.ts +0 -489
  72. package/src/middleware/rate_limit.ts +0 -251
  73. package/src/middleware/request_id.ts +0 -36
  74. package/src/middleware/request_signing.ts +0 -638
  75. package/src/middleware/request_tracer.ts +0 -653
  76. package/src/middleware/response_cache.ts +0 -778
  77. package/src/middleware/security.ts +0 -482
  78. package/src/middleware/security_suite.ts +0 -257
  79. package/src/middleware/session.ts +0 -91
  80. package/src/model-binding/index.ts +0 -18
  81. package/src/model-binding/model-middleware.ts +0 -425
  82. package/src/model-binding/model-registry.ts +0 -550
  83. package/src/model-binding.ts +0 -370
  84. package/src/model-resolver-factory.ts +0 -106
  85. package/src/observability/correlation.ts +0 -691
  86. package/src/observability/health-checks.ts +0 -729
  87. package/src/observability/index.ts +0 -184
  88. package/src/observability/integration.ts +0 -548
  89. package/src/observability/metrics.ts +0 -753
  90. package/src/observability/tracing.ts +0 -638
  91. package/src/optimization/bun-utilities.ts +0 -778
  92. package/src/query-builder-integration.ts +0 -137
  93. package/src/request/context.ts +0 -109
  94. package/src/request/enhanced-request.ts +0 -876
  95. package/src/request/macros.ts +0 -822
  96. package/src/response/macros.ts +0 -665
  97. package/src/response/response-factory.ts +0 -596
  98. package/src/router/api-routes.ts +0 -243
  99. package/src/router/file-based-routing.ts +0 -697
  100. package/src/router/file-streaming.ts +0 -383
  101. package/src/router/fluent-routing.ts +0 -866
  102. package/src/router/group-organization.ts +0 -229
  103. package/src/router/handler-resolver.ts +0 -327
  104. package/src/router/http-methods.ts +0 -407
  105. package/src/router/index.ts +0 -193
  106. package/src/router/middleware-groups.ts +0 -222
  107. package/src/router/middleware-integration.ts +0 -399
  108. package/src/router/middleware.ts +0 -234
  109. package/src/router/model-binding.ts +0 -215
  110. package/src/router/optimized-route-matching.ts +0 -302
  111. package/src/router/route-building.ts +0 -221
  112. package/src/router/route-compiler.ts +0 -691
  113. package/src/router/route-matching.ts +0 -368
  114. package/src/router/route-trie.ts +0 -450
  115. package/src/router/router.ts +0 -1616
  116. package/src/router/server.ts +0 -684
  117. package/src/router/validation-integration.ts +0 -449
  118. package/src/router/view-rendering.ts +0 -233
  119. package/src/router/websocket.ts +0 -100
  120. package/src/routing/route-caching.ts +0 -402
  121. package/src/routing/route-throttling.ts +0 -469
  122. package/src/routing/subdomain-routing.ts +0 -492
  123. package/src/session/database-store.ts +0 -109
  124. package/src/session/file-store.ts +0 -148
  125. package/src/session/index.ts +0 -244
  126. package/src/session/memory-store.ts +0 -88
  127. package/src/session/redis-store.ts +0 -93
  128. package/src/streaming/index.ts +0 -17
  129. package/src/streaming/sse-handler.ts +0 -482
  130. package/src/streaming/stream-handler.ts +0 -552
  131. package/src/testing/auth-testing.ts +0 -448
  132. package/src/testing/file-upload-testing.ts +0 -543
  133. package/src/testing/index.ts +0 -10
  134. package/src/testing/middleware-testing.ts +0 -322
  135. package/src/testing/model-binding-testing.ts +0 -645
  136. package/src/testing/performance-testing.ts +0 -738
  137. package/src/testing/test-client.ts +0 -310
  138. package/src/testing/test-request.ts +0 -315
  139. package/src/testing/test-response.ts +0 -332
  140. package/src/testing/types.ts +0 -224
  141. package/src/testing/websocket-testing.ts +0 -590
  142. package/src/types/controller-types.ts +0 -385
  143. package/src/types/core.ts +0 -683
  144. package/src/types/middleware-types.ts +0 -422
  145. package/src/types/request-response-augmentation.ts +0 -489
  146. package/src/types/route-inference.ts +0 -372
  147. package/src/types.ts +0 -2123
  148. package/src/url.ts +0 -131
  149. package/src/utils/index.ts +0 -1
  150. package/src/utils/query-preservation.ts +0 -201
  151. package/src/utils.ts +0 -395
  152. package/src/validation/validator.ts +0 -688
  153. package/src/websocket/clustering.ts +0 -769
@@ -1,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
- }