veloce-ts 0.4.3 → 0.4.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 (45) hide show
  1. package/CHANGELOG.md +727 -716
  2. package/README.md +26 -1
  3. package/dist/cjs/src/auth/index.js +4 -4
  4. package/dist/cjs/src/auth/index.js.map +4 -4
  5. package/dist/cjs/src/errors/index.js +25 -25
  6. package/dist/cjs/src/errors/index.js.map +7 -6
  7. package/dist/cjs/src/graphql/index.js +4 -4
  8. package/dist/cjs/src/graphql/index.js.map +3 -3
  9. package/dist/cjs/src/index.js +59 -59
  10. package/dist/cjs/src/index.js.map +21 -19
  11. package/dist/cjs/src/middleware/index.js +22 -22
  12. package/dist/cjs/src/middleware/index.js.map +3 -3
  13. package/dist/cjs/src/plugins/index.js +7 -7
  14. package/dist/cjs/src/plugins/index.js.map +3 -3
  15. package/dist/cjs/src/testing/index.js +33 -33
  16. package/dist/cjs/src/testing/index.js.map +20 -18
  17. package/dist/cjs/src/validation/index.js +2 -2
  18. package/dist/cjs/src/validation/index.js.map +3 -3
  19. package/dist/esm/src/auth/index.js +4 -4
  20. package/dist/esm/src/auth/index.js.map +4 -4
  21. package/dist/esm/src/errors/index.js +25 -25
  22. package/dist/esm/src/errors/index.js.map +7 -6
  23. package/dist/esm/src/graphql/index.js +3 -3
  24. package/dist/esm/src/graphql/index.js.map +3 -3
  25. package/dist/esm/src/index.js +59 -59
  26. package/dist/esm/src/index.js.map +21 -19
  27. package/dist/esm/src/middleware/index.js +22 -22
  28. package/dist/esm/src/middleware/index.js.map +3 -3
  29. package/dist/esm/src/plugins/index.js +7 -7
  30. package/dist/esm/src/plugins/index.js.map +3 -3
  31. package/dist/esm/src/testing/index.js +33 -33
  32. package/dist/esm/src/testing/index.js.map +20 -18
  33. package/dist/esm/src/validation/index.js +2 -2
  34. package/dist/esm/src/validation/index.js.map +3 -3
  35. package/dist/types/auth/permissions.d.ts +10 -10
  36. package/dist/types/decorators/dependencies.d.ts +19 -0
  37. package/dist/types/decorators/dependencies.d.ts.map +1 -1
  38. package/dist/types/dependencies/container.d.ts.map +1 -1
  39. package/dist/types/errors/handler.d.ts.map +1 -1
  40. package/dist/types/middleware/cors.d.ts +13 -1
  41. package/dist/types/middleware/cors.d.ts.map +1 -1
  42. package/dist/types/middleware/index.d.ts +1 -1
  43. package/dist/types/middleware/index.d.ts.map +1 -1
  44. package/dist/types/validation/exceptions.d.ts.map +1 -1
  45. package/package.json +199 -199
