veloce-ts 0.4.7 → 0.4.9

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