@bymax-one/nest-core 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -11,6 +11,56 @@ heading here.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.6.2] - 2026-10-22
15
+
16
+ An unexpected error became `500 BYMAX_INTERNAL_ERROR` and the application had no
17
+ way to record what it was. `BymaxCoreModule` builds the filter itself, and the
18
+ only seam — the protected `onUnexpectedError` — is reachable only by subclassing
19
+ a filter the module never lets you substitute. So the access log saw the status
20
+ and nothing else, and a 500 on a read endpoint left no recoverable cause.
21
+
22
+ **This patch adds public surface**, which a patch number cannot tell you: the
23
+ `BYMAX_UNEXPECTED_ERROR_SINK` token and the `IUnexpectedErrorSink` and
24
+ `UnexpectedErrorReport` types. All are additive and nothing is removed or
25
+ renamed, so the digit stays at a patch under this project's versioning policy.
26
+
27
+ **Apply to a derived backend:** nothing is required; with no sink bound the
28
+ filter behaves as before. To record each unexpected error's cause, bind an
29
+ `IUnexpectedErrorSink` under `BYMAX_UNEXPECTED_ERROR_SINK` from a `@Global()`
30
+ module of your own, as the README's "Recording the cause of a 500" shows. A
31
+ backend registered through `forRootAsync` with `telemetry.exposeTraceId` on
32
+ starts serving `traceId` in its error envelopes, which it was configured to do
33
+ and did not; see Fixed.
34
+
35
+ ### Added
36
+
37
+ - **`BYMAX_UNEXPECTED_ERROR_SINK`, `IUnexpectedErrorSink` and
38
+ `UnexpectedErrorReport`.** The filter calls `record(report)` once per
39
+ unexpected error, before replying, with the original thrown value, the
40
+ method, the matched route template (`<unmatched>` before routing), and the
41
+ correlation and trace ids when they resolve. An `HttpException` and an
42
+ exposed `4xx` from the body pipeline never reach it.
43
+
44
+ The report carries no raw URL, query string, headers or body: a log outlives
45
+ the request and a query string is where tokens end up. The thrown value is
46
+ passed uncut whatever `envelope.exposeInternals` says, since that option
47
+ governs the response and the sink is not the response.
48
+
49
+ The response never depends on the sink. A synchronous throw is caught and an
50
+ `async record()` rejection is contained, both silently. The interface is
51
+ structural, so a logging library can ship a compatible class without
52
+ importing this package. The protected `onUnexpectedError` seam is unchanged
53
+ and runs alongside the sink.
54
+
55
+ ### Fixed
56
+
57
+ - **`forRootAsync` never put the trace id in the error envelope.** The async
58
+ filter slot is built by a factory whose injection list did not include
59
+ `BYMAX_TRACE_CONTEXT`, so the filter fell back to its no-op reader: with
60
+ `telemetry.exposeTraceId` on, `forRoot` served `traceId` and `forRootAsync`
61
+ silently did not. The factory now injects every dependency the sync path
62
+ resolves through the class.
63
+
14
64
  ## [1.6.1] - 2026-09-05
15
65
 
16
66
  A library contributing an OpenAPI component under a name the application already
@@ -1087,4 +1137,5 @@ have regressed from. They are kept because the reasoning is worth having.
1087
1137
  [1.5.3]: https://github.com/bymaxone/nest-core/compare/v1.5.2...v1.5.3
1088
1138
  [1.6.0]: https://github.com/bymaxone/nest-core/compare/v1.5.3...v1.6.0
1089
1139
  [1.6.1]: https://github.com/bymaxone/nest-core/compare/v1.6.0...v1.6.1
1090
- [Unreleased]: https://github.com/bymaxone/nest-core/compare/v1.6.1...HEAD
1140
+ [1.6.2]: https://github.com/bymaxone/nest-core/compare/v1.6.1...v1.6.2
1141
+ [Unreleased]: https://github.com/bymaxone/nest-core/compare/v1.6.2...HEAD
package/README.md CHANGED
@@ -516,8 +516,9 @@ requirement.
516
516
  ## 🔑 DI Tokens
517
517
 
518
518
  Every token is a `Symbol`. `BYMAX_CORRELATION_PROVIDER`,
519
- `BYMAX_HEALTH_INDICATORS` and `BYMAX_HEALTH_TRANSITION_SINK` are consumed with
520
- `@Optional()` and are not bound by the module: provide either from your own module to supply your own
519
+ `BYMAX_HEALTH_INDICATORS`, `BYMAX_HEALTH_TRANSITION_SINK` and
520
+ `BYMAX_UNEXPECTED_ERROR_SINK` are consumed with `@Optional()` and are not bound
521
+ by the module: provide any of them from your own module to supply your own
521
522
  implementation, otherwise the internal fallback in the last column applies.
522
523
  `BYMAX_TIMING_SINK` and `BYMAX_METRICS_REGISTRY` behave differently on
523
524
  `forRootAsync`, where options resolve after the module is defined: there the
@@ -535,6 +536,7 @@ below.
535
536
  | `BYMAX_TIMING_SINK` | `ITimingSink` | internal no-op, or the metrics bridge when timing and metrics are both enabled |
536
537
  | `BYMAX_HEALTH_INDICATORS` | `IHealthIndicator[]` | treated as an empty indicator set |
537
538
  | `BYMAX_HEALTH_TRANSITION_SINK` | `IHealthTransitionSink` | no sink; readiness transitions go to Nest's logger instead (binding one stands that line down) |
539
+ | `BYMAX_UNEXPECTED_ERROR_SINK` | `IUnexpectedErrorSink` | no sink; the cause of a `500 BYMAX_INTERNAL_ERROR` is not recorded anywhere |
538
540
  | `BYMAX_METRICS_REGISTRY` | the `prom-client` `Registry` | bound when metrics are enabled; on `forRootAsync` always registered, guarded-placeholder when off |
539
541
  | `BYMAX_TRACE_CONTEXT` | `ITraceContextProvider` | bound on every path: the OpenTelemetry reader when telemetry is enabled, a no-op that resolves no trace otherwise |
540
542
 
@@ -667,6 +669,62 @@ what exhausts the stack leaves a wide margin: one consumer runs `32`, against
667
669
  the ~2000 levels that overflow. Walk the parsed body iteratively — a recursive
668
670
  depth check on a hostile payload overflows the stack it was written to protect.
669
671
 
672
+ ### Recording the cause of a 500
673
+
674
+ An error the filter does not recognise collapses to a fixed
675
+ `500 BYMAX_INTERNAL_ERROR`, and that collapse is the point: the client learns
676
+ nothing about your internals. It also means that once the response is written,
677
+ the thrown value is gone — an access log sees only the status. Bind an
678
+ `IUnexpectedErrorSink` and the filter hands it the original value first:
679
+
680
+ ```typescript
681
+ import { Global, Logger, Module } from '@nestjs/common'
682
+ import { BYMAX_UNEXPECTED_ERROR_SINK } from '@bymax-one/nest-core'
683
+ import type { IUnexpectedErrorSink, UnexpectedErrorReport } from '@bymax-one/nest-core'
684
+
685
+ export class UnexpectedErrorLogger implements IUnexpectedErrorSink {
686
+ private readonly logger = new Logger('UnexpectedError')
687
+
688
+ record({ error, method, route, correlationId }: UnexpectedErrorReport): void {
689
+ this.logger.error(
690
+ `${method} ${route} failed (correlationId=${correlationId ?? '-'})`,
691
+ error instanceof Error ? error.stack : String(error)
692
+ )
693
+ }
694
+ }
695
+
696
+ @Global()
697
+ @Module({
698
+ providers: [{ provide: BYMAX_UNEXPECTED_ERROR_SINK, useClass: UnexpectedErrorLogger }],
699
+ exports: [BYMAX_UNEXPECTED_ERROR_SINK]
700
+ })
701
+ export class ErrorReportingModule {}
702
+ ```
703
+
704
+ The sink is called once per unexpected error, on both registration paths, and
705
+ for nothing else: an `HttpException` is a deliberate answer and an exposed `4xx`
706
+ from the body pipeline is a client mistake, so neither reaches it. The report
707
+ carries the thrown value as it was thrown, the method, the route **template**
708
+ (`/invoices/:id`, or `<unmatched>` for an error raised before routing), and the
709
+ correlation and trace ids when they resolve. It carries no raw URL, query
710
+ string, headers or body.
711
+
712
+ The response never depends on the sink. A sink that throws, or an
713
+ `async record()` that rejects, is absorbed and the client receives the same
714
+ envelope it would have received with no sink bound, so a broken logger cannot
715
+ turn one failure into two. It runs synchronously before the reply, so hand the
716
+ report off and return.
717
+
718
+ The value is passed uncut whatever `envelope.exposeInternals` says, since that
719
+ option governs the response body and the sink is not the response. A driver's
720
+ error message can carry hosts and query fragments: send the report where access
721
+ is already controlled.
722
+
723
+ `IUnexpectedErrorSink` is matched by shape, so a library can ship a compatible
724
+ class without importing this package. Subclassing `BymaxExceptionFilter` and
725
+ overriding `onUnexpectedError` still works and runs alongside the sink; the
726
+ sink is what reaches the filter `BymaxCoreModule` registers itself.
727
+
670
728
  ## ⏱️ Request Timing
