@ddd-ts-kit/http 0.99.0 → 0.101.0

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 (107) hide show
  1. package/README.fr.md +120 -9
  2. package/README.md +109 -7
  3. package/dist/error/answered-edge-error.d.ts +32 -0
  4. package/dist/error/answered-edge-error.d.ts.map +1 -0
  5. package/dist/error/answered-edge-error.js +79 -0
  6. package/dist/error/answered-edge-error.js.map +1 -0
  7. package/dist/error/code-of-status.d.ts +3 -0
  8. package/dist/error/code-of-status.d.ts.map +1 -0
  9. package/dist/error/code-of-status.js +7 -0
  10. package/dist/error/code-of-status.js.map +1 -0
  11. package/dist/error/edge-answer.d.ts +12 -0
  12. package/dist/error/edge-answer.d.ts.map +1 -0
  13. package/dist/error/edge-answer.js +18 -0
  14. package/dist/error/edge-answer.js.map +1 -0
  15. package/dist/error/edge-refusal.d.ts +15 -0
  16. package/dist/error/edge-refusal.d.ts.map +1 -0
  17. package/dist/error/edge-refusal.js +21 -0
  18. package/dist/error/edge-refusal.js.map +1 -0
  19. package/dist/error/refusal-headers.d.ts +9 -0
  20. package/dist/error/refusal-headers.d.ts.map +1 -0
  21. package/dist/error/refusal-headers.js +37 -0
  22. package/dist/error/refusal-headers.js.map +1 -0
  23. package/dist/error/status-title.d.ts.map +1 -1
  24. package/dist/error/status-title.js +2 -25
  25. package/dist/error/status-title.js.map +1 -1
  26. package/dist/error/statuses.d.ts +14 -0
  27. package/dist/error/statuses.d.ts.map +1 -0
  28. package/dist/error/statuses.js +33 -0
  29. package/dist/error/statuses.js.map +1 -0
  30. package/dist/express/mount-express.js +2 -1
  31. package/dist/express/mount-express.js.map +1 -1
  32. package/dist/express/problem-error-handler.d.ts +12 -0
  33. package/dist/express/problem-error-handler.d.ts.map +1 -0
  34. package/dist/express/problem-error-handler.js +22 -0
  35. package/dist/express/problem-error-handler.js.map +1 -0
  36. package/dist/express.d.ts +2 -0
  37. package/dist/express.d.ts.map +1 -1
  38. package/dist/express.js +1 -0
  39. package/dist/express.js.map +1 -1
  40. package/dist/fastify/mount-fastify.d.ts +4 -3
  41. package/dist/fastify/mount-fastify.d.ts.map +1 -1
  42. package/dist/fastify/mount-fastify.js +27 -4
  43. package/dist/fastify/mount-fastify.js.map +1 -1
  44. package/dist/fastify/problem-error-handler.d.ts +13 -0
  45. package/dist/fastify/problem-error-handler.d.ts.map +1 -0
  46. package/dist/fastify/problem-error-handler.js +15 -0
  47. package/dist/fastify/problem-error-handler.js.map +1 -0
  48. package/dist/fastify.d.ts +2 -0
  49. package/dist/fastify.d.ts.map +1 -1
  50. package/dist/fastify.js +1 -0
  51. package/dist/fastify.js.map +1 -1
  52. package/dist/hono/edge-problem.d.ts +1 -7
  53. package/dist/hono/edge-problem.d.ts.map +1 -1
  54. package/dist/hono/edge-problem.js +3 -11
  55. package/dist/hono/edge-problem.js.map +1 -1
  56. package/dist/hono/problem-error-handler.d.ts +12 -0
  57. package/dist/hono/problem-error-handler.d.ts.map +1 -0
  58. package/dist/hono/problem-error-handler.js +14 -0
  59. package/dist/hono/problem-error-handler.js.map +1 -0
  60. package/dist/hono/read-body.d.ts +1 -1
  61. package/dist/hono/read-body.d.ts.map +1 -1
  62. package/dist/hono/read-body.js +3 -16
  63. package/dist/hono/read-body.js.map +1 -1
  64. package/dist/hono.d.ts +2 -0
  65. package/dist/hono.d.ts.map +1 -1
  66. package/dist/hono.js +1 -0
  67. package/dist/hono.js.map +1 -1
  68. package/dist/nest/is-unread-json-body.d.ts +9 -0
  69. package/dist/nest/is-unread-json-body.d.ts.map +1 -0
  70. package/dist/nest/is-unread-json-body.js +26 -0
  71. package/dist/nest/is-unread-json-body.js.map +1 -0
  72. package/dist/nest/problem-exception-filter.d.ts +19 -0
  73. package/dist/nest/problem-exception-filter.d.ts.map +1 -0
  74. package/dist/nest/problem-exception-filter.js +45 -0
  75. package/dist/nest/problem-exception-filter.js.map +1 -0
  76. package/dist/nest.d.ts +2 -0
  77. package/dist/nest.d.ts.map +1 -1
  78. package/dist/nest.js +1 -0
  79. package/dist/nest.js.map +1 -1
  80. package/dist/pipeline/execute-route.d.ts.map +1 -1
  81. package/dist/pipeline/execute-route.js +1 -1
  82. package/dist/pipeline/execute-route.js.map +1 -1
  83. package/dist/pipeline/problem-content-type.d.ts +3 -0
  84. package/dist/pipeline/problem-content-type.d.ts.map +1 -0
  85. package/dist/pipeline/problem-content-type.js +3 -0
  86. package/dist/pipeline/problem-content-type.js.map +1 -0
  87. package/dist/testing/route-of-options.d.ts +18 -0
  88. package/dist/testing/route-of-options.d.ts.map +1 -0
  89. package/dist/testing/route-of-options.js +2 -0
  90. package/dist/testing/route-of-options.js.map +1 -0
  91. package/dist/testing/route-of.d.ts +21 -0
  92. package/dist/testing/route-of.d.ts.map +1 -0
  93. package/dist/testing/route-of.js +49 -0
  94. package/dist/testing/route-of.js.map +1 -0
  95. package/dist/testing/route-under-test.d.ts +13 -0
  96. package/dist/testing/route-under-test.d.ts.map +1 -0
  97. package/dist/testing/route-under-test.js +2 -0
  98. package/dist/testing/route-under-test.js.map +1 -0
  99. package/dist/testing/sent-request.d.ts +13 -0
  100. package/dist/testing/sent-request.d.ts.map +1 -0
  101. package/dist/testing/sent-request.js +2 -0
  102. package/dist/testing/sent-request.js.map +1 -0
  103. package/dist/testing.d.ts +5 -0
  104. package/dist/testing.d.ts.map +1 -0
  105. package/dist/testing.js +2 -0
  106. package/dist/testing.js.map +1 -0
  107. package/package.json +8 -4
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:6f250d2a07b22cea -->
2
+ <!-- translation-of: README.md sha256:313b907e9b6ead67 -->
3
3
 
