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