@stacksjs/bun-router 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/auth.d.ts +22 -8
  2. package/dist/chunk-1ahs68ys.js +18 -0
  3. package/dist/{chunk-0145g1me.js → chunk-cgptvjdf.js} +147 -75
  4. package/dist/chunk-g3ybefhg.js +1923 -0
  5. package/dist/cli.js +3 -2
  6. package/dist/container/container.d.ts +1 -0
  7. package/dist/container/contextual-binding.d.ts +0 -1
  8. package/dist/container/decorators.d.ts +2 -5
  9. package/dist/container/index.d.ts +16 -0
  10. package/dist/container/index.js +322 -0
  11. package/dist/container/service-provider.d.ts +3 -3
  12. package/dist/development/performance-profiler.d.ts +3 -3
  13. package/dist/development/route-debugger.d.ts +1 -1
  14. package/dist/development/route-inspector.d.ts +2 -2
  15. package/dist/file-serving/static-files.d.ts +16 -0
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +1159 -1380
  18. package/dist/middleware/cors.d.ts +9 -0
  19. package/dist/middleware/csrf.d.ts +7 -0
  20. package/dist/middleware/ddos_protection.d.ts +16 -1
  21. package/dist/middleware/rate_limit.d.ts +7 -1
  22. package/dist/middleware/request_tracer.d.ts +15 -9
  23. package/dist/middleware/response_cache.d.ts +2 -1
  24. package/dist/observability/integration.d.ts +1 -1
  25. package/dist/request/context.d.ts +12 -1
  26. package/dist/request/macros.d.ts +40 -2
  27. package/dist/response/macros.d.ts +4 -4
  28. package/dist/router/fluent-routing.d.ts +50 -13
  29. package/dist/router/handler-resolver.d.ts +8 -0
  30. package/dist/router/index.d.ts +9 -7
  31. package/dist/router/route-compiler.d.ts +8 -10
  32. package/dist/router/route-trie.d.ts +7 -1
  33. package/dist/router/router.d.ts +13 -34
  34. package/dist/router/validation-integration.d.ts +10 -4
  35. package/dist/testing/performance-testing.d.ts +2 -2
  36. package/dist/testing/test-client.d.ts +1 -1
  37. package/dist/testing/websocket-testing.d.ts +1 -1
  38. package/dist/types/middleware-types.d.ts +1 -1
  39. package/dist/types/route-inference.d.ts +9 -2
  40. package/dist/types.d.ts +62 -9
  41. package/dist/utils.d.ts +1 -1
  42. package/package.json +12 -3
  43. package/dist/router/fluent-router.d.ts +0 -315
  44. package/src/auth.ts +0 -469
  45. package/src/cache/lru-cache.ts +0 -457
  46. package/src/cache/middleware-memoization.ts +0 -531
  47. package/src/cache/route-cache-warmer.ts +0 -486
  48. package/src/cache/sqlite-cache.ts +0 -783
  49. package/src/cache/streaming-cache.ts +0 -572
  50. package/src/cli/colors.ts +0 -29
  51. package/src/cli/index.ts +0 -287
  52. package/src/cli/middleware.ts +0 -291
  53. package/src/cli/openapi.ts +0 -407
  54. package/src/cli/router.ts +0 -188
  55. package/src/cli/routes.ts +0 -265
  56. package/src/cli/utils.ts +0 -531
  57. package/src/cli.ts +0 -5
  58. package/src/config.ts +0 -322
  59. package/src/container/container.ts +0 -740
  60. package/src/container/contextual-binding.ts +0 -603
  61. package/src/container/decorators.ts +0 -359
  62. package/src/container/service-provider.ts +0 -596
  63. package/src/development/hot-reload.ts +0 -673
  64. package/src/development/index.ts +0 -499
  65. package/src/development/performance-profiler.ts +0 -717
  66. package/src/development/route-debugger.ts +0 -527
  67. package/src/development/route-inspector.ts +0 -749
  68. package/src/development/typescript-utilities.ts +0 -682
  69. package/src/docs.ts +0 -397
  70. package/src/errors/circuit-breaker.ts +0 -732
  71. package/src/errors/error-handler.ts +0 -569
  72. package/src/errors/error-reporting.ts +0 -672
  73. package/src/errors/exceptions.ts +0 -536
  74. package/src/errors/graceful-degradation.ts +0 -621
  75. package/src/errors/index.ts +0 -21
  76. package/src/errors/router-errors.ts +0 -632
  77. package/src/file-serving/static-files.ts +0 -581
  78. package/src/index.ts +0 -14
  79. package/src/middleware/auth.ts +0 -220
  80. package/src/middleware/content_security_policy.ts +0 -215
  81. package/src/middleware/cors.ts +0 -74
  82. package/src/middleware/csrf.ts +0 -118
  83. package/src/middleware/ddos_protection.ts +0 -255
  84. package/src/middleware/file_security.ts +0 -191
  85. package/src/middleware/file_upload.ts +0 -275
  86. package/src/middleware/helmet.ts +0 -268
  87. package/src/middleware/index.ts +0 -117
  88. package/src/middleware/input_validation.ts +0 -449
  89. package/src/middleware/json_body.ts +0 -37
  90. package/src/middleware/performance_alerting.ts +0 -538
  91. package/src/middleware/performance_dashboard.ts +0 -661
  92. package/src/middleware/performance_monitor.ts +0 -943
  93. package/src/middleware/pipeline.ts +0 -489
  94. package/src/middleware/rate_limit.ts +0 -245
  95. package/src/middleware/request_id.ts +0 -36
  96. package/src/middleware/request_signing.ts +0 -636
  97. package/src/middleware/request_tracer.ts +0 -636
  98. package/src/middleware/response_cache.ts +0 -743
  99. package/src/middleware/security.ts +0 -482
  100. package/src/middleware/security_suite.ts +0 -257
  101. package/src/middleware/session.ts +0 -91
  102. package/src/model-binding/index.ts +0 -18
  103. package/src/model-binding/model-middleware.ts +0 -425
  104. package/src/model-binding/model-registry.ts +0 -550
  105. package/src/model-binding.ts +0 -370
  106. package/src/model-resolver-factory.ts +0 -106
  107. package/src/observability/correlation.ts +0 -691
  108. package/src/observability/health-checks.ts +0 -729
  109. package/src/observability/index.ts +0 -184
  110. package/src/observability/integration.ts +0 -548
  111. package/src/observability/metrics.ts +0 -753
  112. package/src/observability/tracing.ts +0 -638
  113. package/src/optimization/bun-utilities.ts +0 -778
  114. package/src/query-builder-integration.ts +0 -137
  115. package/src/request/context.ts +0 -62
  116. package/src/request/enhanced-request.ts +0 -857
  117. package/src/request/macros.ts +0 -688
  118. package/src/response/macros.ts +0 -665
  119. package/src/response/response-factory.ts +0 -596
  120. package/src/router/api-routes.ts +0 -243
  121. package/src/router/file-based-routing.ts +0 -690
  122. package/src/router/file-streaming.ts +0 -383
  123. package/src/router/fluent-router.ts +0 -927
  124. package/src/router/fluent-routing.ts +0 -797
  125. package/src/router/group-organization.ts +0 -213
  126. package/src/router/handler-resolver.ts +0 -291
  127. package/src/router/http-methods.ts +0 -377
  128. package/src/router/index.ts +0 -187
  129. package/src/router/middleware-groups.ts +0 -222
  130. package/src/router/middleware-integration.ts +0 -399
  131. package/src/router/middleware.ts +0 -231
  132. package/src/router/model-binding.ts +0 -215
  133. package/src/router/optimized-route-matching.ts +0 -253
  134. package/src/router/route-building.ts +0 -221
  135. package/src/router/route-compiler.ts +0 -702
  136. package/src/router/route-matching.ts +0 -349
  137. package/src/router/route-trie.ts +0 -464
  138. package/src/router/router.ts +0 -1604
  139. package/src/router/server.ts +0 -462
  140. package/src/router/validation-integration.ts +0 -443
  141. package/src/router/view-rendering.ts +0 -233
  142. package/src/router/websocket.ts +0 -100
  143. package/src/routing/route-caching.ts +0 -402
  144. package/src/routing/route-throttling.ts +0 -469
  145. package/src/routing/subdomain-routing.ts +0 -492
  146. package/src/session/database-store.ts +0 -109
  147. package/src/session/file-store.ts +0 -148
  148. package/src/session/index.ts +0 -244
  149. package/src/session/memory-store.ts +0 -88
  150. package/src/session/redis-store.ts +0 -93
  151. package/src/streaming/index.ts +0 -17
  152. package/src/streaming/sse-handler.ts +0 -482
  153. package/src/streaming/stream-handler.ts +0 -552
  154. package/src/testing/auth-testing.ts +0 -446
  155. package/src/testing/file-upload-testing.ts +0 -543
  156. package/src/testing/index.ts +0 -10
  157. package/src/testing/middleware-testing.ts +0 -322
  158. package/src/testing/model-binding-testing.ts +0 -645
  159. package/src/testing/performance-testing.ts +0 -738
  160. package/src/testing/test-client.ts +0 -310
  161. package/src/testing/test-request.ts +0 -315
  162. package/src/testing/test-response.ts +0 -332
  163. package/src/testing/types.ts +0 -224
  164. package/src/testing/websocket-testing.ts +0 -590
  165. package/src/types/controller-types.ts +0 -385
  166. package/src/types/core.ts +0 -683
  167. package/src/types/middleware-types.ts +0 -419
  168. package/src/types/request-response-augmentation.ts +0 -489
  169. package/src/types/route-inference.ts +0 -357
  170. package/src/types.ts +0 -2067
  171. package/src/url.ts +0 -126
  172. package/src/utils/index.ts +0 -1
  173. package/src/utils/query-preservation.ts +0 -201
  174. package/src/utils.ts +0 -392
  175. package/src/validation/validator.ts +0 -685
  176. package/src/websocket/clustering.ts +0 -762