4
4
  # @ddd-ts-kit/http
5
5
 
@@ -166,6 +166,7 @@ anonyme atteindre `handle`.
166
166
  | `HttpRequest<{ params, query, headers, body }>` | la requête HTTP telle que `handle`, un *mapper* ou une garde la nomment, avec `actor` et `context` |
167
167
  | `controllerRoutes(controllers, { resolve, security, guards })` | la `Route` de chaque contrôleur, donné comme classe (construite par `resolve`) ou comme instance ; `security` nomme les schémas de sécurité de l'application (`['bearer']` par défaut) ; `guards: 'skip'` sert à la *spec* d'un contrôleur seul |
168
168
  | `controllerRoute(controller, options)` | l'unique route d'un contrôleur, pour une *spec* |
169
+ | `routeOf(controller or route, options)` | (`@ddd-ts-kit/http/testing`) la route d'une *spec* et `send(request)`, par tout le pipeline au nom d'un `caller` authentifié, gardes comprises sauf si `guards: 'skip'` dit le contraire, réponses vérifiées : voir [La *spec* d'une route](#la-spec-dune-route--routeof) |
169
170
 
170
171
  Un contrôleur sans groupe et sans garde est refusé dès que sa classe est définie. Les gardes
171
172
  s'exécutent dans l'ordre, après la validation et avant `handle`, dans la portée d'exécution de
@@ -246,6 +247,68 @@ Passez les options de l'application en troisième argument (`validateResponses:
246
247
  tests, `resolvePrincipal` pour appeler au nom d'un acteur donné) : la réponse est celle que le
247
248
  serveur enverrait, en-têtes compris.
248
249
 
250
+ ### La *spec* d'une route : `routeOf`
251
+
252
+ `routeOf` de `@ddd-ts-kit/http/testing` est cet appel, réglé une fois pour toute une *spec* : il
253
+ prend un contrôleur (une instance, ou sa classe avec `resolve`) ou une route déjà construite
254
+ (`defineRoute`, `nestControllerRoute`), et `send` lui confie une requête, chaque partie omise
255
+ étant vide. Chaque requête traverse tout le pipeline, gardes comprises, au nom de `caller`, un
256
+ utilisateur authentifié (`user-1`, sans rôle) sauf si la *spec* en nomme un autre, et sa réponse
257
+ est vérifiée contre la déclaration (`validateResponses: true`). Les autres options
258
+ d'`executeRoute` (`errorMapper` par exemple) sont données une fois, à côté ; `guards: 'skip'`
259
+ laisse de côté les gardes d'un contrôleur, pour la *spec* qui le dit. La *spec* générée de chaque
260
+ route et de chaque contrôleur est écrite avec lui, et avec un bus enregistreur de
261
+ `@ddd-ts-kit/kernel/testing`, pour vérifier ce que le cas d'usage a reçu :
262
+
263
+ <!-- checked sample -->
264
+ ```ts
265
+ import { z } from 'zod';
266
+ import { AuthorizedCommand, type Actor, type CommandBus } from '@ddd-ts-kit/kernel';
267
+ import { Authenticated, Controller, RouteGroup, controllerRoutes, type HttpRequest } from '@ddd-ts-kit/http';
268
+ import type { Infer } from '@ddd-ts-kit/validation';
269
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
270
+
271
+ /** The command of the use case, in the application layer (its @Requires permission left out here). */
272
+ class PlaceOrder extends AuthorizedCommand<string> {
273
+ constructor(
274
+ actor: Actor,
275
+ readonly customerId: string,
276
+ ) {
277
+ super(actor);
278
+ }
279
+ }
280
+
281
+ const body = zodSchema(z.object({ customerId: z.string().min(1) }));
282
+ const placed = zodSchema(z.object({ id: z.string() }), { io: 'output' });
283
+
284
+ type PlaceOrderBody = Infer<typeof body>; // { customerId: string }
285
+ type Placed = Infer<typeof placed>; // { id: string }
286
+
287
+ @RouteGroup({ prefix: '/orders', tags: ['orders'], guards: [Authenticated], errors: ['FORBIDDEN'] })
288
+ export class OrdersRoutes {}
289
+
290
+ @Controller({
291
+ group: OrdersRoutes,
292
+ method: 'POST',
293
+ path: '/',
294
+ summary: 'Place an order',
295
+ body,
296
+ response: { status: 201, body: placed },
297
+ errors: ['OUT_OF_STOCK'],
298
+ })
299
+ export class PlaceOrderController {
300
+ constructor(private readonly commands: CommandBus) {}
301
+
302
+ async handle({ body, actor }: HttpRequest<{ body: PlaceOrderBody }>): Promise<Placed> {
303
+ return { id: await this.commands.execute(new PlaceOrder(actor, body.customerId)) };
304
+ }
305
+ }
306
+
307
+ declare const application: { resolve<T>(target: abstract new (...args: never) => T): T };
308
+
309
+ export const routes = controllerRoutes([PlaceOrderController], { resolve: application.resolve });
310
+ ```
311
+
249
312
  ## Cache HTTP
250
313
 
251
314
  Une lecture dit comment les caches sur le trajet peuvent garder sa réponse, sur son contrôleur,
@@ -1207,34 +1270,64 @@ généré par la CLI les écrit dans `openapi/forms/<operationId>.json` à côt
1207
1270
  ```ts
1208
1271
  import express from 'express';
1209
1272
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1210
- import { mountExpress } from '@ddd-ts-kit/http/express';
1273
+ import type { Logger } from '@ddd-ts-kit/kernel';
1274
+ import { mountExpress, problemErrorHandler } from '@ddd-ts-kit/http/express';
1211
1275
 
1212
1276
  declare const routes: readonly Route[]; // defineRoutes(...), controllerRoutes(...)
1213
1277
  declare const options: ExecuteOptions;
1278
+ declare const logger: Logger;
1214
1279
 
1215
1280
  const app = express();
1216
1281
  app.use(express.json()); // obligatoire : l'adaptateur n'analyse pas les corps
1217
1282
  mountExpress(app, routes, options); // un express.Router() convient aussi
1283
+ app.use(problemErrorHandler({ logger })); // en dernier : ce qu'Express refuse avant une route
1218
1284
  app.listen(3000);
1219
1285
  ```
1220
1286
 
1287
+ `problemErrorHandler` répond sous forme de *problem* à ce qui atteint Express avant une route du
1288
+ kit : un corps que `express.json()` ne sait pas analyser reçoit un 400 `MALFORMED_BODY`, un corps
1289
+ au-delà de sa limite (100 ko par défaut) un 413 `BODY_TOO_LARGE`, une autre erreur porteuse d'un
1290
+ statut (`status` ou `statusCode`, 4xx ou 5xx) ce statut, avec le code que le kit lui donne
1291
+ (`UNAUTHORIZED`, `VALIDATION_FAILED` pour 422, `SERVICE_UNAVAILABLE` pour le 503 d'un stockage
1292
+ en panne) et les en-têtes qu'elle porte pour son client (`WWW-Authenticate`, `Allow`,
1293
+ `Retry-After`), et toute autre erreur qu'un middleware passe à `next` un 500 `INTERNAL_ERROR`,
1294
+ sans rien de son message. Un corps vide atteint la route comme absent (`undefined`), comme sur
1295
+ chaque framework, pour que sa validation décide. Sans lui, le gestionnaire final d'Express répond une page HTML, avec la pile
1296
+ hors production, et écrit l'erreur sur stderr, corps cité compris. Le gestionnaire écrit dans
1297
+ `logger` le type de l'erreur (`entity.parse.failed`), le statut et l'identifiant de la requête,
1298
+ jamais le message ni le corps : un refus comme avertissement, une panne comme erreur.
1299
+
1221
1300
  ## Fastify 5