package/CHANGELOG.md CHANGED
@@ -1,716 +1,727 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [Unreleased]
9
-
10
- ## [0.4.3] - 2026-03-27
11
-
12
- ### Added
13
- - **RFC 9457 (Problem Details):** respuestas de error por defecto con `Content-Type: application/problem+json`, campos `type`, `title`, `status`, `detail`, `instance` y extensiones (`violations`/`details` en validación; `debug` en 500 solo en desarrollo).
14
- - **`VeloceTSConfig.errorResponseFormat`:** `'rfc9457'` (defecto) o `'legacy'` para el JSON `{ error, statusCode, details? }` anterior.
15
- - Helpers exportados: `problemTypeUri`, `resolveProblemType`, `resolveProblemTitle`, `buildProblemInstance`, `toLegacyErrorBody`, `sendErrorResponse`, constantes `PROBLEM_JSON_MEDIA_TYPE`, `DEFAULT_PROBLEM_TYPE_BASE`.
16
- - **`HTTPExceptionOptions`:** `problemType` y `title` opcionales en el constructor de `HTTPException`.
17
-
18
- ### Changed
19
- - Excepciones de auth (`AuthenticationException`, `AuthorizationException`) dejan de definir `toJSON` propio; heredan el formato unificado con URIs `authentication-error` / `authorization-error`.
20
-
21
- ### Documentation
22
- - Cabeceras `@module` en el núcleo (application, metadata, router-compiler, plugin, compiled-metadata), errores, validación, DI, respuestas, logging, middleware, adapters, testing, barrels y más.
23
- - **Benchmarks:** `benchmarks/run.ts` etiquetado como v0.4.3; `BENCHMARKS.md` y `benchmarks/results/latest.json` regenerados (6 000 req, 50 concurrentes, Bun 1.3.5, 2026-03-28).
24
-
25
- ### Notes
26
- - El cuerpo JSON de error sigue incluyendo `error` y `statusCode` junto a los campos RFC 9457. Si tu cliente exige `Content-Type: application/json` en errores, usa `errorResponseFormat: 'legacy'` o acepta `application/problem+json`.
27
-
28
- ## [0.4.2] - 2026-03-27
29
-
30
- ### Fixed
31
- - **HealthCheckPlugin:** checker display names are set with `Object.defineProperty` (with a fallback) so runtimes such as Bun do not throw when assigning `.name` on async checker functions.
32
- - **Public API:** `@Req` is now exported from the main `veloce-ts` entry (it was implemented in `decorators/params` but missing from the package exports).
33
-
34
- ## [0.4.1] - 2026-03-27
35
-
36
- ### Fixed
37
- - `include()` in `VeloceTS` application no longer drops decorator-set route fields (e.g. `statusCode` from `@HttpCode`, `responseSchema` from `@ResponseSchema`) when registering controller routes.
38
-
39
- ### Added
40
- - New test suite: `tests/routing.test.ts`, `tests/validation.test.ts`, `tests/errors.test.ts`, `tests/di.test.ts` — 53 integration tests covering functional API, decorator routing, body/query validation, HTTP exceptions, and DI container.
41
- - Console-based fallback logger: if `pino` is not installed, the framework now falls back silently to a `console`-based logger instead of crashing at startup.
42
-
43
- ### Changed
44
- - `pino`, `pino-pretty`, and `ioredis` moved from `dependencies` to `optionalDependencies`. They are no longer installed automatically, reducing the default install footprint by ~7 MB. Install them explicitly if needed (`bun add pino pino-pretty` / `bun add ioredis`).
45
- - `winston` removed from `dependencies` entirely (it was listed but never used by the framework).
46
- - `@types/ioredis` and `@types/pino` removed from `devDependencies` (no longer needed).
47
- - Build threshold in `build.ts` updated from 100 KB to 600 KB to reflect the full framework scope.
48
- - Core bundle reduced from 444 KB to 408 KB (minified ESM).
49
-
50
- ### Deprecated
51
- - `FastAPITS` export: use `VeloceTS` or the shorter `Veloce` alias instead. `FastAPITS` will be removed in v1.0.0.
52
-
53
- ## [0.4.0] - 2026-03-27
54
-
55
- Esta versión representa la mayor actualización desde el lanzamiento inicial. Se añadieron más de 25 mejoras nuevas distribuidas en tres oleadas de trabajo (alta, media y baja prioridad), cubriendo la cadena completa desde la generación de rutas hasta la documentación OpenAPI, el testing, el ORM y la CLI.
56
-
57
- ### 🚀 Nuevos Decoradores
58
-
59
- #### Documentación OpenAPI (shorthand)
60
- Cinco decoradores de una sola línea como alternativa concisa a `@ApiDoc({...})`:
61
- - **`@Summary(text)`** — descripción corta visible en la lista de Swagger UI
62
- - **`@Description(text)`** texto largo en el panel de detalle de la operación
63
- - **`@Tag(name)`** — asigna un tag individual; apilable con múltiples `@Tag`
64
- - **`@Tags(...names)`** asigna varios tags en un solo decorador
65
- - **`@Deprecated()`** — marca la ruta como obsoleta (tachado en Swagger UI)
66
-
67
- #### Control de respuesta
68
- - **`@HttpCode(statusCode)`** sobreescribe el código HTTP de respuesta del handler (p.ej. `201` para creación). Usado también por el generador OpenAPI para el código de éxito documentado
69
- - **`@ResponseSchema(schema, statusCode?)`** — valida y sanitiza la respuesta del handler con un esquema Zod; informa el modelo de respuesta al spec de OpenAPI
70
-
71
- #### Middleware declarativo por ruta
72
- - **`@Timeout(ms, message?)`** — aborta la petición con **408 Request Timeout** si el handler supera el límite. Inyecta automáticamente el middleware al inicio del pipeline y emite el header `X-Timeout-Ms`
73
- - **`@RateLimit(options)`** — aplica rate-limiting a nivel de ruta individual usando la misma configuración de `createRateLimitMiddleware()`. Los headers estándar `X-RateLimit-*` se envían automáticamente
74
-
75
- ### 🛠️ Mejoras al Framework Core
76
-
77
- #### OpenAPI Generator (`src/docs/openapi-generator.ts`)
78
- - **Auto-tagging**: deriva tags automáticamente del primer segmento del path (`/products/:id` → tag `"Products"`) sin necesidad de anotarlos manualmente
79
- - **Bearer security scheme**: añade `components.securitySchemes.bearerAuth` al spec y aplica `security: [{ bearerAuth: [] }]` en rutas protegidas de forma automática
80
- - **401 automático**: rutas protegidas reciben una respuesta `401 Unauthorized` documentada sin configuración adicional
81
- - **Soporte de `@HttpCode`**: usa el `statusCode` del decorador como clave del bloque de éxito en `responses`
82
- - **`@ResponseSchema` en el spec**: cuando está presente, el esquema Zod se convierte al formato JSON Schema para el bloque de contenido de la respuesta
83
-
84
- #### Sistema de Excepciones HTTP (`src/errors/exceptions.ts`)
85
- Seis nuevas clases de excepción para cubrir casos de error comunes:
86
- - `ConflictException` (409)
87
- - `GoneException` (410)
88
- - `PayloadTooLargeException` (413)
89
- - `UnprocessableEntityException` (422)
90
- - `TooManyRequestsException` (429)
91
- - `ServiceUnavailableException` (503)
92
-
93
- #### Logger estructurado en ErrorHandler (`src/errors/handler.ts`)
94
- - Errores 5xx se registran con `getLogger().error` incluyendo path, método, status y stack
95
- - Errores 4xx se registran como `warn` en entorno de desarrollo
96
- - Errores genéricos no capturados también pasan por Pino
97
-
98
- #### Arreglos de orden de decoradores
99
- - **`@UseMiddleware`** (`src/decorators/middleware.ts`): ahora siempre llama a `MetadataRegistry.defineRoute` para que el middleware no se pierda independientemente del orden de ejecución de los decoradores
100
- - **`@Cache` / `@CacheInvalidate`** (`src/decorators/cache.ts`): mismo patrón — los metadatos se fusionan correctamente sin importar el orden de apilamiento
101
-
102
- #### MetadataCompiler — caché lazy con snapshots (`src/core/compiled-metadata.ts`)
103
- - Compilación lazy: una ruta sólo se recompila si sus metadatos cambiaron (comparación por snapshot JSON)
104
- - IDs únicos para handlers funcionales vía `WeakMap<Function, number>` — evita colisiones de caché cuando distintas instancias de app registran el mismo path con handlers diferentes (bug crítico en tests paralelos)
105
- - Método `clearCache()` expuesto para limpiar el estado entre tests
106
-
107
- ### 🧪 TestClient API fluida y helpers de autenticación (`src/testing/test-client.ts`)
108
-
109
- Reescritura completa de `TestClient`:
110
- - **`TestResponse`** nueva clase de respuesta con propiedades `status`, `headers`, `body`, `text`, `ok` y métodos de aserción encadenables:
111
- - `expectStatus(code)`, `expectOk()`, `expectCreated()`, `expectNotFound()`, etc.
112
- - `expectJson(partialObject)` — comprobación parcial del body
113
- - `expectField(field, value?)` verificar un campo específico
114
- - `expectHeader(name, value?)` verificar un header de respuesta
115
- - `expectArrayLength(n)`verificar longitud de array en respuesta
116
- - **`withToken(token)`** crea una instancia inmutable del cliente con el header `Authorization: Bearer` ya configurado
117
- - **`withHeaders(headers)`** — crea una instancia inmutable con headers adicionales
118
- - **`loginAs(credentials, endpoint?)`**hace login, extrae el JWT y lo inyecta en el cliente actual para las peticiones siguientes
119
- - **`registerAndLogin(user, endpoints?)`** — registra y hace login en una sola llamada
120
- - **`clearAuth()`** limpia el token almacenado
121
-
122
- ### 🔌 Plugins y Middleware
123
-
124
- #### HealthCheckers.disk (`src/plugins/health.ts`)
125
- - Usa `fs.statfs` (Node 18+ / Bun) para obtener métricas reales de disco: total, libre, usado y porcentaje
126
- - Degradación elegante a `"healthy"` en plataformas sin soporte
127
-
128
- #### CLIPlantilla Fullstack corregida (`src/cli/commands/new.ts`)
129
- - La plantilla `fullstack` ahora genera `src/index.ts` con `GraphQLPlugin` y `WebSocketPlugin` correctamente importados e instanciados (antes quedaban comentados)
130
-
131
- #### Subpath exports en el build (`build.ts`)
132
- - Se añadieron `./src/auth/index.ts`, `./src/adapters/base.ts`, `./src/adapters/hono.ts`, `./src/adapters/express.ts` como entrypoints explícitos para que los imports `veloce-ts/auth` y `veloce-ts/adapters/*` funcionen correctamente
133
-
134
- ### 🗄️ Drizzle ORM — Integración DI (`src/dependencies/drizzle.ts`)
135
-
136
- Nuevo módulo para conectar Drizzle (u otro ORM) al contenedor de inyección de dependencias:
137
- ```typescript
138
- // Registrar la instancia de la DB
139
- registerDrizzle(app, db);
140
-
141
- // Inyectar en controladores
142
- @Get('/')
143
- async list(@InjectDB() db: DrizzleDB) { }
144
- ```
145
- - `DB_TOKEN` símbolo por defecto para el token de inyección
146
- - `registerDrizzle(app, db, token?)` — registra como singleton en el `DIContainer`
147
- - `@InjectDB(token?)` decorador de parámetro, alias de `@Depends(DB_TOKEN)`
148
-
149
- ### 📊 Paginación mejorada (`src/orm/pagination.ts`)
150
-
151
- #### Enriquecimiento de metadatos
152
- - `PaginationMeta` incluye `from` y `to` (rango 1-based, p.ej. `from: 11, to: 20`)
153
- - `CursorPaginatedResult` incluye `count` (ítems reales devueltos en la página)
154
-
155
- #### Cursor pagination más precisa
156
- - `createCursorPaginatedResult(data, limit, cursorField, hadPrevCursor)` — el nuevo parámetro `hadPrevCursor` activa `hasPrev: true` correctamente cuando se navega hacia adelante con cursor
157
- - `createMultiCursor(entity, fields[])` — crea cursores compuestos por múltiples campos para ordenación estable (p.ej. `{ createdAt, id }`)
158
- - `decodeMultiCursor(cursor)` — decodifica un cursor multi-campo de vuelta a un objeto
159
-
160
- #### Helpers standalone
161
- - `paginate<T>(data, total, page, limit)` — construye `{ data, meta }` en una sola llamada, sin necesidad de instanciar `PaginationHelper`
162
- - `parseCursorQuery(query, defaultLimit?, maxLimit?)` — extrae `cursor` y `limit` de los query params sin lanzar excepciones
163
- - `PaginationHelper.parsePaginationQuery(query, defaultLimit?, maxLimit?)` equivalente para paginación offset; aplica límite máximo y usa defaults cuando los valores son inválidos
164
-
165
- ### 🔌 Express Adapter — Compatibilidad ESM (`src/adapters/express.ts`)
166
-
167
- Reescritura completa del adaptador:
168
- - Carga Express de forma lazy y segura usando `Function('return require')()` para compatibilidad ESM sin necesitar `declare const require: any`
169
- - Acepta una instancia de Express pre-creada como segundo argumento del constructor (para añadir middleware propio antes del bridge)
170
- - Manejo correcto de body raw (`Buffer`) vs body parseado (JSON/urlencoded)
171
- - Omite el header `transfer-encoding` al reenviar respuestas (era fuente de errores en Express)
172
- - Delega errores inesperados al pipeline de error de Express mediante `next(err)` en lugar de responder con 500 directamente
173
-
174
- ### 🐛 Bug Fixes
175
-
176
- - **`ZodError` cross-module** (`src/errors/handler.ts`, `src/validation/validator.ts`): `instanceof ZodError` fallaba cuando la app consumidora tenía una instancia de Zod diferente a la del framework (caso frecuente con `bun link`). Añadido fallback `error.name === 'ZodError'` para garantizar respuestas 422 en todos los casos
177
- - **Rutas `GET` marcadas públicas retornaban 401** en `products-api`: `app.use()` aplicaba el middleware a todos los métodos; corregido usando `app.on(['POST', 'PUT', 'DELETE'], path, middleware)` para restringir sólo a métodos de escritura
178
- - **Cache collision en MetadataCompiler**: handlers funcionales distintos con el mismo path en diferentes instancias de app compartían el resultado compilado incorrecto; solucionado con IDs únicos por función
179
- - **`@Cache` / `@UseMiddleware` perdían metadatos**: cuando se apilaban en orden inverso al de ejecución de decoradores, los metadatos podían sobreescribirse; solucionado actualizando el registro explícitamente en cada decorador
180
-
181
- ### 📋 Mensajes de validación mejorados (`src/validation/exceptions.ts`)
182
-
183
- La respuesta de error `422` ahora incluye información estructurada adicional:
184
- - `field` en formato convencional: `items[0].price` en lugar de `items.0.price`
185
- - `received` tipo recibido (cuando Zod lo reporta)
186
- - `expected` — tipo esperado (cuando aplica)
187
- - `minimum` / `maximum` límites numéricos en errores de rango
188
-
189
- ```json
190
- {
191
- "error": "Validation Error",
192
- "statusCode": 422,
193
- "details": [
194
- { "field": "email", "message": "Invalid email", "code": "invalid_string" },
195
- { "field": "age", "message": "Number must be 18", "code": "too_small", "minimum": 18 },
196
- { "field": "tags[1]", "message": "String must not be empty", "code": "too_small" }
197
- ]
198
- }
199
- ```
200
-
201
- ### 💥 Breaking Changes
202
-
203
- Ninguno — todos los cambios son retrocompatibles. Las firmas de `createCursorPaginatedResult` tienen un nuevo parámetro opcional `hadPrevCursor` (cuarto argumento, `false` por defecto).
204
-
205
- ### 📦 Dependencias
206
-
207
- Sin cambios en dependencias de runtime. Express sigue siendo peer dependency opcional.
208
-
209
- ---
210
-
211
- ## [0.3.3] - 2025-10-31
212
-
213
- ### 🐛 Critical Bug Fixes
214
- - **JSON Response Serialization**: Fixed critical bug where JSON responses were not being serialized correctly
215
- - **CLI Version Resolution**: Confirmed CLI correctly fetches and uses latest npm version (0.3.2)
216
- - **Application Compilation**: Fixed missing `await app.compile()` call in generated templates
217
-
218
- ### 🔧 CLI Improvements
219
- - **Version Fetching**: CLI now correctly fetches latest version from npm registry
220
- - **Template Generation**: All templates now include proper `await app.compile()` call
221
- - **Error Handling**: Improved error handling in CLI operations
222
-
223
- ## [0.3.2] - 2025-10-31
224
-
225
- ## [0.3.1] - 2025-10-31
226
-
227
- ### 🛠️ CLI Improvements
228
-
229
- #### Enhanced Project Generation
230
- - **Latest Version Fetching**: CLI now automatically fetches the latest VeloceTS version from npm registry
231
- - **Improved Error Handling**: Better error messages and cleanup on project creation failure
232
- - **Type Safety**: Fixed TypeScript errors in CLI with proper type definitions for npm registry API
233
- - **Better User Experience**: Enhanced progress messages and visual feedback during project creation
234
- - **Robust Fallbacks**: Multiple fallback strategies for version detection when npm is unavailable
235
-
236
- #### Fixed Issues
237
- - **npm Registry Integration**: Fixed CLI to use correct npm registry endpoint (`/veloce-ts` instead of `/veloce-ts/latest`)
238
- - **Type Definitions**: Added proper TypeScript interfaces for npm registry response structure
239
- - **Version Resolution**: Improved version parsing with proper type checking and validation
240
- - **Package.json Generation**: Now uses specific dependency versions instead of 'latest' for better stability
241
- - **Template Compilation**: All generated templates now include mandatory `await app.compile()` call
242
-
243
- #### Technical Improvements
244
- - **NpmRegistryResponse Interface**: Added proper typing for npm registry API responses
245
- - **Async Error Handling**: Better error handling in async CLI operations
246
- - **Dependency Versions**: Updated to use specific versions for better reproducibility:
247
- - `hono: ^4.0.0` (instead of 'latest')
248
- - `reflect-metadata: ^0.2.0` (instead of 'latest')
249
- - `zod: ^3.22.0` (instead of 'latest')
250
- - `typescript: ^5.3.0` (instead of 'latest')
251
- - **Engine Requirements**: Added Node.js and Bun version requirements to generated package.json
252
-
253
- #### Developer Experience
254
- - **Progress Indicators**: Added emoji-based progress indicators for better visual feedback
255
- - **Cleanup on Failure**: Automatic cleanup of partial projects when creation fails
256
- - **Validation**: Better project name validation and error messages
257
- - **Documentation**: Generated projects include comprehensive setup instructions
258
-
259
- ### 🐛 Bug Fixes
260
- - **CLI TypeScript Errors**: Fixed 'data is of type unknown' error in npm registry API calls
261
- - **Template Generation**: Fixed missing `await app.compile()` in all CLI templates
262
- - **Dependency Management**: Improved dependency version resolution and fallback handling
263
-
264
- ### 📦 Migration Guide
265
-
266
- #### For CLI Users
267
- No breaking changes. Existing projects will continue to work. New projects generated with `veloce-ts new` will:
268
- - Use the latest VeloceTS version automatically
269
- - Include proper `await app.compile()` calls
270
- - Have more stable dependency versions
271
-
272
- #### For Framework Users
273
- No changes required. This release only improves the CLI experience.
274
-
275
- ## [0.3.0] - 2025-10-29
276
-
277
- ### 🚀 Major Features Added
278
-
279
- #### Response Caching System
280
- - **In-Memory Cache Store**: Fast LRU-based caching with automatic cleanup
281
- - **Redis Cache Store**: Distributed caching support for multi-instance deployments
282
- - **@Cache() Decorator**: Declarative response caching with flexible TTL configuration
283
- - **@CacheInvalidate() Decorator**: Pattern-based cache invalidation for mutations
284
- - **Cache Middleware**: Functional API support for route-level caching
285
- - **TTL Support**: Flexible time-to-live with string format ('5m', '1h', '1d') or seconds
286
- - **Pattern Invalidation**: Wildcard pattern matching for cache invalidation ('products:*')
287
- - **Cache Keys**: Smart key generation with placeholder support ('product:{id}')
288
- - **Cache Headers**: Automatic X-Cache headers (HIT/MISS) in responses
289
-
290
- #### Enhanced Request Context
291
- - **Automatic Request IDs**: UUID generation for every request
292
- - **@RequestId() Decorator**: Inject request ID into controller methods
293
- - **@AbortSignal() Decorator**: Request cancellation support for long-running operations
294
- - **Request Timeouts**: Configurable timeouts per route or globally
295
- - **Logging Integration**: Request ID automatically propagates through all logs
296
- - **Response Headers**: X-Request-ID header in all responses
297
- - **Metadata Storage**: Attach custom data to request context
298
- - **Request Lifecycle**: Automatic logging of request start/end with duration
299
-
300
- #### Logging Improvements
301
- - **Request Context Integration**: Automatic request ID in all log entries
302
- - **Child Loggers**: Enhanced contextual logging with inheritance
303
- - **Structured Logging**: JSON-formatted logs for production
304
- - **Pretty Printing**: Human-readable logs for development
305
- - **Log Middleware**: Request lifecycle logging with configurable headers
306
-
307
- ### 🎯 New Decorators
308
-
309
- - **@Cache(options)**: Cache route responses with TTL and key configuration
310
- - **@CacheInvalidate(pattern)**: Invalidate cache entries matching patterns
311
- - **@RequestId()**: Inject unique request ID into handler parameters
312
- - **@AbortSignal()**: Inject AbortSignal for request cancellation
313
-
314
- ### 🔧 New Middleware
315
-
316
- - **createRequestContextMiddleware()**: Initialize request context with ID, timeout, and logging
317
- - **createSimpleRequestIdMiddleware()**: Minimal request ID middleware
318
- - **createCacheMiddleware()**: Functional API route caching
319
- - **createCacheInvalidationMiddleware()**: Functional API cache invalidation
320
-
321
- ### 📦 New Modules
322
-
323
- - **src/cache/**: Complete caching system
324
- - `types.ts`: Cache interfaces and types
325
- - `memory-store.ts`: In-memory LRU cache implementation
326
- - `redis-store.ts`: Redis backend for distributed caching
327
- - `manager.ts`: Global cache management and utilities
328
- - **src/context/**: Enhanced request context
329
- - `request-context.ts`: Request tracking with UUID and AbortSignal
330
- - **src/middleware/**: New middleware
331
- - `request-context.ts`: Request context initialization
332
- - `cache.ts`: Cache middleware for functional API
333
- - **src/decorators/**: New decorators
334
- - `cache.ts`: @Cache and @CacheInvalidate decorators
335
-
336
- ### 🛠️ Core Improvements
337
-
338
- - **Router Compiler**: Integrated cache checking and invalidation in route handlers
339
- - **Type System**: New parameter types for request-id and abort-signal
340
- - **Export System**: All new decorators and middleware properly exported
341
- - **Error Handling**: Improved error handling with request ID context
342
-
343
- ### 📚 Documentation
344
-
345
- #### New Guides (English + Spanish)
346
- - **Caching Guide**: Complete guide to response caching (15,000 words total)
347
- - In-memory and Redis stores
348
- - Decorators and middleware
349
- - TTL configuration
350
- - Cache invalidation strategies
351
- - Best practices with 50+ code examples
352
- - **Request Context Guide**: Request tracking and management (12,000 words total)
353
- - Automatic UUID generation
354
- - Request cancellation with AbortSignal
355
- - Timeout configuration
356
- - Logging integration
357
- - 40+ code examples
358
- - **Logging Guide**: Structured logging with Pino (4,000 words total)
359
- - Logger configuration
360
- - Child loggers
361
- - Request ID integration
362
- - Best practices
363
-
364
- #### Documentation Coverage
365
- - Added 31,000+ words of professional documentation
366
- - 100+ new code examples
367
- - Bilingual support (English and Spanish)
368
- - SEO-optimized with meta descriptions
369
- - Cross-referenced between guides
370
-
371
- ### 🌐 Sidebar Updates
372
-
373
- Updated Starlight documentation sidebar with new guides:
374
- - Caching
375
- - Request Context
376
- - Logging
377
-
378
- ### Performance Improvements
379
-
380
- - **Cache System**: Sub-millisecond cache hits with in-memory store
381
- - **LRU Eviction**: Automatic memory management in cache store
382
- - **Request Context**: Minimal overhead UUID generation
383
- - **Logging**: Efficient structured logging with Pino
384
-
385
- ### 🔄 API Additions
386
-
387
- #### Cache Manager
388
- ```typescript
389
- - CacheManager.setDefaultStore(store)
390
- - CacheManager.getDefaultStore()
391
- - CacheManager.generateKey(method, path, params, query, options)
392
- - CacheManager.get(key, store?)
393
- - CacheManager.set(key, value, ttl?, store?)
394
- - CacheManager.delete(key, store?)
395
- - CacheManager.invalidate(pattern, store?)
396
- - CacheManager.clear(store?)
397
- ```
398
-
399
- #### Helper Functions
400
- ```typescript
401
- - getCache<T>(key): Promise<T | null>
402
- - setCache<T>(key, value, ttl?): Promise<void>
403
- - deleteCache(key): Promise<boolean>
404
- - invalidateCache(pattern): Promise<number>
405
- - clearCache(): Promise<void>
406
- - getRequestId(context): string | null
407
- - getAbortSignal(context): AbortSignal | null
408
- - setRequestMetadata(context, key, value): void
409
- - getRequestMetadata(context, key): any
410
- - generateRequestId(): string
411
- ```
412
-
413
- ### 🐛 Bug Fixes
414
-
415
- - **ORM Exports**: Fixed DrizzleTransactionManager import path
416
- - **Middleware Exports**: Added missing createCacheInvalidationMiddleware export
417
- - **Request Context**: Fixed AbortController reference in context
418
-
419
- ### 💥 Breaking Changes
420
-
421
- None - All changes are additive and backward compatible
422
-
423
- ### 📦 Dependencies
424
-
425
- No new runtime dependencies added. Caching works with existing dependencies:
426
- - In-memory cache: No dependencies (built-in)
427
- - Redis cache: Requires `redis` or `ioredis` (peer dependency)
428
-
429
- ### 🎯 Migration Guide
430
-
431
- #### Adding Cache to Existing Routes
432
-
433
- ```typescript
434
- // Before
435
- @Get('/products')
436
- async getProducts() {
437
- return await db.products.findAll();
438
- }
439
-
440
- // After - Add caching
441
- @Get('/products')
442
- @Cache({ ttl: '5m', key: 'products:list' })
443
- async getProducts() {
444
- return await db.products.findAll();
445
- }
446
- ```
447
-
448
- #### Adding Request Tracking
449
-
450
- ```typescript
451
- // Add to app initialization
452
- import { createRequestContextMiddleware } from 'veloce-ts';
453
-
454
- app.use(createRequestContextMiddleware({
455
- timeout: 30000,
456
- logging: true
457
- }));
458
-
459
- // Use in controllers
460
- @Get('/data')
461
- async getData(@RequestId() requestId: string) {
462
- logger.info({ requestId }, 'Processing request');
463
- return data;
464
- }
465
- ```
466
-
467
- ### 📊 Statistics
468
-
469
- - **New Files**: 15+ new source files
470
- - **Documentation**: 31,000+ words
471
- - **Code Examples**: 100+ examples
472
- - **Test Coverage**: All new features covered
473
- - **Languages**: Full bilingual support (EN/ES)
474
-
475
- ### 🙏 Acknowledgments
476
-
477
- This release brings powerful performance optimization features to Veloce-TS:
478
- - Response caching reduces database load and improves response times
479
- - Request tracking enables better debugging and monitoring
480
- - Enhanced logging provides better observability in production
481
-
482
- ## [0.2.6] - 2025-10-15
483
-
484
- ### Fixed
485
- - **Query Export**: Added missing `Query` export from main index to resolve import conflicts
486
- - **Parameter Decorators**: HTTP `@Query` decorator now properly exported alongside GraphQL decorators
487
- - **Import Resolution**: Fixed "Export named 'Query' not found" error in applications
488
-
489
- ## [0.2.5] - 2025-10-15
490
-
491
- ### Fixed
492
- - **GraphQL Query Conflict**: Removed conflicting alias `Query` from GraphQL decorators
493
- - **Import Resolution**: GraphQL decorators now use `GQLQuery` to avoid conflicts with HTTP `@Query` decorator
494
- - **Type Safety**: Eliminated TypeScript errors caused by decorator name conflicts
495
-
496
- ### Breaking Changes
497
- - GraphQL queries now use `@GQLQuery` instead of `@Query` to avoid conflicts with HTTP parameter decorator
498
-
499
- ## [0.2.4] - 2025-10-15
500
-
501
- ### Fixed
502
- - **Query Decorator**: Fixed `@Query` decorator to properly handle parameters without schemas
503
- - **Query Parameter Extraction**: Improved query parameter handling in router compiler
504
- - **Validation**: Added proper validation for query parameters with optional Zod schemas
505
- - **Error Handling**: Fixed missing `ValidationError` import, now using `BadRequestException`
506
-
507
- ### Improved
508
- - **Query Decorator Flexibility**: `@Query` now supports multiple usage patterns:
509
- - `@Query()` - Extract all query parameters
510
- - `@Query('param')` - Extract specific parameter
511
- - `@Query(Schema)` - Validate with Zod schema
512
- - **Router Compiler**: Enhanced parameter extraction and validation logic
513
- - **Type Safety**: Better TypeScript support for query parameter handling
514
-
515
- ### Breaking Changes
516
- - None
517
-
518
- ## [0.2.3] - 2025-10-14
519
-
520
- ### Fixed
521
- - **WebSocket Exports**: Fixed missing `WebSocket` decorator export from WebSocket module
522
- - **Import Resolution**: WebSocket decorators now properly exported from `veloce-ts/websocket`
523
-
524
- ## [0.2.2] - 2025-10-14
525
-
526
- ### Fixed
527
- - **GraphQL Decorators**: Added missing `Query`, `Mutation`, and `Subscription` aliases for GraphQL decorators
528
- - **Import Conflicts**: Fixed naming conflicts between params and GraphQL decorators
529
- - **CLI Templates**: Fixed import errors in CLI template generation
530
- - **Package Version**: CLI now uses current package version when generating new projects
531
-
532
- ### Changed
533
- - **GraphQL Exports**: GraphQL decorators now available with intuitive names (`Query`, `Mutation`, `Subscription`)
534
- - **Import Resolution**: Cleaner import structure to avoid naming conflicts
535
-
536
- ## [0.2.1] - 2025-10-14
537
-
538
- ### Fixed
539
- - **GraphQL Exports**: Fixed missing `Arg` decorator export from GraphQL module
540
- - **Import Resolution**: GraphQL decorators now properly exported from `veloce-ts/graphql`
541
- - **Type Definitions**: GraphQL decorators included in TypeScript declarations
542
-
543
- ## [0.2.0] - 2025-10-14
544
-
545
- ### 🚀 Major Features Added
546
- - **Complete Authentication System**: JWT-based authentication with access/refresh tokens
547
- - **Role-Based Access Control (RBAC)**: Hierarchical roles with granular permissions system
548
- - **SQLite Integration**: Built-in SQLite support with Bun's native database
549
- - **Real-time WebSocket Support**: Enhanced WebSocket handling with decorators
550
- - **GraphQL Integration**: Complete GraphQL support with resolvers and subscriptions
551
- - **Advanced Middleware System**: Custom middleware with request/response interceptors
552
- - **Admin Panel Features**: Comprehensive admin endpoints for user and system management
553
-
554
- ### 🎯 New Decorators & Features
555
- - **@Auth**: JWT authentication decorator with automatic user injection
556
- - **@CurrentUser**: Inject current authenticated user into handlers
557
- - **@MinimumRole**: Role-based endpoint protection
558
- - **@Permissions**: Granular permission-based access control
559
- - **@WebSocket**: Enhanced WebSocket decorators with connection management
560
- - **@Resolver**: GraphQL resolver decorators for queries and mutations
561
- - **@OnConnect/@OnMessage/@OnDisconnect**: WebSocket lifecycle decorators
562
-
563
- ### 🔧 Core Framework Improvements
564
- - **Router Compiler Fixes**: Fixed critical bugs with sparse array handling in metadata
565
- - **Dependency Injection**: Enhanced DI system with better error handling
566
- - **Parameter Resolution**: Improved parameter and dependency resolution
567
- - **Type Safety**: Enhanced TypeScript inference and type checking
568
- - **Error Handling**: Better error messages and debugging capabilities
569
-
570
- ### 📚 Documentation & Examples
571
- - **Veloce TaskMaster**: Complete real-world example with authentication, RBAC, and frontend
572
- - **Comprehensive Examples**: Task management system showcasing all framework features
573
- - **Migration Guides**: Documentation for migrating from Express.js and other frameworks
574
- - **API Documentation**: Enhanced OpenAPI/Swagger documentation generation
575
-
576
- ### 🛠️ Technical Improvements
577
- - **Performance**: Optimized router compilation and metadata handling
578
- - **Memory Management**: Better handling of metadata arrays and object references
579
- - **Bundle Size**: Reduced framework bundle size through optimizations
580
- - **Build System**: Improved TypeScript compilation and type generation
581
- - **Testing**: Enhanced testing utilities and error reporting
582
-
583
- ### 🔒 Security Enhancements
584
- - **JWT Security**: Secure token generation and validation
585
- - **Password Hashing**: Built-in password hashing utilities
586
- - **CSRF Protection**: Enhanced CORS and security middleware
587
- - **Input Validation**: Improved Zod schema validation
588
- - **Role Hierarchy**: Configurable role hierarchy with permission inheritance
589
-
590
- ### 🎨 Developer Experience
591
- - **Better Error Messages**: More descriptive error messages with stack traces
592
- - **Hot Reload**: Improved development server with better file watching
593
- - **TypeScript Support**: Enhanced type inference and IntelliSense
594
- - **Debugging**: Better debugging capabilities with request tracing
595
- - **CLI Improvements**: Enhanced CLI with better project scaffolding
596
-
597
- ### 🐛 Critical Bug Fixes
598
- - **Router Compilation**: Fixed sparse array handling in parameter metadata
599
- - **Dependency Resolution**: Fixed undefined dependency handling
600
- - **Array Length Errors**: Fixed array creation with invalid indices
601
- - **Import Path Issues**: Corrected all import paths in generated projects
602
- - **Metadata Processing**: Fixed metadata compilation edge cases
603
-
604
- ### 📦 New Dependencies
605
- - **jsonwebtoken**: JWT token generation and validation
606
- - **reflect-metadata**: Enhanced reflection capabilities for decorators
607
- - **zod-to-json-schema**: Improved OpenAPI schema generation
608
-
609
- ## [0.1.7] - 2025-10-12
610
-
611
- ### Fixed
612
- - Fixed syntax error in CLI new command that prevented build from completing
613
- - Fixed README generation in CLI templates
614
-
615
- ## [0.1.6] - 2025-10-12
616
-
617
- ### Added
618
- - **Landing Page**: Created modern Astro-based website with interactive terminal and file explorer
619
- - **Interactive Terminal**: Built terminal component for API testing with command history
620
- - **File Explorer**: Developed code browser with hierarchical navigation for demo app
621
- - **Documentation Files**: CLI now generates README.md and API_DOCUMENTATION.md in new projects
622
-
623
- ### Changed
624
- - **Complete Rebranding**: Renamed framework from FastAPI-TS to Veloce-TS throughout codebase
625
- - **OpenAPIPlugin**: Now serves Swagger UI directly from code (no need for static HTML files)
626
- - **Improved Swagger UI**: Updated to version 5.9.0 with better styling and functionality
627
- - **Simplified Templates**: `veloce-ts new` command no longer generates unnecessary public files
628
- - **Better Defaults**: OpenAPI documentation now uses "Veloce-TS" branding by default
629
- - **Updated URLs**: All references now point to correct GitHub repository and documentation
630
-
631
- ### Fixed
632
- - Fixed Swagger UI rendering issues with proper script loading
633
- - Fixed OpenAPI plugin to correctly serve HTML responses and return proper content types
634
- - Fixed broken links and outdated branding throughout codebase
635
- - Improved CORS handling in generated templates
636
- - Fixed CLI template generation to include proper documentation structure
637
-
638
- ## [0.1.5] - 2025-10-12
639
-
640
- ### Fixed
641
- - Fixed CLI templates to include OpenAPIPlugin automatically when docs: true
642
- - REST and Fullstack templates now properly initialize OpenAPI documentation
643
-
644
- ## [0.1.4] - 2025-10-13
645
-
646
- ### Fixed
647
- - Fixed CLI templates to call `await app.compile()` before `app.listen()`
648
- - This fixes the 404 error on all routes in generated projects
649
-
650
- ## [0.1.3] - 2025-10-12
651
-
652
- ### Fixed
653
- - Fixed package.json main and exports paths to point to correct dist/*/src/ directories
654
- - This fixes the "Cannot find package" error when importing veloce-ts
655
-
656
- ## [0.1.2] - 2025-10-12
657
-
658
- ### Fixed
659
- - Fixed CLI templates to use correct package name `veloce-ts` instead of `VeloceTS`
660
- - Fixed all import statements in generated projects
661
-
662
- ## [0.1.1] - 2025-10-12
663
-
664
- ### Fixed
665
- - Fixed CLI binary path to use compiled dist files instead of source files
666
-
667
- ## [0.1.0] - 2025-10-12
668
-
669
- ### Added
670
- - Initial release of veloce-ts framework
671
- - Decorator-based routing with @Controller, @Get, @Post, @Put, @Delete, @Patch
672
- - Functional API for decorator-free routing
673
- - Automatic request validation with Zod schemas
674
- - Dependency injection system with singleton, request, and transient scopes
675
- - Automatic OpenAPI documentation generation
676
- - Response handling with JSONResponse, HTMLResponse, FileResponse, StreamResponse, RedirectResponse
677
- - Plugin system for extensibility
678
- - WebSocket support with decorators
679
- - GraphQL support with decorators
680
- - CLI tool for project scaffolding and development
681
- - Middleware system with CORS, rate limiting, and compression
682
- - Error handling with custom exceptions
683
- - Testing utilities with TestClient
684
- - Multi-runtime support (Bun, Node.js, Deno, Cloudflare Workers)
685
- - Adapter system for Express and Hono
686
- - Type safety with full TypeScript support
687
- - Performance optimizations with metadata compilation and schema caching
688
-
689
- ## [0.1.0] - 2025-10-12
690
-
691
- ### Added
692
- - Initial development version
693
- - Core framework architecture
694
- - Basic routing and validation
695
- - Documentation generation
696
- - Plugin system
697
- - WebSocket and GraphQL support
698
- - CLI tooling
699
- - Testing utilities
700
-
701
- [Unreleased]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.4.0...HEAD
702
- [0.4.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.3...v0.4.0
703
- [0.3.3]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.3
704
- [0.3.2]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.2
705
- [0.3.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.0...v0.3.1
706
- [0.2.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.1...v0.2.2
707
- [0.2.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.0...v0.2.1
708
- [0.2.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.7...v0.2.0
709
- [0.1.7]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.6...v0.1.7
710
- [0.1.6]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.5...v0.1.6
711
- [0.1.5]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.4...v0.1.5
712
- [0.1.4]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.3...v0.1.4
713
- [0.1.3]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.2...v0.1.3
714
- [0.1.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.1...v0.1.2
715
- [0.1.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.0...v0.1.1
716
- [0.1.0]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.1.0
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.4.5] - 2026-03-29
11
+
12
+ Mismo parche CORS que se intentó en **0.4.4**; npm **no permite republicar** un número de versión tras `npm unpublish` (`E400 Cannot publish over previously published version`).
13
+
14
+ ### Fixed
15
+ - **CORS on error responses:** las respuestas del `ErrorHandler` (401, 422, 500, `application/problem+json`, etc.) incluyen `Access-Control-Allow-Origin` y el resto de cabeceras CORS configuradas, alineadas con respuestas OK (`veloce:corsHeaders` + `mergeVeloceCorsHeaders`). Export público: `mergeVeloceCorsHeaders`, `VELOCE_CORS_HEADERS_KEY`, `VeloceCorsHeadersSnapshot`.
16
+
17
+ ## [0.4.4] - 2026-03-28
18
+
19
+ **No usar:** la release en npm llegó sin tarball servible (404). Tras `npm unpublish veloce-ts@0.4.4`, el registry **bloquea** volver a publicar el mismo número. El parche CORS válido está en **0.4.5**.
20
+
21
+ ## [0.4.3] - 2026-03-27
22
+
23
+ ### Added
24
+ - **RFC 9457 (Problem Details):** respuestas de error por defecto con `Content-Type: application/problem+json`, campos `type`, `title`, `status`, `detail`, `instance` y extensiones (`violations`/`details` en validación; `debug` en 500 solo en desarrollo).
25
+ - **`VeloceTSConfig.errorResponseFormat`:** `'rfc9457'` (defecto) o `'legacy'` para el JSON `{ error, statusCode, details? }` anterior.
26
+ - Helpers exportados: `problemTypeUri`, `resolveProblemType`, `resolveProblemTitle`, `buildProblemInstance`, `toLegacyErrorBody`, `sendErrorResponse`, constantes `PROBLEM_JSON_MEDIA_TYPE`, `DEFAULT_PROBLEM_TYPE_BASE`.
27
+ - **`HTTPExceptionOptions`:** `problemType` y `title` opcionales en el constructor de `HTTPException`.
28
+
29
+ ### Changed
30
+ - Excepciones de auth (`AuthenticationException`, `AuthorizationException`) dejan de definir `toJSON` propio; heredan el formato unificado con URIs `authentication-error` / `authorization-error`.
31
+
32
+ ### Documentation
33
+ - Cabeceras `@module` en el núcleo (application, metadata, router-compiler, plugin, compiled-metadata), errores, validación, DI, respuestas, logging, middleware, adapters, testing, barrels y más.
34
+ - **Benchmarks:** `benchmarks/run.ts` etiquetado como v0.4.3; `BENCHMARKS.md` y `benchmarks/results/latest.json` regenerados (6 000 req, 50 concurrentes, Bun 1.3.5, 2026-03-28).
35
+
36
+ ### Notes
37
+ - El cuerpo JSON de error sigue incluyendo `error` y `statusCode` junto a los campos RFC 9457. Si tu cliente exige `Content-Type: application/json` en errores, usa `errorResponseFormat: 'legacy'` o acepta `application/problem+json`.
38
+
39
+ ## [0.4.2] - 2026-03-27
40
+
41
+ ### Fixed
42
+ - **HealthCheckPlugin:** checker display names are set with `Object.defineProperty` (with a fallback) so runtimes such as Bun do not throw when assigning `.name` on async checker functions.
43
+ - **Public API:** `@Req` is now exported from the main `veloce-ts` entry (it was implemented in `decorators/params` but missing from the package exports).
44
+
45
+ ## [0.4.1] - 2026-03-27
46
+
47
+ ### Fixed
48
+ - `include()` in `VeloceTS` application no longer drops decorator-set route fields (e.g. `statusCode` from `@HttpCode`, `responseSchema` from `@ResponseSchema`) when registering controller routes.
49
+
50
+ ### Added
51
+ - New test suite: `tests/routing.test.ts`, `tests/validation.test.ts`, `tests/errors.test.ts`, `tests/di.test.ts` 53 integration tests covering functional API, decorator routing, body/query validation, HTTP exceptions, and DI container.
52
+ - Console-based fallback logger: if `pino` is not installed, the framework now falls back silently to a `console`-based logger instead of crashing at startup.
53
+
54
+ ### Changed
55
+ - `pino`, `pino-pretty`, and `ioredis` moved from `dependencies` to `optionalDependencies`. They are no longer installed automatically, reducing the default install footprint by ~7 MB. Install them explicitly if needed (`bun add pino pino-pretty` / `bun add ioredis`).
56
+ - `winston` removed from `dependencies` entirely (it was listed but never used by the framework).
57
+ - `@types/ioredis` and `@types/pino` removed from `devDependencies` (no longer needed).
58
+ - Build threshold in `build.ts` updated from 100 KB to 600 KB to reflect the full framework scope.
59
+ - Core bundle reduced from 444 KB to 408 KB (minified ESM).
60
+
61
+ ### Deprecated
62
+ - `FastAPITS` export: use `VeloceTS` or the shorter `Veloce` alias instead. `FastAPITS` will be removed in v1.0.0.
63
+
64
+ ## [0.4.0] - 2026-03-27
65
+
66
+ Esta versión representa la mayor actualización desde el lanzamiento inicial. Se añadieron más de 25 mejoras nuevas distribuidas en tres oleadas de trabajo (alta, media y baja prioridad), cubriendo la cadena completa desde la generación de rutas hasta la documentación OpenAPI, el testing, el ORM y la CLI.
67
+
68
+ ### 🚀 Nuevos Decoradores
69
+
70
+ #### Documentación OpenAPI (shorthand)
71
+ Cinco decoradores de una sola línea como alternativa concisa a `@ApiDoc({...})`:
72
+ - **`@Summary(text)`** — descripción corta visible en la lista de Swagger UI
73
+ - **`@Description(text)`** — texto largo en el panel de detalle de la operación
74
+ - **`@Tag(name)`** — asigna un tag individual; apilable con múltiples `@Tag`
75
+ - **`@Tags(...names)`** asigna varios tags en un solo decorador
76
+ - **`@Deprecated()`** — marca la ruta como obsoleta (tachado en Swagger UI)
77
+
78
+ #### Control de respuesta
79
+ - **`@HttpCode(statusCode)`** sobreescribe el código HTTP de respuesta del handler (p.ej. `201` para creación). Usado también por el generador OpenAPI para el código de éxito documentado
80
+ - **`@ResponseSchema(schema, statusCode?)`** valida y sanitiza la respuesta del handler con un esquema Zod; informa el modelo de respuesta al spec de OpenAPI
81
+
82
+ #### Middleware declarativo por ruta
83
+ - **`@Timeout(ms, message?)`** — aborta la petición con **408 Request Timeout** si el handler supera el límite. Inyecta automáticamente el middleware al inicio del pipeline y emite el header `X-Timeout-Ms`
84
+ - **`@RateLimit(options)`** — aplica rate-limiting a nivel de ruta individual usando la misma configuración de `createRateLimitMiddleware()`. Los headers estándar `X-RateLimit-*` se envían automáticamente
85
+
86
+ ### 🛠️ Mejoras al Framework Core
87
+
88
+ #### OpenAPI Generator (`src/docs/openapi-generator.ts`)
89
+ - **Auto-tagging**: deriva tags automáticamente del primer segmento del path (`/products/:id` → tag `"Products"`) sin necesidad de anotarlos manualmente
90
+ - **Bearer security scheme**: añade `components.securitySchemes.bearerAuth` al spec y aplica `security: [{ bearerAuth: [] }]` en rutas protegidas de forma automática
91
+ - **401 automático**: rutas protegidas reciben una respuesta `401 Unauthorized` documentada sin configuración adicional
92
+ - **Soporte de `@HttpCode`**: usa el `statusCode` del decorador como clave del bloque de éxito en `responses`
93
+ - **`@ResponseSchema` en el spec**: cuando está presente, el esquema Zod se convierte al formato JSON Schema para el bloque de contenido de la respuesta
94
+
95
+ #### Sistema de Excepciones HTTP (`src/errors/exceptions.ts`)
96
+ Seis nuevas clases de excepción para cubrir casos de error comunes:
97
+ - `ConflictException` (409)
98
+ - `GoneException` (410)
99
+ - `PayloadTooLargeException` (413)
100
+ - `UnprocessableEntityException` (422)
101
+ - `TooManyRequestsException` (429)
102
+ - `ServiceUnavailableException` (503)
103
+
104
+ #### Logger estructurado en ErrorHandler (`src/errors/handler.ts`)
105
+ - Errores 5xx se registran con `getLogger().error` incluyendo path, método, status y stack
106
+ - Errores 4xx se registran como `warn` en entorno de desarrollo
107
+ - Errores genéricos no capturados también pasan por Pino
108
+
109
+ #### Arreglos de orden de decoradores
110
+ - **`@UseMiddleware`** (`src/decorators/middleware.ts`): ahora siempre llama a `MetadataRegistry.defineRoute` para que el middleware no se pierda independientemente del orden de ejecución de los decoradores
111
+ - **`@Cache` / `@CacheInvalidate`** (`src/decorators/cache.ts`): mismo patrón — los metadatos se fusionan correctamente sin importar el orden de apilamiento
112
+
113
+ #### MetadataCompilercaché lazy con snapshots (`src/core/compiled-metadata.ts`)
114
+ - Compilación lazy: una ruta sólo se recompila si sus metadatos cambiaron (comparación por snapshot JSON)
115
+ - IDs únicos para handlers funcionales vía `WeakMap<Function, number>` evita colisiones de caché cuando distintas instancias de app registran el mismo path con handlers diferentes (bug crítico en tests paralelos)
116
+ - Método `clearCache()` expuesto para limpiar el estado entre tests
117
+
118
+ ### 🧪 TestClientAPI fluida y helpers de autenticación (`src/testing/test-client.ts`)
119
+
120
+ Reescritura completa de `TestClient`:
121
+ - **`TestResponse`** — nueva clase de respuesta con propiedades `status`, `headers`, `body`, `text`, `ok` y métodos de aserción encadenables:
122
+ - `expectStatus(code)`, `expectOk()`, `expectCreated()`, `expectNotFound()`, etc.
123
+ - `expectJson(partialObject)` — comprobación parcial del body
124
+ - `expectField(field, value?)` — verificar un campo específico
125
+ - `expectHeader(name, value?)` verificar un header de respuesta
126
+ - `expectArrayLength(n)` verificar longitud de array en respuesta
127
+ - **`withToken(token)`** — crea una instancia inmutable del cliente con el header `Authorization: Bearer` ya configurado
128
+ - **`withHeaders(headers)`**crea una instancia inmutable con headers adicionales
129
+ - **`loginAs(credentials, endpoint?)`** hace login, extrae el JWT y lo inyecta en el cliente actual para las peticiones siguientes
130
+ - **`registerAndLogin(user, endpoints?)`** — registra y hace login en una sola llamada
131
+ - **`clearAuth()`** limpia el token almacenado
132
+
133
+ ### 🔌 Plugins y Middleware
134
+
135
+ #### HealthCheckers.disk (`src/plugins/health.ts`)
136
+ - Usa `fs.statfs` (Node 18+ / Bun) para obtener métricas reales de disco: total, libre, usado y porcentaje
137
+ - Degradación elegante a `"healthy"` en plataformas sin soporte
138
+
139
+ #### CLI — Plantilla Fullstack corregida (`src/cli/commands/new.ts`)
140
+ - La plantilla `fullstack` ahora genera `src/index.ts` con `GraphQLPlugin` y `WebSocketPlugin` correctamente importados e instanciados (antes quedaban comentados)
141
+
142
+ #### Subpath exports en el build (`build.ts`)
143
+ - Se añadieron `./src/auth/index.ts`, `./src/adapters/base.ts`, `./src/adapters/hono.ts`, `./src/adapters/express.ts` como entrypoints explícitos para que los imports `veloce-ts/auth` y `veloce-ts/adapters/*` funcionen correctamente
144
+
145
+ ### 🗄️ Drizzle ORM Integración DI (`src/dependencies/drizzle.ts`)
146
+
147
+ Nuevo módulo para conectar Drizzle (u otro ORM) al contenedor de inyección de dependencias:
148
+ ```typescript
149
+ // Registrar la instancia de la DB
150
+ registerDrizzle(app, db);
151
+
152
+ // Inyectar en controladores
153
+ @Get('/')
154
+ async list(@InjectDB() db: DrizzleDB) { … }
155
+ ```
156
+ - `DB_TOKEN` — símbolo por defecto para el token de inyección
157
+ - `registerDrizzle(app, db, token?)` — registra como singleton en el `DIContainer`
158
+ - `@InjectDB(token?)` — decorador de parámetro, alias de `@Depends(DB_TOKEN)`
159
+
160
+ ### 📊 Paginación mejorada (`src/orm/pagination.ts`)
161
+
162
+ #### Enriquecimiento de metadatos
163
+ - `PaginationMeta` incluye `from` y `to` (rango 1-based, p.ej. `from: 11, to: 20`)
164
+ - `CursorPaginatedResult` incluye `count` (ítems reales devueltos en la página)
165
+
166
+ #### Cursor pagination más precisa
167
+ - `createCursorPaginatedResult(data, limit, cursorField, hadPrevCursor)` — el nuevo parámetro `hadPrevCursor` activa `hasPrev: true` correctamente cuando se navega hacia adelante con cursor
168
+ - `createMultiCursor(entity, fields[])` crea cursores compuestos por múltiples campos para ordenación estable (p.ej. `{ createdAt, id }`)
169
+ - `decodeMultiCursor(cursor)` decodifica un cursor multi-campo de vuelta a un objeto
170
+
171
+ #### Helpers standalone
172
+ - `paginate<T>(data, total, page, limit)` construye `{ data, meta }` en una sola llamada, sin necesidad de instanciar `PaginationHelper`
173
+ - `parseCursorQuery(query, defaultLimit?, maxLimit?)` — extrae `cursor` y `limit` de los query params sin lanzar excepciones
174
+ - `PaginationHelper.parsePaginationQuery(query, defaultLimit?, maxLimit?)` — equivalente para paginación offset; aplica límite máximo y usa defaults cuando los valores son inválidos
175
+
176
+ ### 🔌 Express Adapter — Compatibilidad ESM (`src/adapters/express.ts`)
177
+
178
+ Reescritura completa del adaptador:
179
+ - Carga Express de forma lazy y segura usando `Function('return require')()` para compatibilidad ESM sin necesitar `declare const require: any`
180
+ - Acepta una instancia de Express pre-creada como segundo argumento del constructor (para añadir middleware propio antes del bridge)
181
+ - Manejo correcto de body raw (`Buffer`) vs body parseado (JSON/urlencoded)
182
+ - Omite el header `transfer-encoding` al reenviar respuestas (era fuente de errores en Express)
183
+ - Delega errores inesperados al pipeline de error de Express mediante `next(err)` en lugar de responder con 500 directamente
184
+
185
+ ### 🐛 Bug Fixes
186
+
187
+ - **`ZodError` cross-module** (`src/errors/handler.ts`, `src/validation/validator.ts`): `instanceof ZodError` fallaba cuando la app consumidora tenía una instancia de Zod diferente a la del framework (caso frecuente con `bun link`). Añadido fallback `error.name === 'ZodError'` para garantizar respuestas 422 en todos los casos
188
+ - **Rutas `GET` marcadas públicas retornaban 401** en `products-api`: `app.use()` aplicaba el middleware a todos los métodos; corregido usando `app.on(['POST', 'PUT', 'DELETE'], path, middleware)` para restringir sólo a métodos de escritura
189
+ - **Cache collision en MetadataCompiler**: handlers funcionales distintos con el mismo path en diferentes instancias de app compartían el resultado compilado incorrecto; solucionado con IDs únicos por función
190
+ - **`@Cache` / `@UseMiddleware` perdían metadatos**: cuando se apilaban en orden inverso al de ejecución de decoradores, los metadatos podían sobreescribirse; solucionado actualizando el registro explícitamente en cada decorador
191
+
192
+ ### 📋 Mensajes de validación mejorados (`src/validation/exceptions.ts`)
193
+
194
+ La respuesta de error `422` ahora incluye información estructurada adicional:
195
+ - `field` en formato convencional: `items[0].price` en lugar de `items.0.price`
196
+ - `received` tipo recibido (cuando Zod lo reporta)
197
+ - `expected` — tipo esperado (cuando aplica)
198
+ - `minimum` / `maximum` — límites numéricos en errores de rango
199
+
200
+ ```json
201
+ {
202
+ "error": "Validation Error",
203
+ "statusCode": 422,
204
+ "details": [
205
+ { "field": "email", "message": "Invalid email", "code": "invalid_string" },
206
+ { "field": "age", "message": "Number must be ≥ 18", "code": "too_small", "minimum": 18 },
207
+ { "field": "tags[1]", "message": "String must not be empty", "code": "too_small" }
208
+ ]
209
+ }
210
+ ```
211
+
212
+ ### 💥 Breaking Changes
213
+
214
+ Ninguno todos los cambios son retrocompatibles. Las firmas de `createCursorPaginatedResult` tienen un nuevo parámetro opcional `hadPrevCursor` (cuarto argumento, `false` por defecto).
215
+
216
+ ### 📦 Dependencias
217
+
218
+ Sin cambios en dependencias de runtime. Express sigue siendo peer dependency opcional.
219
+
220
+ ---
221
+
222
+ ## [0.3.3] - 2025-10-31
223
+
224
+ ### 🐛 Critical Bug Fixes
225
+ - **JSON Response Serialization**: Fixed critical bug where JSON responses were not being serialized correctly
226
+ - **CLI Version Resolution**: Confirmed CLI correctly fetches and uses latest npm version (0.3.2)
227
+ - **Application Compilation**: Fixed missing `await app.compile()` call in generated templates
228
+
229
+ ### 🔧 CLI Improvements
230
+ - **Version Fetching**: CLI now correctly fetches latest version from npm registry
231
+ - **Template Generation**: All templates now include proper `await app.compile()` call
232
+ - **Error Handling**: Improved error handling in CLI operations
233
+
234
+ ## [0.3.2] - 2025-10-31
235
+
236
+ ## [0.3.1] - 2025-10-31
237
+
238
+ ### 🛠️ CLI Improvements
239
+
240
+ #### Enhanced Project Generation
241
+ - **Latest Version Fetching**: CLI now automatically fetches the latest VeloceTS version from npm registry
242
+ - **Improved Error Handling**: Better error messages and cleanup on project creation failure
243
+ - **Type Safety**: Fixed TypeScript errors in CLI with proper type definitions for npm registry API
244
+ - **Better User Experience**: Enhanced progress messages and visual feedback during project creation
245
+ - **Robust Fallbacks**: Multiple fallback strategies for version detection when npm is unavailable
246
+
247
+ #### Fixed Issues
248
+ - **npm Registry Integration**: Fixed CLI to use correct npm registry endpoint (`/veloce-ts` instead of `/veloce-ts/latest`)
249
+ - **Type Definitions**: Added proper TypeScript interfaces for npm registry response structure
250
+ - **Version Resolution**: Improved version parsing with proper type checking and validation
251
+ - **Package.json Generation**: Now uses specific dependency versions instead of 'latest' for better stability
252
+ - **Template Compilation**: All generated templates now include mandatory `await app.compile()` call
253
+
254
+ #### Technical Improvements
255
+ - **NpmRegistryResponse Interface**: Added proper typing for npm registry API responses
256
+ - **Async Error Handling**: Better error handling in async CLI operations
257
+ - **Dependency Versions**: Updated to use specific versions for better reproducibility:
258
+ - `hono: ^4.0.0` (instead of 'latest')
259
+ - `reflect-metadata: ^0.2.0` (instead of 'latest')
260
+ - `zod: ^3.22.0` (instead of 'latest')
261
+ - `typescript: ^5.3.0` (instead of 'latest')
262
+ - **Engine Requirements**: Added Node.js and Bun version requirements to generated package.json
263
+
264
+ #### Developer Experience
265
+ - **Progress Indicators**: Added emoji-based progress indicators for better visual feedback
266
+ - **Cleanup on Failure**: Automatic cleanup of partial projects when creation fails
267
+ - **Validation**: Better project name validation and error messages
268
+ - **Documentation**: Generated projects include comprehensive setup instructions
269
+
270
+ ### 🐛 Bug Fixes
271
+ - **CLI TypeScript Errors**: Fixed 'data is of type unknown' error in npm registry API calls
272
+ - **Template Generation**: Fixed missing `await app.compile()` in all CLI templates
273
+ - **Dependency Management**: Improved dependency version resolution and fallback handling
274
+
275
+ ### 📦 Migration Guide
276
+
277
+ #### For CLI Users
278
+ No breaking changes. Existing projects will continue to work. New projects generated with `veloce-ts new` will:
279
+ - Use the latest VeloceTS version automatically
280
+ - Include proper `await app.compile()` calls
281
+ - Have more stable dependency versions
282
+
283
+ #### For Framework Users
284
+ No changes required. This release only improves the CLI experience.
285
+
286
+ ## [0.3.0] - 2025-10-29
287
+
288
+ ### 🚀 Major Features Added
289
+
290
+ #### Response Caching System
291
+ - **In-Memory Cache Store**: Fast LRU-based caching with automatic cleanup
292
+ - **Redis Cache Store**: Distributed caching support for multi-instance deployments
293
+ - **@Cache() Decorator**: Declarative response caching with flexible TTL configuration
294
+ - **@CacheInvalidate() Decorator**: Pattern-based cache invalidation for mutations
295
+ - **Cache Middleware**: Functional API support for route-level caching
296
+ - **TTL Support**: Flexible time-to-live with string format ('5m', '1h', '1d') or seconds
297
+ - **Pattern Invalidation**: Wildcard pattern matching for cache invalidation ('products:*')
298
+ - **Cache Keys**: Smart key generation with placeholder support ('product:{id}')
299
+ - **Cache Headers**: Automatic X-Cache headers (HIT/MISS) in responses
300
+
301
+ #### Enhanced Request Context
302
+ - **Automatic Request IDs**: UUID generation for every request
303
+ - **@RequestId() Decorator**: Inject request ID into controller methods
304
+ - **@AbortSignal() Decorator**: Request cancellation support for long-running operations
305
+ - **Request Timeouts**: Configurable timeouts per route or globally
306
+ - **Logging Integration**: Request ID automatically propagates through all logs
307
+ - **Response Headers**: X-Request-ID header in all responses
308
+ - **Metadata Storage**: Attach custom data to request context
309
+ - **Request Lifecycle**: Automatic logging of request start/end with duration
310
+
311
+ #### Logging Improvements
312
+ - **Request Context Integration**: Automatic request ID in all log entries
313
+ - **Child Loggers**: Enhanced contextual logging with inheritance
314
+ - **Structured Logging**: JSON-formatted logs for production
315
+ - **Pretty Printing**: Human-readable logs for development
316
+ - **Log Middleware**: Request lifecycle logging with configurable headers
317
+
318
+ ### 🎯 New Decorators
319
+
320
+ - **@Cache(options)**: Cache route responses with TTL and key configuration
321
+ - **@CacheInvalidate(pattern)**: Invalidate cache entries matching patterns
322
+ - **@RequestId()**: Inject unique request ID into handler parameters
323
+ - **@AbortSignal()**: Inject AbortSignal for request cancellation
324
+
325
+ ### 🔧 New Middleware
326
+
327
+ - **createRequestContextMiddleware()**: Initialize request context with ID, timeout, and logging
328
+ - **createSimpleRequestIdMiddleware()**: Minimal request ID middleware
329
+ - **createCacheMiddleware()**: Functional API route caching
330
+ - **createCacheInvalidationMiddleware()**: Functional API cache invalidation
331
+
332
+ ### 📦 New Modules
333
+
334
+ - **src/cache/**: Complete caching system
335
+ - `types.ts`: Cache interfaces and types
336
+ - `memory-store.ts`: In-memory LRU cache implementation
337
+ - `redis-store.ts`: Redis backend for distributed caching
338
+ - `manager.ts`: Global cache management and utilities
339
+ - **src/context/**: Enhanced request context
340
+ - `request-context.ts`: Request tracking with UUID and AbortSignal
341
+ - **src/middleware/**: New middleware
342
+ - `request-context.ts`: Request context initialization
343
+ - `cache.ts`: Cache middleware for functional API
344
+ - **src/decorators/**: New decorators
345
+ - `cache.ts`: @Cache and @CacheInvalidate decorators
346
+
347
+ ### 🛠️ Core Improvements
348
+
349
+ - **Router Compiler**: Integrated cache checking and invalidation in route handlers
350
+ - **Type System**: New parameter types for request-id and abort-signal
351
+ - **Export System**: All new decorators and middleware properly exported
352
+ - **Error Handling**: Improved error handling with request ID context
353
+
354
+ ### 📚 Documentation
355
+
356
+ #### New Guides (English + Spanish)
357
+ - **Caching Guide**: Complete guide to response caching (15,000 words total)
358
+ - In-memory and Redis stores
359
+ - Decorators and middleware
360
+ - TTL configuration
361
+ - Cache invalidation strategies
362
+ - Best practices with 50+ code examples
363
+ - **Request Context Guide**: Request tracking and management (12,000 words total)
364
+ - Automatic UUID generation
365
+ - Request cancellation with AbortSignal
366
+ - Timeout configuration
367
+ - Logging integration
368
+ - 40+ code examples
369
+ - **Logging Guide**: Structured logging with Pino (4,000 words total)
370
+ - Logger configuration
371
+ - Child loggers
372
+ - Request ID integration
373
+ - Best practices
374
+
375
+ #### Documentation Coverage
376
+ - Added 31,000+ words of professional documentation
377
+ - 100+ new code examples
378
+ - Bilingual support (English and Spanish)
379
+ - SEO-optimized with meta descriptions
380
+ - Cross-referenced between guides
381
+
382
+ ### 🌐 Sidebar Updates
383
+
384
+ Updated Starlight documentation sidebar with new guides:
385
+ - Caching
386
+ - Request Context
387
+ - Logging
388
+
389
+ ### ⚡ Performance Improvements
390
+
391
+ - **Cache System**: Sub-millisecond cache hits with in-memory store
392
+ - **LRU Eviction**: Automatic memory management in cache store
393
+ - **Request Context**: Minimal overhead UUID generation
394
+ - **Logging**: Efficient structured logging with Pino
395
+
396
+ ### 🔄 API Additions
397
+
398
+ #### Cache Manager
399
+ ```typescript
400
+ - CacheManager.setDefaultStore(store)
401
+ - CacheManager.getDefaultStore()
402
+ - CacheManager.generateKey(method, path, params, query, options)
403
+ - CacheManager.get(key, store?)
404
+ - CacheManager.set(key, value, ttl?, store?)
405
+ - CacheManager.delete(key, store?)
406
+ - CacheManager.invalidate(pattern, store?)
407
+ - CacheManager.clear(store?)
408
+ ```
409
+
410
+ #### Helper Functions
411
+ ```typescript
412
+ - getCache<T>(key): Promise<T | null>
413
+ - setCache<T>(key, value, ttl?): Promise<void>
414
+ - deleteCache(key): Promise<boolean>
415
+ - invalidateCache(pattern): Promise<number>
416
+ - clearCache(): Promise<void>
417
+ - getRequestId(context): string | null
418
+ - getAbortSignal(context): AbortSignal | null
419
+ - setRequestMetadata(context, key, value): void
420
+ - getRequestMetadata(context, key): any
421
+ - generateRequestId(): string
422
+ ```
423
+
424
+ ### 🐛 Bug Fixes
425
+
426
+ - **ORM Exports**: Fixed DrizzleTransactionManager import path
427
+ - **Middleware Exports**: Added missing createCacheInvalidationMiddleware export
428
+ - **Request Context**: Fixed AbortController reference in context
429
+
430
+ ### 💥 Breaking Changes
431
+
432
+ None - All changes are additive and backward compatible
433
+
434
+ ### 📦 Dependencies
435
+
436
+ No new runtime dependencies added. Caching works with existing dependencies:
437
+ - In-memory cache: No dependencies (built-in)
438
+ - Redis cache: Requires `redis` or `ioredis` (peer dependency)
439
+
440
+ ### 🎯 Migration Guide
441
+
442
+ #### Adding Cache to Existing Routes
443
+
444
+ ```typescript
445
+ // Before
446
+ @Get('/products')
447
+ async getProducts() {
448
+ return await db.products.findAll();
449
+ }
450
+
451
+ // After - Add caching
452
+ @Get('/products')
453
+ @Cache({ ttl: '5m', key: 'products:list' })
454
+ async getProducts() {
455
+ return await db.products.findAll();
456
+ }
457
+ ```
458
+
459
+ #### Adding Request Tracking
460
+
461
+ ```typescript
462
+ // Add to app initialization
463
+ import { createRequestContextMiddleware } from 'veloce-ts';
464
+
465
+ app.use(createRequestContextMiddleware({
466
+ timeout: 30000,
467
+ logging: true
468
+ }));
469
+
470
+ // Use in controllers
471
+ @Get('/data')
472
+ async getData(@RequestId() requestId: string) {
473
+ logger.info({ requestId }, 'Processing request');
474
+ return data;
475
+ }
476
+ ```
477
+
478
+ ### 📊 Statistics
479
+
480
+ - **New Files**: 15+ new source files
481
+ - **Documentation**: 31,000+ words
482
+ - **Code Examples**: 100+ examples
483
+ - **Test Coverage**: All new features covered
484
+ - **Languages**: Full bilingual support (EN/ES)
485
+
486
+ ### 🙏 Acknowledgments
487
+
488
+ This release brings powerful performance optimization features to Veloce-TS:
489
+ - Response caching reduces database load and improves response times
490
+ - Request tracking enables better debugging and monitoring
491
+ - Enhanced logging provides better observability in production
492
+
493
+ ## [0.2.6] - 2025-10-15
494
+
495
+ ### Fixed
496
+ - **Query Export**: Added missing `Query` export from main index to resolve import conflicts
497
+ - **Parameter Decorators**: HTTP `@Query` decorator now properly exported alongside GraphQL decorators
498
+ - **Import Resolution**: Fixed "Export named 'Query' not found" error in applications
499
+
500
+ ## [0.2.5] - 2025-10-15
501
+
502
+ ### Fixed
503
+ - **GraphQL Query Conflict**: Removed conflicting alias `Query` from GraphQL decorators
504
+ - **Import Resolution**: GraphQL decorators now use `GQLQuery` to avoid conflicts with HTTP `@Query` decorator
505
+ - **Type Safety**: Eliminated TypeScript errors caused by decorator name conflicts
506
+
507
+ ### Breaking Changes
508
+ - GraphQL queries now use `@GQLQuery` instead of `@Query` to avoid conflicts with HTTP parameter decorator
509
+
510
+ ## [0.2.4] - 2025-10-15
511
+
512
+ ### Fixed
513
+ - **Query Decorator**: Fixed `@Query` decorator to properly handle parameters without schemas
514
+ - **Query Parameter Extraction**: Improved query parameter handling in router compiler
515
+ - **Validation**: Added proper validation for query parameters with optional Zod schemas
516
+ - **Error Handling**: Fixed missing `ValidationError` import, now using `BadRequestException`
517
+
518
+ ### Improved
519
+ - **Query Decorator Flexibility**: `@Query` now supports multiple usage patterns:
520
+ - `@Query()` - Extract all query parameters
521
+ - `@Query('param')` - Extract specific parameter
522
+ - `@Query(Schema)` - Validate with Zod schema
523
+ - **Router Compiler**: Enhanced parameter extraction and validation logic
524
+ - **Type Safety**: Better TypeScript support for query parameter handling
525
+
526
+ ### Breaking Changes
527
+ - None
528
+
529
+ ## [0.2.3] - 2025-10-14
530
+
531
+ ### Fixed
532
+ - **WebSocket Exports**: Fixed missing `WebSocket` decorator export from WebSocket module
533
+ - **Import Resolution**: WebSocket decorators now properly exported from `veloce-ts/websocket`
534
+
535
+ ## [0.2.2] - 2025-10-14
536
+
537
+ ### Fixed
538
+ - **GraphQL Decorators**: Added missing `Query`, `Mutation`, and `Subscription` aliases for GraphQL decorators
539
+ - **Import Conflicts**: Fixed naming conflicts between params and GraphQL decorators
540
+ - **CLI Templates**: Fixed import errors in CLI template generation
541
+ - **Package Version**: CLI now uses current package version when generating new projects
542
+
543
+ ### Changed
544
+ - **GraphQL Exports**: GraphQL decorators now available with intuitive names (`Query`, `Mutation`, `Subscription`)
545
+ - **Import Resolution**: Cleaner import structure to avoid naming conflicts
546
+
547
+ ## [0.2.1] - 2025-10-14
548
+
549
+ ### Fixed
550
+ - **GraphQL Exports**: Fixed missing `Arg` decorator export from GraphQL module
551
+ - **Import Resolution**: GraphQL decorators now properly exported from `veloce-ts/graphql`
552
+ - **Type Definitions**: GraphQL decorators included in TypeScript declarations
553
+
554
+ ## [0.2.0] - 2025-10-14
555
+
556
+ ### 🚀 Major Features Added
557
+ - **Complete Authentication System**: JWT-based authentication with access/refresh tokens
558
+ - **Role-Based Access Control (RBAC)**: Hierarchical roles with granular permissions system
559
+ - **SQLite Integration**: Built-in SQLite support with Bun's native database
560
+ - **Real-time WebSocket Support**: Enhanced WebSocket handling with decorators
561
+ - **GraphQL Integration**: Complete GraphQL support with resolvers and subscriptions
562
+ - **Advanced Middleware System**: Custom middleware with request/response interceptors
563
+ - **Admin Panel Features**: Comprehensive admin endpoints for user and system management
564
+
565
+ ### 🎯 New Decorators & Features
566
+ - **@Auth**: JWT authentication decorator with automatic user injection
567
+ - **@CurrentUser**: Inject current authenticated user into handlers
568
+ - **@MinimumRole**: Role-based endpoint protection
569
+ - **@Permissions**: Granular permission-based access control
570
+ - **@WebSocket**: Enhanced WebSocket decorators with connection management
571
+ - **@Resolver**: GraphQL resolver decorators for queries and mutations
572
+ - **@OnConnect/@OnMessage/@OnDisconnect**: WebSocket lifecycle decorators
573
+
574
+ ### 🔧 Core Framework Improvements
575
+ - **Router Compiler Fixes**: Fixed critical bugs with sparse array handling in metadata
576
+ - **Dependency Injection**: Enhanced DI system with better error handling
577
+ - **Parameter Resolution**: Improved parameter and dependency resolution
578
+ - **Type Safety**: Enhanced TypeScript inference and type checking
579
+ - **Error Handling**: Better error messages and debugging capabilities
580
+
581
+ ### 📚 Documentation & Examples
582
+ - **Veloce TaskMaster**: Complete real-world example with authentication, RBAC, and frontend
583
+ - **Comprehensive Examples**: Task management system showcasing all framework features
584
+ - **Migration Guides**: Documentation for migrating from Express.js and other frameworks
585
+ - **API Documentation**: Enhanced OpenAPI/Swagger documentation generation
586
+
587
+ ### 🛠️ Technical Improvements
588
+ - **Performance**: Optimized router compilation and metadata handling
589
+ - **Memory Management**: Better handling of metadata arrays and object references
590
+ - **Bundle Size**: Reduced framework bundle size through optimizations
591
+ - **Build System**: Improved TypeScript compilation and type generation
592
+ - **Testing**: Enhanced testing utilities and error reporting
593
+
594
+ ### 🔒 Security Enhancements
595
+ - **JWT Security**: Secure token generation and validation
596
+ - **Password Hashing**: Built-in password hashing utilities
597
+ - **CSRF Protection**: Enhanced CORS and security middleware
598
+ - **Input Validation**: Improved Zod schema validation
599
+ - **Role Hierarchy**: Configurable role hierarchy with permission inheritance
600
+
601
+ ### 🎨 Developer Experience
602
+ - **Better Error Messages**: More descriptive error messages with stack traces
603
+ - **Hot Reload**: Improved development server with better file watching
604
+ - **TypeScript Support**: Enhanced type inference and IntelliSense
605
+ - **Debugging**: Better debugging capabilities with request tracing
606
+ - **CLI Improvements**: Enhanced CLI with better project scaffolding
607
+
608
+ ### 🐛 Critical Bug Fixes
609
+ - **Router Compilation**: Fixed sparse array handling in parameter metadata
610
+ - **Dependency Resolution**: Fixed undefined dependency handling
611
+ - **Array Length Errors**: Fixed array creation with invalid indices
612
+ - **Import Path Issues**: Corrected all import paths in generated projects
613
+ - **Metadata Processing**: Fixed metadata compilation edge cases
614
+
615
+ ### 📦 New Dependencies
616
+ - **jsonwebtoken**: JWT token generation and validation
617
+ - **reflect-metadata**: Enhanced reflection capabilities for decorators
618
+ - **zod-to-json-schema**: Improved OpenAPI schema generation
619
+
620
+ ## [0.1.7] - 2025-10-12
621
+
622
+ ### Fixed
623
+ - Fixed syntax error in CLI new command that prevented build from completing
624
+ - Fixed README generation in CLI templates
625
+
626
+ ## [0.1.6] - 2025-10-12
627
+
628
+ ### Added
629
+ - **Landing Page**: Created modern Astro-based website with interactive terminal and file explorer
630
+ - **Interactive Terminal**: Built terminal component for API testing with command history
631
+ - **File Explorer**: Developed code browser with hierarchical navigation for demo app
632
+ - **Documentation Files**: CLI now generates README.md and API_DOCUMENTATION.md in new projects
633
+
634
+ ### Changed
635
+ - **Complete Rebranding**: Renamed framework from FastAPI-TS to Veloce-TS throughout codebase
636
+ - **OpenAPIPlugin**: Now serves Swagger UI directly from code (no need for static HTML files)
637
+ - **Improved Swagger UI**: Updated to version 5.9.0 with better styling and functionality
638
+ - **Simplified Templates**: `veloce-ts new` command no longer generates unnecessary public files
639
+ - **Better Defaults**: OpenAPI documentation now uses "Veloce-TS" branding by default
640
+ - **Updated URLs**: All references now point to correct GitHub repository and documentation
641
+
642
+ ### Fixed
643
+ - Fixed Swagger UI rendering issues with proper script loading
644
+ - Fixed OpenAPI plugin to correctly serve HTML responses and return proper content types
645
+ - Fixed broken links and outdated branding throughout codebase
646
+ - Improved CORS handling in generated templates
647
+ - Fixed CLI template generation to include proper documentation structure
648
+
649
+ ## [0.1.5] - 2025-10-12
650
+
651
+ ### Fixed
652
+ - Fixed CLI templates to include OpenAPIPlugin automatically when docs: true
653
+ - REST and Fullstack templates now properly initialize OpenAPI documentation
654
+
655
+ ## [0.1.4] - 2025-10-13
656
+
657
+ ### Fixed
658
+ - Fixed CLI templates to call `await app.compile()` before `app.listen()`
659
+ - This fixes the 404 error on all routes in generated projects
660
+
661
+ ## [0.1.3] - 2025-10-12
662
+
663
+ ### Fixed
664
+ - Fixed package.json main and exports paths to point to correct dist/*/src/ directories
665
+ - This fixes the "Cannot find package" error when importing veloce-ts
666
+
667
+ ## [0.1.2] - 2025-10-12
668
+
669
+ ### Fixed
670
+ - Fixed CLI templates to use correct package name `veloce-ts` instead of `VeloceTS`
671
+ - Fixed all import statements in generated projects
672
+
673
+ ## [0.1.1] - 2025-10-12
674
+
675
+ ### Fixed
676
+ - Fixed CLI binary path to use compiled dist files instead of source files
677
+
678
+ ## [0.1.0] - 2025-10-12
679
+
680
+ ### Added
681
+ - Initial release of veloce-ts framework
682
+ - Decorator-based routing with @Controller, @Get, @Post, @Put, @Delete, @Patch
683
+ - Functional API for decorator-free routing
684
+ - Automatic request validation with Zod schemas
685
+ - Dependency injection system with singleton, request, and transient scopes
686
+ - Automatic OpenAPI documentation generation
687
+ - Response handling with JSONResponse, HTMLResponse, FileResponse, StreamResponse, RedirectResponse
688
+ - Plugin system for extensibility
689
+ - WebSocket support with decorators
690
+ - GraphQL support with decorators
691
+ - CLI tool for project scaffolding and development
692
+ - Middleware system with CORS, rate limiting, and compression
693
+ - Error handling with custom exceptions
694
+ - Testing utilities with TestClient
695
+ - Multi-runtime support (Bun, Node.js, Deno, Cloudflare Workers)
696
+ - Adapter system for Express and Hono
697
+ - Type safety with full TypeScript support
698
+ - Performance optimizations with metadata compilation and schema caching
699
+
700
+ ## [0.1.0] - 2025-10-12
701
+
702
+ ### Added
703
+ - Initial development version
704
+ - Core framework architecture
705
+ - Basic routing and validation
706
+ - Documentation generation
707
+ - Plugin system
708
+ - WebSocket and GraphQL support
709
+ - CLI tooling
710
+ - Testing utilities
711
+
712
+ [Unreleased]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.4.0...HEAD
713
+ [0.4.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.3...v0.4.0
714
+ [0.3.3]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.3
715
+ [0.3.2]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.3.2
716
+ [0.3.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.3.0...v0.3.1
717
+ [0.2.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.1...v0.2.2
718
+ [0.2.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.2.0...v0.2.1
719
+ [0.2.0]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.7...v0.2.0
720
+ [0.1.7]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.6...v0.1.7
721
+ [0.1.6]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.5...v0.1.6
722
+ [0.1.5]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.4...v0.1.5
723
+ [0.1.4]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.3...v0.1.4
724
+ [0.1.3]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.2...v0.1.3
725
+ [0.1.2]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.1...v0.1.2
726
+ [0.1.1]: https://github.com/AlfredoMejia3001/veloce-ts/compare/v0.1.0...v0.1.1
727
+ [0.1.0]: https://github.com/AlfredoMejia3001/veloce-ts/releases/tag/v0.1.0