@stacksjs/bun-router 0.0.5 → 0.0.6

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 (269) hide show
  1. package/dist/auth.d.ts +134 -0
  2. package/dist/cache/lru-cache.d.ts +139 -0
  3. package/dist/cache/middleware-memoization.d.ts +151 -0
  4. package/dist/cache/route-cache-warmer.d.ts +161 -0
  5. package/dist/cache/sqlite-cache.d.ts +209 -0
  6. package/dist/cache/streaming-cache.d.ts +132 -0
  7. package/dist/cli/colors.d.ts +15 -0
  8. package/dist/cli/index.d.ts +10 -0
  9. package/dist/cli/middleware.d.ts +31 -0
  10. package/dist/cli/openapi.d.ts +17 -0
  11. package/dist/cli/router.d.ts +15 -0
  12. package/dist/cli/routes.d.ts +29 -0
  13. package/dist/cli/utils.d.ts +74 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +1 -1
  16. package/dist/config.d.ts +7 -0
  17. package/dist/container/container.d.ts +273 -0
  18. package/dist/container/contextual-binding.d.ts +240 -0
  19. package/dist/container/decorators.d.ts +141 -0
  20. package/dist/container/service-provider.d.ts +285 -0
  21. package/dist/development/hot-reload.d.ts +187 -0
  22. package/dist/development/index.d.ts +167 -0
  23. package/dist/development/performance-profiler.d.ts +217 -0
  24. package/dist/development/route-debugger.d.ts +154 -0
  25. package/dist/development/route-inspector.d.ts +211 -0
  26. package/dist/development/typescript-utilities.d.ts +209 -0
  27. package/dist/docs.d.ts +11 -0
  28. package/dist/errors/circuit-breaker.d.ts +195 -0
  29. package/dist/errors/error-handler.d.ts +88 -0
  30. package/dist/errors/error-reporting.d.ts +144 -0
  31. package/dist/errors/exceptions.d.ts +184 -0
  32. package/dist/errors/graceful-degradation.d.ts +154 -0
  33. package/dist/errors/index.d.ts +9 -0
  34. package/dist/errors/router-errors.d.ts +110 -0
  35. package/dist/file-serving/static-files.d.ts +143 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +319 -205
  38. package/dist/middleware/auth.d.ts +63 -0
  39. package/dist/middleware/content_security_policy.d.ts +53 -0
  40. package/dist/middleware/cors.d.ts +5 -0
  41. package/dist/middleware/csrf.d.ts +7 -0
  42. package/dist/middleware/ddos_protection.d.ts +39 -0
  43. package/dist/middleware/file_security.d.ts +26 -0
  44. package/dist/middleware/file_upload.d.ts +38 -0
  45. package/dist/middleware/helmet.d.ts +54 -0
  46. package/dist/middleware/index.d.ts +44 -0
  47. package/dist/middleware/input_validation.d.ts +45 -0
  48. package/dist/middleware/json_body.d.ts +4 -0
  49. package/dist/middleware/performance_alerting.d.ts +87 -0
  50. package/dist/middleware/performance_dashboard.d.ts +87 -0
  51. package/dist/middleware/performance_monitor.d.ts +209 -0
  52. package/dist/middleware/pipeline.d.ts +131 -0
  53. package/dist/middleware/rate_limit.d.ts +36 -0
  54. package/dist/middleware/request_id.d.ts +4 -0
  55. package/dist/middleware/request_signing.d.ts +153 -0
  56. package/dist/middleware/request_tracer.d.ts +72 -0
  57. package/dist/middleware/response_cache.d.ts +97 -0
  58. package/dist/middleware/security.d.ts +69 -0
  59. package/dist/middleware/security_suite.d.ts +46 -0
  60. package/dist/middleware/session.d.ts +23 -0
  61. package/dist/model-binding/index.d.ts +2 -0
  62. package/dist/model-binding/model-middleware.d.ts +118 -0
  63. package/dist/model-binding/model-registry.d.ts +164 -0
  64. package/dist/model-binding.d.ts +185 -0
  65. package/dist/model-resolver-factory.d.ts +31 -0
  66. package/dist/observability/correlation.d.ts +187 -0
  67. package/dist/observability/health-checks.d.ts +186 -0
  68. package/dist/observability/index.d.ts +60 -0
  69. package/dist/observability/integration.d.ts +147 -0
  70. package/dist/observability/metrics.d.ts +184 -0
  71. package/dist/observability/tracing.d.ts +187 -0
  72. package/dist/optimization/bun-utilities.d.ts +224 -0
  73. package/dist/query-builder-integration.d.ts +36 -0
  74. package/dist/request/context.d.ts +34 -0
  75. package/dist/request/enhanced-request.d.ts +213 -0
  76. package/dist/request/macros.d.ts +300 -0
  77. package/dist/response/macros.d.ts +245 -0
  78. package/dist/response/response-factory.d.ts +133 -0
  79. package/dist/router/api-routes.d.ts +5 -0
  80. package/dist/router/file-based-routing.d.ts +118 -0
  81. package/dist/router/file-streaming.d.ts +5 -0
  82. package/dist/router/fluent-router.d.ts +315 -0
  83. package/dist/router/fluent-routing.d.ts +271 -0
  84. package/dist/router/group-organization.d.ts +5 -0
  85. package/dist/router/handler-resolver.d.ts +24 -0
  86. package/dist/router/http-methods.d.ts +10 -0
  87. package/dist/router/index.d.ts +113 -0
  88. package/dist/router/middleware-groups.d.ts +94 -0
  89. package/dist/router/middleware-integration.d.ts +112 -0
  90. package/dist/router/middleware.d.ts +5 -0
  91. package/dist/router/model-binding.d.ts +5 -0
  92. package/dist/router/optimized-route-matching.d.ts +6 -0
  93. package/dist/router/route-building.d.ts +5 -0
  94. package/dist/router/route-compiler.d.ts +153 -0
  95. package/dist/router/route-matching.d.ts +5 -0
  96. package/dist/router/route-trie.d.ts +114 -0
  97. package/dist/router/router.d.ts +276 -0
  98. package/dist/router/server.d.ts +5 -0
  99. package/dist/router/validation-integration.d.ts +170 -0
  100. package/dist/router/view-rendering.d.ts +5 -0
  101. package/dist/router/websocket.d.ts +5 -0
  102. package/dist/routing/route-caching.d.ts +129 -0
  103. package/dist/routing/route-throttling.d.ts +150 -0
  104. package/dist/routing/subdomain-routing.d.ts +206 -0
  105. package/dist/session/database-store.d.ts +51 -0
  106. package/dist/session/file-store.d.ts +22 -0
  107. package/dist/session/index.d.ts +106 -0
  108. package/dist/session/memory-store.d.ts +21 -0
  109. package/dist/session/redis-store.d.ts +31 -0
  110. package/dist/streaming/index.d.ts +3 -0
  111. package/dist/streaming/sse-handler.d.ts +138 -0
  112. package/dist/streaming/stream-handler.d.ts +114 -0
  113. package/dist/testing/auth-testing.d.ts +156 -0
  114. package/dist/testing/file-upload-testing.d.ts +190 -0
  115. package/dist/testing/index.d.ts +10 -0
  116. package/dist/testing/middleware-testing.d.ts +138 -0
  117. package/dist/testing/model-binding-testing.d.ts +186 -0
  118. package/dist/testing/performance-testing.d.ts +235 -0
  119. package/dist/testing/test-client.d.ts +117 -0
  120. package/dist/testing/test-request.d.ts +85 -0
  121. package/dist/testing/test-response.d.ts +90 -0
  122. package/dist/testing/types.d.ts +207 -0
  123. package/dist/testing/websocket-testing.d.ts +227 -0
  124. package/dist/types/controller-types.d.ts +208 -0
  125. package/dist/types/core.d.ts +543 -0
  126. package/dist/types/middleware-types.d.ts +227 -0
  127. package/dist/types/request-response-augmentation.d.ts +261 -0
  128. package/dist/types/route-inference.d.ts +168 -0
  129. package/dist/types.d.ts +1776 -0
  130. package/dist/url.d.ts +56 -0
  131. package/dist/utils/index.d.ts +1 -0
  132. package/dist/utils/query-preservation.d.ts +48 -0
  133. package/dist/utils.d.ts +69 -0
  134. package/dist/validation/validator.d.ts +140 -0
  135. package/dist/websocket/clustering.d.ts +185 -0
  136. package/package.json +3 -2
  137. package/src/auth.ts +469 -0
  138. package/src/cache/lru-cache.ts +457 -0
  139. package/src/cache/middleware-memoization.ts +531 -0
  140. package/src/cache/route-cache-warmer.ts +486 -0
  141. package/src/cache/sqlite-cache.ts +783 -0
  142. package/src/cache/streaming-cache.ts +572 -0
  143. package/src/cli/colors.ts +29 -0
  144. package/src/cli/index.ts +287 -0
  145. package/src/cli/middleware.ts +291 -0
  146. package/src/cli/openapi.ts +407 -0
  147. package/src/cli/router.ts +188 -0
  148. package/src/cli/routes.ts +265 -0
  149. package/src/cli/utils.ts +531 -0
  150. package/src/cli.ts +5 -0
  151. package/src/config.ts +322 -0
  152. package/src/container/container.ts +740 -0
  153. package/src/container/contextual-binding.ts +603 -0
  154. package/src/container/decorators.ts +359 -0
  155. package/src/container/service-provider.ts +596 -0
  156. package/src/development/hot-reload.ts +673 -0
  157. package/src/development/index.ts +499 -0
  158. package/src/development/performance-profiler.ts +717 -0
  159. package/src/development/route-debugger.ts +527 -0
  160. package/src/development/route-inspector.ts +749 -0
  161. package/src/development/typescript-utilities.ts +678 -0
  162. package/src/docs.ts +397 -0
  163. package/src/errors/circuit-breaker.ts +732 -0
  164. package/src/errors/error-handler.ts +569 -0
  165. package/src/errors/error-reporting.ts +672 -0
  166. package/src/errors/exceptions.ts +536 -0
  167. package/src/errors/graceful-degradation.ts +621 -0
  168. package/src/errors/index.ts +21 -0
  169. package/src/errors/router-errors.ts +632 -0
  170. package/src/file-serving/static-files.ts +581 -0
  171. package/src/index.ts +14 -0
  172. package/src/middleware/auth.ts +219 -0
  173. package/src/middleware/content_security_policy.ts +215 -0
  174. package/src/middleware/cors.ts +74 -0
  175. package/src/middleware/csrf.ts +108 -0
  176. package/src/middleware/ddos_protection.ts +255 -0
  177. package/src/middleware/file_security.ts +191 -0
  178. package/src/middleware/file_upload.ts +264 -0
  179. package/src/middleware/helmet.ts +268 -0
  180. package/src/middleware/index.ts +117 -0
  181. package/src/middleware/input_validation.ts +449 -0
  182. package/src/middleware/json_body.ts +37 -0
  183. package/src/middleware/performance_alerting.ts +538 -0
  184. package/src/middleware/performance_dashboard.ts +661 -0
  185. package/src/middleware/performance_monitor.ts +943 -0
  186. package/src/middleware/pipeline.ts +489 -0
  187. package/src/middleware/rate_limit.ts +245 -0
  188. package/src/middleware/request_id.ts +36 -0
  189. package/src/middleware/request_signing.ts +636 -0
  190. package/src/middleware/request_tracer.ts +636 -0
  191. package/src/middleware/response_cache.ts +743 -0
  192. package/src/middleware/security.ts +482 -0
  193. package/src/middleware/security_suite.ts +257 -0
  194. package/src/middleware/session.ts +91 -0
  195. package/src/model-binding/index.ts +18 -0
  196. package/src/model-binding/model-middleware.ts +425 -0
  197. package/src/model-binding/model-registry.ts +550 -0
  198. package/src/model-binding.ts +370 -0
  199. package/src/model-resolver-factory.ts +106 -0
  200. package/src/observability/correlation.ts +691 -0
  201. package/src/observability/health-checks.ts +729 -0
  202. package/src/observability/index.ts +184 -0
  203. package/src/observability/integration.ts +548 -0
  204. package/src/observability/metrics.ts +753 -0
  205. package/src/observability/tracing.ts +638 -0
  206. package/src/optimization/bun-utilities.ts +778 -0
  207. package/src/query-builder-integration.ts +137 -0
  208. package/src/request/context.ts +62 -0
  209. package/src/request/enhanced-request.ts +857 -0
  210. package/src/request/macros.ts +688 -0
  211. package/src/response/macros.ts +612 -0
  212. package/src/response/response-factory.ts +588 -0
  213. package/src/router/api-routes.ts +243 -0
  214. package/src/router/file-based-routing.ts +670 -0
  215. package/src/router/file-streaming.ts +372 -0
  216. package/src/router/fluent-router.ts +927 -0
  217. package/src/router/fluent-routing.ts +797 -0
  218. package/src/router/group-organization.ts +213 -0
  219. package/src/router/handler-resolver.ts +291 -0
  220. package/src/router/http-methods.ts +377 -0
  221. package/src/router/index.ts +185 -0
  222. package/src/router/middleware-groups.ts +222 -0
  223. package/src/router/middleware-integration.ts +399 -0
  224. package/src/router/middleware.ts +231 -0
  225. package/src/router/model-binding.ts +215 -0
  226. package/src/router/optimized-route-matching.ts +253 -0
  227. package/src/router/route-building.ts +212 -0
  228. package/src/router/route-compiler.ts +702 -0
  229. package/src/router/route-matching.ts +349 -0
  230. package/src/router/route-trie.ts +464 -0
  231. package/src/router/router.ts +1508 -0
  232. package/src/router/server.ts +406 -0
  233. package/src/router/validation-integration.ts +443 -0
  234. package/src/router/view-rendering.ts +233 -0
  235. package/src/router/websocket.ts +100 -0
  236. package/src/routing/route-caching.ts +402 -0
  237. package/src/routing/route-throttling.ts +469 -0
  238. package/src/routing/subdomain-routing.ts +492 -0
  239. package/src/session/database-store.ts +109 -0
  240. package/src/session/file-store.ts +148 -0
  241. package/src/session/index.ts +244 -0
  242. package/src/session/memory-store.ts +88 -0
  243. package/src/session/redis-store.ts +93 -0
  244. package/src/streaming/index.ts +17 -0
  245. package/src/streaming/sse-handler.ts +482 -0
  246. package/src/streaming/stream-handler.ts +552 -0
  247. package/src/testing/auth-testing.ts +446 -0
  248. package/src/testing/file-upload-testing.ts +543 -0
  249. package/src/testing/index.ts +10 -0
  250. package/src/testing/middleware-testing.ts +322 -0
  251. package/src/testing/model-binding-testing.ts +645 -0
  252. package/src/testing/performance-testing.ts +738 -0
  253. package/src/testing/test-client.ts +310 -0
  254. package/src/testing/test-request.ts +315 -0
  255. package/src/testing/test-response.ts +332 -0
  256. package/src/testing/types.ts +224 -0
  257. package/src/testing/websocket-testing.ts +590 -0
  258. package/src/types/controller-types.ts +385 -0
  259. package/src/types/core.ts +683 -0
  260. package/src/types/middleware-types.ts +419 -0
  261. package/src/types/request-response-augmentation.ts +489 -0
  262. package/src/types/route-inference.ts +357 -0
  263. package/src/types.ts +2049 -0
  264. package/src/url.ts +126 -0
  265. package/src/utils/index.ts +1 -0
  266. package/src/utils/query-preservation.ts +201 -0
  267. package/src/utils.ts +327 -0
  268. package/src/validation/validator.ts +685 -0
  269. package/src/websocket/clustering.ts +762 -0