1222
1301
 
1223
1302
  <!-- checked sample -->
1224
1303
  ```ts
1225
1304
  import Fastify from 'fastify';
1226
1305
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1227
- import { fastifyRoutes, mountFastify } from '@ddd-ts-kit/http/fastify';
1306
+ import type { Logger } from '@ddd-ts-kit/kernel';
1307
+ import { fastifyRoutes, mountFastify, problemErrorHandler } from '@ddd-ts-kit/http/fastify';
1228
1308
 
1229
1309
  declare const routes: readonly Route[];
1230
1310
  declare const options: ExecuteOptions;
1311
+ declare const logger: Logger;
1231
1312
 
1232
1313
  const app = Fastify();
1314
+ app.setErrorHandler(problemErrorHandler({ logger })); // en premier : ce que Fastify refuse avant une route
1233
1315
  mountFastify(app, routes, options);
1234
1316
  // ou, comme plugin :
1235
1317
  await app.register(fastifyRoutes(routes, options), { prefix: '/api' });
1236
1318
  ```
1237
1319
 
1320
+ `problemErrorHandler` de `@ddd-ts-kit/http/fastify` fait sur Fastify ce que fait celui
1321
+ d'Express : un corps que son analyseur refuse reçoit un 400 `MALFORMED_BODY`, un corps au-delà de
1322
+ `bodyLimit` (1 Mio par défaut) un 413 `BODY_TOO_LARGE`, un type de média qu'aucun analyseur ne
1323
+ lit un 415 `UNSUPPORTED_MEDIA_TYPE`, un hook qui lève une erreur le statut qu'elle porte ou un
1324
+ 500 `INTERNAL_ERROR`, ses en-têtes gardés comme sur Express, au lieu
1325
+ de `{ statusCode, code, error, message }`, qui porte au client le message d'une erreur
1326
+ inattendue. Installez-le avant de monter les routes. L'analyseur de Fastify refuse un corps JSON
1327
+ vide, qu'Express et Hono transmettent comme absent : `mountFastify` enregistre les routes dans un
1328
+ contexte à elles où un corps vide les atteint comme absent, tout autre corps lu par l'analyseur
1329
+ JSON de Fastify.
1330
+
1238
1331
  ## Hono 4
1239
1332
 
1240
1333
  <!-- checked sample -->
@@ -1242,12 +1335,15 @@ await app.register(fastifyRoutes(routes, options), { prefix: '/api' });
1242
1335
  import { serve } from '@hono/node-server';
1243
1336
  import { Hono } from 'hono';
1244
1337
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1245
- import { mountHono } from '@ddd-ts-kit/http/hono';
1338
+ import type { Logger } from '@ddd-ts-kit/kernel';
1339
+ import { mountHono, problemErrorHandler } from '@ddd-ts-kit/http/hono';
1246
1340
 
1247
1341
  declare const routes: readonly Route[];
1248
1342
  declare const options: ExecuteOptions;
1343
+ declare const logger: Logger;
1249
1344
 
1250
1345
  const app = new Hono();
1346
+ app.onError(problemErrorHandler({ logger })); // un middleware qui lève une erreur, répondu en problem
1251
1347
  mountHono(app, routes, { ...options, bodyLimit: 2 * 1024 * 1024 }); // bodyLimit : 1 Mio par défaut
1252
1348
  serve({ fetch: app.fetch, port: 3000 });
