@ddd-ts-kit/http 0.16.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.fr.md +1563 -0
  2. package/README.md +375 -48
  3. package/package.json +4 -4
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ **English** · [Français](README.fr.md)
2
+
1
3
  # @ddd-ts-kit/http
2
4
 
3
5
  Declare a route once, without a framework. Mount it on Express 5, Fastify 5, Hono 4 (on Node)
@@ -6,13 +8,27 @@ or NestJS, and generate the OpenAPI 3.1 contract from the same declaration.
6
8
  Every adapter goes through one pipeline (`executeRoute`): validation, handler, error mapping.
7
9
  The behaviour is therefore the same on the four frameworks, and one test suite proves it.
8
10
 
11
+ ![The place of the package in an application: the adapter of each framework hands every request to the same executeRoute pipeline, which runs the handler of the route, and the handler calls a use case; the same list of routes is mounted on the server and given to generateOpenApi, which writes the contract](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/http-package-overview.svg)
12
+
13
+ The package lives in the presentation layer: it turns an HTTP request into a call of your
14
+ handler, and the answer of the handler (or its refusal) into an HTTP response. It decides
15
+ nothing about the business: the handler sends a command or a query to the application, and
16
+ the use case decides.
17
+
9
18
  ## Declare
10
19
 
20
+ <!-- checked sample -->
11
21
  ```ts
12
22
  import { z } from 'zod';
23
+ import type { Actor } from '@ddd-ts-kit/kernel';
13
24
  import { defineRoute, defineRoutes } from '@ddd-ts-kit/http';
14
25
  import { zodSchema } from '@ddd-ts-kit/validation/zod';
15
26
 
27
+ /** The read side of the application, handed to the routes by the composition root. */
28
+ interface OrderQueries {
29
+ byId(orderId: string, actor: Actor): Promise<{ id: string; total: number }>;
30
+ }
31
+
16
32
  const order = zodSchema(z.object({ id: z.string(), total: z.number() }), { io: 'output' });
17
33
 
18
34
  export const orderRoutes = (orders: OrderQueries) =>
@@ -31,33 +47,74 @@ export const orderRoutes = (orders: OrderQueries) =>
31
47
  },
32
48
  async ({ params, context }) => ({
33
49
  status: 200, // must be a declared status, and the body must match its schema
34
- body: await orders.byId(params.orderId, context.principal),
50
+ body: await orders.byId(params.orderId, context.execution.actor),
35
51
  }),
36
52
  ),
37
53
  );
38
54
  ```
39
55
 
40
56
  - `params`, `query`, `headers` and `body` are typed from the schemas. Any `Schema` of
41
- `@ddd-ts-kit/validation` works (zod, class-validator, Standard Schema).
57
+ `@ddd-ts-kit/validation` works (zod, class-validator, TypeBox, Standard Schema).
42
58
  - Paths are literal segments and `:name` parameters, the form Express and Fastify share.
43
59
  - Frameworks hand query values over as strings: coerce in the schema (`z.coerce.number()`).