671
729
 
672
730
  One `RequestTimingSample` is delivered to whatever implements `ITimingSink` for
@@ -1739,26 +1797,27 @@ in the sections above.
1739
1797
 
1740
1798
  ### `.` (root)
1741
1799
 
1742
- | Export | Kind | Description |
1743
- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------- |
1744
- | `BymaxCoreModule` | class | The dynamic module: `forRoot` and `forRootAsync`. |
1745
- | `BymaxCoreModuleOptions`, `EnvelopeOptions`, `TimingOptions`, `HealthOptions`, `MetricsOptions`, `TelemetryOptions`, `OpenApiOptions`, `OpenApiServerDescriptor`, `OpenApiSecurityScheme`, `ResolvedCoreOptions` | types | The options surface and its resolved shape. |
1746
- | `OpenApiSecurityRequirement`, `OpenApiHttpMethod`, `OpenApiOperationKey`, `OperationSecurityMap` | types | The operation-key contract a sibling library targets to ship its own security map. |
1747
- | `OpenApiOperationIdFactory` | type | Names the operations in the generated document. |
1748
- | `BYMAX_CORE_OPTIONS`, `BYMAX_CORRELATION_PROVIDER`, `BYMAX_TIMING_SINK`, `BYMAX_HEALTH_INDICATORS`, `BYMAX_HEALTH_TRANSITION_SINK`, `BYMAX_METRICS_REGISTRY`, `BYMAX_TRACE_CONTEXT` | tokens | The DI tokens; see the [token table](#-di-tokens). |
1749
- | `IHealthTransitionSink`, `HealthTransition`, `HealthTransitionCause` | types | The readiness-transition contract; also on `./health`. |
1750
- | `ICorrelationIdProvider` | type | The correlation-provider contract. |
1751
- | `ITraceContextProvider`, `TraceContext` | types | The trace-context contract and the identifiers it resolves. |
1752
- | `BymaxExceptionFilter` | class | The envelope exception filter. |
1753
- | `FilterErrorContext` | type | The neutral request context passed to the filter's observability seam. |
1754
- | `buildErrorEnvelope` | function | Pure builder assembling an `ErrorEnvelope`. |
1755
- | `ErrorEnvelope`, `ErrorDetails`, `BuildErrorEnvelopeInput` | types | The envelope contract and its builder input. |
1756
- | `BymaxTimingMiddleware` | class | The request-timing middleware, applied to every route when timing is enabled. |
1757
- | `UNMATCHED_ROUTE` | constant | The bounded label recorded when a request matched no route (`<unmatched>`). |
1758
- | `TimingInterceptor` | class | Deprecated: superseded by `BymaxTimingMiddleware`, which the module registers. |
1759
- | `ITimingSink`, `RequestTimingSample` | types | The timing-sink contract and its sample shape. |
1760
- | `BYMAX_BAD_GATEWAY` … `BYMAX_VALIDATION_FAILED` | constants | The full error-code catalog (see [Error envelope](#-error-envelope)). |
1761
- | `codeForStatus` | function | Derives a catalog code from an HTTP status. |
1800
+ | Export | Kind | Description |
1801
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------- |
1802
+ | `BymaxCoreModule` | class | The dynamic module: `forRoot` and `forRootAsync`. |
1803
+ | `BymaxCoreModuleOptions`, `EnvelopeOptions`, `TimingOptions`, `HealthOptions`, `MetricsOptions`, `TelemetryOptions`, `OpenApiOptions`, `OpenApiServerDescriptor`, `OpenApiSecurityScheme`, `ResolvedCoreOptions` | types | The options surface and its resolved shape. |
1804
+ | `OpenApiSecurityRequirement`, `OpenApiHttpMethod`, `OpenApiOperationKey`, `OperationSecurityMap` | types | The operation-key contract a sibling library targets to ship its own security map. |
1805
+ | `OpenApiOperationIdFactory` | type | Names the operations in the generated document. |
1806
+ | `BYMAX_CORE_OPTIONS`, `BYMAX_CORRELATION_PROVIDER`, `BYMAX_TIMING_SINK`, `BYMAX_HEALTH_INDICATORS`, `BYMAX_HEALTH_TRANSITION_SINK`, `BYMAX_UNEXPECTED_ERROR_SINK`, `BYMAX_METRICS_REGISTRY`, `BYMAX_TRACE_CONTEXT` | tokens | The DI tokens; see the [token table](#-di-tokens). |
1807
+ | `IHealthTransitionSink`, `HealthTransition`, `HealthTransitionCause` | types | The readiness-transition contract; also on `./health`. |
1808
+ | `ICorrelationIdProvider` | type | The correlation-provider contract. |
1809
+ | `ITraceContextProvider`, `TraceContext` | types | The trace-context contract and the identifiers it resolves. |
1810
+ | `BymaxExceptionFilter` | class | The envelope exception filter. |
1811
+ | `FilterErrorContext` | type | The neutral request context passed to the filter's observability seam. |
1812
+ | `IUnexpectedErrorSink`, `UnexpectedErrorReport` | types | Receives the cause behind each collapsed `500 BYMAX_INTERNAL_ERROR`; see [Recording the cause of a 500](#recording-the-cause-of-a-500). |
1813
+ | `buildErrorEnvelope` | function | Pure builder assembling an `ErrorEnvelope`. |
1814
+ | `ErrorEnvelope`, `ErrorDetails`, `BuildErrorEnvelopeInput` | types | The envelope contract and its builder input. |
1815
+ | `BymaxTimingMiddleware` | class | The request-timing middleware, applied to every route when timing is enabled. |
1816
+ | `UNMATCHED_ROUTE` | constant | The bounded label recorded when a request matched no route (`<unmatched>`). |
1817
+ | `TimingInterceptor` | class | Deprecated: superseded by `BymaxTimingMiddleware`, which the module registers. |
1818
+ | `ITimingSink`, `RequestTimingSample` | types | The timing-sink contract and its sample shape. |
1819
+ | `BYMAX_BAD_GATEWAY` … `BYMAX_VALIDATION_FAILED` | constants | The full error-code catalog (see [Error envelope](#-error-envelope)). |
1820
+ | `codeForStatus` | function | Derives a catalog code from an HTTP status. |
1762
1821
 
1763
1822
  ### `./pagination`
1764
1823
 
package/dist/index.cjs CHANGED
@@ -160,6 +160,9 @@ var BYMAX_HEALTH_INDICATORS = /* @__PURE__ */ Symbol.for(
160
160
  var BYMAX_HEALTH_TRANSITION_SINK = /* @__PURE__ */ Symbol.for(
161
161
  "@bymax-one/nest-core:health-transition-sink"
162
162
  );
163
+ var BYMAX_UNEXPECTED_ERROR_SINK = /* @__PURE__ */ Symbol.for(
164
+ "@bymax-one/nest-core:unexpected-error-sink"
165
+ );
163
166
  var BYMAX_METRICS_REGISTRY = /* @__PURE__ */ Symbol.for(
164
167
  "@bymax-one/nest-core:metrics-registry"
165
168
  );
@@ -265,6 +268,13 @@ function buildTraceContextProvider() {
265
268
  };
266
269
  }
267
270
 
271
+ // src/contain-rejection.ts
272
+ function containRejection(returned, onFailure) {
273
+ if (typeof returned?.then === "function") {
274
+ Promise.resolve(returned).catch(onFailure);
275
+ }
276
+ }
277
+
268
278
  // src/envelope/error-codes.ts
269
279
  var BYMAX_BAD_REQUEST = "BYMAX_BAD_REQUEST";
270
280
  var BYMAX_VALIDATION_FAILED = "BYMAX_VALIDATION_FAILED";
@@ -328,6 +338,23 @@ function buildErrorEnvelope(input) {
328
338
  };
329
339
  }
330
340
 
341
+ // src/timing/request-info.accessor.ts
342
+ var UNMATCHED_ROUTE = "<unmatched>";
343
+ function readExpressTemplate(request) {
344
+ const path = request.route?.path;
345
+ return path === void 0 ? void 0 : `${request.baseUrl ?? ""}${path}`;
346
+ }
347
+ function readFastifyTemplate(request) {
348
+ return request.routeOptions?.url;
349
+ }
350
+ function readRequestInfo(request) {
351
+ const template = readExpressTemplate(request) ?? readFastifyTemplate(request);
352
+ return { method: request.method ?? "", route: template ?? UNMATCHED_ROUTE };
353
+ }
354
+ function extractRequestInfo(context) {
355
+ return readRequestInfo(context.switchToHttp().getRequest());
356
+ }
357
+
331
358
  // src/envelope/exception.filter.ts
332
359
  var INTERNAL_ERROR_STATUS = 500;
333
360
  var INTERNAL_ERROR_MESSAGE = "Internal server error";
@@ -408,10 +435,13 @@ exports.BymaxExceptionFilter = class BymaxExceptionFilter {
408
435
  * (from their own, globally-visible module) is not shadowed by one; when
409
436
  * nothing is bound, this falls back to a no-op that omits `correlationId`.
410
437
  * @param adapterHost - Host of the live HTTP adapter, resolved lazily per catch.
438
+ * @param traceContext - Reader for the active trace; a no-op when unbound.
439
+ * @param unexpectedErrorSink - Receives every unexpected error; unbound by default.
411
440
  */
412
- constructor(options, correlation, adapterHost, traceContext) {
441
+ constructor(options, correlation, adapterHost, traceContext, unexpectedErrorSink) {
413
442
  this.options = options;
414
443
  this.adapterHost = adapterHost;
444
+ this.unexpectedErrorSink = unexpectedErrorSink;
415
445
  /** Clock used to stamp the envelope timestamp; overridable in tests via fake timers. */
416
446
  this.now = () => /* @__PURE__ */ new Date();
417
447
  this.correlation = correlation ?? new NoopCorrelationIdProvider();
@@ -470,19 +500,20 @@ exports.BymaxExceptionFilter = class BymaxExceptionFilter {
470
500
  ...correlationId !== void 0 ? { correlationId } : {},
471
501
  ...traceId !== void 0 ? { traceId } : {}
472
502
  };
473
- const envelope = this.buildEnvelope(exception, context);
503
+ const envelope = this.buildEnvelope(exception, context, request);
474
504
  httpAdapter.reply(response, envelope, envelope.statusCode);
475
505
  }
476
506
  /**
477
507
  * Select the mapping rule for the exception and build its envelope. An
478
- * unknown error is handed to the observability seam before it collapses, so
479
- * an integration can record the original error with the request context.
508
+ * unknown error is handed to the observability seam once its envelope is
509
+ * built, so an integration can record the original error with the context.
480
510
  *
481
511
  * @param exception - The error that escaped the handler.
482
512
  * @param context - The neutral request context.
513
+ * @param request - The framework request, read only for the sink's route template.
483
514
  * @returns The formatted envelope.
484
515
  */
485
- buildEnvelope(exception, context) {
516
+ buildEnvelope(exception, context, request) {
486
517
  if (exception instanceof common.HttpException) {
487
518
  return this.mapHttpException(exception, context);
488
519
  }
@@ -495,11 +526,39 @@ exports.BymaxExceptionFilter = class BymaxExceptionFilter {
495
526
  context
496
527
  );
497
528
  }
529
+ const envelope = this.mapUnknown(exception, context);
498
530
  try {
499
531
  this.onUnexpectedError(exception, context);
500
532
  } catch {
501
533
  }
502
- return this.mapUnknown(exception, context);
534
+ this.reportUnexpected(exception, context, request);
535
+ return envelope;
536
+ }
537
+ /**
538
+ * Hand an unexpected error to the bound sink, if any. Whatever the sink does
539
+ * — throw, or return a promise that rejects — is absorbed: the response must
540
+ * not depend on it. See `IUnexpectedErrorSink` for the contract.
541
+ *
542
+ * @param error - The original thrown value.
543
+ * @param context - The neutral request context.
544
+ * @param request - The framework request, read for its route template only.
545
+ */
546
+ reportUnexpected(error, context, request) {
547
+ const sink = this.unexpectedErrorSink;
548
+ if (sink === void 0) {
549
+ return;
550
+ }
551
+ try {
552
+ const report = {
553
+ error,
554
+ method: context.method,
555
+ route: readRequestInfo(request).route,
556
+ ...context.correlationId !== void 0 ? { correlationId: context.correlationId } : {},
557
+ ...context.traceId !== void 0 ? { traceId: context.traceId } : {}
558
+ };
559
+ containRejection(sink.record(report), () => void 0);
560
+ } catch {
561
+ }
503
562
  }
504
563
  /**
505
564
  * Map an `HttpException` to the envelope. A domain error passes its own code,
@@ -589,7 +648,7 @@ exports.BymaxExceptionFilter = class BymaxExceptionFilter {
589
648
  }
590
649
  /**
591
650
  * Observability seam invoked for every unexpected (non-`HttpException`) error
592
- * before it collapses to the generic 500. The base implementation is a no-op:
651
+ * collapsed to the generic 500. The base implementation is a no-op:
593
652
  * this library owns no logger. An integration (for example
594
653
  * `@bymax-one/nest-logger`) subclasses the filter and overrides this to record
595
654
  * the original error with the current request context and correlation id.
@@ -608,7 +667,9 @@ exports.BymaxExceptionFilter = __decorateClass([
608
667
  __decorateParam(1, common.Inject(BYMAX_CORRELATION_PROVIDER)),
609
668
  __decorateParam(2, common.Inject(core.HttpAdapterHost)),
610
669
  __decorateParam(3, common.Optional()),
611
- __decorateParam(3, common.Inject(BYMAX_TRACE_CONTEXT))
670
+ __decorateParam(3, common.Inject(BYMAX_TRACE_CONTEXT)),
671
+ __decorateParam(4, common.Optional()),
672
+ __decorateParam(4, common.Inject(BYMAX_UNEXPECTED_ERROR_SINK))
612
673
  ], exports.BymaxExceptionFilter);
613
674
  var PassThroughExceptionFilter = class {
614
675
  constructor(adapterHost) {
@@ -635,15 +696,8 @@ function assertAsyncFeatureEnabled(feature, enabled) {
635
696
  );
636
697
  }
637
698
  }
638
- function selectAsyncExceptionFilter(options, correlation, adapterHost) {
639
- return options.envelope.enabled ? new exports.BymaxExceptionFilter(options, correlation, adapterHost) : new PassThroughExceptionFilter(adapterHost);
640
- }
641
-
642
- // src/contain-rejection.ts
643
- function containRejection(returned, onFailure) {
644
- if (typeof returned?.then === "function") {
645
- Promise.resolve(returned).catch(onFailure);
646
- }
699
+ function selectAsyncExceptionFilter(options, correlation, adapterHost, traceContext, unexpectedErrorSink) {
700
+ return options.envelope.enabled ? new exports.BymaxExceptionFilter(options, correlation, adapterHost, traceContext, unexpectedErrorSink) : new PassThroughExceptionFilter(adapterHost);
647
701
  }
648
702
 
649
703
  // src/discovery.ts
@@ -1354,23 +1408,6 @@ function isFastifyInstance(instance) {
1354
1408
  return typeof instance?.addHook === "function";
1355
1409
  }
1356
1410
 
1357
- // src/timing/request-info.accessor.ts
1358
- var UNMATCHED_ROUTE = "<unmatched>";
1359
- function readExpressTemplate(request) {
1360
- const path = request.route?.path;
1361
- return path === void 0 ? void 0 : `${request.baseUrl ?? ""}${path}`;
1362
- }
1363
- function readFastifyTemplate(request) {
1364
- return request.routeOptions?.url;
1365
- }
1366
- function readRequestInfo(request) {
1367
- const template = readExpressTemplate(request) ?? readFastifyTemplate(request);
1368
- return { method: request.method ?? "", route: template ?? UNMATCHED_ROUTE };
1369
- }
1370
- function extractRequestInfo(context) {
1371
- return readRequestInfo(context.switchToHttp().getRequest());
1372
- }
1373
-
1374
1411
  // src/timing/timing.sample.ts
1375
1412
  function readTraceContext(traceContext) {
1376
1413
  try {
@@ -1529,11 +1566,22 @@ function buildAsyncSlots() {
1529
1566
  return [
1530
1567
  {
1531
1568
  provide: core.APP_FILTER,
1532
- useFactory: (options, correlation, adapterHost) => selectAsyncExceptionFilter(options, correlation, adapterHost),
1569
+ useFactory: (options, correlation, adapterHost, traceContext, unexpectedErrorSink) => selectAsyncExceptionFilter(
1570
+ options,
1571
+ correlation,
1572
+ adapterHost,
1573
+ traceContext,
1574
+ unexpectedErrorSink
1575
+ ),
1576
+ // Every constructor dependency the sync path resolves through `useClass`
1577
+ // has to be listed here by hand; one left out reaches the filter as its
1578
+ // no-op fallback and nothing fails.
1533
1579
  inject: [
1534
1580
  BYMAX_CORE_OPTIONS,
1535
1581
  { token: BYMAX_CORRELATION_PROVIDER, optional: true },
1536
- core.HttpAdapterHost
1582
+ core.HttpAdapterHost,
1583
+ BYMAX_TRACE_CONTEXT,
1584
+ { token: BYMAX_UNEXPECTED_ERROR_SINK, optional: true }
1537
1585
  ]
1538
1586
  }
1539
1587
  ];
@@ -1833,6 +1881,7 @@ exports.BYMAX_TIMING_SINK = BYMAX_TIMING_SINK;
1833
1881
  exports.BYMAX_TOO_MANY_REQUESTS = BYMAX_TOO_MANY_REQUESTS;
1834
1882
  exports.BYMAX_TRACE_CONTEXT = BYMAX_TRACE_CONTEXT;
1835
1883
  exports.BYMAX_UNAUTHORIZED = BYMAX_UNAUTHORIZED;
1884
+ exports.BYMAX_UNEXPECTED_ERROR_SINK = BYMAX_UNEXPECTED_ERROR_SINK;
1836
1885
  exports.BYMAX_UNPROCESSABLE_ENTITY = BYMAX_UNPROCESSABLE_ENTITY;
1837
1886
  exports.BYMAX_UNSUPPORTED_MEDIA_TYPE = BYMAX_UNSUPPORTED_MEDIA_TYPE;
1838
1887
  exports.BYMAX_VALIDATION_FAILED = BYMAX_VALIDATION_FAILED;
package/dist/index.d.cts CHANGED
@@ -564,6 +564,12 @@ declare const BYMAX_HEALTH_INDICATORS: unique symbol;
564
564
  * stands that line down in favour of the sink.
565
565
  */
566
566
  declare const BYMAX_HEALTH_TRANSITION_SINK: unique symbol;
567
+ /**
568
+ * Provide the `IUnexpectedErrorSink` that receives the cause of each collapsed
569
+ * `500 BYMAX_INTERNAL_ERROR`. Nothing is bound by default, and with no
570
+ * sink the filter records nothing.
571
+ */
572
+ declare const BYMAX_UNEXPECTED_ERROR_SINK: unique symbol;
567
573
  /**
568
574
  * Provide the `prom-client` `Registry` backing the metrics endpoint. Bound
569
575
  * lazily and only when the metrics feature is enabled.
@@ -636,6 +642,100 @@ interface ITraceContextProvider {
636
642
  getTraceContext(): TraceContext | undefined;
637
643
  }
638
644
 
645
+ /**
646
+ * @fileoverview The unexpected-error contract: a sink that receives the
647
+ * original value behind every collapsed `500 BYMAX_INTERNAL_ERROR`, with the
648
+ * request it failed.
649
+ *
650
+ * This exists because the collapse is what makes the response safe, and that
651
+ * same collapse is what makes the cause unrecoverable. The envelope carries a
652
+ * fixed message by design, an access log sees only the status, and the thrown
653
+ * value is gone the moment the filter replies. Nothing downstream of the filter
654
+ * can get it back, so the filter has to hand it over before it goes.
655
+ *
656
+ * **Structural on purpose.** A sink is matched by shape, not by inheritance, so
657
+ * a logging library can ship a compatible class without importing this package
658
+ * or declaring it as a peer. Nothing here is a class or a value.
659
+ *
660
+ * **What the report leaves out.** No request body, no headers, no query string
661
+ * and no raw URL: `route` is the template the router matched, the same
662
+ * bounded label the timing sample carries. A sink usually writes to a log that
663
+ * outlives the request and is read by more people than the request's sender,
664
+ * and a query string is where tokens and personal data end up. A sink that
665
+ * needs more than this reads it from its own request context.
666
+ *
667
+ * The thrown value itself is passed as is, uncut and unsanitised, whatever
668
+ * `envelope.exposeInternals` says. That option controls the response body,
669
+ * which goes to an untrusted client; a sink is application code at the same
670
+ * trust level as the logger, and a cause cut down to make it safe is not much
671
+ * of a cause. Treat what reaches it as possibly carrying hosts, queries and
672
+ * credentials from a driver's error message, and send it where access is
673
+ * already controlled.
674
+ * @layer Contract
675
+ */
676
+ /**
677
+ * One unexpected error, as the filter saw it when collapsing it.
678
+ *
679
+ * Optional fields are **absent** when unknown, never present holding
680
+ * `undefined`, so a sink that spreads the report into a structured log line
681
+ * writes no empty keys.
682
+ */
683
+ interface UnexpectedErrorReport {
684
+ /** The original thrown value: an `Error`, or anything else that was thrown. */
685
+ readonly error: unknown;
686
+ /** HTTP method, read through the adapter (Express and Fastify neutral). */
687
+ readonly method: string;
688
+ /**
689
+ * Route template the request matched, for example `"/invoices/:id"`, or
690
+ * `UNMATCHED_ROUTE` when it matched none: an error raised by middleware
691
+ * before routing. Never the raw URL.
692
+ */
693
+ readonly route: string;
694
+ /** Correlation id for the request; absent when no provider resolves one. */
695
+ readonly correlationId?: string;
696
+ /**
697
+ * Trace the request ran under; absent when telemetry is off or nothing was
698
+ * recording. Present whatever `telemetry.exposeTraceId` says, because that
699
+ * option controls the response body and the sink is not the response.
700
+ */
701
+ readonly traceId?: string;
702
+ }
703
+ /**
704
+ * Receives the cause of each collapsed `500 BYMAX_INTERNAL_ERROR`.
705
+ *
706
+ * Bind an implementation under `BYMAX_UNEXPECTED_ERROR_SINK` from a module of
707
+ * your own marked `@Global()`. Nothing is bound by default, and with no sink the
708
+ * filter records nothing: this package owns no logger.
709
+ *
710
+ * Called once per unexpected error, never for an `HttpException` and never for
711
+ * a 4xx the framework's body pipeline raised (a malformed JSON body, a payload
712
+ * over the limit) — those are not unexpected, and a sink would otherwise get a
713
+ * flood of client mistakes mixed in with server failures.
714
+ *
715
+ * Called synchronously from the exception filter, before the response is
716
+ * written, so an implementation must be cheap and must not block: hand the
717
+ * report to a logger and return. Whatever it does, the response does not
718
+ * change. A synchronous throw is caught, and an `async record()` that rejects
719
+ * is contained, and both are dropped silently: the filter is the last thing
720
+ * between an error and the client, and anything it reported about its own sink
721
+ * would push aside the failure the caller actually needs to see.
722
+ *
723
+ * Runs alongside the protected `BymaxExceptionFilter.onUnexpectedError` seam,
724
+ * not instead of it; a subclass overriding that seam still receives every call.
725
+ *
726
+ * Takes a single object, matching `ITimingSink.record` and
727
+ * `IHealthTransitionSink.record`, so a later field is an additive change rather
728
+ * than a new positional parameter.
729
+ */
730
+ interface IUnexpectedErrorSink {
731
+ /**
732
+ * Record one unexpected error.
733
+ *
734
+ * @param report - The original thrown value and the request it failed.
735
+ */
736
+ record(report: UnexpectedErrorReport): void;
737
+ }
738
+
639
739
  /**
640
740
  * Neutral view of the current request handed to {@link BymaxExceptionFilter}
641
741
  * mappers and to the {@link BymaxExceptionFilter.onUnexpectedError} seam. It
@@ -665,6 +765,7 @@ interface FilterErrorContext {
665
765
  declare class BymaxExceptionFilter implements ExceptionFilter {
666
766
  private readonly options;
667
767
  private readonly adapterHost;
768
+ private readonly unexpectedErrorSink?;
668
769
  /** Clock used to stamp the envelope timestamp; overridable in tests via fake timers. */
669
770
  private readonly now;
670
771
  /** The resolved correlation provider, or the no-op fallback when none is bound. */
@@ -679,8 +780,10 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
679
780
  * (from their own, globally-visible module) is not shadowed by one; when
680
781
  * nothing is bound, this falls back to a no-op that omits `correlationId`.
681
782
  * @param adapterHost - Host of the live HTTP adapter, resolved lazily per catch.
783
+ * @param traceContext - Reader for the active trace; a no-op when unbound.
784
+ * @param unexpectedErrorSink - Receives every unexpected error; unbound by default.
682
785
  */
683
- constructor(options: ResolvedCoreOptions, correlation: ICorrelationIdProvider | undefined, adapterHost: HttpAdapterHost, traceContext?: ITraceContextProvider);
786
+ constructor(options: ResolvedCoreOptions, correlation: ICorrelationIdProvider | undefined, adapterHost: HttpAdapterHost, traceContext?: ITraceContextProvider, unexpectedErrorSink?: IUnexpectedErrorSink | undefined);
684
787
  /**
685
788
  * Format the exception into the stable envelope and reply with it.
686
789
  *
@@ -715,14 +818,25 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
715
818
  catch(exception: unknown, host: ArgumentsHost): void;
716
819
  /**
717
820
  * Select the mapping rule for the exception and build its envelope. An
718
- * unknown error is handed to the observability seam before it collapses, so
719
- * an integration can record the original error with the request context.
821
+ * unknown error is handed to the observability seam once its envelope is
822
+ * built, so an integration can record the original error with the context.
720
823
  *
721
824
  * @param exception - The error that escaped the handler.
722
825
  * @param context - The neutral request context.
826
+ * @param request - The framework request, read only for the sink's route template.
723
827
  * @returns The formatted envelope.
724
828
  */
725
829
  private buildEnvelope;
830
+ /**
831
+ * Hand an unexpected error to the bound sink, if any. Whatever the sink does
832
+ * — throw, or return a promise that rejects — is absorbed: the response must
833
+ * not depend on it. See `IUnexpectedErrorSink` for the contract.
834
+ *
835
+ * @param error - The original thrown value.
836
+ * @param context - The neutral request context.
837
+ * @param request - The framework request, read for its route template only.
838
+ */
839
+ private reportUnexpected;
726
840
  /**
727
841
  * Map an `HttpException` to the envelope. A domain error passes its own code,
728
842
  * message and details through, whether it wrote them flat on the response or
@@ -758,7 +872,7 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
758
872
  private toEnvelope;
759
873
  /**
760
874
  * Observability seam invoked for every unexpected (non-`HttpException`) error
761
- * before it collapses to the generic 500. The base implementation is a no-op:
875
+ * collapsed to the generic 500. The base implementation is a no-op:
762
876
  * this library owns no logger. An integration (for example
763
877
  * `@bymax-one/nest-logger`) subclasses the filter and overrides this to record
764
878
  * the original error with the current request context and correlation id.
@@ -1179,4 +1293,4 @@ declare const BYMAX_GATEWAY_TIMEOUT = "BYMAX_GATEWAY_TIMEOUT";
1179
1293
  */
1180
1294
  declare function codeForStatus(status: number): string;
1181
1295
 
1182
- export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, type BuildErrorEnvelopeInput, BymaxCoreModule, type BymaxCoreModuleOptions, BymaxExceptionFilter, BymaxTimingMiddleware, type EnvelopeOptions, type ErrorDetails, type ErrorEnvelope, type FilterErrorContext, type HealthOptions, type ICorrelationIdProvider, type ITimingSink, type ITraceContextProvider, type MetricsOptions, type OpenApiHttpMethod, type OpenApiOperationIdFactory, type OpenApiOperationKey, type OpenApiOptions, type OpenApiSecurityRequirement, type OpenApiSecurityScheme, type OpenApiServerDescriptor, type OperationSecurityMap, type RequestTimingSample, type ResolvedCoreOptions, type TelemetryOptions, TimingInterceptor, type TimingOptions, type TraceContext, UNMATCHED_ROUTE, buildErrorEnvelope, codeForStatus };
1296
+ export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNEXPECTED_ERROR_SINK, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, type BuildErrorEnvelopeInput, BymaxCoreModule, type BymaxCoreModuleOptions, BymaxExceptionFilter, BymaxTimingMiddleware, type EnvelopeOptions, type ErrorDetails, type ErrorEnvelope, type FilterErrorContext, type HealthOptions, type ICorrelationIdProvider, type ITimingSink, type ITraceContextProvider, type IUnexpectedErrorSink, type MetricsOptions, type OpenApiHttpMethod, type OpenApiOperationIdFactory, type OpenApiOperationKey, type OpenApiOptions, type OpenApiSecurityRequirement, type OpenApiSecurityScheme, type OpenApiServerDescriptor, type OperationSecurityMap, type RequestTimingSample, type ResolvedCoreOptions, type TelemetryOptions, TimingInterceptor, type TimingOptions, type TraceContext, UNMATCHED_ROUTE, type UnexpectedErrorReport, buildErrorEnvelope, codeForStatus };
package/dist/index.d.ts CHANGED
@@ -564,6 +564,12 @@ declare const BYMAX_HEALTH_INDICATORS: unique symbol;
564
564
  * stands that line down in favour of the sink.
565
565
  */
566
566
  declare const BYMAX_HEALTH_TRANSITION_SINK: unique symbol;
567
+ /**
568
+ * Provide the `IUnexpectedErrorSink` that receives the cause of each collapsed
569
+ * `500 BYMAX_INTERNAL_ERROR`. Nothing is bound by default, and with no
570
+ * sink the filter records nothing.
571
+ */
572
+ declare const BYMAX_UNEXPECTED_ERROR_SINK: unique symbol;
567
573
  /**
568
574
  * Provide the `prom-client` `Registry` backing the metrics endpoint. Bound
569
575
  * lazily and only when the metrics feature is enabled.
@@ -636,6 +642,100 @@ interface ITraceContextProvider {
636
642
  getTraceContext(): TraceContext | undefined;
637
643
  }
638
644
 
645
+ /**
646
+ * @fileoverview The unexpected-error contract: a sink that receives the
647
+ * original value behind every collapsed `500 BYMAX_INTERNAL_ERROR`, with the
648
+ * request it failed.
649
+ *
650
+ * This exists because the collapse is what makes the response safe, and that
651
+ * same collapse is what makes the cause unrecoverable. The envelope carries a
652
+ * fixed message by design, an access log sees only the status, and the thrown
653
+ * value is gone the moment the filter replies. Nothing downstream of the filter
654
+ * can get it back, so the filter has to hand it over before it goes.
655
+ *
656
+ * **Structural on purpose.** A sink is matched by shape, not by inheritance, so
657
+ * a logging library can ship a compatible class without importing this package
658
+ * or declaring it as a peer. Nothing here is a class or a value.
659
+ *
660
+ * **What the report leaves out.** No request body, no headers, no query string
661
+ * and no raw URL: `route` is the template the router matched, the same
662
+ * bounded label the timing sample carries. A sink usually writes to a log that
663
+ * outlives the request and is read by more people than the request's sender,
664
+ * and a query string is where tokens and personal data end up. A sink that
665
+ * needs more than this reads it from its own request context.
666
+ *
667
+ * The thrown value itself is passed as is, uncut and unsanitised, whatever
668
+ * `envelope.exposeInternals` says. That option controls the response body,
669
+ * which goes to an untrusted client; a sink is application code at the same
670
+ * trust level as the logger, and a cause cut down to make it safe is not much
671
+ * of a cause. Treat what reaches it as possibly carrying hosts, queries and
672
+ * credentials from a driver's error message, and send it where access is
673
+ * already controlled.
674
+ * @layer Contract
675
+ */
676
+ /**
677
+ * One unexpected error, as the filter saw it when collapsing it.
678
+ *
679
+ * Optional fields are **absent** when unknown, never present holding
680
+ * `undefined`, so a sink that spreads the report into a structured log line
681
+ * writes no empty keys.
682
+ */
683
+ interface UnexpectedErrorReport {
684
+ /** The original thrown value: an `Error`, or anything else that was thrown. */
685
+ readonly error: unknown;
686
+ /** HTTP method, read through the adapter (Express and Fastify neutral). */
687
+ readonly method: string;
688
+ /**
689
+ * Route template the request matched, for example `"/invoices/:id"`, or
690
+ * `UNMATCHED_ROUTE` when it matched none: an error raised by middleware
691
+ * before routing. Never the raw URL.
692
+ */
693
+ readonly route: string;
694
+ /** Correlation id for the request; absent when no provider resolves one. */
695
+ readonly correlationId?: string;
696
+ /**
697
+ * Trace the request ran under; absent when telemetry is off or nothing was
698
+ * recording. Present whatever `telemetry.exposeTraceId` says, because that
699
+ * option controls the response body and the sink is not the response.
700
+ */
701
+ readonly traceId?: string;
702
+ }
703
+ /**
704
+ * Receives the cause of each collapsed `500 BYMAX_INTERNAL_ERROR`.
705
+ *
706
+ * Bind an implementation under `BYMAX_UNEXPECTED_ERROR_SINK` from a module of
707
+ * your own marked `@Global()`. Nothing is bound by default, and with no sink the
708
+ * filter records nothing: this package owns no logger.
709
+ *
710
+ * Called once per unexpected error, never for an `HttpException` and never for
711
+ * a 4xx the framework's body pipeline raised (a malformed JSON body, a payload
712
+ * over the limit) — those are not unexpected, and a sink would otherwise get a
713
+ * flood of client mistakes mixed in with server failures.
714
+ *
715
+ * Called synchronously from the exception filter, before the response is
716
+ * written, so an implementation must be cheap and must not block: hand the
717
+ * report to a logger and return. Whatever it does, the response does not
718
+ * change. A synchronous throw is caught, and an `async record()` that rejects
719
+ * is contained, and both are dropped silently: the filter is the last thing
720
+ * between an error and the client, and anything it reported about its own sink
721
+ * would push aside the failure the caller actually needs to see.
722
+ *
723
+ * Runs alongside the protected `BymaxExceptionFilter.onUnexpectedError` seam,
724
+ * not instead of it; a subclass overriding that seam still receives every call.
725
+ *
726
+ * Takes a single object, matching `ITimingSink.record` and
727
+ * `IHealthTransitionSink.record`, so a later field is an additive change rather
728
+ * than a new positional parameter.
729
+ */
730
+ interface IUnexpectedErrorSink {
731
+ /**
732
+ * Record one unexpected error.
733
+ *
734
+ * @param report - The original thrown value and the request it failed.
735
+ */
736
+ record(report: UnexpectedErrorReport): void;
737
+ }
738
+
639
739
  /**
640
740
  * Neutral view of the current request handed to {@link BymaxExceptionFilter}
641
741
  * mappers and to the {@link BymaxExceptionFilter.onUnexpectedError} seam. It
@@ -665,6 +765,7 @@ interface FilterErrorContext {
665
765
  declare class BymaxExceptionFilter implements ExceptionFilter {
666
766
  private readonly options;
667
767
  private readonly adapterHost;
768
+ private readonly unexpectedErrorSink?;
668
769
  /** Clock used to stamp the envelope timestamp; overridable in tests via fake timers. */
669
770
  private readonly now;
670
771
  /** The resolved correlation provider, or the no-op fallback when none is bound. */
@@ -679,8 +780,10 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
679
780
  * (from their own, globally-visible module) is not shadowed by one; when
680
781
  * nothing is bound, this falls back to a no-op that omits `correlationId`.
681
782
  * @param adapterHost - Host of the live HTTP adapter, resolved lazily per catch.
783
+ * @param traceContext - Reader for the active trace; a no-op when unbound.
784
+ * @param unexpectedErrorSink - Receives every unexpected error; unbound by default.
682
785
  */
683
- constructor(options: ResolvedCoreOptions, correlation: ICorrelationIdProvider | undefined, adapterHost: HttpAdapterHost, traceContext?: ITraceContextProvider);
786
+ constructor(options: ResolvedCoreOptions, correlation: ICorrelationIdProvider | undefined, adapterHost: HttpAdapterHost, traceContext?: ITraceContextProvider, unexpectedErrorSink?: IUnexpectedErrorSink | undefined);
684
787
  /**
685
788
  * Format the exception into the stable envelope and reply with it.
686
789
  *
@@ -715,14 +818,25 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
715
818
  catch(exception: unknown, host: ArgumentsHost): void;
716
819
  /**
717
820
  * Select the mapping rule for the exception and build its envelope. An
718
- * unknown error is handed to the observability seam before it collapses, so
719
- * an integration can record the original error with the request context.
821
+ * unknown error is handed to the observability seam once its envelope is
822
+ * built, so an integration can record the original error with the context.
720
823
  *
721
824
  * @param exception - The error that escaped the handler.
722
825
  * @param context - The neutral request context.
826
+ * @param request - The framework request, read only for the sink's route template.
723
827
  * @returns The formatted envelope.
724
828
  */
725
829
  private buildEnvelope;
830
+ /**
831
+ * Hand an unexpected error to the bound sink, if any. Whatever the sink does
832
+ * — throw, or return a promise that rejects — is absorbed: the response must
833
+ * not depend on it. See `IUnexpectedErrorSink` for the contract.
834
+ *
835
+ * @param error - The original thrown value.
836
+ * @param context - The neutral request context.
837
+ * @param request - The framework request, read for its route template only.
838
+ */
839
+ private reportUnexpected;
726
840
  /**
727
841
  * Map an `HttpException` to the envelope. A domain error passes its own code,
728
842
  * message and details through, whether it wrote them flat on the response or
@@ -758,7 +872,7 @@ declare class BymaxExceptionFilter implements ExceptionFilter {
758
872
  private toEnvelope;
759
873
  /**
760
874
  * Observability seam invoked for every unexpected (non-`HttpException`) error
761
- * before it collapses to the generic 500. The base implementation is a no-op:
875
+ * collapsed to the generic 500. The base implementation is a no-op:
762
876
  * this library owns no logger. An integration (for example
763
877
  * `@bymax-one/nest-logger`) subclasses the filter and overrides this to record
764
878
  * the original error with the current request context and correlation id.
@@ -1179,4 +1293,4 @@ declare const BYMAX_GATEWAY_TIMEOUT = "BYMAX_GATEWAY_TIMEOUT";
1179
1293
  */
1180
1294
  declare function codeForStatus(status: number): string;
1181
1295
 
1182
- export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, type BuildErrorEnvelopeInput, BymaxCoreModule, type BymaxCoreModuleOptions, BymaxExceptionFilter, BymaxTimingMiddleware, type EnvelopeOptions, type ErrorDetails, type ErrorEnvelope, type FilterErrorContext, type HealthOptions, type ICorrelationIdProvider, type ITimingSink, type ITraceContextProvider, type MetricsOptions, type OpenApiHttpMethod, type OpenApiOperationIdFactory, type OpenApiOperationKey, type OpenApiOptions, type OpenApiSecurityRequirement, type OpenApiSecurityScheme, type OpenApiServerDescriptor, type OperationSecurityMap, type RequestTimingSample, type ResolvedCoreOptions, type TelemetryOptions, TimingInterceptor, type TimingOptions, type TraceContext, UNMATCHED_ROUTE, buildErrorEnvelope, codeForStatus };
1296
+ export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNEXPECTED_ERROR_SINK, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, type BuildErrorEnvelopeInput, BymaxCoreModule, type BymaxCoreModuleOptions, BymaxExceptionFilter, BymaxTimingMiddleware, type EnvelopeOptions, type ErrorDetails, type ErrorEnvelope, type FilterErrorContext, type HealthOptions, type ICorrelationIdProvider, type ITimingSink, type ITraceContextProvider, type IUnexpectedErrorSink, type MetricsOptions, type OpenApiHttpMethod, type OpenApiOperationIdFactory, type OpenApiOperationKey, type OpenApiOptions, type OpenApiSecurityRequirement, type OpenApiSecurityScheme, type OpenApiServerDescriptor, type OperationSecurityMap, type RequestTimingSample, type ResolvedCoreOptions, type TelemetryOptions, TimingInterceptor, type TimingOptions, type TraceContext, UNMATCHED_ROUTE, type UnexpectedErrorReport, buildErrorEnvelope, codeForStatus };
package/dist/index.mjs CHANGED
@@ -158,6 +158,9 @@ var BYMAX_HEALTH_INDICATORS = /* @__PURE__ */ Symbol.for(
158
158
  var BYMAX_HEALTH_TRANSITION_SINK = /* @__PURE__ */ Symbol.for(
159
159
  "@bymax-one/nest-core:health-transition-sink"
160
160
  );
161
+ var BYMAX_UNEXPECTED_ERROR_SINK = /* @__PURE__ */ Symbol.for(
162
+ "@bymax-one/nest-core:unexpected-error-sink"
163
+ );
161
164
  var BYMAX_METRICS_REGISTRY = /* @__PURE__ */ Symbol.for(
162
165
  "@bymax-one/nest-core:metrics-registry"
163
166
  );
@@ -263,6 +266,13 @@ function buildTraceContextProvider() {
263
266
  };
264
267
  }
265
268
 
269
+ // src/contain-rejection.ts
270
+ function containRejection(returned, onFailure) {
271
+ if (typeof returned?.then === "function") {
272
+ Promise.resolve(returned).catch(onFailure);
273
+ }
274
+ }
275
+
266
276
  // src/envelope/error-codes.ts
267
277
  var BYMAX_BAD_REQUEST = "BYMAX_BAD_REQUEST";
268
278
  var BYMAX_VALIDATION_FAILED = "BYMAX_VALIDATION_FAILED";
@@ -326,6 +336,23 @@ function buildErrorEnvelope(input) {
326
336
  };
327
337
  }
328
338
 
339
+ // src/timing/request-info.accessor.ts
340
+ var UNMATCHED_ROUTE = "<unmatched>";
341
+ function readExpressTemplate(request) {
342
+ const path = request.route?.path;
343
+ return path === void 0 ? void 0 : `${request.baseUrl ?? ""}${path}`;
344
+ }
345
+ function readFastifyTemplate(request) {
346
+ return request.routeOptions?.url;
347
+ }
348
+ function readRequestInfo(request) {
349
+ const template = readExpressTemplate(request) ?? readFastifyTemplate(request);
350
+ return { method: request.method ?? "", route: template ?? UNMATCHED_ROUTE };
351
+ }
352
+ function extractRequestInfo(context) {
353
+ return readRequestInfo(context.switchToHttp().getRequest());
354
+ }
355
+
329
356
  // src/envelope/exception.filter.ts
330
357
  var INTERNAL_ERROR_STATUS = 500;
331
358
  var INTERNAL_ERROR_MESSAGE = "Internal server error";
@@ -406,10 +433,13 @@ var BymaxExceptionFilter = class {
406
433
  * (from their own, globally-visible module) is not shadowed by one; when
407
434
  * nothing is bound, this falls back to a no-op that omits `correlationId`.
408
435
  * @param adapterHost - Host of the live HTTP adapter, resolved lazily per catch.
436
+ * @param traceContext - Reader for the active trace; a no-op when unbound.
437
+ * @param unexpectedErrorSink - Receives every unexpected error; unbound by default.
409
438
  */
410
- constructor(options, correlation, adapterHost, traceContext) {
439
+ constructor(options, correlation, adapterHost, traceContext, unexpectedErrorSink) {
411
440
  this.options = options;
412
441
  this.adapterHost = adapterHost;
442
+ this.unexpectedErrorSink = unexpectedErrorSink;
413
443
  /** Clock used to stamp the envelope timestamp; overridable in tests via fake timers. */
414
444
  this.now = () => /* @__PURE__ */ new Date();
415
445
  this.correlation = correlation ?? new NoopCorrelationIdProvider();
@@ -468,19 +498,20 @@ var BymaxExceptionFilter = class {
468
498
  ...correlationId !== void 0 ? { correlationId } : {},
469
499
  ...traceId !== void 0 ? { traceId } : {}
470
500
  };
471
- const envelope = this.buildEnvelope(exception, context);
501
+ const envelope = this.buildEnvelope(exception, context, request);
472
502
  httpAdapter.reply(response, envelope, envelope.statusCode);
473
503
  }
474
504
  /**
475
505
  * Select the mapping rule for the exception and build its envelope. An
476
- * unknown error is handed to the observability seam before it collapses, so
477
- * an integration can record the original error with the request context.
506
+ * unknown error is handed to the observability seam once its envelope is
507
+ * built, so an integration can record the original error with the context.
478
508
  *
479
509
  * @param exception - The error that escaped the handler.
480
510
  * @param context - The neutral request context.
511
+ * @param request - The framework request, read only for the sink's route template.
481
512
  * @returns The formatted envelope.
482
513
  */
483
- buildEnvelope(exception, context) {
514
+ buildEnvelope(exception, context, request) {
484
515
  if (exception instanceof HttpException) {
485
516
  return this.mapHttpException(exception, context);
486
517
  }
@@ -493,11 +524,39 @@ var BymaxExceptionFilter = class {
493
524
  context
494
525
  );
495
526
  }
527
+ const envelope = this.mapUnknown(exception, context);
496
528
  try {
497
529
  this.onUnexpectedError(exception, context);
498
530
  } catch {
499
531
  }
500
- return this.mapUnknown(exception, context);
532
+ this.reportUnexpected(exception, context, request);
533
+ return envelope;
534
+ }
535
+ /**
536
+ * Hand an unexpected error to the bound sink, if any. Whatever the sink does
537
+ * — throw, or return a promise that rejects — is absorbed: the response must
538
+ * not depend on it. See `IUnexpectedErrorSink` for the contract.
539
+ *
540
+ * @param error - The original thrown value.
541
+ * @param context - The neutral request context.
542
+ * @param request - The framework request, read for its route template only.
543
+ */
544
+ reportUnexpected(error, context, request) {
545
+ const sink = this.unexpectedErrorSink;
546
+ if (sink === void 0) {
547
+ return;
548
+ }
549
+ try {
550
+ const report = {
551
+ error,
552
+ method: context.method,
553
+ route: readRequestInfo(request).route,
554
+ ...context.correlationId !== void 0 ? { correlationId: context.correlationId } : {},
555
+ ...context.traceId !== void 0 ? { traceId: context.traceId } : {}
556
+ };
557
+ containRejection(sink.record(report), () => void 0);
558
+ } catch {
559
+ }
501
560
  }
502
561
  /**
503
562
  * Map an `HttpException` to the envelope. A domain error passes its own code,
@@ -587,7 +646,7 @@ var BymaxExceptionFilter = class {
587
646
  }
588
647
  /**
589
648
  * Observability seam invoked for every unexpected (non-`HttpException`) error
590
- * before it collapses to the generic 500. The base implementation is a no-op:
649
+ * collapsed to the generic 500. The base implementation is a no-op:
591
650
  * this library owns no logger. An integration (for example
592
651
  * `@bymax-one/nest-logger`) subclasses the filter and overrides this to record
593
652
  * the original error with the current request context and correlation id.
@@ -606,7 +665,9 @@ BymaxExceptionFilter = __decorateClass([
606
665
  __decorateParam(1, Inject(BYMAX_CORRELATION_PROVIDER)),
607
666
  __decorateParam(2, Inject(HttpAdapterHost)),
608
667
  __decorateParam(3, Optional()),
609
- __decorateParam(3, Inject(BYMAX_TRACE_CONTEXT))
668
+ __decorateParam(3, Inject(BYMAX_TRACE_CONTEXT)),
669
+ __decorateParam(4, Optional()),
670
+ __decorateParam(4, Inject(BYMAX_UNEXPECTED_ERROR_SINK))
610
671
  ], BymaxExceptionFilter);
611
672
  var PassThroughExceptionFilter = class {
612
673
  constructor(adapterHost) {
@@ -633,15 +694,8 @@ function assertAsyncFeatureEnabled(feature, enabled) {
633
694
  );
634
695
  }
635
696
  }
636
- function selectAsyncExceptionFilter(options, correlation, adapterHost) {
637
- return options.envelope.enabled ? new BymaxExceptionFilter(options, correlation, adapterHost) : new PassThroughExceptionFilter(adapterHost);
638
- }
639
-
640
- // src/contain-rejection.ts
641
- function containRejection(returned, onFailure) {
642
- if (typeof returned?.then === "function") {
643
- Promise.resolve(returned).catch(onFailure);
644
- }
697
+ function selectAsyncExceptionFilter(options, correlation, adapterHost, traceContext, unexpectedErrorSink) {
698
+ return options.envelope.enabled ? new BymaxExceptionFilter(options, correlation, adapterHost, traceContext, unexpectedErrorSink) : new PassThroughExceptionFilter(adapterHost);
645
699
  }
646
700
 
647
701
  // src/discovery.ts
@@ -1352,23 +1406,6 @@ function isFastifyInstance(instance) {
1352
1406
  return typeof instance?.addHook === "function";
1353
1407
  }
1354
1408
 
1355
- // src/timing/request-info.accessor.ts
1356
- var UNMATCHED_ROUTE = "<unmatched>";
1357
- function readExpressTemplate(request) {
1358
- const path = request.route?.path;
1359
- return path === void 0 ? void 0 : `${request.baseUrl ?? ""}${path}`;
1360
- }
1361
- function readFastifyTemplate(request) {
1362
- return request.routeOptions?.url;
1363
- }
1364
- function readRequestInfo(request) {
1365
- const template = readExpressTemplate(request) ?? readFastifyTemplate(request);
1366
- return { method: request.method ?? "", route: template ?? UNMATCHED_ROUTE };
1367
- }
1368
- function extractRequestInfo(context) {
1369
- return readRequestInfo(context.switchToHttp().getRequest());
1370
- }
1371
-
1372
1409
  // src/timing/timing.sample.ts
1373
1410
  function readTraceContext(traceContext) {
1374
1411
  try {
@@ -1527,11 +1564,22 @@ function buildAsyncSlots() {
1527
1564
  return [
1528
1565
  {
1529
1566
  provide: APP_FILTER,
1530
- useFactory: (options, correlation, adapterHost) => selectAsyncExceptionFilter(options, correlation, adapterHost),
1567
+ useFactory: (options, correlation, adapterHost, traceContext, unexpectedErrorSink) => selectAsyncExceptionFilter(
1568
+ options,
1569
+ correlation,
1570
+ adapterHost,
1571
+ traceContext,
1572
+ unexpectedErrorSink
1573
+ ),
1574
+ // Every constructor dependency the sync path resolves through `useClass`
1575
+ // has to be listed here by hand; one left out reaches the filter as its
1576
+ // no-op fallback and nothing fails.
1531
1577
  inject: [
1532
1578
  BYMAX_CORE_OPTIONS,
1533
1579
  { token: BYMAX_CORRELATION_PROVIDER, optional: true },
1534
- HttpAdapterHost
1580
+ HttpAdapterHost,
1581
+ BYMAX_TRACE_CONTEXT,
1582
+ { token: BYMAX_UNEXPECTED_ERROR_SINK, optional: true }
1535
1583
  ]
1536
1584
  }
1537
1585
  ];
@@ -1811,4 +1859,4 @@ TimingInterceptor = __decorateClass([
1811
1859
  __decorateParam(3, Inject(BYMAX_TRACE_CONTEXT))
1812
1860
  ], TimingInterceptor);
1813
1861
 
1814
- export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, BymaxCoreModule, BymaxExceptionFilter, BymaxTimingMiddleware, TimingInterceptor, UNMATCHED_ROUTE, buildErrorEnvelope, codeForStatus };
1862
+ export { BYMAX_BAD_GATEWAY, BYMAX_BAD_REQUEST, BYMAX_CLIENT_ERROR, BYMAX_CONFLICT, BYMAX_CORE_OPTIONS, BYMAX_CORRELATION_PROVIDER, BYMAX_FORBIDDEN, BYMAX_GATEWAY_TIMEOUT, BYMAX_HEALTH_INDICATORS, BYMAX_HEALTH_TRANSITION_SINK, BYMAX_INTERNAL_ERROR, BYMAX_METRICS_REGISTRY, BYMAX_NOT_FOUND, BYMAX_NOT_IMPLEMENTED, BYMAX_PAYLOAD_TOO_LARGE, BYMAX_SERVICE_UNAVAILABLE, BYMAX_TIMING_SINK, BYMAX_TOO_MANY_REQUESTS, BYMAX_TRACE_CONTEXT, BYMAX_UNAUTHORIZED, BYMAX_UNEXPECTED_ERROR_SINK, BYMAX_UNPROCESSABLE_ENTITY, BYMAX_UNSUPPORTED_MEDIA_TYPE, BYMAX_VALIDATION_FAILED, BymaxCoreModule, BymaxExceptionFilter, BymaxTimingMiddleware, TimingInterceptor, UNMATCHED_ROUTE, buildErrorEnvelope, codeForStatus };
@@ -594,14 +594,13 @@ function augmentDocument(document, options, pathPrefixes = [""], contributions =
594
594
  const merged = new Map(Object.entries(components));
595
595
  if (openapi.includeCoreSchemas) {
596
596
  const keep = () => void 0;
597
- merged.set(
598
- "schemas",
599
- placeComponentEntries(components["schemas"], "schemas", CORE_SCHEMAS, keep)
600
- );
601
- merged.set(
602
- "parameters",
603
- placeComponentEntries(components["parameters"], "parameters", CORE_PARAMETERS, keep)
604
- );
597
+ const catalogue = [
598
+ ["schemas", CORE_SCHEMAS],
599
+ ["parameters", CORE_PARAMETERS]
600
+ ];
601
+ for (const [member, entries] of catalogue) {
602
+ merged.set(member, placeComponentEntries(merged.get(member), member, entries, keep));
603
+ }
605
604
  }
606
605
  const scrapeScheme = options.metrics.authToken === void 0 ? {} : {
607
606
  [METRICS_SCHEME_NAME]: {
@@ -592,14 +592,13 @@ function augmentDocument(document, options, pathPrefixes = [""], contributions =
592
592
  const merged = new Map(Object.entries(components));
593
593
  if (openapi.includeCoreSchemas) {
594
594
  const keep = () => void 0;
595
- merged.set(
596
- "schemas",
597
- placeComponentEntries(components["schemas"], "schemas", CORE_SCHEMAS, keep)
598
- );
599
- merged.set(
600
- "parameters",
601
- placeComponentEntries(components["parameters"], "parameters", CORE_PARAMETERS, keep)
602
- );
595
+ const catalogue = [
596
+ ["schemas", CORE_SCHEMAS],
597
+ ["parameters", CORE_PARAMETERS]
598
+ ];
599
+ for (const [member, entries] of catalogue) {
600
+ merged.set(member, placeComponentEntries(merged.get(member), member, entries, keep));
601
+ }
603
602
  }
604
603
  const scrapeScheme = options.metrics.authToken === void 0 ? {} : {
605
604
  [METRICS_SCHEME_NAME]: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-core",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "description": "Zero-dependency NestJS 11 application foundation kit: error-envelope exception filter, request-timing interceptor, pagination helpers, health endpoints with indicator discovery, an optional Prometheus metrics endpoint with a contribution contract, OpenAPI documents in development, and OpenTelemetry trace correlation.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",