1253
1349
  ```
@@ -1260,7 +1356,10 @@ un type de média que la route consomme (`consumes`) est lu comme du texte sous
1260
1356
  pour sa représentation ; un autre type de média n'est pas lu, et le pipeline répond 415 quand des
1261
1357
  représentations sont montées. Un téléversement et un corps brut sont lus depuis le flux de la
1262
1358
  requête HTTP, avec les limites que déclare leur route, et une réponse en flux ou une liste en flux
1263
- est envoyée en flux. Une requête HTTP porte `HonoRaw`
1359
+ est envoyée en flux. Un middleware placé devant les routes qui lève une erreur reçoit sa réponse
1360
+ sous forme de *problem* de `problemErrorHandler`, un 500 `INTERNAL_ERROR` ou le statut d'une
1361
+ `HTTPException` avec les en-têtes de sa réponse, journalisé comme sur Express, au lieu d'un texte
1362
+ avec l'erreur écrite sur stderr. Une requête HTTP porte `HonoRaw`
1264
1363
  comme requête brute (ses en-têtes sous forme d'objet, que lisent les authentificateurs du kit,
1265
1364
  et le `Context` de Hono), et un paramètre de chaîne de requête répété est une liste, comme sur
1266
1365
  Express et Fastify. L'adaptateur n'importe rien de Hono à l'exécution, et `node:stream` pour les
@@ -1301,6 +1400,17 @@ contournent les pipes, les guards, les intercepteurs, les filtres d'exceptions e
1301
1400
  global de Nest : la validation et la correspondance des erreurs sont celles décrites plus haut.
1302
1401
  Utilisez `prefixRoutes` pour un préfixe.
1303
1402
 
1403
+ Ce qui atteint Nest avant une route du kit, un corps que son analyseur refuse, un chemin
1404
+ qu'aucune route ne sert, un middleware en échec, reçoit sa réponse du filtre d'exceptions de
1405
+ Nest, `{ statusCode, message }`, un message qui peut citer le corps, et est journalisé en entier.
1406
+ `ProblemExceptionFilter` y répond plutôt sous forme de *problem*, sur Express comme sur Fastify,
1407
+ et le journalise comme `problemErrorHandler` :
1408
+ `app.useGlobalFilters(new ProblemExceptionFilter(app.getHttpAdapter(), { logger }))`. Un corps
1409
+ trop grand reçoit un 413 `BODY_TOO_LARGE`, un chemin qu'aucune route ne sert un 404 `NOT_FOUND`,
1410
+ un corps qui n'est pas du JSON un 400 `MALFORMED_BODY` comme sur les autres frameworks : Nest
1411
+ enveloppe l'erreur de son analyseur dans une exception à lui avant tout filtre, que le filtre
1412
+ reconnaît à son statut, à son message et à une requête JSON dont le corps n'a jamais été lu.
1413
+
1304
1414
  ### Contrôleurs Nest servis par le kit
1305
1415
 
1306
1416
  Un projet qui écrit des contrôleurs Nest les garde : `@Controller`, `@Get`, `@Post` et les autres
@@ -1335,7 +1445,7 @@ declare const invoicing: Invoicing;
1335
1445
  class IssueInvoiceBody {
1336
1446
  @IsString()
1337
1447
  @MinLength(1)
1338
- customerId = '';
1448
+ declare customerId: string;
1339
1449
  }
1340
1450
 
1341
1451
  @Controller('invoices')
@@ -1773,9 +1883,10 @@ schéma de corps n'est jamais refusée par un 406.
1773
1883
  ## Limites
1774
1884
 
1775
1885
  - Sur Express, Fastify et NestJS, un corps que le framework refuse lui-même (JSON mal formé,
1776
- charge trop grande) reçoit sa réponse du gestionnaire d'erreurs du framework, avant que le
1777
- pipeline s'exécute. L'adaptateur Hono lit lui-même le corps et répond aux deux cas par des
1778
- *problems* (voir « Hono 4 »).
1886
+ charge trop grande) est refusé avant que le pipeline s'exécute : il reçoit un *problem* une fois
1887
+ `problemErrorHandler` ou `ProblemExceptionFilter` installé, la réponse du gestionnaire
1888
+ d'erreurs du framework sinon. L'adaptateur Hono lit lui-même le corps et répond aux deux cas
1889
+ par des *problems* (voir « Hono 4 »).
1779
1890
  - Les routes sont d'abord JSON. Un gestionnaire peut répondre un texte, des octets ou un flux en
1780
1891
  fixant son propre en-tête `content-type`, auquel aucune représentation ne touche. Un corps de
1781
1892
  requête HTTP n'est reçu en flux que comme téléversement déclaré ou comme corps brut
package/README.md CHANGED
@@ -157,6 +157,7 @@ It answers 201 with `{ id }`, documents `OUT_OF_STOCK` (its own), `FORBIDDEN` (i
157
157
  | `HttpRequest<{ params, query, headers, body }>` | the request as `handle`, a mapper or a guard names it, with `actor` and `context` |
158
158
  | `controllerRoutes(controllers, { resolve, security, guards })` | the `Route` of each controller, given as a class (built by `resolve`) or as an instance; `security` names the schemes of the application (`['bearer']` by default); `guards: 'skip'` is for the spec of a controller alone |
159
159
  | `controllerRoute(controller, options)` | the one route of one controller, for a spec |
160
+ | `routeOf(controller or route, options)` | (`@ddd-ts-kit/http/testing`) the route of a spec and `send(request)`, through the whole pipeline as an authenticated `caller`, guards included unless `guards: 'skip'` says otherwise, answers checked: see [The spec of a route](#the-spec-of-a-route-routeof) |
160
161
 
161
162
  A controller with no group and no guard is refused when its class is defined. Guards run in
162
163
  order, after validation and before `handle`, inside the execution scope of the request, and
@@ -233,6 +234,62 @@ Pass the options of the application as the third argument (`validateResponses: t
233
234
  tests, `resolvePrincipal` to call as a given actor): the answer is the one the server would
234
235
  send, headers included.
235
236
 