@@ -1,685 +0,0 @@
1
- /**
2
- * Request/Response Enhancements - Validation System
3
- *
4
- * Laravel-style validation with custom rules and error handling
5
- */
6
-
7
- import type { EnhancedRequest, NextFunction } from '../types'
8
- import { ValidationException } from '../errors/exceptions'
9
-
10
- export interface ValidationRule {
11
- name: string
12
- validate: (value: any, parameters: string[], field: string, data: Record<string, any>) => Promise<boolean> | boolean
13
- message: string | ((_field: string, _parameters: string[]) => string)
14
- }
15
-
16
- export interface ValidationRules {
17
- [field: string]: string | ValidationRule[]
18
- }
19
-
20
- export interface ValidationErrors {
21
- [field: string]: string[]
22
- }
23
-
24
- export interface ValidatorConfig {
25
- stopOnFirstFailure?: boolean
26
- customMessages?: Record<string, string>
27
- customAttributes?: Record<string, string>
28
- bail?: boolean
29
- }
30
-
31
- /**
32
- * Built-in validation rules
33
- */
34
- export const BuiltInRules: Record<string, ValidationRule> = {
35
- required: {
36
- name: 'required',
37
- validate: (value) => {
38
- if (value === null || value === undefined)
39
- return false
40
- if (typeof value === 'string')
41
- return value.trim().length > 0
42
- if (Array.isArray(value))
43
- return value.length > 0
44
- if (typeof value === 'object')
45
- return Object.keys(value).length > 0
46
- return true
47
- },
48
- message: 'The :field field is required.',
49
- },
50
-
51
- string: {
52
- name: 'string',
53
- validate: value => typeof value === 'string',
54
- message: 'The :field field must be a string.',
55
- },
56
-
57
- number: {
58
- name: 'number',
59
- validate: value => typeof value === 'number' && !Number.isNaN(value),
60
- message: 'The :field field must be a number.',
61
- },
62
-
63
- integer: {
64
- name: 'integer',
65
- validate: value => Number.isInteger(Number(value)),
66
- message: 'The :field field must be an integer.',
67
- },
68
-
69
- boolean: {
70
- name: 'boolean',
71
- validate: value => typeof value === 'boolean' || value === 'true' || value === 'false' || value === '1' || value === '0',
72
- message: 'The :field field must be true or false.',
73
- },
74
-
75
- email: {
76
- name: 'email',
77
- validate: (value) => {
78
- const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
79
- return typeof value === 'string' && emailRegex.test(value)
80
- },
81
- message: 'The :field field must be a valid email address.',
82
- },
83
-
84
- url: {
85
- name: 'url',
86
- validate: (value) => {
87
- try {
88
- const url = new URL(value)
89
- return Boolean(url)
90
- }
91
- catch {
92
- return false
93
- }
94
- },
95
- message: 'The :field field must be a valid URL.',
96
- },
97
-
98
- min: {
99
- name: 'min',
100
- validate: (value, parameters) => {
101
- const min = Number(parameters[0])
102
- if (typeof value === 'string')
103
- return value.length >= min
104
- if (typeof value === 'number')
105
- return value >= min
106
- if (Array.isArray(value))
107
- return value.length >= min
108
- return false
109
- },
110
- message: (field, parameters) => `The ${field} field must be at least ${parameters[0]} characters.`,
111
- },
112
-
113
- max: {
114
- name: 'max',
115
- validate: (value, parameters) => {
116
- const max = Number(parameters[0])
117
- if (typeof value === 'string')
118
- return value.length <= max
119
- if (typeof value === 'number')
120
- return value <= max
121
- if (Array.isArray(value))
122
- return value.length <= max
123
- return false
124
- },
125
- message: (field, parameters) => `The ${field} field must not exceed ${parameters[0]} characters.`,
126
- },
127
-
128
- between: {
129
- name: 'between',
130
- validate: (value, parameters) => {
131
- const min = Number(parameters[0])
132
- const max = Number(parameters[1])
133
- if (typeof value === 'string')
134
- return value.length >= min && value.length <= max
135
- if (typeof value === 'number')
136
- return value >= min && value <= max
137
- if (Array.isArray(value))
138
- return value.length >= min && value.length <= max
139
- return false
140
- },
141
- message: (field, parameters) => `The ${field} field must be between ${parameters[0]} and ${parameters[1]}.`,
142
- },
143
-
144
- in: {
145
- name: 'in',
146
- validate: (value, parameters) => parameters.includes(String(value)),
147
- message: (field, parameters) => `The ${field} field must be one of: ${parameters.join(', ')}.`,
148
- },
149
-
150
- notIn: {
151
- name: 'not_in',
152
- validate: (value, parameters) => !parameters.includes(String(value)),
153
- message: (field, parameters) => `The ${field} field must not be one of: ${parameters.join(', ')}.`,
154
- },
155
-
156
- regex: {
157
- name: 'regex',
158
- validate: (value, parameters) => {
159
- const pattern = new RegExp(parameters[0])
160
- return typeof value === 'string' && pattern.test(value)
161
- },
162
- message: 'The :field field format is invalid.',
163
- },
164
-
165
- alpha: {
166
- name: 'alpha',
167
- validate: value => typeof value === 'string' && /^[a-z]+$/i.test(value),
168
- message: 'The :field field must contain only letters.',
169
- },
170
-
171
- alphaNum: {
172
- name: 'alpha_num',
173
- validate: value => typeof value === 'string' && /^[a-z0-9]+$/i.test(value),
174
- message: 'The :field field must contain only letters and numbers.',
175
- },
176
-
177
- alphaDash: {
178
- name: 'alpha_dash',
179
- validate: value => typeof value === 'string' && /^[\w-]+$/.test(value),
180
- message: 'The :field field must contain only letters, numbers, dashes, and underscores.',
181
- },
182
-
183
- date: {
184
- name: 'date',
185
- validate: (value) => {
186
- const date = new Date(value)
187
- return !Number.isNaN(date.getTime())
188
- },
189
- message: 'The :field field must be a valid date.',
190
- },
191
-
192
- dateAfter: {
193
- name: 'after',
194
- validate: (value, parameters) => {
195
- const date = new Date(value)
196
- const afterDate = new Date(parameters[0])
197
- return !Number.isNaN(date.getTime()) && !Number.isNaN(afterDate.getTime()) && date > afterDate
198
- },
199
- message: (field, parameters) => `The ${field} field must be after ${parameters[0]}.`,
200
- },
201
-
202
- dateBefore: {
203
- name: 'before',
204
- validate: (value, parameters) => {
205
- const date = new Date(value)
206
- const beforeDate = new Date(parameters[0])
207
- return !Number.isNaN(date.getTime()) && !Number.isNaN(beforeDate.getTime()) && date < beforeDate
208
- },
209
- message: (field, parameters) => `The ${field} field must be before ${parameters[0]}.`,
210
- },
211
-
212
- confirmed: {
213
- name: 'confirmed',
214
- validate: (value, parameters, field, data) => {
215
- const confirmationField = parameters[0] || `${field}_confirmation`
216
- return value === data[confirmationField]
217
- },
218
- message: 'The :field confirmation does not match.',
219
- },
220
-
221
- same: {
222
- name: 'same',
223
- validate: (value, parameters, field, data) => {
224
- return value === data[parameters[0]]
225
- },
226
- message: (field, parameters) => `The ${field} field must match ${parameters[0]}.`,
227
- },
228
-
229
- different: {
230
- name: 'different',
231
- validate: (value, parameters, field, data) => {
232
- return value !== data[parameters[0]]
233
- },
234
- message: (field, parameters) => `The ${field} field must be different from ${parameters[0]}.`,
235
- },
236
-
237
- json: {
238
- name: 'json',
239
- validate: (value) => {
240
- try {
241
- JSON.parse(value)
242
- return true
243
- }
244
- catch {
245
- return false
246
- }
247
- },
248
- message: 'The :field field must be valid JSON.',
249
- },
250
-
251
- uuid: {
252
- name: 'uuid',
253
- validate: (value) => {
254
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
255
- return typeof value === 'string' && uuidRegex.test(value)
256
- },
257
- message: 'The :field field must be a valid UUID.',
258
- },
259
-
260
- array: {
261
- name: 'array',
262
- validate: value => Array.isArray(value),
263
- message: 'The :field field must be an array.',
264
- },
265
-
266
- object: {
267
- name: 'object',
268
- validate: value => typeof value === 'object' && value !== null && !Array.isArray(value),
269
- message: 'The :field field must be an object.',
270
- },
271
- }
272
-
273
- /**
274
- * Database validation rules (require external implementation)
275
- */
276
- export const DatabaseRules: Record<string, ValidationRule> = {
277
- unique: {
278
- name: 'unique',
279
- validate: async (_value, _parameters) => {
280
- // This would need to be implemented with actual database queries
281
- // For now, return true as a placeholder
282
- console.warn('Database validation rule "unique" requires external implementation')
283
- return true
284
- },
285
- message: 'The :field field must be unique.',
286
- },
287
-
288
- exists: {
289
- name: 'exists',
290
- validate: async (_value, _parameters) => {
291
- // This would need to be implemented with actual database queries
292
- // For now, return true as a placeholder
293
- console.warn('Database validation rule "exists" requires external implementation')
294
- return true
295
- },
296
- message: 'The selected :field is invalid.',
297
- },
298
- }
299
-
300
- /**
301
- * Main validator class
302
- */
303
- export class Validator {
304
- private rules: Record<string, ValidationRule> = {}
305
- private config: ValidatorConfig
306
-
307
- constructor(config: ValidatorConfig = {}) {
308
- this.config = {
309
- stopOnFirstFailure: false,
310
- bail: false,
311
- ...config,
312
- }
313
-
314
- // Register built-in rules
315
- this.registerRules(BuiltInRules)
316
- }
317
-
318
- /**
319
- * Register validation rules
320
- */
321
- registerRule(rule: ValidationRule): void {
322
- this.rules[rule.name] = rule
323
- }
324
-
325
- /**
326
- * Register multiple validation rules
327
- */
328
- registerRules(rules: Record<string, ValidationRule>): void {
329
- Object.values(rules).forEach(rule => this.registerRule(rule))
330
- }
331
-
332
- /**
333
- * Parse validation rule string
334
- */
335
- private parseRuleString(ruleString: string): Array<{ name: string, parameters: string[] }> {
336
- return ruleString.split('|').map((rule) => {
337
- const [name, ...paramParts] = rule.split(':')
338
- const parameters = paramParts.length > 0 ? paramParts.join(':').split(',') : []
339
- return { name: name.trim(), parameters }
340
- })
341
- }
342
-
343
- /**
344
- * Validate data against rules
345
- */
346
- async validate(data: Record<string, any>, rules: ValidationRules): Promise<ValidationErrors> {
347
- const errors: ValidationErrors = {}
348
-
349
- for (const [field, fieldRules] of Object.entries(rules)) {
350
- const fieldErrors: string[] = []
351
- const value = this.getNestedValue(data, field)
352
-
353
- // Parse rules if they're in string format
354
- const parsedRules = typeof fieldRules === 'string'
355
- ? this.parseRuleString(fieldRules)
356
- : fieldRules.map(rule => ({ name: rule.name, parameters: [] }))
357
-
358
- for (const { name, parameters } of parsedRules) {
359
- const rule = this.rules[name]
360
- if (!rule) {
361
- console.warn(`Validation rule "${name}" not found`)
362
- continue
363
- }
364
-
365
- try {
366
- const isValid = await rule.validate(value, parameters, field, data)
367
-
368
- if (!isValid) {
369
- const message = this.formatErrorMessage(rule, field, parameters)
370
- fieldErrors.push(message)
371
-
372
- if (this.config.stopOnFirstFailure || this.config.bail) {
373
- break
374
- }
375
- }
376
- }
377
- catch (error) {
378
- console.error(`Error validating rule "${name}" for field "${field}":`, error)
379
- fieldErrors.push(`Validation error for ${field}`)
380
- }
381
- }
382
-
383
- if (fieldErrors.length > 0) {
384
- errors[field] = fieldErrors
385
- }
386
- }
387
-
388
- return errors
389
- }
390
-
391
- /**
392
- * Validate and throw exception if validation fails
393
- */
394
- async validateOrFail(data: Record<string, any>, rules: ValidationRules): Promise<void> {
395
- const errors = await this.validate(data, rules)
396
-
397
- if (Object.keys(errors).length > 0) {
398
- throw new ValidationException('Validation failed', errors)
399
- }
400
- }
401
-
402
- /**
403
- * Get nested value from object using dot notation
404
- */
405
- private getNestedValue(obj: Record<string, any>, path: string): any {
406
- return path.split('.').reduce((current, key) => {
407
- return current && current[key] !== undefined ? current[key] : undefined
408
- }, obj)
409
- }
410
-
411
- /**
412
- * Format error message
413
- */
414
- private formatErrorMessage(rule: ValidationRule, field: string, parameters: string[]): string {
415
- const customMessage = this.config.customMessages?.[`${field}.${rule.name}`]
416
- || this.config.customMessages?.[rule.name]
417
-
418
- if (customMessage) {
419
- return this.replacePlaceholders(customMessage, field, parameters)
420
- }
421
-
422
- const message = typeof rule.message === 'function'
423
- ? rule.message(field, parameters)
424
- : rule.message
425
-
426
- return this.replacePlaceholders(message, field, parameters)
427
- }
428
-
429
- /**
430
- * Replace placeholders in error messages
431
- */
432
- private replacePlaceholders(message: string, field: string, parameters: string[]): string {
433
- const fieldName = this.config.customAttributes?.[field] || field.replace(/_/g, ' ')
434
-
435
- return message
436
- .replace(/:field/g, fieldName)
437
- .replace(/:attribute/g, fieldName)
438
- .replace(/:value/g, parameters[0] || '')
439
- .replace(/:other/g, parameters[1] || '')
440
- }
441
- }
442
-
443
- /**
444
- * Global validator instance
445
- */
446
- export const globalValidator: Validator = new Validator()
447
-
448
- /**
449
- * Validation middleware factory
450
- */
451
- export function createValidationMiddleware(rules: ValidationRules, config?: ValidatorConfig) {
452
- const validator = new Validator(config)
453
-
454
- return async (req: EnhancedRequest, next: NextFunction): Promise<Response | null> => {
455
- try {
456
- // Get data from request body, query, and params
457
- const data = {
458
- ...req.query,
459
- ...req.params,
460
- ...(req.jsonBody || {}),
461
- ...(req.formBody || {}),
462
- }
463
-
464
- await validator.validateOrFail(data, rules)
465
-
466
- // Add validated data to request
467
- req.validated = data
468
-
469
- return await next()
470
- }
471
- catch (error) {
472
- if (error instanceof ValidationException) {
473
- throw error
474
- }
475
- throw new ValidationException('Validation error occurred')
476
- }
477
- }
478
- }
479
-
480
- /**
481
- * Validation rule builder for fluent API
482
- */
483
- export class ValidationRuleBuilder {
484
- private rules: string[] = []
485
-
486
- required(): this {
487
- this.rules.push('required')
488
- return this
489
- }
490
-
491
- string(): this {
492
- this.rules.push('string')
493
- return this
494
- }
495
-
496
- number(): this {
497
- this.rules.push('number')
498
- return this
499
- }
500
-
501
- integer(): this {
502
- this.rules.push('integer')
503
- return this
504
- }
505
-
506
- boolean(): this {
507
- this.rules.push('boolean')
508
- return this
509
- }
510
-
511
- email(): this {
512
- this.rules.push('email')
513
- return this
514
- }
515
-
516
- url(): this {
517
- this.rules.push('url')
518
- return this
519
- }
520
-
521
- min(value: number): this {
522
- this.rules.push(`min:${value}`)
523
- return this
524
- }
525
-
526
- max(value: number): this {
527
- this.rules.push(`max:${value}`)
528
- return this
529
- }
530
-
531
- between(min: number, max: number): this {
532
- this.rules.push(`between:${min},${max}`)
533
- return this
534
- }
535
-
536
- in(...values: string[]): this {
537
- this.rules.push(`in:${values.join(',')}`)
538
- return this
539
- }
540
-
541
- notIn(...values: string[]): this {
542
- this.rules.push(`not_in:${values.join(',')}`)
543
- return this
544
- }
545
-
546
- regex(pattern: string): this {
547
- this.rules.push(`regex:${pattern}`)
548
- return this
549
- }
550
-
551
- alpha(): this {
552
- this.rules.push('alpha')
553
- return this
554
- }
555
-
556
- alphaNum(): this {
557
- this.rules.push('alpha_num')
558
- return this
559
- }
560
-
561
- alphaDash(): this {
562
- this.rules.push('alpha_dash')
563
- return this
564
- }
565
-
566
- date(): this {
567
- this.rules.push('date')
568
- return this
569
- }
570
-
571
- after(date: string): this {
572
- this.rules.push(`after:${date}`)
573
- return this
574
- }
575
-
576
- before(date: string): this {
577
- this.rules.push(`before:${date}`)
578
- return this
579
- }
580
-
581
- confirmed(field?: string): this {
582
- this.rules.push(field ? `confirmed:${field}` : 'confirmed')
583
- return this
584
- }
585
-
586
- same(field: string): this {
587
- this.rules.push(`same:${field}`)
588
- return this
589
- }
590
-
591
- different(field: string): this {
592
- this.rules.push(`different:${field}`)
593
- return this
594
- }
595
-
596
- json(): this {
597
- this.rules.push('json')
598
- return this
599
- }
600
-
601
- uuid(): this {
602
- this.rules.push('uuid')
603
- return this
604
- }
605
-
606
- array(): this {
607
- this.rules.push('array')
608
- return this
609
- }
610
-
611
- object(): this {
612
- this.rules.push('object')
613
- return this
614
- }
615
-
616
- unique(table: string, column?: string): this {
617
- this.rules.push(column ? `unique:${table},${column}` : `unique:${table}`)
618
- return this
619
- }
620
-
621
- exists(table: string, column?: string): this {
622
- this.rules.push(column ? `exists:${table},${column}` : `exists:${table}`)
623
- return this
624
- }
625
-
626
- custom(ruleName: string, ...parameters: string[]): this {
627
- this.rules.push(parameters.length > 0 ? `${ruleName}:${parameters.join(',')}` : ruleName)
628
- return this
629
- }
630
-
631
- build(): string {
632
- return this.rules.join('|')
633
- }
634
- }
635
-
636
- /**
637
- * Factory function to create validation rule builder
638
- */
639
- export function rule(): ValidationRuleBuilder {
640
- return new ValidationRuleBuilder()
641
- }
642
-
643
- /**
644
- * Validation helper functions
645
- */
646
- export const ValidationHelpers = {
647
- /**
648
- * Create validation rules object
649
- */
650
- rules(rules: Record<string, string | ValidationRuleBuilder>): ValidationRules {
651
- const result: ValidationRules = {}
652
-
653
- for (const [field, fieldRules] of Object.entries(rules)) {
654
- result[field] = fieldRules instanceof ValidationRuleBuilder
655
- ? fieldRules.build()
656
- : fieldRules
657
- }
658
-
659
- return result
660
- },
661
-
662
- /**
663
- * Validate single value
664
- */
665
- async validateValue(value: any, rules: string, field = 'value'): Promise<string[]> {
666
- const validator = new Validator()
667
- const errors = await validator.validate({ [field]: value }, { [field]: rules })
668
- return errors[field] || []
669
- },
670
-
671
- /**
672
- * Check if value passes validation
673
- */
674
- async passes(value: any, rules: string): Promise<boolean> {
675
- const errors = await this.validateValue(value, rules)
676
- return errors.length === 0
677
- },
678
-
679
- /**
680
- * Check if value fails validation
681
- */
682
- async fails(value: any, rules: string): Promise<boolean> {
683
- return !(await this.passes(value, rules))
684
- },
685
- }