@@ -0,0 +1,678 @@
1
+ /**
2
+ * Development Tools - TypeScript Utilities
3
+ *
4
+ * TypeScript development utilities, type checking, and code generation
5
+ */
6
+
7
+ import type { EnhancedRequest } from '../types'
8
+
9
+ export interface TypeScriptConfig {
10
+ strictMode?: boolean
11
+ generateTypes?: boolean
12
+ validateTypes?: boolean
13
+ outputDir?: string
14
+ includeComments?: boolean
15
+ generateSchemas?: boolean
16
+ }
17
+
18
+ export interface RouteTypeInfo {
19
+ method: string
20
+ pattern: string
21
+ requestType: string
22
+ responseType: string
23
+ paramsType: string
24
+ queryType: string
25
+ bodyType: string
26
+ middlewareTypes: string[]
27
+ handlerSignature: string
28
+ }
29
+
30
+ export interface TypeDefinition {
31
+ name: string
32
+ type: 'interface' | 'type' | 'enum' | 'class'
33
+ definition: string
34
+ imports: string[]
35
+ exports: string[]
36
+ documentation?: string
37
+ }
38
+
39
+ export interface ValidationSchema {
40
+ type: 'object' | 'array' | 'string' | 'number' | 'boolean'
41
+ properties?: Record<string, ValidationSchema>
42
+ items?: ValidationSchema
43
+ required?: string[]
44
+ pattern?: string
45
+ minimum?: number
46
+ maximum?: number
47
+ enum?: any[]
48
+ }
49
+
50
+ /**
51
+ * TypeScript utilities for development
52
+ */
53
+ export class TypeScriptUtilities {
54
+ private config: TypeScriptConfig
55
+ private routeTypes = new Map<string, RouteTypeInfo>()
56
+ private typeDefinitions = new Map<string, TypeDefinition>()
57
+
58
+ constructor(config: TypeScriptConfig = {}) {
59
+ this.config = {
60
+ strictMode: true,
61
+ generateTypes: true,
62
+ validateTypes: true,
63
+ outputDir: './types',
64
+ includeComments: true,
65
+ generateSchemas: true,
66
+ ...config,
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Register route type information
72
+ */
73
+ registerRouteTypes(
74
+ method: string,
75
+ pattern: string,
76
+ options: {
77
+ requestType?: string
78
+ responseType?: string
79
+ paramsType?: string
80
+ queryType?: string
81
+ bodyType?: string
82
+ middlewareTypes?: string[]
83
+ handlerSignature?: string
84
+ } = {},
85
+ ): void {
86
+ const routeKey = `${method.toUpperCase()}:${pattern}`
87
+
88
+ const typeInfo: RouteTypeInfo = {
89
+ method: method.toUpperCase(),
90
+ pattern,
91
+ requestType: options.requestType || 'EnhancedRequest',
92
+ responseType: options.responseType || 'Response',
93
+ paramsType: options.paramsType || this.inferParamsType(pattern),
94
+ queryType: options.queryType || 'Record<string, string>',
95
+ bodyType: options.bodyType || 'unknown',
96
+ middlewareTypes: options.middlewareTypes || [],
97
+ handlerSignature: options.handlerSignature || this.generateHandlerSignature(options),
98
+ }
99
+
100
+ this.routeTypes.set(routeKey, typeInfo)
101
+ }
102
+
103
+ /**
104
+ * Generate TypeScript definitions for all routes
105
+ */
106
+ generateRouteTypes(): string {
107
+ const routes = Array.from(this.routeTypes.values())
108
+ let output = ''
109
+
110
+ // Add imports
111
+ output += this.generateImports()
112
+ output += '\n\n'
113
+
114
+ // Generate parameter types
115
+ output += this.generateParamTypes(routes)
116
+ output += '\n\n'
117
+
118
+ // Generate handler types
119
+ output += this.generateHandlerTypes(routes)
120
+ output += '\n\n'
121
+
122
+ // Generate route registry type
123
+ output += this.generateRouteRegistryType(routes)
124
+ output += '\n\n'
125
+
126
+ // Generate utility types
127
+ output += this.generateUtilityTypes()
128
+
129
+ return output
130
+ }
131
+
132
+ /**
133
+ * Generate validation schemas from TypeScript types
134
+ */
135
+ generateValidationSchemas(): Record<string, ValidationSchema> {
136
+ const schemas: Record<string, ValidationSchema> = {}
137
+
138
+ this.routeTypes.forEach((typeInfo, routeKey) => {
139
+ // Generate schema for request body
140
+ if (typeInfo.bodyType && typeInfo.bodyType !== 'unknown') {
141
+ schemas[`${routeKey}_body`] = this.typeToSchema(typeInfo.bodyType)
142
+ }
143
+
144
+ // Generate schema for query parameters
145
+ if (typeInfo.queryType && typeInfo.queryType !== 'Record<string, string>') {
146
+ schemas[`${routeKey}_query`] = this.typeToSchema(typeInfo.queryType)
147
+ }
148
+
149
+ // Generate schema for route parameters
150
+ if (typeInfo.paramsType && typeInfo.paramsType !== 'Record<string, string>') {
151
+ schemas[`${routeKey}_params`] = this.typeToSchema(typeInfo.paramsType)
152
+ }
153
+ })
154
+
155
+ return schemas
156
+ }
157
+
158
+ /**
159
+ * Generate OpenAPI schema from route types
160
+ */
161
+ generateOpenAPISchema(): any {
162
+ const routes = Array.from(this.routeTypes.values())
163
+ const openapi = {
164
+ openapi: '3.0.0',
165
+ info: {
166
+ title: 'API Documentation',
167
+ version: '1.0.0',
168
+ },
169
+ paths: {} as Record<string, any>,
170
+ components: {
171
+ schemas: {} as Record<string, any>,
172
+ },
173
+ }
174
+
175
+ routes.forEach((route) => {
176
+ const path = route.pattern.replace(/\{([^}:]+)(?::[^}]+)?\}/g, '{$1}')
177
+ const method = route.method.toLowerCase()
178
+
179
+ if (!openapi.paths[path]) {
180
+ openapi.paths[path] = {}
181
+ }
182
+
183
+ const operation: any = {
184
+ summary: `${route.method} ${route.pattern}`,
185
+ operationId: `${method}${this.pathToOperationId(path)}`,
186
+ responses: {
187
+ 200: {
188
+ description: 'Success',
189
+ content: {
190
+ 'application/json': {
191
+ schema: this.typeToOpenAPISchema(route.responseType),
192
+ },
193
+ },
194
+ },
195
+ },
196
+ }
197
+
198
+ // Add parameters
199
+ const params = this.extractPathParameters(route.pattern)
200
+ if (params.length > 0) {
201
+ operation.parameters = params.map(param => ({
202
+ name: param.name,
203
+ in: 'path',
204
+ required: true,
205
+ schema: { type: param.type === 'number' ? 'integer' : 'string' },
206
+ }))
207
+ }
208
+
209
+ // Add request body for POST/PUT/PATCH
210
+ if (['post', 'put', 'patch'].includes(method) && route.bodyType !== 'unknown') {
211
+ operation.requestBody = {
212
+ required: true,
213
+ content: {
214
+ 'application/json': {
215
+ schema: this.typeToOpenAPISchema(route.bodyType),
216
+ },
217
+ },
218
+ }
219
+ }
220
+
221
+ openapi.paths[path][method] = operation
222
+ })
223
+
224
+ return openapi
225
+ }
226
+
227
+ /**
228
+ * Validate request against TypeScript types
229
+ */
230
+ validateRequest(req: EnhancedRequest, routeKey: string): {
231
+ valid: boolean
232
+ errors: string[]
233
+ warnings: string[]
234
+ } {
235
+ const typeInfo = this.routeTypes.get(routeKey)
236
+ if (!typeInfo) {
237
+ return { valid: false, errors: ['Route type information not found'], warnings: [] }
238
+ }
239
+
240
+ const errors: string[] = []
241
+ const warnings: string[] = []
242
+
243
+ // Validate parameters
244
+ if (typeInfo.paramsType !== 'Record<string, string>') {
245
+ const paramErrors = this.validateParams(req, typeInfo.paramsType)
246
+ errors.push(...paramErrors)
247
+ }
248
+
249
+ // Validate query parameters
250
+ if (typeInfo.queryType !== 'Record<string, string>') {
251
+ const queryErrors = this.validateQuery(req, typeInfo.queryType)
252
+ errors.push(...queryErrors)
253
+ }
254
+
255
+ // Validate request body
256
+ if (typeInfo.bodyType !== 'unknown' && req.body) {
257
+ const bodyErrors = this.validateBody(req, typeInfo.bodyType)
258
+ errors.push(...bodyErrors)
259
+ }
260
+
261
+ return {
262
+ valid: errors.length === 0,
263
+ errors,
264
+ warnings,
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Generate type-safe route builder
270
+ */
271
+ generateRouteBuilder(): string {
272
+ const routes = Array.from(this.routeTypes.values())
273
+
274
+ let output = `/**
275
+ * Type-safe route builder
276
+ * Generated automatically from route definitions
277
+ */
278
+
279
+ import type { EnhancedRequest } from '../types'
280
+
281
+ export class TypeSafeRouteBuilder {
282
+ `
283
+
284
+ routes.forEach((route) => {
285
+ const methodName = `${route.method.toLowerCase()}${this.pathToMethodName(route.pattern)}`
286
+
287
+ output += ` /**
288
+ * ${route.method} ${route.pattern}
289
+ */
290
+ ${methodName}(
291
+ handler: (req: ${route.requestType} & { params: ${route.paramsType} }) => Promise<${route.responseType}>
292
+ ): void {
293
+ // Implementation would register the route with proper typing
294
+ }
295
+
296
+ `
297
+ })
298
+
299
+ output += '}\n'
300
+ return output
301
+ }
302
+
303
+ /**
304
+ * Generate middleware type definitions
305
+ */
306
+ generateMiddlewareTypes(): string {
307
+ const middlewareTypes = new Set<string>()
308
+
309
+ this.routeTypes.forEach((route) => {
310
+ route.middlewareTypes.forEach(type => middlewareTypes.add(type))
311
+ })
312
+
313
+ let output = `/**
314
+ * Middleware type definitions
315
+ */
316
+
317
+ export type MiddlewareFunction<T = any> = (
318
+ req: EnhancedRequest,
319
+ next: () => Promise<Response>
320
+ ) => Promise<Response>
321
+
322
+ export type MiddlewareWithConfig<T> = (config: T) => MiddlewareFunction
323
+
324
+ `
325
+
326
+ middlewareTypes.forEach((type) => {
327
+ output += `export type ${type}Middleware = MiddlewareFunction\n`
328
+ })
329
+
330
+ return output
331
+ }
332
+
333
+ /**
334
+ * Get route type information
335
+ */
336
+ getRouteTypes(): RouteTypeInfo[] {
337
+ return Array.from(this.routeTypes.values())
338
+ }
339
+
340
+ /**
341
+ * Get type definition
342
+ */
343
+ getTypeDefinition(name: string): TypeDefinition | undefined {
344
+ return this.typeDefinitions.get(name)
345
+ }
346
+
347
+ /**
348
+ * Register custom type definition
349
+ */
350
+ registerTypeDefinition(definition: TypeDefinition): void {
351
+ this.typeDefinitions.set(definition.name, definition)
352
+ }
353
+
354
+ /**
355
+ * Clear all type information
356
+ */
357
+ clear(): void {
358
+ this.routeTypes.clear()
359
+ this.typeDefinitions.clear()
360
+ }
361
+
362
+ /**
363
+ * Infer parameter types from route pattern
364
+ */
365
+ private inferParamsType(pattern: string): string {
366
+ const params = this.extractPathParameters(pattern)
367
+
368
+ if (params.length === 0) {
369
+ return 'Record<string, never>'
370
+ }
371
+
372
+ const properties = params.map((param) => {
373
+ const type = param.type === 'number' ? 'number' : 'string'
374
+ return ` ${param.name}: ${type}`
375
+ }).join('\n')
376
+
377
+ return `{\n${properties}\n}`
378
+ }
379
+
380
+ /**
381
+ * Extract path parameters from pattern
382
+ */
383
+ private extractPathParameters(pattern: string): Array<{ name: string, type: string, optional: boolean }> {
384
+ const params: Array<{ name: string, type: string, optional: boolean }> = []
385
+ const paramRegex = /\{([^}]+)\}/g
386
+
387
+ for (const match of pattern.matchAll(paramRegex)) {
388
+ const paramDef = match[1]
389
+ const [name, constraint] = paramDef.split(':')
390
+
391
+ params.push({
392
+ name: name.trim(),
393
+ type: this.inferParamType(constraint),
394
+ optional: paramDef.includes('?'),
395
+ })
396
+ }
397
+
398
+ return params
399
+ }
400
+
401
+ /**
402
+ * Infer parameter type from constraint
403
+ */
404
+ private inferParamType(constraint?: string): string {
405
+ if (!constraint)
406
+ return 'string'
407
+
408
+ if (constraint.includes('number') || constraint.includes('int'))
409
+ return 'number'
410
+ if (constraint.includes('uuid'))
411
+ return 'string'
412
+ if (constraint.includes('slug'))
413
+ return 'string'
414
+
415
+ return 'string'
416
+ }
417
+
418
+ /**
419
+ * Generate handler signature
420
+ */
421
+ private generateHandlerSignature(options: any): string {
422
+ const requestType = options.requestType || 'EnhancedRequest'
423
+ const responseType = options.responseType || 'Response'
424
+ const paramsType = options.paramsType || 'Record<string, string>'
425
+
426
+ return `(req: ${requestType} & { params: ${paramsType} }) => Promise<${responseType}>`
427
+ }
428
+
429
+ /**
430
+ * Generate imports section
431
+ */
432
+ private generateImports(): string {
433
+ return `import type { EnhancedRequest } from '../types'
434
+
435
+ // Generated route types`
436
+ }
437
+
438
+ /**
439
+ * Generate parameter types
440
+ */
441
+ private generateParamTypes(routes: RouteTypeInfo[]): string {
442
+ const paramTypes = new Set<string>()
443
+
444
+ routes.forEach((route) => {
445
+ if (route.paramsType !== 'Record<string, string>' && !route.paramsType.startsWith('{')) {
446
+ paramTypes.add(route.paramsType)
447
+ }
448
+ })
449
+
450
+ let output = '// Route parameter types\n'
451
+
452
+ routes.forEach((route) => {
453
+ if (route.paramsType.startsWith('{')) {
454
+ const typeName = `${route.method}${this.pathToTypeName(route.pattern)}Params`
455
+ output += `export interface ${typeName} ${route.paramsType}\n\n`
456
+ }
457
+ })
458
+
459
+ return output
460
+ }
461
+
462
+ /**
463
+ * Generate handler types
464
+ */
465
+ private generateHandlerTypes(routes: RouteTypeInfo[]): string {
466
+ let output = '// Route handler types\n'
467
+
468
+ routes.forEach((route) => {
469
+ const handlerName = `${route.method}${this.pathToTypeName(route.pattern)}Handler`
470
+ output += `export type ${handlerName} = ${route.handlerSignature}\n\n`
471
+ })
472
+
473
+ return output
474
+ }
475
+
476
+ /**
477
+ * Generate route registry type
478
+ */
479
+ private generateRouteRegistryType(routes: RouteTypeInfo[]): string {
480
+ let output = '// Route registry type\nexport interface RouteRegistry {\n'
481
+
482
+ routes.forEach((route) => {
483
+ const key = `'${route.method} ${route.pattern}'`
484
+ const handlerType = `${route.method}${this.pathToTypeName(route.pattern)}Handler`
485
+ output += ` ${key}: ${handlerType}\n`
486
+ })
487
+
488
+ output += '}\n'
489
+ return output
490
+ }
491
+
492
+ /**
493
+ * Generate utility types
494
+ */
495
+ private generateUtilityTypes(): string {
496
+ return `// Utility types
497
+ export type RouteMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'
498
+
499
+ export type RoutePattern = keyof RouteRegistry
500
+
501
+ export type HandlerForRoute<T extends RoutePattern> = RouteRegistry[T]
502
+
503
+ export type ExtractParams<T extends string> =
504
+ T extends \`\${string}{\${infer Param}}\${infer Rest}\`
505
+ ? { [K in Param]: string } & ExtractParams<Rest>
506
+ : {}
507
+
508
+ export type TypedRequest<T extends RoutePattern> = EnhancedRequest & {
509
+ params: ExtractParams<T>
510
+ }
511
+ `
512
+ }
513
+
514
+ /**
515
+ * Convert path to type name
516
+ */
517
+ private pathToTypeName(path: string): string {
518
+ return path
519
+ .replace(/[{}]/g, '')
520
+ .replace(/[^a-z0-9]/gi, '_')
521
+ .replace(/_+/g, '_')
522
+ .replace(/^_|_$/g, '')
523
+ .split('_')
524
+ .map(part => part.charAt(0).toUpperCase() + part.slice(1))
525
+ .join('')
526
+ }
527
+
528
+ /**
529
+ * Convert path to method name
530
+ */
531
+ private pathToMethodName(path: string): string {
532
+ const typeName = this.pathToTypeName(path)
533
+ return typeName.charAt(0).toLowerCase() + typeName.slice(1)
534
+ }
535
+
536
+ /**
537
+ * Convert path to operation ID
538
+ */
539
+ private pathToOperationId(path: string): string {
540
+ return this.pathToTypeName(path)
541
+ }
542
+
543
+ /**
544
+ * Convert TypeScript type to validation schema
545
+ */
546
+ private typeToSchema(type: string): ValidationSchema {
547
+ // Simplified type to schema conversion
548
+ if (type.includes('string')) {
549
+ return { type: 'string' }
550
+ }
551
+ else if (type.includes('number')) {
552
+ return { type: 'number' }
553
+ }
554
+ else if (type.includes('boolean')) {
555
+ return { type: 'boolean' }
556
+ }
557
+ else if (type.includes('[]')) {
558
+ return { type: 'array', items: { type: 'string' } }
559
+ }
560
+ else {
561
+ return { type: 'object' }
562
+ }
563
+ }
564
+
565
+ /**
566
+ * Convert TypeScript type to OpenAPI schema
567
+ */
568
+ private typeToOpenAPISchema(type: string): any {
569
+ if (type.includes('string')) {
570
+ return { type: 'string' }
571
+ }
572
+ else if (type.includes('number')) {
573
+ return { type: 'number' }
574
+ }
575
+ else if (type.includes('boolean')) {
576
+ return { type: 'boolean' }
577
+ }
578
+ else if (type.includes('[]')) {
579
+ return { type: 'array', items: { type: 'string' } }
580
+ }
581
+ else {
582
+ return { type: 'object' }
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Validate request parameters
588
+ */
589
+ private validateParams(_req: EnhancedRequest, _expectedType: string): string[] {
590
+ // Simplified validation - in a real implementation, this would use a proper type checker
591
+ return []
592
+ }
593
+
594
+ /**
595
+ * Validate query parameters
596
+ */
597
+ private validateQuery(_req: EnhancedRequest, _expectedType: string): string[] {
598
+ // Simplified validation
599
+ return []
600
+ }
601
+
602
+ /**
603
+ * Validate request body
604
+ */
605
+ private validateBody(_req: EnhancedRequest, _expectedType: string): string[] {
606
+ // Simplified validation
607
+ return []
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Global TypeScript utilities instance
613
+ */
614
+ let globalTsUtils: TypeScriptUtilities | null = null
615
+
616
+ /**
617
+ * Initialize global TypeScript utilities
618
+ */
619
+ export function initializeTypeScriptUtilities(config?: TypeScriptConfig): TypeScriptUtilities {
620
+ globalTsUtils = new TypeScriptUtilities(config)
621
+ return globalTsUtils
622
+ }
623
+
624
+ /**
625
+ * Get global TypeScript utilities
626
+ */
627
+ export function getTypeScriptUtilities(): TypeScriptUtilities | null {
628
+ return globalTsUtils
629
+ }
630
+
631
+ /**
632
+ * TypeScript development helpers
633
+ */
634
+ export const TypeScriptHelpers = {
635
+ /**
636
+ * Generate types for current routes
637
+ */
638
+ generateTypes: (): string => {
639
+ const tsUtils = getTypeScriptUtilities()
640
+ if (!tsUtils) {
641
+ throw new Error('TypeScript utilities not initialized')
642
+ }
643
+ return tsUtils.generateRouteTypes()
644
+ },
645
+
646
+ /**
647
+ * Generate validation schemas
648
+ */
649
+ generateSchemas: (): Record<string, ValidationSchema> => {
650
+ const tsUtils = getTypeScriptUtilities()
651
+ if (!tsUtils) {
652
+ throw new Error('TypeScript utilities not initialized')
653
+ }
654
+ return tsUtils.generateValidationSchemas()
655
+ },
656
+
657
+ /**
658
+ * Generate OpenAPI documentation
659
+ */
660
+ generateOpenAPI: (): any => {
661
+ const tsUtils = getTypeScriptUtilities()
662
+ if (!tsUtils) {
663
+ throw new Error('TypeScript utilities not initialized')
664
+ }
665
+ return tsUtils.generateOpenAPISchema()
666
+ },
667
+
668
+ /**
669
+ * Validate request types
670
+ */
671
+ validateRequest: (req: EnhancedRequest, routeKey: string): { valid: boolean, errors: string[], warnings: string[] } => {
672
+ const tsUtils = getTypeScriptUtilities()
673
+ if (!tsUtils) {
674
+ return { valid: true, errors: [], warnings: ['TypeScript utilities not initialized'] }
675
+ }
676
+ return tsUtils.validateRequest(req, routeKey)
677
+ },
678
+ }