237
+ ### The spec of a route: `routeOf`
238
+
239
+ `routeOf` of `@ddd-ts-kit/http/testing` is that call, set once for a whole spec: it takes a
240
+ controller (an instance, or its class with `resolve`) or a route already built (`defineRoute`,
241
+ `nestControllerRoute`), and `send` hands it one request, each part left out empty. Every request
242
+ goes through the whole pipeline, guards included, as `caller`, an authenticated user (`user-1`,
243
+ no role) unless the spec names another one, and its answer is checked against the declaration
244
+ (`validateResponses: true`). The other options of `executeRoute` (`errorMapper` for one) are
245
+ given once, beside it; `guards: 'skip'` leaves the guards of a controller out, for the spec that
246
+ says so. The generated spec of every route and controller is written with it, and with a
247
+ recording bus of `@ddd-ts-kit/kernel/testing`, so that it asserts what the use case was handed:
248
+
249
+ <!-- checked sample -->
250
+ ```ts
251
+ import { z } from 'zod';
252
+ import { AuthorizedCommand, type Actor, type CommandBus } from '@ddd-ts-kit/kernel';
253
+ import { RecordingCommandBus } from '@ddd-ts-kit/kernel/testing';
254
+ import { defineRoute } from '@ddd-ts-kit/http';
255
+ import { routeOf } from '@ddd-ts-kit/http/testing';
256
+ import { zodSchema } from '@ddd-ts-kit/validation/zod';
257
+
258
+ class CancelOrderCommand extends AuthorizedCommand {
259
+ constructor(
260
+ actor: Actor,
261
+ readonly orderId: string,
262
+ ) {
263
+ super(actor);
264
+ }
265
+ }
266
+
267
+ const cancelOrderRoute = (commands: CommandBus) =>
268
+ defineRoute(
269
+ {
270
+ method: 'POST',
271
+ path: '/orders/:orderId/cancellation',
272
+ operationId: 'cancelOrder',
273
+ summary: 'Cancel an order',
274
+ request: { params: zodSchema(z.object({ orderId: z.string().min(1) })) },
275
+ responses: { 204: { description: 'Done.' } },
276
+ security: ['bearer'],
277
+ },
278
+ async ({ params, context }) => {
279
+ await commands.execute(new CancelOrderCommand(context.execution.actor, params.orderId));
280
+
281
+ return { status: 204 };
282
+ },
283
+ );
284
+
285
+ const commands = new RecordingCommandBus();
286
+ const { caller, send } = routeOf(cancelOrderRoute(commands));
287
+
288
+ export const response = await send({ params: { orderId: 'order-1' } }); // 204
289
+ export const handed = commands.executed; // [new CancelOrderCommand(caller, 'order-1')]
290
+ export const sentBy = caller;
291
+ ```
292
+
236
293
  ## HTTP caching
237
294
 
238
295
  A read says how the caches on the way may keep its answer, on its controller, on its route
@@ -1157,34 +1214,62 @@ both formats, for the documentation: a project generated by the CLI writes them
1157
1214
  ```ts
1158
1215
  import express from 'express';
1159
1216
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1160
- import { mountExpress } from '@ddd-ts-kit/http/express';
1217
+ import type { Logger } from '@ddd-ts-kit/kernel';
1218
+ import { mountExpress, problemErrorHandler } from '@ddd-ts-kit/http/express';
1161
1219
 
1162
1220
  declare const routes: readonly Route[]; // defineRoutes(...), controllerRoutes(...)
1163
1221
  declare const options: ExecuteOptions;
1222
+ declare const logger: Logger;
1164
1223
 
1165
1224
  const app = express();
1166
1225
  app.use(express.json()); // required: the adapter does not parse bodies
1167
1226
  mountExpress(app, routes, options); // an express.Router() works too
1227
+ app.use(problemErrorHandler({ logger })); // last: what Express refuses before a route
1168
1228
  app.listen(3000);
1169
1229
  ```
1170
1230
 
1231
+ `problemErrorHandler` answers as a problem what reaches Express before a route of the kit: a body
1232
+ `express.json()` cannot parse is 400 `MALFORMED_BODY`, a body over its limit (100 kB by default)
1233
+ 413 `BODY_TOO_LARGE`, another error that carries a status (`status` or `statusCode`, 4xx or 5xx)
1234
+ that status, with the code the kit gives it (`UNAUTHORIZED`, `VALIDATION_FAILED` for 422,
1235
+ `SERVICE_UNAVAILABLE` for the 503 of a store down) and the headers it carries for its client
1236
+ (`WWW-Authenticate`, `Allow`, `Retry-After`), and any other error a middleware passes to `next`
1237
+ 500 `INTERNAL_ERROR`, with nothing of its message. An empty body reaches the route as absent
1238
+ (`undefined`), as on every framework, for its validation to decide. Without it, the final handler of Express
1239
+ answers an HTML page, with the stack outside production, and writes the error to stderr, the
1240
+ body it quotes included. The handler writes to `logger` the type of the error
1241
+ (`entity.parse.failed`), the status and the request id, never the message nor the body: a
1242
+ refusal as a warning, a failure as an error.
1243
+
1171
1244
  ## Fastify 5
1172
1245
 
1173
1246
  <!-- checked sample -->
1174
1247
  ```ts
1175
1248
  import Fastify from 'fastify';
1176
1249
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1177
- import { fastifyRoutes, mountFastify } from '@ddd-ts-kit/http/fastify';
1250
+ import type { Logger } from '@ddd-ts-kit/kernel';
1251
+ import { fastifyRoutes, mountFastify, problemErrorHandler } from '@ddd-ts-kit/http/fastify';
1178
1252
 
1179
1253
  declare const routes: readonly Route[];
1180
1254
  declare const options: ExecuteOptions;
1255
+ declare const logger: Logger;
1181
1256
 
1182
1257
  const app = Fastify();
1258
+ app.setErrorHandler(problemErrorHandler({ logger })); // first: what Fastify refuses before a route
1183
1259
  mountFastify(app, routes, options);
1184
1260
  // or, as a plugin:
1185
1261
  await app.register(fastifyRoutes(routes, options), { prefix: '/api' });
1186
1262
  ```