44
- - `context` is `{ requestId, execution, principal?, raw }`. `execution` is the kernel
45
- `ExecutionContext` of the request (see "The execution context of a request"); `raw` is the
46
- framework's request object.
60
+ - `context` is `{ requestId, execution, principal?, rawHeaders?, raw, expectedVersion?, stream? }`.
61
+ `execution` is the kernel `ExecutionContext` of the request (see "The execution context of a
62
+ request"); `raw` is the framework's request object and `rawHeaders` the headers as they
63
+ arrived; `expectedVersion` is read from `If-Match` (see "Conditional requests") and `stream`
64
+ is the unparsed body of a route declared with `rawBody`.
47
65
  - `security` is required: the names of the security schemes that apply, or `false` for a route
48
66
  anybody may call. A route is never public by omission: leaving it out does not compile, and
49
67
  `defineRoute` refuses an empty list, which would say the same as `false` without saying it.
50
68
  - `defineRoutes` and every mount refuse a duplicate `operationId` or method and path.
51
69
  - `prefixRoutes('/api', routes)` moves routes under a prefix, for the server and the contract.
52
70
 
71
+ A refusal is thrown, not returned. The handler answers only the success it declares; what can
72
+ go wrong is a code in `errors`, which the contract documents and the pipeline answers:
73
+
74
+ ```ts
75
+ // Instead of: a 404 written by hand, a second shape of answer that every route invents again
76
+ responses: { 200: { description: 'The order.', body: order }, 404: { description: 'No such order.' } },
77
+ async ({ params }) => {
78
+ const found = await orders.find(params.orderId);
79
+ return found === undefined ? { status: 404 } : { status: 200, body: found };
80
+ },
81
+
82
+ // Write: the use case throws a refusal (NotFoundError, or a factory of a ConceptError) and the
83
+ // route lists its code; the answer is a problem document, the same on every route (see "Errors")
84
+ responses: { 200: { description: 'The order.', body: order } },
85
+ errors: ['NOT_FOUND'],
86
+ async ({ params, context }) => ({ status: 200, body: await orders.byId(params.orderId, context.execution.actor) }),
87
+ ```
88
+
53
89
  ## Controllers, route groups and guards
54
90
 
55
91
  A route may also be a class: one class per route, one method, `handle`. Its decorator is the
56
92
  declaration, and the compiler holds `handle` to it: a part the schemas do not produce, or
57
93
  another body than the declared response, is an error on the decorator.
58
94
 
95
+ <!-- checked sample -->
59
96
  ```ts
60
- import { Authenticated, Controller, RouteGroup, type HttpRequest } from '@ddd-ts-kit/http';
97
+ import { z } from 'zod';
98
+ import { AuthorizedCommand, type Actor, type CommandBus } from '@ddd-ts-kit/kernel';
99
+ import { Authenticated, Controller, RouteGroup, controllerRoutes, type HttpRequest } from '@ddd-ts-kit/http';
100
+ import type { Infer } from '@ddd-ts-kit/validation';
101
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
102
+
103
+ /** The command of the use case, in the application layer (its @Requires permission left out here). */
104
+ class PlaceOrder extends AuthorizedCommand<string> {
105
+ constructor(
106
+ actor: Actor,
107
+ readonly customerId: string,
108
+ ) {
109
+ super(actor);
110
+ }
111
+ }
112
+
113
+ const body = zodSchema(z.object({ customerId: z.string().min(1) }));
114
+ const placed = zodSchema(z.object({ id: z.string() }), { io: 'output' });
115
+
116
+ type PlaceOrderBody = Infer<typeof body>; // { customerId: string }
117
+ type Placed = Infer<typeof placed>; // { id: string }
61
118
 
62
119
  @RouteGroup({ prefix: '/orders', tags: ['orders'], guards: [Authenticated], errors: ['FORBIDDEN'] })
63
120
  export class OrdersRoutes {}
@@ -74,17 +131,24 @@ export class OrdersRoutes {}
74
131
  export class PlaceOrderController {
75
132
  constructor(private readonly commands: CommandBus) {}
76
133
 
77
- async handle({ body, actor }: HttpRequest<{ body: Infer<typeof body> }>): Promise<Infer<typeof placed>> {
134
+ async handle({ body, actor }: HttpRequest<{ body: PlaceOrderBody }>): Promise<Placed> {
78
135
  return { id: await this.commands.execute(new PlaceOrder(actor, body.customerId)) };
79
136
  }
80
137
  }
81
138
 
82
- const routes = controllerRoutes([PlaceOrderController], { resolve: application.resolve });
139
+ declare const application: { resolve<T>(target: abstract new (...args: never) => T): T };
140
+
141
+ export const routes = controllerRoutes([PlaceOrderController], { resolve: application.resolve });
83
142
  ```
84
143
 
144
+ The route of this controller is `POST /orders`: the prefix of its group, then its own path
145
+ (`/` is the prefix itself).
146
+ It answers 201 with `{ id }`, documents `OUT_OF_STOCK` (its own), `FORBIDDEN` (its group) and
147
+ `UNAUTHORIZED` (the `Authenticated` guard), and lets no anonymous caller reach `handle`.
148
+
85
149
  | Export | What it is |
86
150
  |---|---|
87
- | `Controller(spec)` | the decorator of a controller: `group`, `method`, `path` (after the prefix of the group), `operationId` (the class name without `Controller` by default), `summary`, `description`, `tags`, `params`, `query`, `headers`, `body`, `response: { status, description?, body? }`, `errors`, `guards`, `deprecated`, `cache` and `ifMatch` (see "HTTP caching"), `produces` and `consumes` (see [Representations](#representations-json-xml-csv)), `form` (see [Forms described by the server](#forms-described-by-the-server)) |
151
+ | `Controller(spec)` | the decorator of a controller: `group`, `method`, `path` (after the prefix of the group), `operationId` (the class name without `Controller` by default), `summary`, `description`, `tags`, `params`, `query`, `headers`, `body`, `upload` (see "Uploads and files"), `response: { status, description?, body? }`, `errors`, `guards`, `deprecated`, `cache` and `ifMatch` (see "HTTP caching"), `produces` and `consumes` (see [Representations](#representations-json-xml-csv)), `form` (see [Forms described by the server](#forms-described-by-the-server)) |
88
152
  | `RouteGroup({ parent, prefix, tags, guards, errors, cache })` | names a set of routes on an empty class; a child inherits from its `parent` and adds; the nearest `cache` wins |
89
153
  | `Guard` | the interface `{ documents?, check(request: GuardRequest) }`, and the decorator of a guard class that takes dependencies |
90
154
  | `Authenticated`, `Public`, `HasRole(...roles)`, `HasScope(...scopes)`, `TenantMember` | the guards the package ships, over the `Actor` and the `Session` of the request: 401 to the anonymous caller, 403 without one of the roles, without every scope named (`Session.scopes`, typed by the `SessionScopes` of the project) or outside the tenant of the request; `Public` lets everybody in and stands alone. A refusal of a guard is reported to `onGuardRefusal` |
@@ -103,6 +167,65 @@ in `DeclaredEdges`. A controller has one response and answers its body: a route
103
167
  success statuses, response headers or a raw body stays a `defineRoute` function. The reasons
104
168
  are on the [presentation layer](../../docs/concepts/presentation-layer.md) page.
105
169
 
170
+ ## One request, step by step
171
+
172
+ `executeRoute(route, request, options)` is the whole behaviour of the package: an adapter only
173
+ copies the request of its framework into a `RawRequest` (`params`, `query`, `headers`, `body`,
174
+ `raw`, and the body `stream`), calls it, and writes back the `RouteResponse` it returns.
175
+
176
+ ![The steps executeRoute takes for one request: the identifiers, then, inside the around hook, authentication, upload, validation, If-Match, execution context and tenant, then guards and handle inside the execution scope, the check of the answer, the headers and the 304; each step that can refuse names its status, and every refusal becomes a problem document](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/http-package-pipeline.svg)
177
+
178
+ The steps that are not needed are skipped: no upload, no `If-Match`, no guard, no validator.
179
+ The first refusal ends the request: a request that is not valid never reaches a guard, and a
180
+ caller a guard refuses never reaches `handle`. Guards run after validation, so they read typed
181
+ parameters; a credential that `resolvePrincipal` rejects is refused before anything else.
182
+
183
+ Since `executeRoute` needs no server, a spec of a route calls it directly, as the adapters do:
184
+
185
+ <!-- checked sample -->
186
+ ```ts
187
+ import { z } from 'zod';
188
+ import { NotFoundError } from '@ddd-ts-kit/kernel';
189
+ import { defineRoute, executeRoute, type RawRequest } from '@ddd-ts-kit/http';
190
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
191
+
192
+ const orders = new Map([['7', { id: '7', total: 42 }]]);
193
+
194
+ const getOrder = defineRoute(
195
+ {
196
+ method: 'GET',
197
+ path: '/orders/:orderId',
198
+ operationId: 'getOrder',
199
+ summary: 'Read an order',
200
+ request: { params: zodSchema(z.object({ orderId: z.string().regex(/^\d+$/) })) },
201
+ responses: {
202
+ 200: { description: 'The order.', body: zodSchema(z.object({ id: z.string(), total: z.number() }), { io: 'output' }) },
203
+ },
204
+ errors: ['NOT_FOUND'],
205
+ security: false,
206
+ },
207
+ async ({ params }) => {
208
+ const found = orders.get(params.orderId);
209
+
210
+ if (found === undefined) {
211
+ throw new NotFoundError(`Order ${params.orderId} does not exist.`);
212
+ }
213
+
214
+ return { status: 200, body: found };
215
+ },
216
+ );
217
+
218
+ const request = (orderId: string): RawRequest => ({ params: { orderId }, query: {}, headers: {}, body: undefined, raw: undefined });
219
+
220
+ export const found = await executeRoute(getOrder, request('7')); // 200, { id: '7', total: 42 }
221
+ export const missing = await executeRoute(getOrder, request('8')); // 404, a problem with the code NOT_FOUND
222
+ export const invalid = await executeRoute(getOrder, request('x')); // 422, VALIDATION_FAILED, one issue at params.orderId
223
+ ```
224
+
225
+ Pass the options of the application as the third argument (`validateResponses: true` in
226
+ tests, `resolvePrincipal` to call as a given actor): the answer is the one the server would
227
+ send, headers included.
228
+
106
229
  ## HTTP caching
107
230
 
108
231
  A read says how the caches on the way may keep its answer, on its controller, on its route
@@ -147,6 +270,21 @@ A policy that cannot stand is refused when the route is declared, with a `Declar
147
270
  The ESLint rule `presentation/shared-cache-varies` reports the same declaration in the editor,
148
271
  for what one file shows.
149
272
 
273
+ ```ts
274
+ // Instead of: refused with a DeclarationError; a CDN would hand the agenda of one caller to the next
275
+ @RouteGroup({ prefix: '/me', guards: [Authenticated], cache: { scope: CacheScope.public, maxAge: '1m' } })
276
+
277
+ // Write: kept by the browser of the caller only
278
+ @RouteGroup({ prefix: '/me', guards: [Authenticated], cache: { scope: CacheScope.private, maxAge: '1m' } })
279
+
280
+ // Or, when a shared cache must keep it: one copy per credential
281
+ @RouteGroup({
282
+ prefix: '/me',
283
+ guards: [Authenticated],
284
+ cache: { scope: CacheScope.public, maxAge: '1m', vary: ['Authorization'] },
285
+ })
286
+ ```
287
+
150
288
  When the routes are mounted (`mountExpress`, `mountFastify`, `createRoutesModule`), the options of
151
289
  the application are known, and a public answer is held to them with a `DeclarationError`:
152
290
 
@@ -275,11 +413,19 @@ the transaction of the command. A command that rolls back purges nothing; one th
275
413
  purges even when the process stops right after the commit, since the row waits for the next
276
414
  relay. The relay hands the requests to a `CachePurger` and every other event to the broker:
277
415
 
416
+ <!-- checked sample -->
278
417
  ```ts
279
- import { PurgingPublisher } from '@ddd-ts-kit/kernel';
418
+ import { OutboxRelay, type OutboxStore } from '@ddd-ts-kit/events';
419
+ import { PurgingPublisher, type Clock, type IntegrationEventPublisher } from '@ddd-ts-kit/kernel';
280
420
  import { VarnishCachePurger } from '@ddd-ts-kit/http/purgers';
281
421
 
282
- const relay = new OutboxRelay({
422
+ declare const store: OutboxStore;
423
+ declare const broker: IntegrationEventPublisher;
424
+ declare const clock: Clock;
425
+ declare const varnishUrl: string;
426
+ declare const varnishPurgeKey: string;
427
+
428
+ export const relay = new OutboxRelay({
283
429
  store,
284
430
  publisher: new PurgingPublisher(new VarnishCachePurger({ url: varnishUrl, key: varnishPurgeKey }), broker),
285
431
  clock,
@@ -318,66 +464,120 @@ A handler throws a `DomainError`; its `code` is mapped to a status in one place
318
464
  "detail": "Order 7 does not exist.", "requestId": "..." }
319
465
  ```
320
466
 
467
+ ![How the answer to an error is chosen: an error that is not a DomainError answers 500 with no detail; a DomainError gets the status its code maps to, from the defaults, the codes of the application, else 422; a 5xx answers its status and code only, a 4xx a problem document with its detail, its exposed facts and its issues](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/http-package-error-answer.svg)
468
+
321
469
  A refusal built by a factory of a `ConceptError` carries facts, and they are private: the
322
470
  document holds, under `facts`, only the ones its factory exposed by name, and no `facts` member
323
471
  when it exposed none.
324
472
 
473
+ <!-- checked sample -->
325
474
  ```ts
326
- static slotTaken(calendarId: string, startsAt: Date) {
327
- return AppointmentError.refusal('SLOT_TAKEN', 'The slot is already held.', { calendarId, startsAt }).exposing('startsAt');
475
+ import { ConceptError } from '@ddd-ts-kit/kernel';
476
+
477
+ export class AppointmentError extends ConceptError {
478
+ static slotTaken(calendarId: string, startsAt: Date) {
479
+ return AppointmentError.refusal('SLOT_TAKEN', 'The slot is already held.', { calendarId, startsAt }).exposing('startsAt');
480
+ }
328
481
  }
329
482
  ```
330
483
 
484
+ With `SLOT_TAKEN` mapped to 409 (`createErrorMapper({ SLOT_TAKEN: 409 })`, below), a handler
485
+ that throws `AppointmentError.slotTaken('c-1', startsAt)` answers:
486
+
331
487
  ```json
332
488
  { "type": "urn:problem:slot-taken", "title": "Conflict", "status": 409, "code": "SLOT_TAKEN",
333
489
  "detail": "The slot is already held.", "facts": { "startsAt": "2026-03-02T09:00:00.000Z" }, "requestId": "..." }
334
490
  ```
335
491
 
492
+ `calendarId` stays in the process: the factory did not expose it.
493
+
336
494
  `facts` is an optional object of the `Problem` schema of the OpenAPI document. A client
337
495
  branches on `code` and reads data from `facts`, never from `detail`, which is a sentence for a
338
496
  human and may change. The message is answered as it was written: it says nothing the caller
339
497
  did not send, and nothing about another person. A refusal mapped to a 5xx answers neither its
340
498
  message nor its facts.
341
499
 
500
+ <!-- checked sample -->
501
+ ```ts
502
+ import type { Problem } from '@ddd-ts-kit/http';
503
+
504
+ // Instead of: data parsed out of the sentence, which breaks the day the sentence is reworded
505
+ export function startsAtFromDetail(problem: Problem): string | undefined {
506
+ return /held at (.+)\.$/.exec(problem.detail ?? '')?.[1];
507
+ }
508
+
509
+ // Write: branch on the stable code, read the fact the refusal exposed
510
+ export function startsAtOf(problem: Problem): string | undefined {
511
+ if (problem.code !== 'SLOT_TAKEN') {
512
+ return undefined;
513
+ }
514
+
515
+ const startsAt = problem.facts?.['startsAt'];
516
+
517
+ return typeof startsAt === 'string' ? startsAt : undefined;
518
+ }
519
+ ```
520
+
342
521
  Defaults: `VALIDATION_FAILED` 422 (with `issues`, paths prefixed by the part:
343
522
  `body.items.0.sku`), `NOT_FOUND` 404, `CONFLICT` 409, `INVARIANT_VIOLATION` 422, `UNAUTHORIZED`
344
- 401, `FORBIDDEN` 403, `NOT_ACCEPTABLE` 406, `PRECONDITION_FAILED` 412, `UNSUPPORTED_MEDIA_TYPE` 415,
345
- `PRECONDITION_REQUIRED` 428. A domain code that is not mapped answers 422.
523
+ 401, `FORBIDDEN` 403, `NOT_ACCEPTABLE` 406, `PRECONDITION_FAILED` 412, `UNSUPPORTED_MEDIA_TYPE` 415
524
+ (a body or a file of a type the route does not take), `PRECONDITION_REQUIRED` 428, and for files
525
+ `FILE_NOT_FOUND` 404, `FILE_TOO_LARGE` 413. A domain code that is not mapped answers 422
526
+ (`fallbackStatus` of the second argument changes it).
346
527
 
528
+ <!-- checked sample -->
347
529
  ```ts
348
530
  import { createErrorMapper } from '@ddd-ts-kit/http';
349
531
 
350
- const errorMapper = createErrorMapper({ ORDER_ALREADY_SHIPPED: 409, QUOTA_EXCEEDED: 429 });
532
+ export const errorMapper = createErrorMapper({ ORDER_ALREADY_SHIPPED: 409, QUOTA_EXCEEDED: 429, SLOT_TAKEN: 409 });
533
+
534
+ errorMapper.statusOf('SLOT_TAKEN'); // 409, the code of the application
535
+ errorMapper.statusOf('NOT_FOUND'); // 404, a default
536
+ errorMapper.statusOf('INVALID_EMAIL'); // 422, a code not mapped
537
+ errorMapper.typeOf('SLOT_TAKEN'); // 'urn:problem:slot-taken', the type of its problem document
351
538
  ```
352
539
 
353
- Anything that is not a `DomainError` answers 500 `Internal Server Error` with no detail: the
354
- message of an unexpected error never leaves the process. Log it from the `onError` hook, and
355
- report it to the error tracker with `onError: reportHttpErrors(errorReporter)`: every request
356
- answered 5xx goes to the kernel `ErrorReporter`, once, with the correlation, actor and tenant
357
- ids of its execution context (`context.execution`, present once the request got that far); a
358
- 4xx never does.
540
+ Anything that is not a `DomainError` answers 500 `Internal Server Error` with no detail (its
541
+ code is `INTERNAL_ERROR`): the message of an unexpected error never leaves the process. Log it
542
+ from the `onError` hook, and report it to the error tracker with
543
+ `onError: reportHttpErrors(errorReporter)`: every request answered 5xx goes to the kernel
544
+ `ErrorReporter`, once, with the correlation, actor and tenant ids of its execution context
545
+ (`context.execution`, present once the request got that far); a 4xx never does.
359
546
 
360
547
  A refusal built by a factory (`ConceptError`) answers its message as `detail` unless the message
361
548
  quotes a fact the factory did not expose: then the client reads a sentence made from the code
362
549
  (`INVALID_EMAIL` gives `Invalid email.`) and the message stays in the logs and the error
363
550
  reports. A fact is found in the message as a text, a number or an ISO instant; a fact written
364
- another way (a formatted date, a part of an object) is not seen, so expose what a client may
551
+ another way (a formatted date, a rounded number) is not seen, so expose what a client may
365
552
  read and keep the rest out of the sentence.
366
553
 
367
554
  ## Options shared by the adapters
368
555
 
369
- ```ts
370
- import type { ExecuteOptions } from '@ddd-ts-kit/http';
556
+ Every mount takes the same `ExecuteOptions`, a plain object built where the server starts:
371
557
 
372
- const options: ExecuteOptions = {
373
- errorMapper,
558
+ <!-- checked sample -->
559
+ ```ts
560
+ import { auditGuardRefusals } from '@ddd-ts-kit/audit';
561
+ import { CacheTagHeader, createErrorMapper, type ExecuteOptions } from '@ddd-ts-kit/http';
562
+ import type { AuditTrail, Clock, IdGenerator } from '@ddd-ts-kit/kernel';
563
+ import { tracedRoutes } from '@ddd-ts-kit/tracing';
564
+
565
+ declare function authenticate(raw: unknown): Promise<unknown>;
566
+ declare const logger: { error(fields: Record<string, unknown>): void };
567
+ declare const trail: AuditTrail;
568
+ declare const clock: Clock;
569
+ declare const ids: IdGenerator;
570
+
571
+ export const options: ExecuteOptions = {
572
+ errorMapper: createErrorMapper({ ORDER_ALREADY_SHIPPED: 409 }),
374
573
  resolvePrincipal: (raw) => authenticate(raw), // throw UnauthorizedError to refuse
375
574
  onError: (error, { requestId, correlationId, operationId, problem }) => {
376
575
  if (problem.status >= 500) {
377
576
  logger.error({ requestId, correlationId, operationId, error });
378
577
  }
379
578
  },
380
- validateResponses: process.env.NODE_ENV === 'test', // checks answers against the declaration
579
+ onGuardRefusal: auditGuardRefusals(trail, { clock, ids }), // the refusals at the edge, in the audit trail
580
+ validateResponses: process.env['NODE_ENV'] === 'test', // checks answers against the declaration
381
581
  around: tracedRoutes(), // of @ddd-ts-kit/tracing: the span of the request, named by its route template
382
582
  // the header the shared cache in front reads the tags from; honoursVary and perTenant: see HTTP caching
383
583
  cacheTags: { header: CacheTagHeader.xkey },
@@ -416,10 +616,16 @@ as `context.execution`:
416
616
  | `locale` | the locale of the session, else the preferred language of `Accept-Language` |
417
617
  | `deadline` | arrival plus `requestTimeoutMs`, when the option is set |
418
618
 
619
+ <!-- checked sample -->
419
620
  ```ts
621
+ import { principalResolver, type Authenticator } from '@ddd-ts-kit/auth';
622
+ import type { ExecuteOptions } from '@ddd-ts-kit/http';
420
623
  import { Clock, ExecutionScope } from '@ddd-ts-kit/kernel';
421
624
 
422
- const options: ExecuteOptions = {
625
+ declare const authenticator: Authenticator;
626
+ declare const app: { resolve<T>(token: abstract new (...args: never) => T): T };
627
+
628
+ export const options: ExecuteOptions = {
423
629
  resolvePrincipal: principalResolver(authenticator), // of @ddd-ts-kit/auth: answers a Session
424
630
  executionScope: app.resolve(ExecutionScope), // the scope the application runs its use cases in
425
631
  clock: app.resolve(Clock),
@@ -441,10 +647,11 @@ or `actorOf(context.principal)` of `@ddd-ts-kit/auth`, which reads the same acto
441
647
 
442
648
  A multi-tenant application says where a request names its tenant with `resolveTenant`:
443
649
 
650
+ <!-- checked sample -->
444
651
  ```ts
445
- import { firstTenantOf, tenantFromClaim, tenantFromSubdomain } from '@ddd-ts-kit/http';
652
+ import { firstTenantOf, tenantFromClaim, tenantFromSubdomain, type ExecuteOptions } from '@ddd-ts-kit/http';
446
653
 
447
- const options: ExecuteOptions = {
654
+ export const options: ExecuteOptions = {
448
655
  resolveTenant: firstTenantOf(tenantFromSubdomain('app.example.com'), tenantFromClaim()),
449
656
  // or tenantFromHeader('x-tenant-id'), tenantFromPath('tenantId')
450
657
  };
@@ -466,7 +673,16 @@ opens another tenant's data. An anonymous caller keeps the tenant it addressed,
466
673
  routes of a tenant. The guard `TenantMember` puts a group of routes behind a tenant: 401 to the
467
674
  anonymous caller, 403 to a request in no tenant or of another tenant. Platform staff do not pass
468
675
  it: they reach tenants through an elevation of the kernel (`acrossTenants`), behind guards of their
469
- own.
676
+ own. A tenant id that no tenant can have (`*`, a list, a `:`, outside the grammar of `isTenantId`)
677
+ is answered 404 before anything reads it, whoever calls.
678
+
679
+ | Caller | Tenant named by the request | Answer |
680
+ |---|---|---|
681
+ | anonymous | any | goes on, in the tenant it addressed; a `TenantMember` route answers 401 |
682
+ | member of `acme` | `acme` | goes on, `execution.tenantId` is `acme` |
683
+ | member of `acme` | `globex` | 403, before any guard or handler, reported to `onGuardRefusal` |
684
+ | member of `acme` | none | goes on in `acme`, the tenant of the actor |
685
+ | anybody | `*` or `a,b` | 404 |
470
686
 
471
687
  ## In the composition root
472
688
 
@@ -474,11 +690,14 @@ The package binds and resolves nothing: routes are a plain list and `ExecuteOpti
474
690
  object, both built where the server starts. What it takes from the application are ports,
475
691
  resolved by their class:
476
692
 
693
+ <!-- checked sample -->
477
694
  ```ts
478
- import { createApplication, defineContextModule, kernelModule } from '@ddd-ts-kit/di';
695
+ import { createApplication, defineContextModule, kernelModule, type ContextModule } from '@ddd-ts-kit/di';
479
696
  import { ErrorMapper, createErrorMapper, type ExecuteOptions } from '@ddd-ts-kit/http';
480
697
  import { Clock, ExecutionScope } from '@ddd-ts-kit/kernel';
481
698
 
699
+ declare const orderingModule: ContextModule; // the module of a bounded context
700
+
482
701
  const httpModule = defineContextModule({
483
702
  name: 'http',
484
703
  register(builder) {
@@ -488,7 +707,7 @@ const httpModule = defineContextModule({
488
707
 
489
708
  const app = createApplication({ modules: [kernelModule(), httpModule, orderingModule] });
490
709
 
491
- const options: ExecuteOptions = {
710
+ export const options: ExecuteOptions = {
492
711
  errorMapper: app.resolve(ErrorMapper),
493
712
  executionScope: app.resolve(ExecutionScope),
494
713
  clock: app.resolve(Clock),
@@ -509,10 +728,25 @@ One query vocabulary and one answer for every search, on top of the kernel `Page
509
728
  `Page`: `limit`, `offset` or `cursor`, and `sort` (`placedAt,-total`: comma-separated fields, a
510
729
  leading `-` for descending).
511
730
 
731
+ <!-- checked sample -->
512
732
  ```ts
733
+ import { z } from 'zod';
734
+ import type { Page, PageRequest } from '@ddd-ts-kit/kernel';
513
735
  import { defineRoute, pageQuerySchema, pageResponse, pageSchemaOf } from '@ddd-ts-kit/http';
736
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
514
737
 
515
- const searchOrders = defineRoute(
738
+ interface Order {
739
+ readonly id: string;
740
+ readonly placedAt: Date;
741
+ readonly total: number;
742
+ }
743
+
744
+ declare const orders: { search(page: PageRequest<'placedAt' | 'total'>): Promise<Page<Order>> };
745
+
746
+ const order = zodSchema(z.object({ id: z.string(), placedAt: z.string(), total: z.number() }), { io: 'output' });
747
+ const toOrderDto = ({ id, placedAt, total }: Order) => ({ id, placedAt: placedAt.toISOString(), total });
748
+
749
+ export const searchOrders = defineRoute(
516
750
  {
517
751
  method: 'GET',
518
752
  path: '/orders',
@@ -624,6 +858,8 @@ into the text of one media type, chosen per request by the `Accept` header among
624
858
  route declares. The application registers its representations once and gives the same set to
625
859
  the adapters and to the contract generator:
626
860
 
861
+ ![A handler answers a typed value; the response schema checks it; field access leaves out what the caller may not read; negotiation on Accept picks JSON, XML or CSV among what the route produces, or refuses with 406 when none is in common](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/representations-and-forms-one-value.svg)
862
+
627
863
  ```ts
628
864
  import { Representations, type ExecuteOptions } from '@ddd-ts-kit/http';
629
865
 
@@ -826,6 +1062,8 @@ A route that declares `form` is described as a form, from what it already declar
826
1062
  body schema, the restricted fields of that schema, and a few presentation hints. `formRoutes`
827
1063
  serves one `GET /forms/<operationId>` per such route, mounted and documented like any route:
828
1064
 
1065
+ ![The body schema of the booking reserves the internal note; the form route asks the permission to book and Access about the calendar; the practitioner who holds the desk may set every field, an assistant on a delegated desk sees the note read-only, a patient booking for themselves does not see it, and an assistant without a delegation is refused with 403](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/representations-and-forms-one-form-per-caller.svg)
1066
+
829
1067
  ```ts
830
1068
  // presentation/http/appointments/book-appointment/book-appointment.controller.ts, next to its schemas
831
1069
  const form = defineForm<Infer<typeof body>>({
@@ -900,36 +1138,52 @@ both formats, for the documentation: a project generated by the CLI writes them
900
1138
 
901
1139
  ## Express 5
902
1140
 
1141
+ <!-- checked sample -->
903
1142
  ```ts
904
1143
  import express from 'express';
1144
+ import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
905
1145
  import { mountExpress } from '@ddd-ts-kit/http/express';
906
1146
 
1147
+ declare const routes: readonly Route[]; // defineRoutes(...), controllerRoutes(...)
1148
+ declare const options: ExecuteOptions;
1149
+
907
1150
  const app = express();
908
1151
  app.use(express.json()); // required: the adapter does not parse bodies
909
- mountExpress(app, orderRoutes(orders), options); // an express.Router() works too
1152
+ mountExpress(app, routes, options); // an express.Router() works too
1153
+ app.listen(3000);
910
1154
  ```
911
1155
 
912
1156
  ## Fastify 5
913
1157
 
1158
+ <!-- checked sample -->
914
1159
  ```ts
915
1160
  import Fastify from 'fastify';
1161
+ import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
916
1162
  import { fastifyRoutes, mountFastify } from '@ddd-ts-kit/http/fastify';
917
1163
 
1164
+ declare const routes: readonly Route[];
1165
+ declare const options: ExecuteOptions;
1166
+
918
1167
  const app = Fastify();
919
- mountFastify(app, orderRoutes(orders), options);
1168
+ mountFastify(app, routes, options);
920
1169
  // or, as a plugin:
921
- await app.register(fastifyRoutes(orderRoutes(orders), options), { prefix: '/api' });
1170
+ await app.register(fastifyRoutes(routes, options), { prefix: '/api' });
922
1171
  ```
923
1172
 
924
1173
  ## Hono 4
925
1174
 
1175
+ <!-- checked sample -->
926
1176
  ```ts
927
1177
  import { serve } from '@hono/node-server';
928
1178
  import { Hono } from 'hono';
1179
+ import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
929
1180
  import { mountHono } from '@ddd-ts-kit/http/hono';
930
1181
 
1182
+ declare const routes: readonly Route[];
1183
+ declare const options: ExecuteOptions;
1184
+
931
1185
  const app = new Hono();
932
- mountHono(app, orderRoutes(orders), options);
1186
+ mountHono(app, routes, { ...options, bodyLimit: 2 * 1024 * 1024 }); // bodyLimit: 1 MiB by default
933
1187
  serve({ fetch: app.fetch, port: 3000 });
934
1188
  ```
935
1189
 
@@ -951,10 +1205,19 @@ Node with `@hono/node-server`, not Bun, Deno or an edge runtime.
951
1205
  No decorator per route: a module mounts the routes on the underlying HTTP server at module
952
1206
  init, whether Nest runs on Express or on Fastify. Handlers get their dependencies by closure.
953
1207
 
1208
+ <!-- checked sample: legacy-decorators -->
954
1209
  ```ts
955
1210
  import { Module } from '@nestjs/common';
1211
+ import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
956
1212
  import { createRoutesModule } from '@ddd-ts-kit/http/nest';
957
1213
 
1214
+ /** A token of the Nest application, exported by OrdersModule. */
1215
+ abstract class OrderQueries {}
1216
+
1217
+ declare class OrdersModule {}
1218
+ declare function orderRoutes(orders: OrderQueries): readonly Route[];
1219
+ declare const options: ExecuteOptions;
1220
+
958
1221
  @Module({
959
1222
  imports: [
960
1223
  createRoutesModule(
@@ -972,14 +1235,19 @@ are those described above. Use `prefixRoutes` for a prefix.
972
1235
 
973
1236
  ## OpenAPI 3.1
974
1237
 
1238
+ <!-- checked sample -->
975
1239
  ```ts
976
1240
  import { readFileSync, writeFileSync } from 'node:fs';
1241
+ import type { ErrorMapper, Route } from '@ddd-ts-kit/http';
977
1242
  import { checkOpenApiDrift, generateOpenApi, stringifyOpenApi } from '@ddd-ts-kit/http/openapi';
978
1243
 
1244
+ declare const routes: readonly Route[]; // the very list the server mounts
1245
+ declare const errorMapper: ErrorMapper;
1246
+
979
1247
  const document = generateOpenApi({
980
1248
  info: { title: 'Orders', version: '1.0.0' },
981
1249
  servers: [{ url: 'https://api.example.com' }],
982
- routes: orderRoutes(orders),
1250
+ routes,
983
1251
  securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } },
984
1252
  errorMapper, // the one the server runs with
985
1253
  });
@@ -1038,10 +1306,16 @@ Fields reserved by `withFieldAccess` stay reserved whichever of the two wraps th
1038
1306
 
1039
1307
  ## Serving the contract and its page
1040
1308
 
1309
+ <!-- checked sample -->
1041
1310
  ```ts
1311
+ import type { Route } from '@ddd-ts-kit/http';
1042
1312
  import { openApiDocsRoutes } from '@ddd-ts-kit/http/docs';
1313
+ import type { OpenApiDocument } from '@ddd-ts-kit/http/openapi';
1314
+
1315
+ declare const orderRoutes: readonly Route[];
1316
+ declare const document: OpenApiDocument; // generateOpenApi(...) of orderRoutes
1043
1317
 
1044
- const routes = [...orderRoutes(orders), ...openApiDocsRoutes(document, { ui: 'scalar' })];
1318
+ export const routes = [...orderRoutes, ...openApiDocsRoutes(document, { ui: 'scalar' })];
1045
1319
  ```
1046
1320
 
1047
1321
  Two public routes (`security: false`), mounted next to the application routes and absent
@@ -1055,10 +1329,14 @@ the UI chosen by `--docs-ui`, unless documentation is switched off by its config
1055
1329
 
1056
1330
  ## A contract split into documents
1057
1331
 
1332
+ <!-- checked sample -->
1058
1333
  ```ts
1334
+ import type { Route } from '@ddd-ts-kit/http';
1059
1335
  import { openApiDocumentsRoutes } from '@ddd-ts-kit/http/docs';
1060
1336
  import { generateOpenApi, routesByDocument } from '@ddd-ts-kit/http/openapi';
1061
1337
 
1338
+ declare const routes: readonly Route[];
1339
+
1062
1340
  const documents = routesByDocument(routes, [
1063
1341
  { name: 'public', title: 'Booking API', groups: ['AppointmentRoutes'] },
1064
1342
  { name: 'back-office', title: 'Back office', tags: ['audit'], operations: ['openPractice'] },
@@ -1067,7 +1345,7 @@ const documents = routesByDocument(routes, [
1067
1345
  document: generateOpenApi({ info: { title: title ?? 'API', version: '1.0.0' }, routes: selected }),
1068
1346
  }));
1069
1347
 
1070
- const served = [...routes, ...openApiDocumentsRoutes(documents, { ui: 'swagger' })];
1348
+ export const served = [...routes, ...openApiDocumentsRoutes(documents, { ui: 'swagger' })];
1071
1349
  ```
1072
1350
 
1073
1351
  `routesByDocument` gives each document the routes of its route groups (a controller route
@@ -1086,22 +1364,62 @@ A controller that receives a file declares it, and the declaration is the contra
1086
1364
  the most it may weigh and the media types it may be, which the OpenAPI document states
1087
1365
  (`multipart/form-data`, `x-max-bytes`, `x-media-types`, the 413, 415 and 422 refusals).
1088
1366
 
1367
+ <!-- checked sample -->
1089
1368
  ```ts
1369
+ import { z } from 'zod';
1370
+ import { AuthorizedCommand, FileUpload, type Actor, type CommandBus, type ReceivedFile } from '@ddd-ts-kit/kernel';
1371
+ import {
1372
+ acceptedSchema,
1373
+ Authenticated,
1374
+ Controller,
1375
+ RouteGroup,
1376
+ type Accepted,
1377
+ type HttpRequest,
1378
+ type IncomingFile,
1379
+ } from '@ddd-ts-kit/http';
1380
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
1381
+
1382
+ /** The command carries the file: the bus stages it before the transaction opens. */
1383
+ class AttachDocument extends AuthorizedCommand<string> {
1384
+ readonly document: FileUpload;
1385
+
1386
+ constructor(
1387
+ actor: Actor,
1388
+ readonly appointmentId: string,
1389
+ file: ReceivedFile,
1390
+ ) {
1391
+ super(actor);
1392
+ this.document = new FileUpload(file, 'appointment-documents');
1393
+ }
1394
+ }
1395
+
1396
+ @RouteGroup({ prefix: '/appointments', guards: [Authenticated] })
1397
+ export class AppointmentRoutes {}
1398
+
1399
+ const params = zodSchema(z.object({ appointmentId: z.string().min(1) }));
1400
+ const body = zodSchema(z.object({ note: z.string().max(200).optional() })); // the text fields, sent before the file
1401
+
1090
1402
  @Controller({
1091
1403
  group: AppointmentRoutes,
1092
1404
  method: 'POST',
1093
1405
  path: '/:appointmentId/document',
1094
1406
  summary: 'Attach a document to an appointment',
1095
1407
  params,
1096
- body, // the text fields, sent before the file
1408
+ body,
1097
1409
  upload: { field: 'document', maxBytes: 10_000_000, mediaTypes: ['application/pdf', 'image/*'] },
1098
- response: { status: 201, body: attached },
1410
+ response: { status: 201, body: acceptedSchema },
1099
1411
  })
1100
1412
  export class AttachDocumentController {
1101
1413
  constructor(private readonly commands: CommandBus) {}
1102
1414
 
1103
- async handle({ params, upload, actor }: HttpRequest<{ params: Params; upload: IncomingFile }>) {
1104
- return this.commands.execute(new AttachDocument(actor, params.appointmentId, upload));
1415
+ async handle({
1416
+ params,
1417
+ upload,
1418
+ actor,
1419
+ }: HttpRequest<{ params: { appointmentId: string }; upload: IncomingFile }>): Promise<Accepted> {
1420
+ await this.commands.execute(new AttachDocument(actor, params.appointmentId, upload));
1421
+
1422
+ return { id: params.appointmentId };
1105
1423
  }
1106
1424
  }
1107
1425
  ```
@@ -1109,9 +1427,17 @@ export class AttachDocumentController {
1109
1427
  The routes are mounted with an upload reader, `multipartUploads()` of `@ddd-ts-kit/http/uploads`
1110
1428
  (on busboy, an optional peer: `npm i busboy`):
1111
1429
 
1430
+ <!-- checked sample -->
1112
1431
  ```ts
1432
+ import type { Express } from 'express';
1433
+ import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1434
+ import { mountExpress } from '@ddd-ts-kit/http/express';
1113
1435
  import { multipartUploads } from '@ddd-ts-kit/http/uploads';
1114
1436
 
1437
+ declare const app: Express;
1438
+ declare const routes: readonly Route[];
1439
+ declare const options: ExecuteOptions;
1440
+
1115
1441
  mountExpress(app, routes, { ...options, uploads: multipartUploads() });
1116
1442
  ```
1117
1443
 
@@ -1145,8 +1471,9 @@ writes a file, and a route that declares no body schema is never refused 406.
1145
1471
 
1146
1472
  ## Limits
1147
1473
 
1148
- - A body the framework itself refuses (malformed JSON, payload too large) is answered by the
1149
- framework's own error handler, before the pipeline runs.
1474
+ - On Express, Fastify and NestJS, a body the framework itself refuses (malformed JSON, payload
1475
+ too large) is answered by the framework's own error handler, before the pipeline runs. The
1476
+ Hono adapter reads the body itself and answers both as problems (see "Hono 4").
1150
1477
  - Routes are JSON first. A handler may answer a string, bytes or a stream by setting its own
1151
1478
  `content-type` header, which no representation touches. A request body streams only as a
1152
1479
  declared upload or a raw body (`rawBody`): server-sent events and WebSockets are written