@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,449 +0,0 @@
1
- /**
2
- * Router Validation Integration
3
- *
4
- * Integration layer for validation and macros with the router.
5
- * Provides RouteBuilder and ValidationFluentRouter for building routes with validation support.
6
- */
7
-
8
- import type { EnhancedRequest, MiddlewareHandler, NextFunction, RouteHandler } from '../types'
9
- import type { ValidationRules, ValidatorConfig } from '../validation/validator'
10
- import { RequestWithMacros } from '../request/macros'
11
- import { ResponseWithMacros } from '../response/macros'
12
- import { createValidationMiddleware } from '../validation/validator'
13
-
14
- /**
15
- * Route builder with validation support
16
- */
17
- export class RouteBuilder {
18
- private validationRules?: ValidationRules
19
- private validatorConfig?: ValidatorConfig
20
-
21
- constructor(
22
- private method: string,
23
- private path: string,
24
- private handler: RouteHandler,
25
- ) {}
26
-
27
- /**
28
- * Add validation to the route
29
- */
30
- validate(rules: ValidationRules, config?: ValidatorConfig): this {
31
- this.validationRules = rules
32
- this.validatorConfig = config
33
- return this
34
- }
35
-
36
- /**
37
- * Build the route with middleware
38
- */
39
- build(): { method: string, path: string, handler: RouteHandler, middleware?: MiddlewareHandler[] } {
40
- const middleware: MiddlewareHandler[] = []
41
-
42
- // Add validation middleware if rules are provided
43
- if (this.validationRules) {
44
- middleware.push(createValidationMiddleware(this.validationRules, this.validatorConfig))
45
- }
46
-
47
- // Add request macro middleware
48
- middleware.push(async (req: EnhancedRequest, next: NextFunction) => {
49
- // Apply request macros
50
- RequestWithMacros.applyMacros(req)
51
- const result = await next()
52
- return result || new Response('Not Found', { status: 404 })
53
- })
54
-
55
- return {
56
- method: this.method,
57
- path: this.path,
58
- handler: this.handler,
59
- middleware: middleware.length > 0 ? middleware : undefined,
60
- }
61
- }
62
- }
63
-
64
- /**
65
- * Minimal route collector with validation support.
66
- *
67
- * Renamed from `FluentRouter`: this module used to declare a third class
68
- * with that name. It was shadowed by the canonical `FluentRouter` exported
69
- * from `fluent-routing.ts` (explicit exports win over `export *`), so
70
- * `createFluentRouter()` silently returned a different class than the
71
- * public `FluentRouter` symbol. The distinct name removes the ambiguity.
72
- */
73
- export class ValidationFluentRouter {
74
- private routes: Array<{
75
- method: string
76
- path: string
77
- handler: RouteHandler
78
- middleware?: MiddlewareHandler[]
79
- }> = []
80
-
81
- /**
82
- * Create GET route
83
- */
84
- get(path: string, handler: RouteHandler): RouteBuilder {
85
- return new RouteBuilder('GET', path, handler)
86
- }
87
-
88
- /**
89
- * Create POST route
90
- */
91
- post(path: string, handler: RouteHandler): RouteBuilder {
92
- return new RouteBuilder('POST', path, handler)
93
- }
94
-
95
- /**
96
- * Create PUT route
97
- */
98
- put(path: string, handler: RouteHandler): RouteBuilder {
99
- return new RouteBuilder('PUT', path, handler)
100
- }
101
-
102
- /**
103
- * Create PATCH route
104
- */
105
- patch(path: string, handler: RouteHandler): RouteBuilder {
106
- return new RouteBuilder('PATCH', path, handler)
107
- }
108
-
109
- /**
110
- * Create DELETE route
111
- */
112
- delete(path: string, handler: RouteHandler): RouteBuilder {
113
- return new RouteBuilder('DELETE', path, handler)
114
- }
115
-
116
- /**
117
- * Register a built route
118
- */
119
- register(routeBuilder: RouteBuilder): void {
120
- const route = routeBuilder.build()
121
- this.routes.push(route)
122
- }
123
-
124
- /**
125
- * Get all registered routes
126
- */
127
- getRoutes(): Array<{
128
- method: string
129
- path: string
130
- handler: RouteHandler
131
- middleware?: MiddlewareHandler[]
132
- }> {
133
- return this.routes
134
- }
135
- }
136
-
137
- /**
138
- * Router middleware factory for request/response enhancements
139
- */
140
- export function createEnhancementMiddleware() {
141
- return async (req: EnhancedRequest, next: () => Promise<Response>): Promise<Response> => {
142
- // Apply request macros
143
- RequestWithMacros.applyMacros(req)
144
-
145
- // Add start time for age calculation
146
- ;(req as any).startTime = Date.now()
147
-
148
- return await next()
149
- }
150
- }
151
-
152
- /**
153
- * Validation middleware factory with fluent API
154
- */
155
- export class ValidationMiddlewareBuilder {
156
- private rules: ValidationRules = {}
157
- private config: ValidatorConfig = {}
158
-
159
- /**
160
- * Add validation rule for field
161
- */
162
- field(name: string, rules: string): this {
163
- this.rules[name] = rules
164
- return this
165
- }
166
-
167
- /**
168
- * Add multiple validation rules
169
- */
170
- fields(rules: ValidationRules): this {
171
- Object.assign(this.rules, rules)
172
- return this
173
- }
174
-
175
- /**
176
- * Set validator configuration
177
- */
178
- configure(config: ValidatorConfig): this {
179
- Object.assign(this.config, config)
180
- return this
181
- }
182
-
183
- /**
184
- * Stop on first validation failure
185
- */
186
- stopOnFirstFailure(): this {
187
- this.config.stopOnFirstFailure = true
188
- return this
189
- }
190
-
191
- /**
192
- * Set custom error messages
193
- */
194
- messages(messages: Record<string, string>): this {
195
- this.config.customMessages = messages
196
- return this
197
- }
198
-
199
- /**
200
- * Set custom field attributes
201
- */
202
- attributes(attributes: Record<string, string>): this {
203
- this.config.customAttributes = attributes
204
- return this
205
- }
206
-
207
- /**
208
- * Build the validation middleware
209
- */
210
- build(): MiddlewareHandler {
211
- return createValidationMiddleware(this.rules, this.config)
212
- }
213
- }
214
-
215
- /**
216
- * Factory function to create validation middleware builder
217
- */
218
- export function validate(): ValidationMiddlewareBuilder {
219
- return new ValidationMiddlewareBuilder()
220
- }
221
-
222
- /** Resource handlers configuration */
223
- export interface ResourceHandlers {
224
- index?: RouteHandler
225
- show?: RouteHandler
226
- store?: RouteHandler
227
- update?: RouteHandler
228
- destroy?: RouteHandler
229
- }
230
-
231
- /** Resource validation configuration */
232
- export interface ResourceValidation {
233
- store?: ValidationRules
234
- update?: ValidationRules
235
- }
236
-
237
- /**
238
- * Route helper functions
239
- */
240
- export const RouteHelpers: {
241
- validated: (method: string, path: string, handler: RouteHandler, rules: ValidationRules, config?: ValidatorConfig) => RouteBuilder
242
- apiRoute: (method: string, path: string, handler: RouteHandler, rules?: ValidationRules) => RouteBuilder
243
- resourceRoute: (basePath: string, handlers: ResourceHandlers, validation?: ResourceValidation) => RouteBuilder[]
244
- } = {
245
- /**
246
- * Create validated route
247
- */
248
- validated: (
249
- method: string,
250
- path: string,
251
- handler: RouteHandler,
252
- rules: ValidationRules,
253
- config?: ValidatorConfig,
254
- ): RouteBuilder => {
255
- const builder = new RouteBuilder(method, path, handler)
256
- return builder.validate(rules, config)
257
- },
258
-
259
- /**
260
- * Create API route with JSON validation
261
- */
262
- apiRoute: (
263
- method: string,
264
- path: string,
265
- handler: RouteHandler,
266
- rules?: ValidationRules,
267
- ): RouteBuilder => {
268
- const builder = new RouteBuilder(method, path, async (req): Promise<Response> => {
269
- // Ensure request expects JSON
270
- if (!req.expectsJson()) {
271
- return ResponseWithMacros.callMacro('error', 'API endpoint requires JSON Accept header', undefined, 406)
272
- }
273
-
274
- return await handler(req)
275
- })
276
-
277
- if (rules) {
278
- builder.validate(rules)
279
- }
280
-
281
- return builder
282
- },
283
-
284
- /**
285
- * Create resource route with validation
286
- */
287
- resourceRoute: (
288
- basePath: string,
289
- handlers: ResourceHandlers,
290
- validation?: ResourceValidation,
291
- ): RouteBuilder[] => {
292
- const routes: RouteBuilder[] = []
293
-
294
- if (handlers.index) {
295
- routes.push(new RouteBuilder('GET', basePath, handlers.index))
296
- }
297
-
298
- if (handlers.show) {
299
- routes.push(new RouteBuilder('GET', `${basePath}/{id}`, handlers.show))
300
- }
301
-
302
- if (handlers.store) {
303
- const builder = new RouteBuilder('POST', basePath, handlers.store)
304
- if (validation?.store) {
305
- builder.validate(validation.store)
306
- }
307
- routes.push(builder)
308
- }
309
-
310
- if (handlers.update) {
311
- const builder = new RouteBuilder('PUT', `${basePath}/{id}`, handlers.update)
312
- if (validation?.update) {
313
- builder.validate(validation.update)
314
- }
315
- routes.push(builder)
316
- }
317
-
318
- if (handlers.destroy) {
319
- routes.push(new RouteBuilder('DELETE', `${basePath}/{id}`, handlers.destroy))
320
- }
321
-
322
- return routes
323
- },
324
- }
325
-
326
- /**
327
- * Fluent router factory
328
- */
329
- export function createFluentRouter(): ValidationFluentRouter {
330
- return new ValidationFluentRouter()
331
- }
332
-
333
- /**
334
- * Middleware composition helpers
335
- */
336
- export const MiddlewareHelpers = {
337
- /**
338
- * Compose multiple middleware into one
339
- */
340
- compose: (...middleware: MiddlewareHandler[]): MiddlewareHandler => {
341
- return async (req: EnhancedRequest, next: NextFunction): Promise<Response | null> => {
342
- let index = 0
343
-
344
- const dispatch = async (): Promise<Response | null> => {
345
- if (index >= middleware.length) {
346
- return await next()
347
- }
348
-
349
- const currentMiddleware = middleware[index++]
350
- return await currentMiddleware(req, dispatch)
351
- }
352
-
353
- return await dispatch()
354
- }
355
- },
356
-
357
- /**
358
- * Create conditional middleware
359
- */
360
- when: (
361
- condition: (req: EnhancedRequest) => boolean,
362
- middleware: MiddlewareHandler,
363
- ): MiddlewareHandler => {
364
- return async (req: EnhancedRequest, next: NextFunction): Promise<Response | null> => {
365
- if (condition(req)) {
366
- return await middleware(req, next)
367
- }
368
- return await next()
369
- }
370
- },
371
-
372
- /**
373
- * Create middleware that runs unless condition is met
374
- */
375
- unless: (
376
- condition: (req: EnhancedRequest) => boolean,
377
- middleware: MiddlewareHandler,
378
- ): MiddlewareHandler => {
379
- return MiddlewareHelpers.when(req => !condition(req), middleware)
380
- },
381
-
382
- /**
383
- * Create middleware group
384
- */
385
- group: (middleware: MiddlewareHandler[]): MiddlewareHandler => {
386
- return MiddlewareHelpers.compose(...middleware)
387
- },
388
- }
389
-
390
- /** Enhancement middleware type */
391
- export type EnhancementMiddleware = (req: EnhancedRequest, next: () => Promise<Response>) => Promise<Response>
392
-
393
- /**
394
- * Request/Response enhancement presets
395
- */
396
- export const EnhancementPresets: {
397
- api: () => EnhancementMiddleware[]
398
- web: () => EnhancementMiddleware[]
399
- validation: (rules: ValidationRules, config?: ValidatorConfig) => EnhancementMiddleware[]
400
- } = {
401
- /**
402
- * API preset with JSON validation and response macros
403
- */
404
- api: (): EnhancementMiddleware[] => [
405
- createEnhancementMiddleware(),
406
- async (req: EnhancedRequest, next: () => Promise<Response>): Promise<Response> => {
407
- try {
408
- const response = await next()
409
-
410
- // Add API headers
411
- const headers = new Headers(response.headers)
412
- headers.set('X-API-Version', '1.0')
413
- headers.set('X-Response-Time', new Date().toISOString())
414
-
415
- return new Response(response.body, {
416
- status: response.status,
417
- statusText: response.statusText,
418
- headers,
419
- })
420
- }
421
- catch (error) {
422
- console.error(error)
423
- // Return JSON error response
424
- return ResponseWithMacros.callMacro('error', 'Internal server error', undefined, 500)
425
- }
426
- },
427
- ],
428
-
429
- /**
430
- * Web preset with request enhancements and CSRF protection
431
- */
432
- web: (): EnhancementMiddleware[] => [
433
- createEnhancementMiddleware(),
434
- async (req: EnhancedRequest, next: () => Promise<Response>): Promise<Response> => {
435
- // Add web-specific enhancements
436
- ;(req as any).session = {} // Placeholder for session
437
-
438
- return await next()
439
- },
440
- ],
441
-
442
- /**
443
- * Validation preset with comprehensive validation
444
- */
445
- validation: (rules: ValidationRules, config?: ValidatorConfig): EnhancementMiddleware[] => [
446
- createEnhancementMiddleware(),
447
- createValidationMiddleware(rules, config) as EnhancementMiddleware,
448
- ],
449
- }
@@ -1,233 +0,0 @@
1
- import type { ActionHandler, EnhancedRequest, RouterConfig } from '../types'
2
- import type { Router } from './router'
3
- import { join } from 'node:path'
4
- import { processHtmlTemplate, resolveViewPath, injectQueryPreservationScript } from '../utils'
5
-
6
- /**
7
- * View rendering extension for Router class
8
- */
9
- export function registerViewRendering(RouterClass: typeof Router): void {
10
- Object.defineProperties(RouterClass.prototype, {
11
- /**
12
- * Render a view with data
13
- */
14
- renderView: {
15
- async value(
16
- view: string,
17
- data: Record<string, any> = {},
18
- options: { layout?: string } = {},
19
- ): Promise<string> {
20
- const viewsConfig = this.config.views || {
21
- viewsPath: 'resources/views',
22
- extensions: ['.html', '.stx'],
23
- cache: Bun.env.NODE_ENV === 'production',
24
- engine: 'auto',
25
- }
26
-
27
- // Check cache first if enabled
28
- const cacheKey = `${view}:${options.layout || ''}`
29
- if (viewsConfig.cache && this.templateCache.has(cacheKey)) {
30
- return this.processTemplate(this.templateCache.get(cacheKey)!, data, viewsConfig)
31
- }
32
-
33
- // Resolve the view path
34
- const viewPath = await resolveViewPath(view, viewsConfig.viewsPath, viewsConfig.extensions)
35
- if (!viewPath) {
36
- throw new Error(`View '${view}' not found`)
37
- }
38
-
39
- // Read the view file
40
- let viewContent = await Bun.file(viewPath).text()
41
-
42
- // Apply layout if specified or if a default layout is configured
43
- const layoutName = options.layout || viewsConfig.defaultLayout
44
- if (layoutName) {
45
- const layoutPath = await resolveViewPath(
46
- join('layouts', layoutName),
47
- viewsConfig.viewsPath,
48
- viewsConfig.extensions,
49
- )
50
-
51
- if (!layoutPath) {
52
- throw new Error(`Layout '${layoutName}' not found`)
53
- }
54
-
55
- const layoutContent = await Bun.file(layoutPath).text()
56
- // Replace {{content}} placeholder with the view content
57
- viewContent = layoutContent.replace(/\{\{\s*content\s*\}\}/g, viewContent)
58
- }
59
-
60
- // Cache the template if caching is enabled
61
- if (viewsConfig.cache) {
62
- this.templateCache.set(cacheKey, viewContent)
63
- }
64
-
65
- // Process the template with data
66
- return this.processTemplate(viewContent, data, viewsConfig)
67
- },
68
- writable: true,
69
- configurable: true,
70
- },
71
-
72
- /**
73
- * Process a template with data
74
- */
75
- processTemplate: {
76
- async value(
77
- template: string,
78
- data: Record<string, any>,
79
- viewConfig: RouterConfig['views'],
80
- ): Promise<string> {
81
- // Choose template engine based on configuration
82
- const engine = viewConfig?.engine || 'auto'
83
-
84
- if (engine === 'custom' && viewConfig?.customRenderer) {
85
- return viewConfig.customRenderer(template, data, {})
86
- }
87
-
88
- // Default to simple template processing
89
- let processedTemplate = processHtmlTemplate(template, data)
90
-
91
- // Apply minification if configured
92
- if (viewConfig?.minify?.enabled) {
93
- try {
94
- const _minifyOptions = viewConfig.minify.options || {
95
- removeComments: true,
96
- collapseWhitespace: true,
97
- minifyJS: true,
98
- minifyCSS: true,
99
- }
100
-
101
- // In a real implementation, you would use a library like html-minifier
102
- // This is just a placeholder
103
- processedTemplate = processedTemplate
104
- .replace(/\s+/g, ' ')
105
- .replace(/<!--[\s\S]*?-->/g, '')
106
- }
107
- catch (err) {
108
- console.error('Error minifying HTML:', err)
109
- }
110
- }
111
-
112
- return processedTemplate
113
- },
114
- writable: true,
115
- configurable: true,
116
- },
117
-
118
- /**
119
- * Register a view route
120
- */
121
- view: {
122
- value(
123
- path: string,
124
- viewOrData: string | Record<string, any>,
125
- dataOrOptions: Record<string, any> | { layout?: string, status?: number, headers?: Record<string, string> } = {},
126
- optionsOrType: { layout?: string, status?: number, headers?: Record<string, string> } | 'web' | 'api' = {},
127
- typeOrName: 'web' | 'api' | string = 'web',
128
- name?: string,
129
- ): Router {
130
- let view: string
131
- let data: Record<string, any> = {}
132
- let options: { layout?: string, status?: number, headers?: Record<string, string> } = {}
133
- let type: 'web' | 'api' = 'web'
134
- let routeName: string | undefined
135
-
136
- // Parse the flexible parameters
137
- if (typeof viewOrData === 'string') {
138
- view = viewOrData
139
-
140
- if (typeof dataOrOptions === 'object' && !Array.isArray(dataOrOptions)) {
141
- // If dataOrOptions has layout, status, or headers, it's options
142
- if ('layout' in dataOrOptions || 'status' in dataOrOptions || 'headers' in dataOrOptions) {
143
- options = dataOrOptions as { layout?: string, status?: number, headers?: Record<string, string> }
144
- }
145
- else {
146
- // Otherwise it's data
147
- data = dataOrOptions
148
- }
149
- }
150
-
151
- if (typeof optionsOrType === 'object') {
152
- options = { ...options, ...optionsOrType }
153
- }
154
- else if (typeof optionsOrType === 'string') {
155
- type = optionsOrType as 'web' | 'api'
156
- }
157
-
158
- if (typeof typeOrName === 'string') {
159
- if (typeOrName === 'web' || typeOrName === 'api') {
160
- type = typeOrName
161
- }
162
- else {
163
- routeName = typeOrName
164
- }
165
- }
166
-
167
- if (name) {
168
- routeName = name
169
- }
170
- }
171
- else {
172
- // viewOrData is actually data
173
- data = viewOrData
174
-
175
- if (typeof dataOrOptions === 'string') {
176
- view = dataOrOptions
177
- }
178
- else {
179
- throw new TypeError('View name must be a string')
180
- }
181
-
182
- if (typeof optionsOrType === 'object') {
183
- options = optionsOrType
184
- }
185
- else if (typeof optionsOrType === 'string') {
186
- if (optionsOrType === 'web' || optionsOrType === 'api') {
187
- type = optionsOrType
188
- }
189
- else {
190
- view = optionsOrType
191
- type = 'web'
192
- }
193
- }
194
- }
195
-
196
- // Create the route handler
197
- const handler: ActionHandler = async (_req: EnhancedRequest) => {
198
- let renderedView = await this.renderView(view, data, {
199
- layout: options.layout,
200
- })
201
-
202
- // Inject query preservation script if configured
203
- const queryPreservationConfig = this.config?.queryPreservation
204
- if (queryPreservationConfig?.enabled !== false && queryPreservationConfig?.preserve?.length) {
205
- renderedView = injectQueryPreservationScript(renderedView, queryPreservationConfig)
206
- }
207
-
208
- const headers = new Headers()
209
- headers.set('Content-Type', 'text/html; charset=utf-8')
210
-
211
- // Add custom headers if provided
212
- if (options.headers) {
213
- for (const [key, value] of Object.entries(options.headers)) {
214
- headers.set(key, value)
215
- }
216
- }
217
-
218
- return new Response(renderedView, {
219
- status: options.status || 200,
220
- headers,
221
- })
222
- }
223
-
224
- // Register the route
225
- this.get(path, handler, type, routeName)
226
-
227
- return this
228
- },
229
- writable: true,
230
- configurable: true,
231
- },
232
- })
233
- }