1187
1263
 
1264
+ `problemErrorHandler` of `@ddd-ts-kit/http/fastify` does on Fastify what the one of Express does:
1265
+ a body its parser refuses is 400 `MALFORMED_BODY`, a body over `bodyLimit` (1 MiB by default)
1266
+ 413 `BODY_TOO_LARGE`, a media type no parser reads 415 `UNSUPPORTED_MEDIA_TYPE`, a hook that
1267
+ throws the status it carries or 500 `INTERNAL_ERROR`, with its headers kept as on Express, instead of `{ statusCode, code, error, message }`, which carries the
1268
+ message of an unexpected error to the client. Set it before the routes are mounted. The parser
1269
+ of Fastify refuses an empty JSON body, which Express and Hono hand over as absent: `mountFastify`
1270
+ registers the routes in a context of their own where an empty body reaches them as absent, any
1271
+ other read by the JSON parser of Fastify.
1272
+
1188
1273
  ## Hono 4
1189
1274
 
1190
1275
  <!-- checked sample -->
@@ -1192,12 +1277,15 @@ await app.register(fastifyRoutes(routes, options), { prefix: '/api' });
1192
1277
  import { serve } from '@hono/node-server';
1193
1278
  import { Hono } from 'hono';
1194
1279
  import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
1195
- import { mountHono } from '@ddd-ts-kit/http/hono';
1280
+ import type { Logger } from '@ddd-ts-kit/kernel';
1281
+ import { mountHono, problemErrorHandler } from '@ddd-ts-kit/http/hono';
1196
1282
 
1197
1283
  declare const routes: readonly Route[];
1198
1284
  declare const options: ExecuteOptions;
1285
+ declare const logger: Logger;
1199
1286
 
1200
1287
  const app = new Hono();
1288
+ app.onError(problemErrorHandler({ logger })); // a middleware that throws, answered as a problem
1201
1289
  mountHono(app, routes, { ...options, bodyLimit: 2 * 1024 * 1024 }); // bodyLimit: 1 MiB by default
1202
1290
  serve({ fetch: app.fetch, port: 3000 });
1203
1291
  ```
@@ -1209,7 +1297,9 @@ without holding the body whole. A body in a media type the route consumes (`cons
1209
1297
  as text under the same limit, for its representation; another media type is not read, and the
1210
1298
  pipeline answers 415 when representations are mounted. An upload and a raw body are read from
1211
1299
  the request stream, with the limits their route declares, and a stream answer or a streamed
1212
- list is streamed. A request carries `HonoRaw` as
1300
+ list is streamed. A middleware in front of the routes that throws is answered as a problem by
1301
+ `problemErrorHandler`, 500 `INTERNAL_ERROR` or the status of an `HTTPException` with the headers
1302
+ of its response, logged as on Express, instead of a text with the error written to stderr. A request carries `HonoRaw` as
1213
1303
  its raw request (its headers as a record, which the authenticators of the kit read, and the
1214
1304
  `Context` of Hono), and a repeated query parameter is a list, as on Express and Fastify. The
1215
1305
  adapter imports nothing of Hono at run time and `node:stream` for the streams: the kit proves
@@ -1248,6 +1338,16 @@ A plain array works as well: `createRoutesModule(routes, options)`. These routes
1248
1338
  pipes, guards, interceptors, exception filters and global prefix: validation and error mapping
1249
1339
  are those described above. Use `prefixRoutes` for a prefix.
1250
1340
 
1341
+ What reaches Nest before a route of the kit, a body its parser refuses, a path no route serves,
1342
+ a middleware that fails, is answered by the exception filter of Nest with `{ statusCode, message }`,
1343
+ a message that may quote the body, and logged whole. `ProblemExceptionFilter` answers it as a
1344
+ problem instead, on Express and on Fastify, and logs it as `problemErrorHandler` does:
1345
+ `app.useGlobalFilters(new ProblemExceptionFilter(app.getHttpAdapter(), { logger }))`. A body too
1346
+ large is 413 `BODY_TOO_LARGE`, a path no route serves 404 `NOT_FOUND`, a body that is not JSON
1347
+ 400 `MALFORMED_BODY` as on the other frameworks: Nest wraps the error of its parser in an
1348
+ exception of its own before any filter, which the filter tells by its status, its message and a
1349
+ JSON request whose body was never read.
1350
+
1251
1351
  ### Nest controllers served by the kit
1252
1352
 
1253
1353
  A project that writes Nest controllers keeps them: `@Controller`, `@Get`, `@Post` and the other
@@ -1281,7 +1381,7 @@ declare const invoicing: Invoicing;
1281
1381
  class IssueInvoiceBody {
1282
1382
  @IsString()
1283
1383
  @MinLength(1)
1284
- customerId = '';
1384
+ declare customerId: string;
1285
1385
  }
1286
1386
 
1287
1387
  @Controller('invoices')
@@ -1705,8 +1805,10 @@ writes a file, and a route that declares no body schema is never refused 406.
1705
1805
  ## Limits
1706
1806
 
1707
1807
  - On Express, Fastify and NestJS, a body the framework itself refuses (malformed JSON, payload
1708
- too large) is answered by the framework's own error handler, before the pipeline runs. The
1709
- Hono adapter reads the body itself and answers both as problems (see "Hono 4").
1808
+ too large) is refused before the pipeline runs: it is answered as a problem once
1809
+ `problemErrorHandler` or `ProblemExceptionFilter` is installed, by the framework's own error
1810
+ handler otherwise. The Hono adapter reads the body itself and answers both as problems (see
1811
+ "Hono 4").
1710
1812
  - Routes are JSON first. A handler may answer a string, bytes or a stream by setting its own
1711
1813
  `content-type` header, which no representation touches. A request body streams only as a
1712
1814
  declared upload or a raw body (`rawBody`): server-sent events and WebSockets are written
