@macss/modular-api 0.7.1 → 0.7.2

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,895 @@
1
+ # Changelog
2
+
3
+ ## [0.7.2](https://github.com/ccisnedev/modular_api/compare/modular_api-v0.7.1...modular_api-v0.7.2) (2026-11-26)
4
+
5
+
6
+ ### Miscellaneous Chores
7
+
8
+ * **release:** release modular_api and modular_api_rest_client as 0.7.2 ([#55](https://github.com/ccisnedev/modular_api/issues/55)) ([77b357e](https://github.com/ccisnedev/modular_api/commit/77b357ef6ded03defda15e96ea34b2d7fa448778))
9
+
10
+ ## [0.7.1 and earlier] Before release-please
11
+
12
+ Until 0.7.1 each language kept its own changelog. They are reproduced below unchanged, one
13
+ subsection per language, with their headings moved down two levels. From 0.7.2 on,
14
+ this file is written by release-please and covers the three languages at once
15
+ ([ADR-0006](https://github.com/ccisnedev/modular_api/blob/main/docs/adr/0006-per-project-versioning-across-the-three-sdks.md)).
16
+
17
+ ### Dart (pub.dev)
18
+
19
+ #### [0.7.1] - 2026-09-13
20
+
21
+ - Version bump for cross-SDK parity (ADR-0002); no functional changes.
22
+
23
+ #### [0.7.0] - 2026-08-01
24
+
25
+ - **`trace_id` changes shape when tracing is configured.** Without `tracing` it stays a dashed UUID
26
+ v4, exactly as before; with `tracing` it becomes the 32-hex W3C trace id of the server span, which
27
+ is what a trace backend can join on. The change is **gated on adopting tracing** so that consumers
28
+ who do not ask for it are unaffected. Check any query, dashboard or alert that assumes the dashed
29
+ form — see [the observability guide](../../../docs/guides/observability.md#the-trace_id-shape-change)
30
+ - add distributed tracing: `tracing: TracingOptions(tracerProvider: ...)` on the `ModularApi`
31
+ constructor. Absent means no spans, no propagation and no cost — there is no `tracingEnabled`
32
+ boolean, so "off" cannot be misconfigured
33
+ - the framework **instruments**, the application **supplies the OTel SDK**. Core now declares the
34
+ OpenTelemetry **API** as a direct dependency and will never declare an SDK, exporter, gRPC or
35
+ protobuf; a test enforces that boundary. The API is no-op without an SDK, so tracing costs nothing
36
+ until you configure a provider (ADR-0005 amendment A1/A2)
37
+ - the server span is opened by the host **outside every plugin middleware slot**, and made ambient,
38
+ so a use case or satellite package reaches it with nothing threaded through any signature
39
+ - add `span_id` and `request_id` to log lines. `request_id` carries the client's `X-Request-ID`
40
+ verbatim and is **never** used as the trace id and never invented: a retried request reuses its
41
+ request id on purpose, so one request id can span several traces
42
+ - add a propagation chain, first-valid-wins: W3C `traceparent`/`tracestate`, then
43
+ `X-Cloud-Trace-Context` so a trace started by a Google load balancer is not orphaned.
44
+ `X-Cloud-Trace-Context` is **read** by default and **written** only when asked — the framework
45
+ emits open formats and nothing vendor-specific
46
+ - add `trustIncomingTraceContext` (default `true`); set it `false` at an internet-facing edge, where
47
+ a caller controlling `traceparent` controls which trace their request joins
48
+ - add `traceFieldFormatter`, the hook through which a platform correlation field such as
49
+ `logging.googleapis.com/trace` reaches log lines. No vendor field is emitted by default, because
50
+ the value needs a project id the framework does not know
51
+ - add `onShutdown`, invoked when the server closes. The framework owns the *timing*, the application
52
+ owns the resource — it never shuts down or flushes a provider it did not create. On a scale-to-zero
53
+ platform this is the only window a batching processor has to flush
54
+ - operational routes (health, docs, openapi, metrics) produce **no span**; the exclusion list is
55
+ derived from the same source as the routes rather than hardcoded
56
+ - **tracing is not a plugin and has no endpoint.** The span must sit outside every plugin middleware
57
+ slot, while a plugin registers *into* one by definition (ADR-0005 amendment A7)
58
+ - `duration_ms` is now slightly smaller than the server span, because tracing is the outermost layer
59
+ and logging sits inside it. Expected, not a regression
60
+ - **Dart only:** `OTel.initialize` takes a singular `spanProcessor`, and its default exporter speaks
61
+ gRPC. Targeting an OTLP/HTTP Collector means passing `OtlpHttpSpanExporter` explicitly
62
+
63
+ #### [0.6.1] - 2026-07-02
64
+
65
+ ##### Added
66
+
67
+ - **Web-safe DTO contract entry-point** — new `package:modular_api/dto.dart`
68
+ library exporting only the runtime-free contract surface (`Input`, `Output`,
69
+ `SchemaField`, `buildSchema`, `validateJsonFields`, `InputValidationException`,
70
+ `UseCaseException`). Import it from packages shared with web/desktop clients
71
+ (e.g. a Flutter app's DTO package) to define and validate DTOs without pulling
72
+ in the server runtime.
73
+
74
+ ##### Changed
75
+
76
+ - **Logger no longer imports `dart:io` directly** — the `ModularLogger`/`LogLevel`
77
+ contract moved to a pure `modular_logger.dart`, and `RequestScopedLogger`'s
78
+ default sink is resolved via a conditional import (`stdout` on `dart:io`
79
+ platforms, a `print`-based sink on web). Importing the full barrel — or the
80
+ `Input`/`Output` contract — no longer breaks web compilation.
81
+ - Corrected `modularApiPackageVersion` (was stale at `0.4.7`) to track the
82
+ package version.
83
+
84
+ #### [0.6.0] - 2026-06-13
85
+
86
+ ##### Changed
87
+
88
+ - version bump for coordinated ecosystem release (ADR-0002); no functional changes in this package
89
+
90
+ #### [0.5.0] - 2026-06-12
91
+
92
+ ##### Added
93
+
94
+ - **Plugin OpenAPI contributions (ADR-0003)** — `PluginRoute` gains an optional `openapi` field
95
+ (standard OpenAPI Operation object); the official OpenApiPlugin merges `custom`/`transport`
96
+ plugin routes into the generated spec, so plugin-served endpoints (e.g. binaries) appear in
97
+ `/openapi.json`, `/openapi.yaml`, and `/docs`.
98
+ - **`PluginHost.routes()`** — read view of registered plugin routes (pluginId, method, mounted
99
+ path, visibility, openapi operation).
100
+
101
+ ##### Changed
102
+
103
+ - **Metrics route labels cover plugin routes** — registered plugin route paths join
104
+ `registeredPaths`, so plugin routes report their real `route` label instead of `UNMATCHED`.
105
+
106
+ #### [0.4.8] - 2026-06-06
107
+
108
+ ##### Changed
109
+
110
+ - **Clean-room driver isolation** — the base package no longer declares concrete SQL Server or Postgres drivers, so REST-only and GraphQL-base consumers can install/import `modular_api` without external database drivers.
111
+ - **Public physical model kept in core** — `PhysicalCatalog`, `PhysicalObject`, `PhysicalField`, `PhysicalRelationSeed`, and `PhysicalObjectKind` remain exported from the base package as GraphQL-base contracts.
112
+
113
+ ##### Removed
114
+
115
+ - **SQL Server metadata reader ownership from core** — the concrete SQL Server metadata reader and connection settings moved out of `modular_api` and into `modular_api_sqlserver`, keeping driver ownership at the engine-package boundary.
116
+
117
+ #### [0.4.7] - 2026-06-01
118
+
119
+ ##### Changed
120
+
121
+ - **Plugin middleware guardrails** — request-completed logs now annotate attributable short-circuit metadata (`short_circuit_*`) when a plugin middleware terminates the pipeline before the core handler.
122
+ - **Host-owned error normalization** — uncaught plugin-pipeline exceptions now return a structured JSON `500` response instead of falling through to framework-default error handling.
123
+
124
+ #### [0.4.6] - 2026-04-24
125
+
126
+ ##### Changed
127
+
128
+ - **Version bump for cross-SDK parity** — aligns with TypeScript 0.4.6 re-release (see ADR-0002). No functional changes.
129
+
130
+ #### [0.4.5] - 2026-03-28
131
+
132
+ ##### Added
133
+
134
+ - **`servers` parameter** in `ModularApi` constructor — configures the OpenAPI `servers` field so Swagger UI "Try it out" targets the correct host (LAN IP, domain, reverse proxy URL). Defaults to `localhost:{port}` when omitted.
135
+ - **`corsMiddleware()`** — configurable CORS middleware replacing `exampleCorsMiddleware()`. Accepts `origin` (String or List), `methods`, and `allowedHeaders`. Aligned with TypeScript `cors()` and Python `cors_middleware()`.
136
+ - **`SchemaField.object()`** — factory constructor for nested JSON object fields (`type: 'object'`). Enables webhook payloads with arbitrary nested objects to be declared, validated, and documented in OpenAPI (issue #8).
137
+ - **`object` case in `_isJsonTypeValid`** — validates that a field declared as `object` receives a `Map` value; rejects strings, arrays, and other types.
138
+ - **`Map` case in `_inferOpenApiType`** — infers `'object'` for `Map` values in example-based schema generation.
139
+
140
+ ##### Fixed
141
+
142
+ - **`useCaseHttpHandler` catch blocks use scoped logger** — `UseCaseException` and unexpected errors are now logged through `req.context['modular.logger']` instead of `stderr.writeln`, enabling Loki correlation with `trace_id` (issue #7).
143
+
144
+ ##### Removed
145
+
146
+ - **`exampleCorsMiddleware()`** — replaced by the configurable `corsMiddleware()`
147
+
148
+ #### [0.4.4] - 2026-03-14
149
+
150
+ ##### Changed
151
+
152
+ - **Swagger UI replaced with `@macss/docs-ui`** — the ~200-line inline HTML/CSS/JS reduced to a ~15-line bootloader that loads `@macss/docs-ui@0.1` from jsdelivr CDN
153
+ - Dark mode now delegated to `docs-ui` package — single source of truth across all three SDKs
154
+
155
+ #### [0.4.3] - 2026-03-13
156
+
157
+ ##### Changed (BREAKING)
158
+
159
+ - **`execute()` returns `Future<O>`** — no longer `Future<void>`; the handler reads the returned Output directly
160
+ - **Removed `output` field** from `UseCase` — no mutable state; `execute()` returns the result
161
+ - **Removed `toJson()`** from `UseCase` — the handler calls `output.toJson()` on the returned value
162
+ - **`inputExample` / `outputExample` now required** in `ModuleBuilder.usecase()` — OpenAPI schema extraction uses them directly
163
+ - **Removed Strategy 2 fallback** in OpenAPI schema extraction — no `factory({}).output` path
164
+
165
+ ##### Removed
166
+
167
+ - **`@Field` annotation** — was decorative only (no runtime effect in Dart); `schemaFields` getter is the sole schema source
168
+
169
+ #### [0.4.2] - 2026-03-12
170
+
171
+ ##### Added
172
+
173
+ - **Auto-schema generation** — `Input` and `Output` DTOs derive OpenAPI 3.0.3 schemas automatically from `schemaFields` getter + `SchemaField` metadata
174
+ - `@Field` annotation — decorative per-field documentation (`@Field(description: 'x')`)
175
+ - `SchemaField` class — metadata with factories: `.string()`, `.integer()`, `.number()`, `.boolean()`, `.array()`
176
+ - `buildSchema()` utility — converts `List<SchemaField>` to OpenAPI 3.0.3-compatible `Map<String, dynamic>`
177
+ - `Input` / `Output` base classes gain generative constructors and default `toSchema()` from `schemaFields`
178
+ - Cross-language schema conformance tests against shared JSON fixtures
179
+
180
+ ##### Changed
181
+
182
+ - DTOs now use `extends Input` / `extends Output` instead of `implements` (for inherited `toSchema()` default)
183
+ - Manual `toSchema()` override is deprecated — use `schemaFields` getter instead (removal in v0.5.0)
184
+
185
+ #### [0.4.1] - 2026-03-12
186
+
187
+ ##### Changed
188
+
189
+ - Replaced `shelf_swagger_ui` with built-in Swagger UI served via CDN — zero external UI dependencies
190
+ - Built-in dark mode support for Swagger UI (system-aware via `prefers-color-scheme`)
191
+
192
+ ##### Added
193
+
194
+ - `SwaggerDocs` — internal handler serving the Swagger UI HTML page at `/docs`
195
+ - Cross-language parity with TypeScript and Python implementations
196
+
197
+ #### [0.4.0] - 2026-03-03
198
+
199
+ ##### Removed
200
+
201
+ - **BREAKING:** `useCaseTestHandler` — removed from public API and deleted `lib/src/core/usecase/usecase_test_handler.dart`
202
+ - Testing now uses direct constructor injection: instantiate the UseCase with its Input, call `validate()`, `execute()`, and assert on `output` directly
203
+ - Barrel export removed from `lib/modular_api.dart`
204
+
205
+ ##### Added
206
+
207
+ - **`GET /openapi.json`** — returns the full OpenAPI 3.0 specification as `application/json`
208
+ - **`GET /openapi.yaml`** — returns the full OpenAPI 3.0 specification as `application/x-yaml`
209
+ - `OpenApi.openapiJson` / `OpenApi.openapiYaml` — Shelf handlers for raw spec access
210
+ - `OpenApi.jsonToYaml()` — zero-dependency JSON-to-YAML converter
211
+ - Spec is cached at startup alongside Swagger UI (no per-request rebuild)
212
+ - 18 new tests: jsonToYaml unit (8), /openapi.json integration (4), /openapi.yaml integration (5), consistency (1)
213
+
214
+ ##### Changed
215
+
216
+ - Updated testing guide (`doc/testing_guide.md`) to document the constructor-injection approach
217
+ - Updated `doc/usecase_implementation.md` and `doc/logger_guide.md` to remove `useCaseTestHandler` references
218
+ - Updated `AGENTS.md` and `README.md` examples to reflect the new testing pattern
219
+
220
+ #### [0.3.0] - 2026-02-26
221
+ ##### Added
222
+ - **Structured JSON Logger** — request-scoped logging compatible with Loki, Grafana, Elasticsearch, and any JSON log aggregator
223
+ - `LogLevel` enum — 8 RFC 5424 severity levels (emergency..debug) with configurable filtering
224
+ - `ModularLogger` interface — 8 logging methods (one per level) with optional structured `fields`
225
+ - `RequestScopedLogger` — implementation with injectable `StringSink` for testability
226
+ - `loggingMiddleware()` — Shelf middleware that creates a per-request logger with unique `trace_id`
227
+ - `trace_id` auto-generated (UUID v4, zero dependencies) or propagated from `X-Request-ID` header
228
+ - `X-Request-ID` response header set on every response for client-side correlation
229
+ - Logger injected as `UseCase.logger` property — zero breaking change to `execute()` signature
230
+ - Automatic status-to-level mapping: 2xx→info, 4xx→warning, 5xx→error
231
+ - Excluded routes: `/health`, `/metrics`, `/docs`, `/docs/` (no request/response logs)
232
+ - `logLevel` parameter on `ModularApi` constructor (default: `LogLevel.info`)
233
+ - `useCaseTestHandler` now accepts optional `logger` parameter for test observability
234
+ - `generateUuidV4()` — manual UUID v4 using `dart:math Random.secure()` (no external deps)
235
+ - Barrel exports: `LogLevel`, `ModularLogger` from `package:modular_api/modular_api.dart`
236
+ - 68 new tests: logger (27), uuid (6), middleware (23), integration (12)
237
+ - Documentation: `doc/logger_guide.md`
238
+
239
+ #### [0.2.0] - 2026-02-24
240
+ ##### Added
241
+ - **IETF Health Check Response Format** — `GET /health` now returns `application/health+json` following [draft-inadarei-api-health-check](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check)
242
+ - `HealthCheck` abstract class — implement to register custom health checks (database, cache, queue, etc.)
243
+ - `HealthCheckResult` — result DTO with `status`, `responseTime` (ms), and optional `output`
244
+ - `HealthStatus` enum — `pass`, `warn`, `fail` with worst-status-wins aggregation
245
+ - `HealthService` — executes checks in parallel with per-check configurable timeout (default: 5s)
246
+ - `HealthResponse` — aggregated response with `version`, `releaseId`, `checks` map, and `httpStatusCode` (200 for pass/warn, 503 for fail)
247
+ - `healthHandler()` — Shelf handler for `GET /health`
248
+ - `ModularApi.addHealthCheck()` — register health checks via method chaining
249
+ - `ModularApi` constructor now accepts `version` and optional `releaseId` parameters
250
+ - `releaseId` defaults to `version-debug`; override at compile time with `--define=RELEASE_ID=x.y.z`
251
+ - **Prometheus Metrics Endpoint** — opt-in `GET /metrics` in [Prometheus text exposition format](https://prometheus.io/docs/instrumenting/exposition_formats/)
252
+ - `Counter`, `Gauge`, `Histogram` — pure Dart metric types (zero runtime dependencies)
253
+ - `MetricsRegistrar` — public API for registering custom metrics via `api.metrics`
254
+ - `metricsEnabled`, `metricsPath`, `excludedMetricsRoutes` constructor parameters
255
+ - Built-in HTTP instrumentation: `http_requests_total`, `http_request_duration_seconds`, `http_requests_in_flight`, `process_start_time_seconds`
256
+
257
+ ##### Changed
258
+ - **BREAKING:** `GET /health` response changed from plaintext `ok` to JSON `application/health+json`
259
+ - **BREAKING:** `ModularApi` constructor signature changed — added `version` parameter (defaults to `'0.0.0'`)
260
+
261
+ #### [0.1.0] - 2026-02-21
262
+ ##### Changed
263
+ - **BREAKING:** Stripped to core-only — aligned Dart and TypeScript SDKs at feature parity
264
+ - Version bump from 0.0.10 to 0.1.0 (semver: new public API surface)
265
+ - `ModularApi` constructor no longer accepts `oauthService` parameter
266
+ - `ModuleBuilder.usecase()` no longer accepts `requiredScopes` parameter
267
+ - Reduced dependencies from 14 to 3 (`shelf`, `shelf_router`, `shelf_swagger_ui`)
268
+ - Simplified `doc/INDEX.md` to core-only development flow
269
+ - Example no longer uses `Env` — hardcoded port for simplicity
270
+
271
+ ##### Removed
272
+ - `lib/src/auth/` — `JwtHelper`, `OAuthService`, `OAuthClient`, `PasswordHasher`, `TokenHasher`, all OAuth2 types
273
+ - `lib/src/core/oauth_handler.dart` — `createOAuthTokenHandler`
274
+ - `lib/src/middlewares/apikey.dart` — `exampleApiKeyMiddleware`
275
+ - `lib/src/middlewares/bearer.dart` — `bearer()`, `requireAuth()`
276
+ - `lib/src/utils/env.dart` — `Env` utility
277
+ - `lib/src/utils/get_local_ip.dart` — `getLocalIp`
278
+ - Dependencies: `http`, `ffi`, `dotenv`, `path`, `cryptography`, `bcrypt`, `dart_jsonwebtoken`, `crypto`, `ffigen`
279
+ - Documentation: `auth_implementation_guide.md`, `authentication_guide.md`, `http_client_guide.md`
280
+
281
+ ##### Kept (Core)
282
+ - `UseCase<I, O>`, `Input`, `Output` — abstract base classes
283
+ - `UseCaseException` — structured error handling
284
+ - `ModularApi`, `ModuleBuilder` — routing and module registration
285
+ - `useCaseHttpHandler` — Shelf HTTP adapter
286
+ - `useCaseTestHandler` — unit test helper
287
+ - `exampleCorsMiddleware` — CORS middleware
288
+ - `OpenApi` — automatic Swagger/OpenAPI docs at `/docs`
289
+ - `GET /health` — health check endpoint
290
+
291
+ #### [0.0.10] - 2025-12-23
292
+ ##### Added
293
+ - **`UseCaseException`** — Dedicated exception for use case execution errors:
294
+ - `statusCode` — HTTP status code to return (400, 404, 422, 500, etc.)
295
+ - `message` — Human-readable error message
296
+ - `errorCode` — Optional error code for client-side handling
297
+ - `details` — Optional additional details (validation errors, context)
298
+ - Automatically caught by `useCaseHttpHandler` and converted to appropriate HTTP responses
299
+ - Allows fine-grained control over error responses instead of generic 500 errors
300
+
301
+ ##### Changed
302
+ - Updated `useCaseHttpHandler` to catch `UseCaseException` and return the specified status code
303
+ - Enhanced error handling with structured error responses
304
+
305
+ #### [0.0.9] - 2025-12-15
306
+ ##### Added
307
+ - **OAuth2 Client Credentials Support** — full OAuth2 implementation:
308
+ - `OAuthService` — manages client authentication and JWT token generation
309
+ - `OAuthClient` — represents registered clients with credentials and scopes
310
+ - `TokenRequest`, `TokenResponse`, `TokenErrorResponse` — OAuth2 data structures
311
+ - `AccessToken` — decoded JWT with scope validation methods
312
+ - `createOAuthTokenHandler` — POST /oauth/token endpoint handler
313
+ - `bearer()` middleware — validates Bearer tokens and enforces scopes
314
+ - `requireAuth()` middleware — marks routes as requiring authentication
315
+ - HS256 (HMAC-SHA256) JWT signing algorithm
316
+ - Scope-based authorization for protected endpoints
317
+ - Follows RFC 6749 OAuth2 specification
318
+
319
+ ##### Changed
320
+ - Exported auth utilities: `JwtHelper`, `hashPassword`, `verifyPassword`, `hashToken`
321
+ - Updated exports to include OAuth2 types and services
322
+
323
+ ##### Removed
324
+ - **Removed `template/` folder** — Simplified project structure by removing the full example template
325
+ - Template project has been removed to reduce repository complexity
326
+ - Only the minimal `example/` folder remains for quick reference
327
+ - Previous template code included extensive examples, tests, and infrastructure that were redundant
328
+
329
+ ##### Documentation
330
+ - Added comprehensive OAuth2 guides and examples
331
+ - Updated AGENTS.md with OAuth2 usage patterns
332
+ - Updated all documentation to remove references to `template/` folder
333
+ - Simplified examples to focus on the minimal `example/` implementation
334
+ - Cleaned up README.md, AGENTS.md, and guides to reflect simplified structure
335
+
336
+ #### [0.0.8] - 2025-12-04
337
+ ##### Added
338
+ - **Output.statusCode** — customizable HTTP status code for UseCase responses:
339
+ - `Output` abstract class now includes `int get statusCode => 200;` getter
340
+ - Override in your Output DTO to return custom HTTP status codes (e.g., 201 for created, 400 for bad request)
341
+ - `useCaseHttpHandler` uses `output.statusCode` instead of hardcoded 200
342
+ - Enables proper RESTful responses without modifying the HTTP handler
343
+
344
+ ##### Changed
345
+ - **Output DTOs** now use `extends Output` instead of `implements Output` to inherit the default `statusCode` getter
346
+ - Example and template Output classes updated to extend Output
347
+
348
+ ##### Migration Guide
349
+ If you have existing Output DTOs using `implements Output`, change them to `extends Output`:
350
+ ```dart
351
+ // Before
352
+ class MyOutput implements Output { ... }
353
+
354
+ // After
355
+ class MyOutput extends Output { ... }
356
+ ```
357
+ Alternatively, add the statusCode getter manually: `@override int get statusCode => 200;`
358
+
359
+ #### [0.0.7] - 2025-11-04
360
+ ##### Added
361
+ - **httpClient** — intelligent HTTP client with automatic authentication:
362
+ - Automatic token attachment for authenticated requests (`auth: true`)
363
+ - Auto-capture of access and refresh tokens from login responses
364
+ - Transparent retry with refresh token on 401 responses
365
+ - Throws `AuthReLoginException` when refresh fails (signals re-login required)
366
+ - Per-user token management via `user` parameter
367
+ - **Token** (in-memory session) — static class for managing access tokens:
368
+ - `Token.accessToken` — current access token
369
+ - `Token.accessExp` — access token expiration timestamp
370
+ - `Token.isAuthenticated` — check if user has valid token
371
+ - `Token.isExpired` — check if current token is expired
372
+ - `Token.clear()` — clear session
373
+ - **TokenVault** (persistent storage) — configurable adapter for refresh tokens:
374
+ - `TokenVault.saveRefresh(userId, token)` — persist refresh token
375
+ - `TokenVault.readRefresh(userId)` — retrieve refresh token
376
+ - `TokenVault.deleteRefresh(userId)` — delete specific refresh token
377
+ - `TokenVault.deleteAll()` — clear all tokens
378
+ - `TokenVault.configure(adapter)` — set storage adapter
379
+ - Includes `MemoryStorageAdapter` (default) and `FileStorageAdapter` with optional encryption
380
+ - **JwtHelper** — JWT generation and validation utilities:
381
+ - `generateAccessToken({userId, username})` — create access tokens (15 min)
382
+ - `generateRefreshToken({userId, tokenId})` — create refresh tokens (7 days)
383
+ - `verifyToken(token)` — validate and decode JWT
384
+ - `calculateRefreshTokenExpiration()` — get refresh token expiry date
385
+ - Reads secret from `JWT_SECRET` environment variable
386
+ - **PasswordHasher** — bcrypt password hashing:
387
+ - `hash(password, {cost = 12})` — generate bcrypt hash
388
+ - `verify(password, hash)` — verify password against hash
389
+ - `needsRehash(hash, {cost})` — check if hash needs update
390
+ - **TokenHasher** — SHA-256 token hashing for secure storage:
391
+ - `hash(token)` — generate SHA-256 hash (64 hex chars)
392
+ - `verify(token, expectedHash)` — verify token against hash
393
+ - **AuthReLoginException** — specialized exception for auth flow control
394
+ - Comprehensive authentication documentation:
395
+ - **docs/auth_implementation_guide.md** — Complete JWT authentication implementation guide with refresh tokens, including database setup, repository patterns, use cases, and client integration (Flutter & Dart)
396
+ - **docs/http_client_guide.md** — Focused guide for using httpClient in Flutter and pure Dart applications with configuration examples and best practices
397
+ - Complete E2E authentication test suite:
398
+ - `template/test/e2e/auth_flow_test.dart` — 25+ comprehensive tests covering login, refresh, logout, protected endpoints, concurrent requests, auto-refresh behavior, and re-login exception handling
399
+
400
+ ##### Changed
401
+ - All documentation translated to English for consistency
402
+
403
+ #### [0.0.6] - 2025-10-30
404
+ ##### Added
405
+ - Exported `useCaseTestHandler` in main library export (`lib/modular_api.dart`) for convenient unit testing of UseCases without starting an HTTP server.
406
+ - Comprehensive documentation guides:
407
+ - **AGENTS.md** — Framework overview and implementation guide optimized for AI assistants
408
+ - **docs/USECASE_DTO_GUIDE.md** — Complete guide for creating Input/Output DTOs with type mapping reference and advanced examples
409
+ - **docs/usecase_implementation.md** — Step-by-step guide for implementing UseCases with validation, database access, and repository patterns
410
+ - **docs/TESTING_GUIDE.md** — Quick reference for testing UseCases using `useCaseTestHandler`
411
+ - Complete test suite for template project:
412
+ - `template/test/module1/hello_world_test.dart` — 5 tests for HelloWorld use case
413
+ - `template/test/module2/sum_case_test.dart` — 7 tests for SumCase use case
414
+ - `template/test/module2/upper_case_test.dart` — 7 tests for UpperCase use case
415
+ - `template/test/module3/lower_case_test.dart` — 7 tests for LowerCase use case
416
+ - `template/test/module3/multiply_case_test.dart` — 9 tests for MultiplyCase use case
417
+ - All 35 tests demonstrate proper usage of `useCaseTestHandler` with success and failure scenarios
418
+
419
+ #### [0.0.5] - 2025-10-25
420
+ ##### Changed
421
+ - `Env` now initializes automatically on first access (lazy singleton pattern). No need to call `Env.init()` explicitly, though it remains available for manual initialization if needed.
422
+ - .usecase() now trims leading slashes from usecase names to prevent double slashes in registered paths.
423
+
424
+ #### [0.0.4] - 2025-10-23
425
+ ##### Changed
426
+ - `Env` behavior: when a `.env` file is not found the library reads values from `Platform.environment`. If a requested key is missing from both sources an `EnvKeyNotFoundException` is thrown.
427
+
428
+ #### [0.0.3] - 2025-10-23
429
+ ##### Added
430
+ - Automatic health endpoint: the server registers `GET /health` which responds with `ok` on startup. Implemented in `modular_api.dart` (exposes `_root.get('/health', (Request request) => Response.ok('ok'));`).
431
+
432
+ #### [0.0.2] - 2025-10-21
433
+ ##### Changed
434
+ - refactor: improve OpenAPI initialization (now initialized automatically internally)
435
+ - Rename middlewares as examples
436
+ - rename example project to template
437
+ - Add a simple example
438
+
439
+ #### [0.0.1] - 2025-10-21
440
+ ##### Added
441
+ - Initial release of **modular_api**. Main features:
442
+ - Use-case centric framework with `UseCase<I extends Input, O extends Output>` base classes and DTO helpers (`Input`/`Output`).
443
+ - HTTP adapter `useCaseHttpHandler()` to expose UseCases as Shelf `Handler`s.
444
+ - Built-in middlewares: `cors()` and `apiKey()` for CORS handling and header-based API key authentication.
445
+ - OpenAPI/Swagger generation helpers (`OpenApi.init`, `OpenApi.docs`) that infer schemas from DTO `toSchema()`.
446
+ - Utilities: `Env.getString`, `Env.getInt`, `Env.setString` (.env support via dotenv) and `getLocalIp`.
447
+ - Minimal ODBC `DbClient` (DSN-based) exported for database access; example factories and usage provided in `example/` (tested with Oracle and SQL Server; see `NOTICE` for provenance).
448
+ - Example project demonstrating modules and usecases under `example/` and unit-test helpers (`useCaseTestHandler`) under `test/`.
449
+ - Public API exports in `lib/modular_api.dart` for easy consumption.
450
+
451
+ ### TypeScript (npm)
452
+
453
+ #### [0.7.1] - 2026-09-13
454
+
455
+ ##### Fixed
456
+
457
+ - Allow configuring the JSON body size limit through `ModularApiOptions.jsonBodyLimit`
458
+ (size string or number of bytes), applied per instance by `serve()`. The default
459
+ remains `'100kb'` (102,400 bytes); oversized bodies keep the existing error response.
460
+
461
+ #### [0.7.0] - 2026-08-01
462
+
463
+ - **`trace_id` changes shape when tracing is configured.** Without `tracing` it stays a dashed UUID
464
+ v4, exactly as before; with `tracing` it becomes the 32-hex W3C trace id of the server span, which
465
+ is what a trace backend can join on. The change is **gated on adopting tracing** so that consumers
466
+ who do not ask for it are unaffected. Check any query, dashboard or alert that assumes the dashed
467
+ form — see [the observability guide](../../../docs/guides/observability.md#the-trace_id-shape-change)
468
+ - add distributed tracing: `tracing: TracingOptions(tracerProvider: ...)` on the `ModularApi`
469
+ constructor. Absent means no spans, no propagation and no cost — there is no `tracingEnabled`
470
+ boolean, so "off" cannot be misconfigured
471
+ - the framework **instruments**, the application **supplies the OTel SDK**. Core now declares the
472
+ OpenTelemetry **API** as a direct dependency and will never declare an SDK, exporter, gRPC or
473
+ protobuf; a test enforces that boundary. The API is no-op without an SDK, so tracing costs nothing
474
+ until you configure a provider (ADR-0005 amendment A1/A2)
475
+ - the server span is opened by the host **outside every plugin middleware slot**, and made ambient,
476
+ so a use case or satellite package reaches it with nothing threaded through any signature
477
+ - add `span_id` and `request_id` to log lines. `request_id` carries the client's `X-Request-ID`
478
+ verbatim and is **never** used as the trace id and never invented: a retried request reuses its
479
+ request id on purpose, so one request id can span several traces
480
+ - add a propagation chain, first-valid-wins: W3C `traceparent`/`tracestate`, then
481
+ `X-Cloud-Trace-Context` so a trace started by a Google load balancer is not orphaned.
482
+ `X-Cloud-Trace-Context` is **read** by default and **written** only when asked — the framework
483
+ emits open formats and nothing vendor-specific
484
+ - add `trustIncomingTraceContext` (default `true`); set it `false` at an internet-facing edge, where
485
+ a caller controlling `traceparent` controls which trace their request joins
486
+ - add `traceFieldFormatter`, the hook through which a platform correlation field such as
487
+ `logging.googleapis.com/trace` reaches log lines. No vendor field is emitted by default, because
488
+ the value needs a project id the framework does not know
489
+ - add `onShutdown`, invoked when the server closes. The framework owns the *timing*, the application
490
+ owns the resource — it never shuts down or flushes a provider it did not create. On a scale-to-zero
491
+ platform this is the only window a batching processor has to flush
492
+ - operational routes (health, docs, openapi, metrics) produce **no span**; the exclusion list is
493
+ derived from the same source as the routes rather than hardcoded
494
+ - **tracing is not a plugin and has no endpoint.** The span must sit outside every plugin middleware
495
+ slot, while a plugin registers *into* one by definition (ADR-0005 amendment A7)
496
+ - `duration_ms` is now slightly smaller than the server span, because tracing is the outermost layer
497
+ and logging sits inside it. Expected, not a regression
498
+ - **TypeScript only:** call `provider.register()` when configuring the SDK. Without a registered
499
+ context manager `context.with` does not propagate and every child span silently becomes a root —
500
+ you get spans, they just are not a trace
501
+
502
+ #### [0.6.1] - 2026-07-02
503
+
504
+ ##### Added
505
+
506
+ - **Web-safe DTO contract entry-point** — new `@macss/modular-api/dto` subpath
507
+ export exposing only the runtime-free contract surface (`Input`, `Output`,
508
+ `Field`, `getFieldMetadata`, `UseCaseException`, `InputValidationError`).
509
+ Import it from packages shared with browser/front-end code to define and
510
+ validate DTOs without pulling in the Express server runtime. The `usecase`
511
+ module already imports the logger as a type-only import, so this surface is
512
+ Node-global-free at runtime.
513
+
514
+ ##### Changed
515
+
516
+ - `package.json` now declares an `exports` map (`.` for the full barrel, `./dto`
517
+ for the contract). The full barrel remains server-only.
518
+
519
+ #### [0.6.0] - 2026-06-13
520
+
521
+ ##### Changed
522
+
523
+ - version bump for coordinated ecosystem release (ADR-0002); no functional changes in this package
524
+
525
+ #### [0.5.0] - 2026-06-12
526
+
527
+ ##### Added
528
+
529
+ - **Plugin OpenAPI contributions (ADR-0003)** — `PluginRoute` gains an optional `openapi` field
530
+ (standard OpenAPI Operation object); the official OpenApiPlugin merges `custom`/`transport`
531
+ plugin routes into the generated spec, so plugin-served endpoints (e.g. binaries) appear in
532
+ `/openapi.json`, `/openapi.yaml`, and `/docs`.
533
+ - **`PluginHost.routes()`** — read view of registered plugin routes (pluginId, method, mounted
534
+ path, visibility, openapi operation).
535
+
536
+ ##### Changed
537
+
538
+ - **Metrics route labels cover plugin routes** — registered plugin route paths join
539
+ `registeredPaths`, so plugin routes report their real `route` label instead of `UNMATCHED`.
540
+
541
+ #### [0.4.8] - 2026-06-06
542
+
543
+ ##### Changed
544
+
545
+ - **Clean-room driver isolation** — the base package no longer declares `mssql` or `pg` in its manifest, so `@macss/modular-api` installs cleanly without concrete database drivers.
546
+ - **Optional SQL Server introspection** — SQL Server metadata support now relies on lazy driver loading and explains how to install `mssql` only when that engine-specific feature is used.
547
+
548
+ #### [0.4.7] - 2026-06-01
549
+
550
+ ##### Changed
551
+
552
+ - **Plugin middleware guardrails** — request-completed logs now annotate attributable short-circuit metadata (`short_circuit_*`) when a plugin middleware terminates the pipeline before the core handler.
553
+ - **Host-owned error normalization** — uncaught plugin-pipeline exceptions now return a structured JSON `500` response instead of falling through to framework-default error pages.
554
+
555
+ #### [0.4.6] - 2026-04-24
556
+
557
+ ##### Fixed
558
+
559
+ - **Re-release** — v0.4.5 npm package was published with a stale `dist/` that did not include `Field.object()` or body-parser error handler changes. All v0.4.5 changelog features are now correctly included in the published build.
560
+
561
+ ##### Changed
562
+
563
+ - **`prepublishOnly` script** — `npm run build` now runs automatically before `npm publish`, preventing stale build artifacts from being published (see ADR-0002).
564
+
565
+ #### [0.4.5] - 2026-03-28
566
+
567
+ ##### Added
568
+
569
+ - **`servers` option** in `ModularApiOptions` — configures the OpenAPI `servers` field so Swagger UI "Try it out" targets the correct host (LAN IP, domain, reverse proxy URL). Defaults to `localhost:{port}` when omitted.
570
+ - **`bodyParserErrorHandler`** — Express error middleware that catches body-parser `SyntaxError` and returns 400 with structured JSON.
571
+ - **`Field.object()`** — decorator for nested JSON object fields (`type: 'object'`). Enables webhook payloads with arbitrary nested objects to be declared, validated, and documented in OpenAPI (issue #8).
572
+ - **`object` case in `isJsonTypeValid`** — validates that a field declared as `object` receives a plain object; rejects strings, arrays, and null.
573
+
574
+ ##### Fixed
575
+
576
+ - **body-parser SyntaxError now carries `trace_id`** — moved `express.json()` after `loggingMiddleware` in the middleware chain so malformed-body errors are logged as structured JSON with `trace_id` (issue #7).
577
+ - **`useCaseHandler` catch blocks use scoped logger** — `UseCaseException` and unexpected errors are now logged through `res.locals['modularLogger']` instead of `console.error`, enabling Loki correlation.
578
+
579
+ #### [0.4.4] - 2026-03-14
580
+
581
+ ##### Changed
582
+
583
+ - **Swagger UI replaced with `@macss/docs-ui`** — the ~200-line inline HTML/CSS/JS reduced to a ~15-line bootloader that loads `@macss/docs-ui@0.1` from jsdelivr CDN
584
+ - Dark mode now delegated to `docs-ui` package — single source of truth across all three SDKs
585
+
586
+ #### [0.4.3] - 2026-03-13
587
+
588
+ ##### Changed (BREAKING)
589
+
590
+ - **`execute()` returns `Promise<O>`** — no longer `Promise<void>`; the handler reads the returned Output directly
591
+ - **Removed `output` field** from `UseCase` — no mutable state; `execute()` returns the result
592
+ - **Removed `toJson()`** from `UseCase` — the handler calls `output.toJson()` on the returned value
593
+ - **`inputClass` / `outputClass` now required** in `UseCaseOptions` — OpenAPI schema extraction uses them directly
594
+ - **Removed Strategy 2 fallback** in OpenAPI schema extraction — no `factory({}).output` path
595
+
596
+ #### [0.4.2] - 2026-03-12
597
+
598
+ ##### Added
599
+
600
+ - **Auto-schema generation** — `Input` and `Output` DTOs derive OpenAPI 3.0.3 schemas automatically from `@Field` decorator metadata
601
+ - `@Field` decorators — Stage 3 decorators: `.string()`, `.integer()`, `.number()`, `.boolean()`, `.array()`, `.optional()`
602
+ - `Symbol.metadata` polyfill for Node.js < 22 compatibility
603
+ - `getFieldMetadata()` / `FieldMeta` / `FieldOptions` — public API for reading decorator metadata
604
+ - `Input` / `Output` base classes provide concrete `toSchema()`, `toJson()`, `fromJson()` from decorator metadata
605
+ - Cross-language schema conformance tests against shared JSON fixtures
606
+
607
+ ##### Changed
608
+
609
+ - TypeScript target changed from `ES2020` to `ES2022` for Stage 3 decorator support
610
+ - Manual `toSchema()` override is deprecated — use `@Field` decorators instead (removal in v0.5.0)
611
+ - `_extractSchemas` simplified — decorator metadata resolves schemas without manual methods
612
+
613
+ #### [0.4.1] - 2026-03-12
614
+
615
+ ##### Removed
616
+
617
+ - **`prom-client`** — removed external dependency; all Prometheus metrics are now pure TypeScript
618
+ - Zero runtime dependencies besides `express`
619
+
620
+ ##### Added
621
+
622
+ - `Counter`, `Gauge`, `Histogram` — pure TypeScript metric types with Prometheus text exposition format
623
+ - `DEFAULT_BUCKETS`, `MetricSample` — public exports for custom metric usage
624
+ - `SwaggerDocs` — replaced `swagger-ui-express` with built-in Swagger UI served via CDN
625
+ - Built-in dark mode support for Swagger UI (system-aware via `prefers-color-scheme`)
626
+ - Cross-language parity with Dart and Python implementations
627
+
628
+ #### [0.4.0] - 2026-03-03
629
+
630
+ ##### Removed
631
+
632
+ - **BREAKING:** `useCaseTestHandler` — removed from public API and deleted `src/core/usecase_test_handler.ts`
633
+ - Testing now uses direct constructor injection: instantiate the UseCase with its Input, call `validate()`, `execute()`, and assert on `output` directly
634
+ - Barrel exports removed from `src/index.ts` (`useCaseTestHandler`, `TestResponse`)
635
+
636
+ ##### Added
637
+
638
+ - **`GET /openapi.json`** — returns the full OpenAPI 3.0 specification as `application/json`
639
+ - **`GET /openapi.yaml`** — returns the full OpenAPI 3.0 specification as `application/x-yaml`
640
+ - `openApiJsonHandler()` / `openApiYamlHandler()` — Express handlers for raw spec access
641
+ - `jsonToYaml()` — zero-dependency JSON-to-YAML converter
642
+ - Spec is cached at startup alongside Swagger UI (no per-request rebuild)
643
+ - Barrel exports: `buildOpenApiSpec`, `jsonToYaml`, `openApiJsonHandler`, `openApiYamlHandler`
644
+ - 18 new tests: jsonToYaml unit (8), /openapi.json integration (4), /openapi.yaml integration (5), consistency (1)
645
+
646
+ ##### Changed
647
+
648
+ - Added comprehensive testing guide (`doc/testing_guide.md`) documenting the constructor-injection approach
649
+ - Updated `README.md` examples to reflect the new testing pattern
650
+
651
+ #### [0.3.0] - 2026-02-26
652
+
653
+ ##### Added
654
+
655
+ - **Structured JSON Logger** — request-scoped logging compatible with Loki, Grafana, Elasticsearch, and any JSON log aggregator
656
+ - `LogLevel` enum — 8 RFC 5424 severity levels (emergency..debug) with configurable filtering
657
+ - `ModularLogger` interface — 8 logging methods (one per level) with optional structured `fields` and `traceId` property
658
+ - `RequestScopedLogger` — implementation with injectable `writeFn` for testability
659
+ - `loggingMiddleware()` — Express middleware that creates a per-request logger with unique `trace_id`
660
+ - `trace_id` auto-generated (UUID v4 via `crypto.randomUUID()`) or propagated from `X-Request-ID` header
661
+ - `X-Request-ID` response header set on every response for client-side correlation
662
+ - Logger injected as `UseCase.logger` property — zero breaking change to `execute()` signature
663
+ - Automatic status-to-level mapping: 2xx→info, 4xx→warning, 5xx→error
664
+ - Excluded routes: `/health`, `/metrics`, `/docs`, `/docs/` (no request/response logs)
665
+ - `logLevel` option on `ModularApiOptions` (default: `LogLevel.info`)
666
+ - `useCaseTestHandler` now accepts optional `{ logger }` options parameter
667
+ - Barrel exports: `LogLevel`, `RequestScopedLogger`, `ModularLogger`, `loggingMiddleware`, `LOGGER_LOCALS_KEY`, `LoggingMiddlewareOptions`
668
+ - 51 new tests: logger (26), middleware (19), integration (6)
669
+ - Documentation: `doc/logger_guide.md`
670
+
671
+ #### [0.2.0] - 2026-02-24
672
+
673
+ ##### Added
674
+
675
+ - **IETF Health Check Response Format** — `GET /health` now returns `application/health+json` following [draft-inadarei-api-health-check](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check)
676
+ - `HealthCheck` abstract class — implement to register custom health checks (database, cache, queue, etc.)
677
+ - `HealthCheckResult` — result DTO with `status`, `responseTime` (ms), and optional `output`
678
+ - `HealthStatus` type — `'pass' | 'warn' | 'fail'` with worst-status-wins aggregation
679
+ - `HealthService` — executes checks in parallel with per-check configurable timeout (default: 5s)
680
+ - `HealthResponse` — aggregated response with `version`, `releaseId`, `checks` map, and `httpStatusCode` (200 for pass/warn, 503 for fail)
681
+ - `healthHandler()` — Express handler for `GET /health`
682
+ - `ModularApi.addHealthCheck()` — register health checks via method chaining
683
+ - `ModularApiOptions` now accepts `version` and optional `releaseId`
684
+ - `releaseId` defaults to `version-debug`; override via `process.env.RELEASE_ID`
685
+ - **Prometheus Metrics Endpoint** — opt-in `GET /metrics` in [Prometheus text exposition format](https://prometheus.io/docs/instrumenting/exposition_formats/)
686
+ - `MetricsRegistrar` — public API for registering custom metrics via `api.metrics`
687
+ - `metricsEnabled`, `metricsPath`, `excludedMetricsRoutes` constructor options
688
+ - Built-in HTTP instrumentation: `http_requests_total`, `http_request_duration_seconds`, `http_requests_in_flight`, `process_start_time_seconds`
689
+ - `prom-client` dependency for Prometheus metric types
690
+ - Test infrastructure: vitest + supertest
691
+
692
+ ##### Changed
693
+
694
+ - **BREAKING:** `GET /health` response changed from plaintext `ok` to JSON `application/health+json`
695
+ - **BREAKING:** `ModularApiOptions` extended — `version` parameter added (defaults to `'0.0.0'`)
696
+
697
+ #### [0.1.0] - 2026-02-21
698
+
699
+ ##### Added
700
+
701
+ - **Initial release** — TypeScript port of [modular_api](https://pub.dev/packages/modular_api) (Dart)
702
+ - `UseCase<I, O>`, `Input`, `Output` — abstract base classes for use-case centric architecture
703
+ - `UseCaseFactory<I, O>` — type alias for static `fromJson` factories
704
+ - `UseCaseException` — structured error handling with `statusCode`, `message`, `errorCode`, `details`
705
+ - `ModularApi` — main orchestrator: module registration, middleware pipeline, Express server
706
+ - `ModuleBuilder` — fluent builder to register use cases as HTTP endpoints
707
+ - `useCaseHandler` — wraps any `UseCaseFactory` into an Express `RequestHandler`
708
+ - `useCaseTestHandler` — unit test helper (no HTTP server required)
709
+ - `cors()` middleware — configurable CORS with zero dependencies
710
+ - Automatic OpenAPI 3.0 spec generation from registered use cases
711
+ - Swagger UI auto-mounted at `GET /docs`
712
+ - Health check at `GET /health`
713
+ - All endpoints default to `POST` (configurable per use case)
714
+ - Schema introspection via `Input.toSchema()` / `Output.toSchema()`
715
+ - Custom HTTP status codes via `Output.statusCode` getter
716
+ - Full TypeScript declarations (`.d.ts`) included
717
+
718
+ ##### Stack
719
+
720
+ - Express 4.x
721
+ - swagger-ui-express 5.x
722
+ - TypeScript 5.x, strict mode, ES2020 target
723
+
724
+ ### Python (PyPI)
725
+
726
+ #### [0.7.1] - 2026-09-13
727
+
728
+ - Version bump for cross-SDK parity (ADR-0002); no functional changes.
729
+
730
+ #### [0.7.0] - 2026-08-01
731
+
732
+ - **`trace_id` changes shape when tracing is configured.** Without `tracing` it stays a dashed UUID
733
+ v4, exactly as before; with `tracing` it becomes the 32-hex W3C trace id of the server span, which
734
+ is what a trace backend can join on. The change is **gated on adopting tracing** so that consumers
735
+ who do not ask for it are unaffected. Check any query, dashboard or alert that assumes the dashed
736
+ form — see [the observability guide](../../../docs/guides/observability.md#the-trace_id-shape-change)
737
+ - add distributed tracing: `tracing: TracingOptions(tracerProvider: ...)` on the `ModularApi`
738
+ constructor. Absent means no spans, no propagation and no cost — there is no `tracingEnabled`
739
+ boolean, so "off" cannot be misconfigured
740
+ - the framework **instruments**, the application **supplies the OTel SDK**. Core now declares the
741
+ OpenTelemetry **API** as a direct dependency and will never declare an SDK, exporter, gRPC or
742
+ protobuf; a test enforces that boundary. The API is no-op without an SDK, so tracing costs nothing
743
+ until you configure a provider (ADR-0005 amendment A1/A2)
744
+ - the server span is opened by the host **outside every plugin middleware slot**, and made ambient,
745
+ so a use case or satellite package reaches it with nothing threaded through any signature
746
+ - add `span_id` and `request_id` to log lines. `request_id` carries the client's `X-Request-ID`
747
+ verbatim and is **never** used as the trace id and never invented: a retried request reuses its
748
+ request id on purpose, so one request id can span several traces
749
+ - add a propagation chain, first-valid-wins: W3C `traceparent`/`tracestate`, then
750
+ `X-Cloud-Trace-Context` so a trace started by a Google load balancer is not orphaned.
751
+ `X-Cloud-Trace-Context` is **read** by default and **written** only when asked — the framework
752
+ emits open formats and nothing vendor-specific
753
+ - add `trustIncomingTraceContext` (default `true`); set it `false` at an internet-facing edge, where
754
+ a caller controlling `traceparent` controls which trace their request joins
755
+ - add `traceFieldFormatter`, the hook through which a platform correlation field such as
756
+ `logging.googleapis.com/trace` reaches log lines. No vendor field is emitted by default, because
757
+ the value needs a project id the framework does not know
758
+ - add `onShutdown`, invoked when the server closes. The framework owns the *timing*, the application
759
+ owns the resource — it never shuts down or flushes a provider it did not create. On a scale-to-zero
760
+ platform this is the only window a batching processor has to flush
761
+ - operational routes (health, docs, openapi, metrics) produce **no span**; the exclusion list is
762
+ derived from the same source as the routes rather than hardcoded
763
+ - **tracing is not a plugin and has no endpoint.** The span must sit outside every plugin middleware
764
+ slot, while a plugin registers *into* one by definition (ADR-0005 amendment A7)
765
+ - `duration_ms` is now slightly smaller than the server span, because tracing is the outermost layer
766
+ and logging sits inside it. Expected, not a regression
767
+ - **Python only:** `on_shutdown` may be sync or async, because both are idiomatic here
768
+
769
+ #### [0.6.1] - 2026-07-02
770
+
771
+ ##### Added
772
+
773
+ - **`modular_api.dto` contract module** — symmetry counterpart of the Dart
774
+ `package:modular_api/dto.dart` and TypeScript `@macss/modular-api/dto`
775
+ entry-points. Re-exports the runtime-free DTO surface (`Input`, `Output`,
776
+ `UseCaseException`, and pydantic's `Field`) for code that only needs the data
777
+ contract. Python has no browser target, so this is import hygiene / API
778
+ symmetry rather than a compilation fix.
779
+
780
+ #### [0.6.0] - 2026-06-13
781
+
782
+ ##### Changed
783
+
784
+ - version bump for coordinated ecosystem release (ADR-0002); no functional changes in this package
785
+
786
+ #### [0.5.0] - 2026-06-12
787
+
788
+ ##### Added
789
+
790
+ - **Plugin OpenAPI contributions (ADR-0003)** — `PluginRoute` gains an optional `openapi` field
791
+ (standard OpenAPI Operation object); the official OpenApiPlugin merges `custom`/`transport`
792
+ plugin routes into the generated spec, so plugin-served endpoints (e.g. binaries) appear in
793
+ `/openapi.json`, `/openapi.yaml`, and `/docs`.
794
+ - **`PluginHost.routes()`** — read view of registered plugin routes (`plugin_id`, method, mounted
795
+ path, visibility, openapi operation), exposed as `RegisteredPluginRouteView`.
796
+
797
+ ##### Changed
798
+
799
+ - **Metrics route labels cover plugin routes** — registered plugin route paths join
800
+ `registered_paths`, so plugin routes report their real `route` label instead of `UNMATCHED`.
801
+
802
+ #### [0.4.8] - 2026-06-06
803
+
804
+ ##### Changed
805
+
806
+ - **Clean-room driver isolation** — the base package no longer declares `pyodbc` or `psycopg` in its published metadata, so `macss-modular-api` remains installable without concrete database drivers.
807
+ - **Optional SQL Server introspection** — `SqlServerMetadataReader` now loads `pyodbc` lazily and raises a clear actionable error only when SQL Server introspection is actually invoked without the optional driver.
808
+
809
+ #### [0.4.7] - 2026-06-01
810
+
811
+ ##### Changed
812
+
813
+ - **Plugin middleware guardrails** — request-completed logs now annotate attributable short-circuit metadata (`short_circuit_*`) when a plugin middleware terminates the pipeline before the core handler.
814
+ - **Host-owned error normalization** — uncaught plugin-pipeline exceptions now return a structured JSON `500` response instead of falling through to framework-default error handling.
815
+
816
+ #### [0.4.6] - 2026-04-24
817
+
818
+ ##### Changed
819
+
820
+ - **Version bump for cross-SDK parity** — aligns with TypeScript 0.4.6 re-release (see ADR-0002). No functional changes.
821
+
822
+ #### [0.4.5] - 2026-03-28
823
+
824
+ ##### Added
825
+
826
+ - **`servers` parameter** in `ModularApi` constructor — configures the OpenAPI `servers` field so Swagger UI "Try it out" targets the correct host (LAN IP, domain, reverse proxy URL). Defaults to `localhost:{port}` when omitted.
827
+
828
+ ##### Fixed
829
+
830
+ - **`usecase_handler` catch blocks use scoped logger** — `UseCaseException` and unexpected errors are now logged through `request.state.modular_logger` instead of `print(stderr)`, enabling Loki correlation with `trace_id` (issue #7).
831
+ - **`_normalize_schema` strips `additionalProperties`** — Pydantic emits `additionalProperties: true` for `dict[str, Any]` fields; now stripped for cross-SDK parity with Dart/TS (issue #8).
832
+
833
+ #### [0.4.4] - 2026-03-14
834
+
835
+ ##### Changed
836
+
837
+ - **Swagger UI replaced with `@macss/docs-ui`** — the ~200-line inline HTML/CSS/JS reduced to a ~15-line bootloader that loads `@macss/docs-ui@0.1` from jsdelivr CDN
838
+ - Dark mode now delegated to `docs-ui` package — single source of truth across all three SDKs
839
+
840
+ #### [0.4.3] - 2026-03-13
841
+
842
+ ##### Changed (BREAKING)
843
+
844
+ - **`execute()` returns `O`** — no longer `None`; the handler reads the returned Output directly
845
+ - **Removed `output` property** from `UseCase` — no mutable state; `execute()` returns the result
846
+ - **Removed `to_json()`** from `UseCase` — the handler calls `output.to_json()` on the returned value
847
+ - **Removed Strategy 2 fallback** in OpenAPI schema extraction — no `factory({}).output` path
848
+
849
+ #### [0.4.2] - 2026-03-12
850
+
851
+ ##### Added
852
+
853
+ - **Auto-schema generation** — `Input` and `Output` inherit from Pydantic `BaseModel`; schemas derived automatically from field declarations
854
+ - `Field(description='x')` re-exported from Pydantic — uniform field metadata across all three SDKs
855
+ - Class-level schema extraction in `ModuleBuilder` — no `factory({})` dummy call needed
856
+ - `_normalize_schema()` — converts Pydantic JSON Schema Draft 2020-12 to OpenAPI 3.0.3 (`anyOf` → `nullable`, strip `title`/`default`)
857
+ - Cross-language schema conformance tests against shared JSON fixtures
858
+
859
+ ##### Changed
860
+
861
+ - `Input` / `Output` now inherit from `BaseModel` — `to_json()`, `to_schema()`, `from_json()` are automatic
862
+ - Manual `to_schema()` override is deprecated via `__init_subclass__()` detection — use field declarations instead (removal in v0.5.0)
863
+ - `_extract_schemas()` uses return type hint introspection (Strategy 1) with `factory({})` fallback (Strategy 2)
864
+
865
+ #### [0.4.1] - 2026-03-12
866
+
867
+ ##### Added
868
+
869
+ - PyPI publish script (`publish.ps1`) with `.env` token management
870
+ - Published to PyPI: `pip install modular-api`
871
+
872
+ ##### Fixed
873
+
874
+ - Schema extraction for nested Pydantic models in OpenAPI spec
875
+ - Dictionary guard for input validation edge cases
876
+ - Default output initialization in `UseCase`
877
+
878
+ #### [0.4.0] - 2026-03-11
879
+
880
+ ##### Added
881
+
882
+ - Initial Python implementation of `modular_api` reaching feature parity with Dart and TypeScript
883
+ - `UseCase[I, O]` — abstract base class for pure business logic, no HTTP concerns
884
+ - `Input` / `Output` — DTOs with `to_json()` and `to_schema()` for automatic OpenAPI
885
+ - `Output.status_code` — custom HTTP status codes per response
886
+ - `UseCaseException` — structured error handling (status_code, message, error_code, details)
887
+ - `ModularApi` + `ModuleBuilder` — module registration and routing via Starlette
888
+ - `cors_middleware` — built-in CORS support
889
+ - Scalar docs at `/docs` — auto-generated from registered use cases
890
+ - OpenAPI spec at `/openapi.json` and `/openapi.yaml` — raw spec download
891
+ - Health check at `GET /health` — IETF Health Check Response Format
892
+ - Prometheus metrics at `GET /metrics` — native implementation, zero external dependencies
893
+ - Structured JSON logging — Loki/Grafana compatible, request-scoped with `trace_id`
894
+ - All endpoints default to `POST` (configurable per use case)
895
+ - Full type annotations with `py.typed` marker (PEP 561)
@@ -6,7 +6,7 @@
6
6
  * the spec. Styling, dark mode, and Swagger UI loading are handled
7
7
  * entirely by docs-ui — no inline CSS or JS in this template.
8
8
  *
9
- * See: https://github.com/macss-dev/modular_api/tree/main/code/docs-ui
9
+ * See: https://github.com/ccisnedev/modular_api/tree/main/code/docs-ui
10
10
  */
11
11
  import type { RequestHandler } from 'express';
12
12
  export declare function buildSwaggerDocsHtml(options: {
@@ -7,7 +7,7 @@
7
7
  * the spec. Styling, dark mode, and Swagger UI loading are handled
8
8
  * entirely by docs-ui — no inline CSS or JS in this template.
9
9
  *
10
- * See: https://github.com/macss-dev/modular_api/tree/main/code/docs-ui
10
+ * See: https://github.com/ccisnedev/modular_api/tree/main/code/docs-ui
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.buildSwaggerDocsHtml = buildSwaggerDocsHtml;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@macss/modular-api",
3
- "version": "0.7.1",
4
- "description": "Use-case-centric toolkit for building modular APIs with Express. Define UseCase classes (input \u2192 validate \u2192 execute \u2192 output), connect them to HTTP routes, and expose Swagger/OpenAPI documentation automatically.",
3
+ "version": "0.7.2",
4
+ "description": "Use-case-centric toolkit for building modular APIs with Express. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose Swagger/OpenAPI documentation automatically.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "exports": {
@@ -17,7 +17,8 @@
17
17
  "files": [
18
18
  "dist",
19
19
  "README.md",
20
- "LICENSE"
20
+ "LICENSE",
21
+ "CHANGELOG.md"
21
22
  ],
22
23
  "scripts": {
23
24
  "build": "tsc --project tsconfig.build.json",
@@ -41,12 +42,12 @@
41
42
  "repository": {
42
43
  "type": "git",
43
44
  "url": "https://github.com/ccisnedev/modular_api.git",
44
- "directory": "code/ts/modular_api"
45
+ "directory": "code/modular_api/ts"
45
46
  },
46
47
  "bugs": {
47
48
  "url": "https://github.com/ccisnedev/modular_api/issues"
48
49
  },
49
- "homepage": "https://github.com/ccisnedev/modular_api/tree/main/code/ts/modular_api#readme",
50
+ "homepage": "https://github.com/ccisnedev/modular_api/tree/main/code/modular_api/ts#readme",
50
51
  "dependencies": {
51
52
  "@opentelemetry/api": "^1.9.0",
52
53
  "express": "^4.22.1",