@@ -0,0 +1,32 @@
1
+ import { type Logger } from '@ddd-ts-kit/kernel';
2
+ import type { RawHeaders } from '../route/raw-headers.js';
3
+ import { type EdgeAnswer } from './edge-answer.js';
4
+ import { type EdgeRefusal } from './edge-refusal.js';
5
+ export interface EdgeErrorOptions {
6
+ /**
7
+ * Where each error is written: its type (`entity.parse.failed`, `FST_ERR_CTP_BODY_TOO_LARGE`,
8
+ * the class of an unexpected error), the status answered and the request id, never its message
9
+ * nor the body, which may quote personal data. A refusal is a warning, a failure an error.
10
+ * Left out, nothing is written.
11
+ */
12
+ readonly logger?: Logger;
13
+ }
14
+ /** What reached the framework, and the request it came with. */
15
+ export interface EdgeError {
16
+ readonly error: unknown;
17
+ readonly headers: Readonly<RawHeaders>;
18
+ /** What the error is, when the adapter knows better than the error says (Nest wraps the error of its parser). */
19
+ readonly refusal?: EdgeRefusal;
20
+ }
21
+ /**
22
+ * The answer to an error the framework raised before a route of the kit ran, or a middleware
23
+ * passed on: a body refused by its parser, the failure of a middleware. A body that is not JSON
24
+ * is `MALFORMED_BODY` (400), an error with the status 413 `BODY_TOO_LARGE`, another error that
25
+ * carries a status of a refusal or of a failure (`status` or `statusCode`, 4xx or 5xx) that
26
+ * status, its code the one the kit gives it (`NOT_FOUND`, `VALIDATION_FAILED` for 422,
27
+ * `SERVICE_UNAVAILABLE` for the 503 of a store down), anything else `INTERNAL_ERROR` (500). The
28
+ * message of the error is never answered: a parser quotes the body in it. The headers an error with
29
+ * a status carries for its client (`WWW-Authenticate`, `Allow`, `Retry-After`) are kept.
30
+ */
31
+ export declare function answeredEdgeError({ error, headers, refusal }: EdgeError, options: EdgeErrorOptions): EdgeAnswer;
32
+ //# sourceMappingURL=answered-edge-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answered-edge-error.d.ts","sourceRoot":"","sources":["../../src/error/answered-edge-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EAAE,KAAK,UAAU,EAAc,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAgB,KAAK,WAAW,EAAkB,MAAM,gBAAgB,CAAC;AAKhF,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,gEAAgE;AAChE,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC;IACvC,iHAAiH;IACjH,QAAQ,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC;CAChC;AAaD;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,GAAG,UAAU,CAc/G"}
@@ -0,0 +1,79 @@
1
+ import { identifyError } from '@ddd-ts-kit/kernel';
2
+ import { codeOfStatus } from './code-of-status.js';
3
+ import { edgeAnswer } from './edge-answer.js';
4
+ import { bodyTooLarge, MALFORMED_BODY } from './edge-refusal.js';
5
+ import { INTERNAL_ERROR_CODE } from './internal-error-code.js';
6
+ import { refusalHeaders } from './refusal-headers.js';
7
+ import { statusTitle } from './status-title.js';
8
+ /** What `express.json()` (body-parser) and the parser of Fastify name a body that is not JSON; an empty body is not one. */
9
+ const MALFORMED_KINDS = new Set(['entity.parse.failed', 'FST_ERR_CTP_INVALID_JSON_BODY']);
10
+ const KIND = /^[A-Za-z0-9_.]{1,64}$/;
11
+ const CONTENT_TOO_LARGE = 413;
12
+ const FIRST_REFUSAL = 400;
13
+ const LAST_FAILURE = 599;
14
+ const INTERNAL = { status: 500, title: statusTitle(500), code: INTERNAL_ERROR_CODE };
15
+ /**
16
+ * The answer to an error the framework raised before a route of the kit ran, or a middleware
17
+ * passed on: a body refused by its parser, the failure of a middleware. A body that is not JSON
18
+ * is `MALFORMED_BODY` (400), an error with the status 413 `BODY_TOO_LARGE`, another error that
19
+ * carries a status of a refusal or of a failure (`status` or `statusCode`, 4xx or 5xx) that
20
+ * status, its code the one the kit gives it (`NOT_FOUND`, `VALIDATION_FAILED` for 422,
21
+ * `SERVICE_UNAVAILABLE` for the 503 of a store down), anything else `INTERNAL_ERROR` (500). The
22
+ * message of the error is never answered: a parser quotes the body in it. The headers an error with
23
+ * a status carries for its client (`WWW-Authenticate`, `Allow`, `Retry-After`) are kept.
24
+ */
25
+ export function answeredEdgeError({ error, headers, refusal }, options) {
26
+ const refused = edgeAnswer(headers, refusal ?? refusalOf(error));
27
+ // The headers of the refusal under those of the problem: a challenge kept, the media type and the identifiers the problem's.
28
+ const kept = statusOf(error) === undefined ? {} : refusalHeaders(error);
29
+ const answer = { ...refused, headers: { ...kept, ...refused.headers } };
30
+ const fields = { errorType: typeOf(error), status: answer.status, requestId: answer.problem.requestId };
31
+ if (answer.status >= 500) {
32
+ options.logger?.error('request failed before its route', fields);
33
+ }
34
+ else {
35
+ options.logger?.warn('request refused before its route', fields);
36
+ }
37
+ return answer;
38
+ }
39
+ function refusalOf(error) {
40
+ const kind = kindOf(error);
41
+ if (kind !== undefined && MALFORMED_KINDS.has(kind)) {
42
+ return MALFORMED_BODY;
43
+ }
44
+ const status = statusOf(error);
45
+ if (status === undefined) {
46
+ return INTERNAL;
47
+ }
48
+ if (status === CONTENT_TOO_LARGE) {
49
+ return bodyTooLarge(numberAt(error, 'limit'));
50
+ }
51
+ return { status, title: statusTitle(status), code: codeOfStatus(status) };
52
+ }
53
+ /** The status the error carries (`status`, else `statusCode`), when it is one of a refusal or of a failure. */
54
+ function statusOf(error) {
55
+ const status = numberAt(error, 'status') ?? numberAt(error, 'statusCode');
56
+ return status !== undefined && Number.isInteger(status) && status >= FIRST_REFUSAL && status <= LAST_FAILURE
57
+ ? status
58
+ : undefined;
59
+ }
60
+ /** The `type` body-parser gives its errors, else the `code` of a Fastify error. */
61
+ function kindOf(error) {
62
+ const kind = textAt(error, 'type') ?? textAt(error, 'code');
63
+ return kind !== undefined && KIND.test(kind) ? kind : undefined;
64
+ }
65
+ function typeOf(error) {
66
+ return kindOf(error) ?? identifyError(error).errorType;
67
+ }
68
+ function textAt(error, key) {
69
+ const value = valueAt(error, key);
70
+ return typeof value === 'string' ? value : undefined;
71
+ }
72
+ function numberAt(error, key) {
73
+ const value = valueAt(error, key);
74
+ return typeof value === 'number' ? value : undefined;
75
+ }
76
+ function valueAt(error, key) {
77
+ return typeof error === 'object' && error !== null ? Reflect.get(error, key) : undefined;
78
+ }
79
+ //# sourceMappingURL=answered-edge-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answered-edge-error.js","sourceRoot":"","sources":["../../src/error/answered-edge-error.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,3 @@
1
+ /** The code of a problem answered with `status` and nothing more precise: a bad request, or an internal error, when the kit does not name it. */
2
+ export declare function codeOfStatus(status: number): string;
3
+ //# sourceMappingURL=code-of-status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-of-status.d.ts","sourceRoot":"","sources":["../../src/error/code-of-status.ts"],"names":[],"mappings":"AAGA,iJAAiJ;AACjJ,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnD"}
@@ -0,0 +1,7 @@
1
+ import { INTERNAL_ERROR_CODE } from './internal-error-code.js';
2
+ import { FIRST_SERVER_STATUS, STATUSES } from './statuses.js';
3
+ /** The code of a problem answered with `status` and nothing more precise: a bad request, or an internal error, when the kit does not name it. */
4
+ export function codeOfStatus(status) {
5
+ return STATUSES[status]?.code ?? (status >= FIRST_SERVER_STATUS ? INTERNAL_ERROR_CODE : 'BAD_REQUEST');
6
+ }
7
+ //# sourceMappingURL=code-of-status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-of-status.js","sourceRoot":"","sources":["../../src/error/code-of-status.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3D,iJAAiJ;AACjJ,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,IAAI,CAAC,MAAM,IAAI,mBAAmB,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC;AACzG,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { RawHeaders } from '../route/raw-headers.js';
2
+ import type { EdgeRefusal } from './edge-refusal.js';
3
+ import type { Problem } from './problem.js';
4
+ /** What a request refused before the pipeline receives: a problem document, as every other refusal. */
5
+ export interface EdgeAnswer {
6
+ readonly status: number;
7
+ readonly headers: Readonly<Record<string, string>>;
8
+ readonly problem: Problem;
9
+ }
10
+ /** The problem of the refusal, with the identifiers of the request the pipeline would have given it. */
11
+ export declare function edgeAnswer(headers: Readonly<RawHeaders>, refusal: EdgeRefusal): EdgeAnswer;
12
+ //# sourceMappingURL=edge-answer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edge-answer.d.ts","sourceRoot":"","sources":["../../src/error/edge-answer.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEzC,uGAAuG;AACvG,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAED,wGAAwG;AACxG,wBAAgB,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,WAAW,GAAG,UAAU,CAY1F"}
@@ -0,0 +1,18 @@
1
+ import { correlationIdOf } from '../pipeline/correlation-id-of.js';
2
+ import { CORRELATION_HEADER } from '../pipeline/correlation-header.js';
3
+ import { PROBLEM_CONTENT_TYPE } from '../pipeline/problem-content-type.js';
4
+ import { wellFormedIdentifier } from '../pipeline/well-formed-identifier.js';
5
+ /** The problem of the refusal, with the identifiers of the request the pipeline would have given it. */
6
+ export function edgeAnswer(headers, refusal) {
7
+ const requestId = wellFormedIdentifier(headers['x-request-id']) ?? globalThis.crypto.randomUUID();
8
+ return {
9
+ status: refusal.status,
10
+ headers: {
11
+ 'content-type': PROBLEM_CONTENT_TYPE,
12
+ 'x-request-id': requestId,
13
+ [CORRELATION_HEADER]: correlationIdOf(headers, requestId),
14
+ },
15
+ problem: { type: 'about:blank', ...refusal, requestId },
16
+ };
17
+ }
18
+ //# sourceMappingURL=edge-answer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edge-answer.js","sourceRoot":"","sources":["../../src/error/edge-answer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAY1E,wGAAwG;AACxG,MAAM,UAAU,UAAU,CAAC,OAA6B,EAAE,OAAoB;IAC5E,MAAM,SAAS,GAAG,oBAAoB,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;IAElG,OAAO;QACL,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE;YACP,cAAc,EAAE,oBAAoB;YACpC,cAAc,EAAE,SAAS;YACzB,CAAC,kBAAkB,CAAC,EAAE,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC;SAC1D;QACD,OAAO,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE;KACxD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * A request refused before the pipeline runs, by an adapter or by the framework under it: a body
3
+ * that is not JSON, a body too large. Its status, its code and, when it says nothing of the
4
+ * request, what is wrong.
5
+ */
6
+ export interface EdgeRefusal {
7
+ readonly status: number;
8
+ readonly title: string;
9
+ readonly code: string;
10
+ readonly detail?: string;
11
+ }
12
+ export declare const MALFORMED_BODY: EdgeRefusal;
13
+ /** A body beyond what the server reads: the limit is said when the framework tells it. */
14
+ export declare function bodyTooLarge(limit: number | undefined): EdgeRefusal;
15
+ //# sourceMappingURL=edge-refusal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edge-refusal.d.ts","sourceRoot":"","sources":["../../src/error/edge-refusal.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAKD,eAAO,MAAM,cAAc,EAAE,WAK5B,CAAC;AAEF,0FAA0F;AAC1F,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,WAAW,CASnE"}