@bymax-one/nest-notification 1.1.1 → 1.2.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,102 @@ All notable changes to `@bymax-one/nest-notification` will be documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.0] - 2026-08-14
9
+
10
+ ### Added
11
+
12
+ - **`NotificationException` now carries the underlying error as the native `Error.cause`.** A failed
13
+ dispatch used to log _what_ failed and never _why_: `EMAIL_SEND_FAILED` discarded the provider's
14
+ error, so a `connect ECONNREFUSED` existed only in a separate `warn` line — recoverable by
15
+ request-id correlation, and entirely absent for a deployment logging at `error`. Since dispatch is
16
+ fire-and-forget, the log is the only surface where the reason can appear at all. Reported by a
17
+ consumer with a live reproduction (SMTP pointed at a closed port), and verified against this
18
+ release the same way: the reason now sits nested inside the same serialized `err` object, with no
19
+ change on the logging side — cause-walking serializers (e.g. pino's `err`) pick it up natively.
20
+
21
+ The third constructor parameter accepts an options bag,
22
+ `new NotificationException(key, details, { status?, message?, cause? })`, mirroring how
23
+ `HttpException` itself evolved; the positional `(key, details, status, message)` form keeps
24
+ working unchanged. All five sites that previously discarded the underlying error now attach it:
25
+ `EMAIL_SEND_FAILED`, `TEMPLATE_RENDER_FAILED`, and the three `AUDIT_LOG_FAILED` throw sites.
26
+ `NotificationExceptionOptions` is exported from the server subpath.
27
+
28
+ The cause is stored as a **log-safe copy**, not the raw object: `name`, `message`, `stack`, and
29
+ the nested `cause` chain survive (depth-bounded); every other property is dropped. Provider/SDK
30
+ errors routinely retain the request payload in extra properties (an axios-style `config.data`),
31
+ and for an OTP email that payload contains the code — attaching the raw object would have handed
32
+ a cause-walking serializer exactly what the never-log-codes rule exists to keep out of logs.
33
+ Non-Error object causes are flattened to their `String()` form for the same reason; primitives
34
+ pass through. One nuance, inherited from Nest and documented on the option: `HttpException`
35
+ installs only a _truthy_ cause, so a falsy cause is silently ignored.
36
+
37
+ ### Fixed
38
+
39
+ - **`AUDIT_LOG_FAILED` no longer leaks internal error text into the HTTP response.** The three
40
+ audit-failure sites stuffed the caught error's message into `details.cause` — and `details` is
41
+ serialized into the response body, so storage/audit internals reached the HTTP client on a 502
42
+ whenever `audit.swallowErrors` was `false`. The error now rides only on `Error.cause` (never
43
+ serialized into the response) and those responses carry `details: null`. The security gate was
44
+ extended to match: tests serialize thrown exceptions recursively — message, stack, response body,
45
+ and every nested cause — and assert the plaintext OTP code appears at no depth.
46
+
47
+ - **A delivery error that echoes the plaintext code is scrubbed before it leaves `OtpService`.**
48
+ The renderer receives the code inside its template `data` and the provider receives it inside
49
+ the rendered body, so either may echo it in a thrown error's message or stack. On a failed OTP
50
+ delivery the service now replaces every occurrence of the code with `[redacted]` — in the audit
51
+ entry's `errorMessage` and across the rethrown error chain (message and stack at every link) —
52
+ at the one layer that knows the secret. The scrub also covers `name` (serializers emit it like
53
+ `message`), deletes payload-bearing own enumerable properties from arbitrary errors (a storage
54
+ may reject with `Object.assign(new Error(...), { entry })` — and the entry carries the code —
55
+ while a `NotificationException` keeps its contract properties, safe by construction), and
56
+ flattens a non-`Error` `cause` link — a primitive string tail carries the secret verbatim and
57
+ an object tail can carry it in a property, and neither can be walked as an Error.
58
+ Traversal is identity-based (`WeakSet`), so a cyclic chain terminates and no depth limit leaves
59
+ an unscrubbed tail; writes go through `Reflect.set`, so a frozen foreign error degrades to
60
+ best-effort instead of throwing. Any non-`Error` rejection — a string, or an object a custom
61
+ storage may reject with that retains the entry — is flattened to a redacted string, since a raw
62
+ object could carry the code in its properties.
63
+
64
+ - **`EmailService` redacts declared secrets from its own failed-audit entry.** The email `failed`
65
+ audit entry records the provider's message, which is written before `OtpService` can scrub the
66
+ rethrown chain — so a provider that echoes the rendered body leaked the code into that one
67
+ entry. `EmailSendInput`/`EmailSendTemplateInput` gain `auditRedactValues`: secret values the
68
+ caller declares (only the caller knows them) that are replaced with `[redacted]` in the entry's
69
+ `errorMessage`. OTP delivery passes `[code]` automatically; a real-path regression (real
70
+ `EmailService`, echoing provider) asserts both audit entries and the rethrown chain are
71
+ code-free.
72
+
73
+ ## [1.1.2] - 2026-08-14
74
+
75
+ ### Fixed
76
+
77
+ - **A failed optional-peer import no longer always blames a missing package.** `SmtpEmailProvider`
78
+ and `ResendEmailProvider` both wrapped their lazy `import()` in a bare `catch` that mapped _every_
79
+ failure to `` `<pkg>` package is not installed. Run `pnpm add <pkg>` ``. That is worse than no
80
+ message: it names a fix that cannot work, so a consumer reinstalls a package that is already in
81
+ `node_modules` and starts doubting their dependency tree.
82
+
83
+ The case that actually bites, reported by a consumer and reproduced against the published 1.1.1
84
+ tarball: a Jest suite running **without `--experimental-vm-modules`** cannot service a dynamic
85
+ `import()` at all and fails with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG` while the package
86
+ is installed. Every consumer unit test reaching `send()` hit the wrong diagnosis.
87
+
88
+ Now the install instruction requires two things: a module-resolution code —
89
+ `ERR_MODULE_NOT_FOUND` (dynamic import) or `MODULE_NOT_FOUND` (the CommonJS `require` form) — **and**
90
+ a message naming that exact specifier. The code alone is not enough: an _installed_ peer whose own
91
+ evaluation fails because one of **its** dependencies is missing rejects with the very same codes,
92
+ verified on Node 24 with a fixture package, and blaming the top-level peer there would be the same
93
+ bug one level down. The specifier check degrades safely — when it cannot confirm the name, the
94
+ honest message is used, so the worst case is a lost hint rather than a confident wrong claim.
95
+
96
+ Anything else is surfaced as ``Failed to load `<pkg>`: <the real message>`` with the original error
97
+ kept as `cause`. The loading logic now lives once in an internal `loadOptionalPeer` helper, so the
98
+ two adapters cannot drift.
99
+
100
+ **Apply to a derived backend:** none. If a unit suite needs to exercise a code path that reaches
101
+ `send()`, run Jest with `--experimental-vm-modules` — that is the supported way to service a
102
+ dynamic `import()` under Jest, and the error now says so instead of misdirecting.
103
+
8
104
  ## [1.1.1] - 2026-08-14
9
105
 
10
106
  ### Added
@@ -282,6 +378,8 @@ rejected at startup rather than failing on the first send.
282
378
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
283
379
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
284
380
  [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...HEAD
381
+ [1.2.0]: https://github.com/bymaxone/nest-notification/compare/v1.1.2...v1.2.0
382
+ [1.1.2]: https://github.com/bymaxone/nest-notification/compare/v1.1.1...v1.1.2
285
383
  [1.1.1]: https://github.com/bymaxone/nest-notification/compare/v1.1.0...v1.1.1
286
384
  [1.1.0]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...v1.1.0
287
385
  [1.0.6]: https://github.com/bymaxone/nest-notification/compare/v1.0.5...v1.0.6
package/README.md CHANGED
@@ -623,7 +623,8 @@ The library **never** writes a code to a sink that can be read back:
623
623
 
624
624
  - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
625
625
  - Not to a console or logger line.
626
- - Not inside an `errorMessage`, which carries the message only — never a stack trace, whose frames can hold the code as an argument.
626
+ - Not inside an `errorMessage`, which carries the message only — never a stack trace.
627
+ - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every occurrence of the code is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry is covered too: OTP delivery declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's `errorMessage`. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
627
628
 
628
629
  Codes exist only inside the OTP store, under a TTL, and in process memory for the duration of the request. `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
629
630
 
@@ -688,8 +689,8 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
688
689
 
689
690
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
690
691
  - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): every viable seeded fault killed, with **no survivors**, against a `break` threshold of 100. The equivalents that no test can kill carry their reason on the line they apply to, so the number is an accounting rather than a target
691
- - ✅ **389 tests** — unit and end-to-end, spanning all three subpaths
692
- - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false`), not a review convention
692
+ - ✅ **557 tests** — unit and end-to-end, spanning all three subpaths
693
+ - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false` on every audit entry, and the thrown exception is serialized recursively — message, stack, response body, every nested `cause` — asserting the code appears at no depth), not a review convention
693
694
  - ✅ **Published shape verified** — `attw` resolves every entrypoint against the packed tarball, and a dogfood smoke test installs the package into a scratch consumer before any tag is cut
694
695
  - ✅ **Every equivalent mutant documented** — the ones no test can kill carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
695
696
 
@@ -750,11 +751,14 @@ pnpm mutation # Stryker mutation testing
750
751
  | Member | Purpose |
751
752
  | -------------------------------- | -------------------------------------------------------------------------- |
752
753
  | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
754
+ | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
753
755
  | `NOTIFICATION_ERROR_CODES` | The 22 stable `notification.*` codes — branch on these, not on messages |
754
756
  | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
755
757
 
756
758
  Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_cooldown_active`, `notification.email_send_failed`, …) and never change once published. Default messages are English; localize on the `code`.
757
759
 
760
+ Failures raised by the library carry the underlying error as the native `Error.cause` — a provider's `connect ECONNREFUSED` sits on `exception.cause`, where cause-walking log serializers (e.g. pino's `err`) print it alongside the stable code. The cause is stored as a **log-safe copy**: `name`, `message`, `stack`, and the nested `cause` chain survive (depth-bounded); every other property is dropped, because SDK errors routinely retain the request payload (an axios-style `config.data`) and for an OTP email that payload contains the code. The cause never enters the HTTP response body either: `details` stays reserved for the structured, client-safe context shown above. To attach a cause in your own code, pass the options bag as the third constructor argument — `new NotificationException('EMAIL_SEND_FAILED', { providerName }, { cause: error })`; the positional `(key, details, status, message)` form keeps working.
761
+
758
762
  ### Reference adapters
759
763
 
760
764
  | Export | Implements | Use for |
@@ -272,23 +272,53 @@ var FALLBACK_DEFINITION = {
272
272
  status: common.HttpStatus.INTERNAL_SERVER_ERROR,
273
273
  message: "Unknown notification error"
274
274
  };
275
+ var MAX_CAUSE_DEPTH = 5;
276
+ var UNREADABLE_CAUSE_MESSAGE = "Cause unavailable: inspecting it threw";
277
+ function toLogSafeCause(cause, depth = 0) {
278
+ try {
279
+ return copyLogSafeCause(cause, depth);
280
+ } catch {
281
+ return new Error(UNREADABLE_CAUSE_MESSAGE);
282
+ }
283
+ }
284
+ function copyLogSafeCause(cause, depth) {
285
+ if (cause instanceof Error) {
286
+ const safe = new Error(cause.message);
287
+ Object.defineProperty(safe, "name", { value: cause.name, writable: true });
288
+ if (cause.stack !== void 0) {
289
+ safe.stack = cause.stack;
290
+ }
291
+ if (depth < MAX_CAUSE_DEPTH && "cause" in cause) {
292
+ Object.defineProperty(safe, "cause", {
293
+ value: toLogSafeCause(cause.cause, depth + 1),
294
+ writable: true
295
+ });
296
+ }
297
+ return safe;
298
+ }
299
+ return typeof cause === "object" && cause !== null ? String(cause) : cause;
300
+ }
275
301
  var NotificationException = class extends common.HttpException {
276
302
  /**
277
303
  * @param key - Catalog key selecting the code, default HTTP status, and message.
278
304
  * @param details - Optional structured context placed under `error.details`.
279
- * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
280
- * @param overrideMessage - Replaces the catalog's default message when supplied.
305
+ * @param optionsOrStatus - An {@link NotificationExceptionOptions} object, or — kept
306
+ * for backward compatibility — a bare `HttpStatus` acting as `options.status`.
307
+ * @param overrideMessage - Replaces the catalog's default message when supplied;
308
+ * kept for backward compatibility with the positional form. `options.message` wins
309
+ * when both are given.
281
310
  */
282
- constructor(key, details, overrideStatus, overrideMessage) {
311
+ constructor(key, details, optionsOrStatus, overrideMessage) {
283
312
  const definition = NOTIFICATION_ERROR_DEFINITION_MAP.get(key) ?? FALLBACK_DEFINITION;
313
+ const options = typeof optionsOrStatus === "number" ? { status: optionsOrStatus } : optionsOrStatus ?? {};
284
314
  const body = {
285
315
  error: {
286
316
  code: definition.code,
287
- message: overrideMessage ?? definition.message,
317
+ message: options.message ?? overrideMessage ?? definition.message,
288
318
  details: details ?? null
289
319
  }
290
320
  };
291
- super(body, overrideStatus ?? definition.status);
321
+ super(body, options.status ?? definition.status, { cause: toLogSafeCause(options.cause) });
292
322
  this.code = definition.code;
293
323
  }
294
324
  };
@@ -510,6 +540,189 @@ exports.NoOpNotificationLogRepository = class NoOpNotificationLogRepository {
510
540
  exports.NoOpNotificationLogRepository = __decorateClass([
511
541
  common.Injectable()
512
542
  ], exports.NoOpNotificationLogRepository);
543
+
544
+ // src/server/utils/redact.ts
545
+ var REDACTED_VALUE = "[redacted]";
546
+ function redactValues(text, values) {
547
+ return values.reduce(
548
+ (cleaned, value) => value === "" ? cleaned : cleaned.split(value).join(REDACTED_VALUE),
549
+ text
550
+ );
551
+ }
552
+ function coerceRedacted(value, values) {
553
+ try {
554
+ return redactValues(String(value), values);
555
+ } catch {
556
+ return REDACTED_VALUE;
557
+ }
558
+ }
559
+ function readRedactedMessage(error, values) {
560
+ try {
561
+ const message = error instanceof Error ? error.message : String(error);
562
+ return values ? redactValues(message, values) : message;
563
+ } catch {
564
+ return REDACTED_VALUE;
565
+ }
566
+ }
567
+ function isSafeError(value) {
568
+ try {
569
+ return value instanceof Error;
570
+ } catch {
571
+ return false;
572
+ }
573
+ }
574
+ function attachCauseIfAbsent(target, cause) {
575
+ try {
576
+ if (target instanceof Error && !("cause" in target)) {
577
+ return Reflect.set(target, "cause", cause) && target.cause === cause;
578
+ }
579
+ return false;
580
+ } catch {
581
+ return false;
582
+ }
583
+ }
584
+ function scrubValuesFromErrorChain(error, values) {
585
+ if (!isSafeError(error)) {
586
+ if (error === void 0 || error === null) {
587
+ return error;
588
+ }
589
+ return coerceRedacted(error, values);
590
+ }
591
+ const seen = /* @__PURE__ */ new WeakMap();
592
+ const chain = [];
593
+ let headRepresentative = error;
594
+ let cursor = error;
595
+ while (!seen.has(cursor)) {
596
+ const link = registerLink(cursor, values, seen);
597
+ chain.push(link);
598
+ if (cursor === error) {
599
+ headRepresentative = link.representative;
600
+ }
601
+ if (!link.hasCause || !isSafeError(link.rawCause)) {
602
+ break;
603
+ }
604
+ cursor = link.rawCause;
605
+ }
606
+ wireCauses(chain, values, seen);
607
+ return headRepresentative;
608
+ }
609
+ function wireCauses(chain, values, seen) {
610
+ for (const link of chain) {
611
+ if (!link.hasCause) {
612
+ continue;
613
+ }
614
+ const raw = link.rawCause;
615
+ let childRepresentative;
616
+ if (isSafeError(raw)) {
617
+ childRepresentative = seen.get(raw);
618
+ } else if (raw === void 0 || raw === null) {
619
+ childRepresentative = raw;
620
+ } else {
621
+ childRepresentative = coerceRedacted(raw, values);
622
+ }
623
+ if (link.representative === link.node) {
624
+ Reflect.set(link.node, "cause", childRepresentative);
625
+ } else {
626
+ Object.defineProperty(link.representative, "cause", {
627
+ value: childRepresentative,
628
+ writable: true
629
+ });
630
+ }
631
+ }
632
+ }
633
+ function registerLink(node, values, seen) {
634
+ try {
635
+ const name = redactValues(node.name, values);
636
+ const message = redactValues(node.message, values);
637
+ const stack = node.stack === void 0 ? void 0 : redactValues(node.stack, values);
638
+ const hasCause = "cause" in node;
639
+ const rawCause = hasCause ? node.cause : void 0;
640
+ const applied = stripExtraProperties(node, values) && (node.name === name || Reflect.set(node, "name", name)) && Reflect.set(node, "message", message) && (stack === void 0 || Reflect.set(node, "stack", stack)) && (!hasCause || Reflect.set(node, "cause", void 0));
641
+ const inPlace = applied && node.name === name && node.message === message && // When `stack` is undefined the node had none and none was written, so
642
+ // the single read-back comparison covers both shapes.
643
+ node.stack === stack && (!hasCause || node.cause === void 0);
644
+ const representative = inPlace ? node : buildRedactedCopy(name, message, stack);
645
+ seen.set(node, representative);
646
+ return { node, representative, hasCause, rawCause };
647
+ } catch {
648
+ const representative = buildRedactedCopy("Error", REDACTED_VALUE, void 0);
649
+ seen.set(node, representative);
650
+ return { node, representative, hasCause: false, rawCause: void 0 };
651
+ }
652
+ }
653
+ function cloneRedacted(root, values) {
654
+ const seen = /* @__PURE__ */ new WeakMap();
655
+ const pending = [];
656
+ const cloneValue = (value) => {
657
+ if (typeof value === "string") {
658
+ return redactValues(value, values);
659
+ }
660
+ if (typeof value === "number" || typeof value === "bigint") {
661
+ return redactValues(String(value), values) === String(value) ? value : REDACTED_VALUE;
662
+ }
663
+ if (typeof value !== "object" || value === null) {
664
+ return value;
665
+ }
666
+ const existing = seen.get(value);
667
+ if (existing !== void 0) {
668
+ return existing;
669
+ }
670
+ const target = Array.isArray(value) ? [] : {};
671
+ seen.set(value, target);
672
+ pending.push({ source: value, target });
673
+ return target;
674
+ };
675
+ const result = cloneValue(root);
676
+ for (let entry = pending.pop(); entry !== void 0; entry = pending.pop()) {
677
+ for (const [key, descriptor] of collectOwnEntries(entry.source)) {
678
+ Object.defineProperty(entry.target, redactValues(key, values), {
679
+ value: "value" in descriptor ? cloneValue(descriptor.value) : REDACTED_VALUE,
680
+ enumerable: true,
681
+ configurable: true
682
+ });
683
+ }
684
+ }
685
+ return result;
686
+ }
687
+ function collectOwnEntries(source) {
688
+ try {
689
+ return Object.entries(Object.getOwnPropertyDescriptors(source)).filter(
690
+ ([, descriptor]) => descriptor.enumerable === true
691
+ );
692
+ } catch {
693
+ return [];
694
+ }
695
+ }
696
+ var STANDARD_ERROR_KEYS = /* @__PURE__ */ new Set(["name", "message", "stack", "cause"]);
697
+ var EXCEPTION_CONTRACT_KEYS = /* @__PURE__ */ new Set(["response", "status", "options", "code"]);
698
+ function deleteExtraOwnKeys(node, contractKeys) {
699
+ return Reflect.ownKeys(node).every(
700
+ (key) => STANDARD_ERROR_KEYS.has(key) || contractKeys.has(key) || Reflect.deleteProperty(node, key)
701
+ );
702
+ }
703
+ var NO_CONTRACT_KEYS = /* @__PURE__ */ new Set();
704
+ function stripExtraProperties(node, values) {
705
+ try {
706
+ if (node instanceof NotificationException) {
707
+ const redactedResponse = cloneRedacted(node.getResponse(), values);
708
+ const rebuiltOptions = {};
709
+ return Reflect.set(node, "response", redactedResponse) && node.getResponse() === redactedResponse && Reflect.set(node, "options", rebuiltOptions) && Reflect.get(node, "options") === rebuiltOptions && deleteExtraOwnKeys(node, EXCEPTION_CONTRACT_KEYS);
710
+ }
711
+ return deleteExtraOwnKeys(node, NO_CONTRACT_KEYS);
712
+ } catch {
713
+ return false;
714
+ }
715
+ }
716
+ function buildRedactedCopy(name, message, stack) {
717
+ const copy = new Error(message);
718
+ Object.defineProperty(copy, "name", { value: name, writable: true });
719
+ if (stack !== void 0) {
720
+ copy.stack = stack;
721
+ }
722
+ return copy;
723
+ }
724
+
725
+ // src/server/services/email.service.ts
513
726
  var FALLBACK_LOCALE = "en";
514
727
  exports.EmailService = class EmailService {
515
728
  /**
@@ -559,10 +772,14 @@ exports.EmailService = class EmailService {
559
772
  }
560
773
  await this.audit(
561
774
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
562
- errorMessage: error instanceof Error ? error.message : String(error)
775
+ errorMessage: readRedactedMessage(error, input.auditRedactValues)
563
776
  })
564
777
  );
565
- throw new NotificationException("EMAIL_SEND_FAILED", { providerName: this.provider.name });
778
+ throw new NotificationException(
779
+ "EMAIL_SEND_FAILED",
780
+ { providerName: this.provider.name },
781
+ { cause: error }
782
+ );
566
783
  }
567
784
  }
568
785
  /**
@@ -588,7 +805,8 @@ exports.EmailService = class EmailService {
588
805
  ...input.from !== void 0 ? { from: input.from } : {},
589
806
  ...input.fromName !== void 0 ? { fromName: input.fromName } : {},
590
807
  ...input.replyTo !== void 0 ? { replyTo: input.replyTo } : {},
591
- ...input.userId !== void 0 ? { userId: input.userId } : {}
808
+ ...input.userId !== void 0 ? { userId: input.userId } : {},
809
+ ...input.auditRedactValues !== void 0 ? { auditRedactValues: input.auditRedactValues } : {}
592
810
  });
593
811
  }
594
812
  /** Returns the resolved email options or throws when the channel is not configured. */
@@ -649,8 +867,8 @@ exports.EmailService = class EmailService {
649
867
  async renderTemplate(template, data, locale) {
650
868
  try {
651
869
  return await this.renderer.render(template, data, locale);
652
- } catch {
653
- throw new NotificationException("TEMPLATE_RENDER_FAILED", { template });
870
+ } catch (error) {
871
+ throw new NotificationException("TEMPLATE_RENDER_FAILED", { template }, { cause: error });
654
872
  }
655
873
  }
656
874
  /** Builds an audit entry with the recipient already masked. */
@@ -673,9 +891,7 @@ exports.EmailService = class EmailService {
673
891
  await this.auditLog.create(entry);
674
892
  } catch (error) {
675
893
  if (!this.options.audit.swallowErrors) {
676
- throw new NotificationException("AUDIT_LOG_FAILED", {
677
- cause: error instanceof Error ? error.message : String(error)
678
- });
894
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
679
895
  }
680
896
  }
681
897
  }
@@ -922,13 +1138,22 @@ exports.OtpService = class OtpService {
922
1138
  });
923
1139
  await this.deliverOtp(input, code, cfg);
924
1140
  } catch (error) {
925
- await this.releaseOtp(input);
1141
+ let failure = error;
1142
+ try {
1143
+ await this.releaseOtp(input);
1144
+ } catch (cleanupError) {
1145
+ attachCauseIfAbsent(cleanupError, error);
1146
+ failure = cleanupError;
1147
+ }
1148
+ const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
926
1149
  await this.audit(
927
1150
  this.otpAuditEntry("failed", input, {
928
- errorMessage: error instanceof Error ? error.message : String(error)
1151
+ // `outgoing` is already fully redacted by the scrub above; this read
1152
+ // only needs the fail-closed guard, not a second redaction pass.
1153
+ errorMessage: readRedactedMessage(outgoing)
929
1154
  })
930
1155
  );
931
- throw error;
1156
+ throw outgoing;
932
1157
  }
933
1158
  }
934
1159
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
@@ -955,6 +1180,9 @@ exports.OtpService = class OtpService {
955
1180
  to: input.recipient,
956
1181
  template: input.emailTemplate ?? DEFAULT_OTP_TEMPLATE,
957
1182
  data: { ...input.emailData, code, expiresInMinutes, purpose: input.purpose },
1183
+ // The provider receives the code inside the rendered body and may echo it
1184
+ // in an error; EmailService must redact it from ITS OWN failed-audit entry.
1185
+ auditRedactValues: [code],
958
1186
  ...input.locale !== void 0 ? { locale: input.locale } : {},
959
1187
  ...input.userId !== void 0 ? { userId: input.userId } : {}
960
1188
  };
@@ -999,9 +1227,7 @@ exports.OtpService = class OtpService {
999
1227
  await this.auditLog.create(entry);
1000
1228
  } catch (error) {
1001
1229
  if (!this.options.audit.swallowErrors) {
1002
- throw new NotificationException("AUDIT_LOG_FAILED", {
1003
- cause: error instanceof Error ? error.message : String(error)
1004
- });
1230
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1005
1231
  }
1006
1232
  }
1007
1233
  }
@@ -1437,7 +1663,7 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
1437
1663
  await this.auditLog.create(this.buildEntry(input, tenantId, verb, errorMessage));
1438
1664
  } catch (error) {
1439
1665
  if (!this.options.audit.swallowErrors) {
1440
- throw new NotificationException("AUDIT_LOG_FAILED", { cause: toErrorMessage(error) });
1666
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1441
1667
  }
1442
1668
  }
1443
1669
  }
@@ -1586,6 +1812,34 @@ exports.NoOpEmailProvider = class NoOpEmailProvider {
1586
1812
  exports.NoOpEmailProvider = __decorateClass([
1587
1813
  common.Injectable()
1588
1814
  ], exports.NoOpEmailProvider);
1815
+
1816
+ // src/server/utils/load-optional-peer.ts
1817
+ var MODULE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
1818
+ "ERR_MODULE_NOT_FOUND",
1819
+ "MODULE_NOT_FOUND"
1820
+ ]);
1821
+ function isModuleNotFound(error, moduleName) {
1822
+ const candidate = error;
1823
+ if (typeof candidate?.code !== "string" || !MODULE_NOT_FOUND_CODES.has(candidate.code)) {
1824
+ return false;
1825
+ }
1826
+ return typeof candidate.message === "string" && candidate.message.includes(`'${moduleName}'`);
1827
+ }
1828
+ async function loadOptionalPeer(moduleName) {
1829
+ try {
1830
+ return await import(moduleName);
1831
+ } catch (error) {
1832
+ if (isModuleNotFound(error, moduleName)) {
1833
+ throw new Error(
1834
+ `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`
1835
+ );
1836
+ }
1837
+ const reason = error instanceof Error ? error.message : String(error);
1838
+ throw new Error(`Failed to load \`${moduleName}\`: ${reason}`, { cause: error });
1839
+ }
1840
+ }
1841
+
1842
+ // src/server/providers/resend-email.provider.ts
1589
1843
  var RESEND_MODULE = "resend";
1590
1844
  var _clientPromise, _options;
1591
1845
  exports.ResendEmailProvider = class ResendEmailProvider {
@@ -1710,17 +1964,12 @@ exports.ResendEmailProvider = class ResendEmailProvider {
1710
1964
  * Dynamically imports the optional `resend` peer dependency.
1711
1965
  *
1712
1966
  * @returns The SDK's `Resend` constructor.
1713
- * @throws Error When the package is not installed in the consumer app.
1967
+ * @throws Error When the package is not installed, or — reported as itself rather
1968
+ * than as a missing package — when the import fails for any other reason.
1714
1969
  */
1715
1970
  async loadResendConstructor() {
1716
- try {
1717
- const mod = await import(RESEND_MODULE);
1718
- return mod.Resend;
1719
- } catch {
1720
- throw new Error(
1721
- "`resend` package is not installed. Run `pnpm add resend` in the consumer app."
1722
- );
1723
- }
1971
+ const mod = await loadOptionalPeer(RESEND_MODULE);
1972
+ return mod.Resend;
1724
1973
  }
1725
1974
  };
1726
1975
  _clientPromise = new WeakMap();
@@ -2077,17 +2326,11 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2077
2326
  * a named export, and one where the CommonJS module lands under `default`.
2078
2327
  *
2079
2328
  * @returns The module's callable surface.
2080
- * @throws Error When the package is not installed in the consumer app.
2329
+ * @throws Error When the package is not installed, or — reported as itself rather
2330
+ * than as a missing package — when the import fails for any other reason.
2081
2331
  */
2082
2332
  async loadNodemailer() {
2083
- let mod;
2084
- try {
2085
- mod = await import(NODEMAILER_MODULE);
2086
- } catch {
2087
- throw new Error(
2088
- "`nodemailer` package is not installed. Run `pnpm add nodemailer` in the consumer app."
2089
- );
2090
- }
2333
+ const mod = await loadOptionalPeer(NODEMAILER_MODULE);
2091
2334
  const candidate = mod.createTransport ? mod : mod.default;
2092
2335
  if (!candidate?.createTransport) {
2093
2336
  throw new Error("`nodemailer` package exposes no createTransport export");
@@ -754,6 +754,11 @@ interface EmailSendInput {
754
754
  attachments?: EmailSendOptions['attachments'];
755
755
  /** Associated user id, recorded in the audit entry. */
756
756
  userId?: string;
757
+ /**
758
+ * Secret values (e.g. an OTP code the body carries) redacted from the audit
759
+ * entry's `errorMessage` when a provider failure echoes them back.
760
+ */
761
+ auditRedactValues?: readonly string[];
757
762
  }
758
763
  /** Input for {@link EmailService.sendTemplate} — the renderer produces the body. */
759
764
  interface EmailSendTemplateInput {
@@ -767,6 +772,11 @@ interface EmailSendTemplateInput {
767
772
  replyTo?: string;
768
773
  tags?: ReadonlyArray<EmailTag$1>;
769
774
  userId?: string;
775
+ /**
776
+ * Secret values (e.g. an OTP code inside `data`) redacted from the audit
777
+ * entry's `errorMessage` when a provider failure echoes them back.
778
+ */
779
+ auditRedactValues?: readonly string[];
770
780
  }
771
781
  /** Transactional email service. */
772
782
  declare class EmailService {
@@ -1485,7 +1495,8 @@ declare class ResendEmailProvider implements IEmailProvider {
1485
1495
  * Dynamically imports the optional `resend` peer dependency.
1486
1496
  *
1487
1497
  * @returns The SDK's `Resend` constructor.
1488
- * @throws Error When the package is not installed in the consumer app.
1498
+ * @throws Error When the package is not installed, or — reported as itself rather
1499
+ * than as a missing package — when the import fails for any other reason.
1489
1500
  */
1490
1501
  private loadResendConstructor;
1491
1502
  }
@@ -1798,7 +1809,8 @@ declare class SmtpEmailProvider implements IEmailProvider {
1798
1809
  * a named export, and one where the CommonJS module lands under `default`.
1799
1810
  *
1800
1811
  * @returns The module's callable surface.
1801
- * @throws Error When the package is not installed in the consumer app.
1812
+ * @throws Error When the package is not installed, or — reported as itself rather
1813
+ * than as a missing package — when the import fails for any other reason.
1802
1814
  */
1803
1815
  private loadNodemailer;
1804
1816
  }
@@ -2364,12 +2376,33 @@ type NotificationErrorKey = keyof typeof NOTIFICATION_ERROR_DEFINITIONS;
2364
2376
  * on `error.code` to localize the message.
2365
2377
  */
2366
2378
 
2379
+ /**
2380
+ * Optional construction knobs, mirroring how `HttpException` itself moved its
2381
+ * positional arguments into an options object.
2382
+ */
2383
+ interface NotificationExceptionOptions {
2384
+ /** Replaces the catalog's default HTTP status when supplied. */
2385
+ status?: HttpStatus;
2386
+ /** Replaces the catalog's default message when supplied. */
2387
+ message?: string;
2388
+ /**
2389
+ * The underlying error, exposed as the native `Error.cause` so log serializers
2390
+ * can walk the chain. Stored as a log-safe copy — `name`, `message`, `stack`,
2391
+ * and the nested `cause` chain are preserved (depth-bounded); every other
2392
+ * property is dropped so an SDK error that retains the request payload cannot
2393
+ * leak an OTP-bearing body into logs. Never serialized into the HTTP response
2394
+ * body. A falsy value is ignored — `HttpException` only installs a truthy cause.
2395
+ */
2396
+ cause?: unknown;
2397
+ }
2367
2398
  /**
2368
2399
  * Typed HTTP exception over the notification error catalog.
2369
2400
  *
2370
2401
  * @example
2371
2402
  * ```ts
2372
2403
  * throw new NotificationException('OTP_INVALID_LENGTH', { provided: 0, allowed: '1-32' })
2404
+ * // With the underlying error attached as `Error.cause`:
2405
+ * throw new NotificationException('EMAIL_SEND_FAILED', { providerName: 'smtp' }, { cause: error })
2373
2406
  * ```
2374
2407
  */
2375
2408
  declare class NotificationException extends HttpException {
@@ -2378,10 +2411,13 @@ declare class NotificationException extends HttpException {
2378
2411
  /**
2379
2412
  * @param key - Catalog key selecting the code, default HTTP status, and message.
2380
2413
  * @param details - Optional structured context placed under `error.details`.
2381
- * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
2382
- * @param overrideMessage - Replaces the catalog's default message when supplied.
2414
+ * @param optionsOrStatus - An {@link NotificationExceptionOptions} object, or — kept
2415
+ * for backward compatibility — a bare `HttpStatus` acting as `options.status`.
2416
+ * @param overrideMessage - Replaces the catalog's default message when supplied;
2417
+ * kept for backward compatibility with the positional form. `options.message` wins
2418
+ * when both are given.
2383
2419
  */
2384
- constructor(key: NotificationErrorKey, details?: Record<string, unknown>, overrideStatus?: HttpStatus, overrideMessage?: string);
2420
+ constructor(key: NotificationErrorKey, details?: Record<string, unknown>, optionsOrStatus?: HttpStatus | NotificationExceptionOptions, overrideMessage?: string);
2385
2421
  }
2386
2422
 
2387
2423
  /**
@@ -2458,4 +2494,4 @@ declare const DEFAULT_TTLS: {
2458
2494
  readonly OTP_GENERIC_SECONDS: 600;
2459
2495
  };
2460
2496
 
2461
- export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2497
+ export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationExceptionOptions, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
@@ -754,6 +754,11 @@ interface EmailSendInput {
754
754
  attachments?: EmailSendOptions['attachments'];
755
755
  /** Associated user id, recorded in the audit entry. */
756
756
  userId?: string;
757
+ /**
758
+ * Secret values (e.g. an OTP code the body carries) redacted from the audit
759
+ * entry's `errorMessage` when a provider failure echoes them back.
760
+ */
761
+ auditRedactValues?: readonly string[];
757
762
  }
758
763
  /** Input for {@link EmailService.sendTemplate} — the renderer produces the body. */
759
764
  interface EmailSendTemplateInput {
@@ -767,6 +772,11 @@ interface EmailSendTemplateInput {
767
772
  replyTo?: string;
768
773
  tags?: ReadonlyArray<EmailTag$1>;
769
774
  userId?: string;
775
+ /**
776
+ * Secret values (e.g. an OTP code inside `data`) redacted from the audit
777
+ * entry's `errorMessage` when a provider failure echoes them back.
778
+ */
779
+ auditRedactValues?: readonly string[];
770
780
  }
771
781
  /** Transactional email service. */
772
782
  declare class EmailService {
@@ -1485,7 +1495,8 @@ declare class ResendEmailProvider implements IEmailProvider {
1485
1495
  * Dynamically imports the optional `resend` peer dependency.
1486
1496
  *
1487
1497
  * @returns The SDK's `Resend` constructor.
1488
- * @throws Error When the package is not installed in the consumer app.
1498
+ * @throws Error When the package is not installed, or — reported as itself rather
1499
+ * than as a missing package — when the import fails for any other reason.
1489
1500
  */
1490
1501
  private loadResendConstructor;
1491
1502
  }
@@ -1798,7 +1809,8 @@ declare class SmtpEmailProvider implements IEmailProvider {
1798
1809
  * a named export, and one where the CommonJS module lands under `default`.
1799
1810
  *
1800
1811
  * @returns The module's callable surface.
1801
- * @throws Error When the package is not installed in the consumer app.
1812
+ * @throws Error When the package is not installed, or — reported as itself rather
1813
+ * than as a missing package — when the import fails for any other reason.
1802
1814
  */
1803
1815
  private loadNodemailer;
1804
1816
  }
@@ -2364,12 +2376,33 @@ type NotificationErrorKey = keyof typeof NOTIFICATION_ERROR_DEFINITIONS;
2364
2376
  * on `error.code` to localize the message.
2365
2377
  */
2366
2378
 
2379
+ /**
2380
+ * Optional construction knobs, mirroring how `HttpException` itself moved its
2381
+ * positional arguments into an options object.
2382
+ */
2383
+ interface NotificationExceptionOptions {
2384
+ /** Replaces the catalog's default HTTP status when supplied. */
2385
+ status?: HttpStatus;
2386
+ /** Replaces the catalog's default message when supplied. */
2387
+ message?: string;
2388
+ /**
2389
+ * The underlying error, exposed as the native `Error.cause` so log serializers
2390
+ * can walk the chain. Stored as a log-safe copy — `name`, `message`, `stack`,
2391
+ * and the nested `cause` chain are preserved (depth-bounded); every other
2392
+ * property is dropped so an SDK error that retains the request payload cannot
2393
+ * leak an OTP-bearing body into logs. Never serialized into the HTTP response
2394
+ * body. A falsy value is ignored — `HttpException` only installs a truthy cause.
2395
+ */
2396
+ cause?: unknown;
2397
+ }
2367
2398
  /**
2368
2399
  * Typed HTTP exception over the notification error catalog.
2369
2400
  *
2370
2401
  * @example
2371
2402
  * ```ts
2372
2403
  * throw new NotificationException('OTP_INVALID_LENGTH', { provided: 0, allowed: '1-32' })
2404
+ * // With the underlying error attached as `Error.cause`:
2405
+ * throw new NotificationException('EMAIL_SEND_FAILED', { providerName: 'smtp' }, { cause: error })
2373
2406
  * ```
2374
2407
  */
2375
2408
  declare class NotificationException extends HttpException {
@@ -2378,10 +2411,13 @@ declare class NotificationException extends HttpException {
2378
2411
  /**
2379
2412
  * @param key - Catalog key selecting the code, default HTTP status, and message.
2380
2413
  * @param details - Optional structured context placed under `error.details`.
2381
- * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
2382
- * @param overrideMessage - Replaces the catalog's default message when supplied.
2414
+ * @param optionsOrStatus - An {@link NotificationExceptionOptions} object, or — kept
2415
+ * for backward compatibility — a bare `HttpStatus` acting as `options.status`.
2416
+ * @param overrideMessage - Replaces the catalog's default message when supplied;
2417
+ * kept for backward compatibility with the positional form. `options.message` wins
2418
+ * when both are given.
2383
2419
  */
2384
- constructor(key: NotificationErrorKey, details?: Record<string, unknown>, overrideStatus?: HttpStatus, overrideMessage?: string);
2420
+ constructor(key: NotificationErrorKey, details?: Record<string, unknown>, optionsOrStatus?: HttpStatus | NotificationExceptionOptions, overrideMessage?: string);
2385
2421
  }
2386
2422
 
2387
2423
  /**
@@ -2458,4 +2494,4 @@ declare const DEFAULT_TTLS: {
2458
2494
  readonly OTP_GENERIC_SECONDS: 600;
2459
2495
  };
2460
2496
 
2461
- export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2497
+ export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationExceptionOptions, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
@@ -270,23 +270,53 @@ var FALLBACK_DEFINITION = {
270
270
  status: HttpStatus.INTERNAL_SERVER_ERROR,
271
271
  message: "Unknown notification error"
272
272
  };
273
+ var MAX_CAUSE_DEPTH = 5;
274
+ var UNREADABLE_CAUSE_MESSAGE = "Cause unavailable: inspecting it threw";
275
+ function toLogSafeCause(cause, depth = 0) {
276
+ try {
277
+ return copyLogSafeCause(cause, depth);
278
+ } catch {
279
+ return new Error(UNREADABLE_CAUSE_MESSAGE);
280
+ }
281
+ }
282
+ function copyLogSafeCause(cause, depth) {
283
+ if (cause instanceof Error) {
284
+ const safe = new Error(cause.message);
285
+ Object.defineProperty(safe, "name", { value: cause.name, writable: true });
286
+ if (cause.stack !== void 0) {
287
+ safe.stack = cause.stack;
288
+ }
289
+ if (depth < MAX_CAUSE_DEPTH && "cause" in cause) {
290
+ Object.defineProperty(safe, "cause", {
291
+ value: toLogSafeCause(cause.cause, depth + 1),
292
+ writable: true
293
+ });
294
+ }
295
+ return safe;
296
+ }
297
+ return typeof cause === "object" && cause !== null ? String(cause) : cause;
298
+ }
273
299
  var NotificationException = class extends HttpException {
274
300
  /**
275
301
  * @param key - Catalog key selecting the code, default HTTP status, and message.
276
302
  * @param details - Optional structured context placed under `error.details`.
277
- * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
278
- * @param overrideMessage - Replaces the catalog's default message when supplied.
303
+ * @param optionsOrStatus - An {@link NotificationExceptionOptions} object, or — kept
304
+ * for backward compatibility — a bare `HttpStatus` acting as `options.status`.
305
+ * @param overrideMessage - Replaces the catalog's default message when supplied;
306
+ * kept for backward compatibility with the positional form. `options.message` wins
307
+ * when both are given.
279
308
  */
280
- constructor(key, details, overrideStatus, overrideMessage) {
309
+ constructor(key, details, optionsOrStatus, overrideMessage) {
281
310
  const definition = NOTIFICATION_ERROR_DEFINITION_MAP.get(key) ?? FALLBACK_DEFINITION;
311
+ const options = typeof optionsOrStatus === "number" ? { status: optionsOrStatus } : optionsOrStatus ?? {};
282
312
  const body = {
283
313
  error: {
284
314
  code: definition.code,
285
- message: overrideMessage ?? definition.message,
315
+ message: options.message ?? overrideMessage ?? definition.message,
286
316
  details: details ?? null
287
317
  }
288
318
  };
289
- super(body, overrideStatus ?? definition.status);
319
+ super(body, options.status ?? definition.status, { cause: toLogSafeCause(options.cause) });
290
320
  this.code = definition.code;
291
321
  }
292
322
  };
@@ -508,6 +538,189 @@ var NoOpNotificationLogRepository = class {
508
538
  NoOpNotificationLogRepository = __decorateClass([
509
539
  Injectable()
510
540
  ], NoOpNotificationLogRepository);
541
+
542
+ // src/server/utils/redact.ts
543
+ var REDACTED_VALUE = "[redacted]";
544
+ function redactValues(text, values) {
545
+ return values.reduce(
546
+ (cleaned, value) => value === "" ? cleaned : cleaned.split(value).join(REDACTED_VALUE),
547
+ text
548
+ );
549
+ }
550
+ function coerceRedacted(value, values) {
551
+ try {
552
+ return redactValues(String(value), values);
553
+ } catch {
554
+ return REDACTED_VALUE;
555
+ }
556
+ }
557
+ function readRedactedMessage(error, values) {
558
+ try {
559
+ const message = error instanceof Error ? error.message : String(error);
560
+ return values ? redactValues(message, values) : message;
561
+ } catch {
562
+ return REDACTED_VALUE;
563
+ }
564
+ }
565
+ function isSafeError(value) {
566
+ try {
567
+ return value instanceof Error;
568
+ } catch {
569
+ return false;
570
+ }
571
+ }
572
+ function attachCauseIfAbsent(target, cause) {
573
+ try {
574
+ if (target instanceof Error && !("cause" in target)) {
575
+ return Reflect.set(target, "cause", cause) && target.cause === cause;
576
+ }
577
+ return false;
578
+ } catch {
579
+ return false;
580
+ }
581
+ }
582
+ function scrubValuesFromErrorChain(error, values) {
583
+ if (!isSafeError(error)) {
584
+ if (error === void 0 || error === null) {
585
+ return error;
586
+ }
587
+ return coerceRedacted(error, values);
588
+ }
589
+ const seen = /* @__PURE__ */ new WeakMap();
590
+ const chain = [];
591
+ let headRepresentative = error;
592
+ let cursor = error;
593
+ while (!seen.has(cursor)) {
594
+ const link = registerLink(cursor, values, seen);
595
+ chain.push(link);
596
+ if (cursor === error) {
597
+ headRepresentative = link.representative;
598
+ }
599
+ if (!link.hasCause || !isSafeError(link.rawCause)) {
600
+ break;
601
+ }
602
+ cursor = link.rawCause;
603
+ }
604
+ wireCauses(chain, values, seen);
605
+ return headRepresentative;
606
+ }
607
+ function wireCauses(chain, values, seen) {
608
+ for (const link of chain) {
609
+ if (!link.hasCause) {
610
+ continue;
611
+ }
612
+ const raw = link.rawCause;
613
+ let childRepresentative;
614
+ if (isSafeError(raw)) {
615
+ childRepresentative = seen.get(raw);
616
+ } else if (raw === void 0 || raw === null) {
617
+ childRepresentative = raw;
618
+ } else {
619
+ childRepresentative = coerceRedacted(raw, values);
620
+ }
621
+ if (link.representative === link.node) {
622
+ Reflect.set(link.node, "cause", childRepresentative);
623
+ } else {
624
+ Object.defineProperty(link.representative, "cause", {
625
+ value: childRepresentative,
626
+ writable: true
627
+ });
628
+ }
629
+ }
630
+ }
631
+ function registerLink(node, values, seen) {
632
+ try {
633
+ const name = redactValues(node.name, values);
634
+ const message = redactValues(node.message, values);
635
+ const stack = node.stack === void 0 ? void 0 : redactValues(node.stack, values);
636
+ const hasCause = "cause" in node;
637
+ const rawCause = hasCause ? node.cause : void 0;
638
+ const applied = stripExtraProperties(node, values) && (node.name === name || Reflect.set(node, "name", name)) && Reflect.set(node, "message", message) && (stack === void 0 || Reflect.set(node, "stack", stack)) && (!hasCause || Reflect.set(node, "cause", void 0));
639
+ const inPlace = applied && node.name === name && node.message === message && // When `stack` is undefined the node had none and none was written, so
640
+ // the single read-back comparison covers both shapes.
641
+ node.stack === stack && (!hasCause || node.cause === void 0);
642
+ const representative = inPlace ? node : buildRedactedCopy(name, message, stack);
643
+ seen.set(node, representative);
644
+ return { node, representative, hasCause, rawCause };
645
+ } catch {
646
+ const representative = buildRedactedCopy("Error", REDACTED_VALUE, void 0);
647
+ seen.set(node, representative);
648
+ return { node, representative, hasCause: false, rawCause: void 0 };
649
+ }
650
+ }
651
+ function cloneRedacted(root, values) {
652
+ const seen = /* @__PURE__ */ new WeakMap();
653
+ const pending = [];
654
+ const cloneValue = (value) => {
655
+ if (typeof value === "string") {
656
+ return redactValues(value, values);
657
+ }
658
+ if (typeof value === "number" || typeof value === "bigint") {
659
+ return redactValues(String(value), values) === String(value) ? value : REDACTED_VALUE;
660
+ }
661
+ if (typeof value !== "object" || value === null) {
662
+ return value;
663
+ }
664
+ const existing = seen.get(value);
665
+ if (existing !== void 0) {
666
+ return existing;
667
+ }
668
+ const target = Array.isArray(value) ? [] : {};
669
+ seen.set(value, target);
670
+ pending.push({ source: value, target });
671
+ return target;
672
+ };
673
+ const result = cloneValue(root);
674
+ for (let entry = pending.pop(); entry !== void 0; entry = pending.pop()) {
675
+ for (const [key, descriptor] of collectOwnEntries(entry.source)) {
676
+ Object.defineProperty(entry.target, redactValues(key, values), {
677
+ value: "value" in descriptor ? cloneValue(descriptor.value) : REDACTED_VALUE,
678
+ enumerable: true,
679
+ configurable: true
680
+ });
681
+ }
682
+ }
683
+ return result;
684
+ }
685
+ function collectOwnEntries(source) {
686
+ try {
687
+ return Object.entries(Object.getOwnPropertyDescriptors(source)).filter(
688
+ ([, descriptor]) => descriptor.enumerable === true
689
+ );
690
+ } catch {
691
+ return [];
692
+ }
693
+ }
694
+ var STANDARD_ERROR_KEYS = /* @__PURE__ */ new Set(["name", "message", "stack", "cause"]);
695
+ var EXCEPTION_CONTRACT_KEYS = /* @__PURE__ */ new Set(["response", "status", "options", "code"]);
696
+ function deleteExtraOwnKeys(node, contractKeys) {
697
+ return Reflect.ownKeys(node).every(
698
+ (key) => STANDARD_ERROR_KEYS.has(key) || contractKeys.has(key) || Reflect.deleteProperty(node, key)
699
+ );
700
+ }
701
+ var NO_CONTRACT_KEYS = /* @__PURE__ */ new Set();
702
+ function stripExtraProperties(node, values) {
703
+ try {
704
+ if (node instanceof NotificationException) {
705
+ const redactedResponse = cloneRedacted(node.getResponse(), values);
706
+ const rebuiltOptions = {};
707
+ return Reflect.set(node, "response", redactedResponse) && node.getResponse() === redactedResponse && Reflect.set(node, "options", rebuiltOptions) && Reflect.get(node, "options") === rebuiltOptions && deleteExtraOwnKeys(node, EXCEPTION_CONTRACT_KEYS);
708
+ }
709
+ return deleteExtraOwnKeys(node, NO_CONTRACT_KEYS);
710
+ } catch {
711
+ return false;
712
+ }
713
+ }
714
+ function buildRedactedCopy(name, message, stack) {
715
+ const copy = new Error(message);
716
+ Object.defineProperty(copy, "name", { value: name, writable: true });
717
+ if (stack !== void 0) {
718
+ copy.stack = stack;
719
+ }
720
+ return copy;
721
+ }
722
+
723
+ // src/server/services/email.service.ts
511
724
  var FALLBACK_LOCALE = "en";
512
725
  var EmailService = class {
513
726
  /**
@@ -557,10 +770,14 @@ var EmailService = class {
557
770
  }
558
771
  await this.audit(
559
772
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
560
- errorMessage: error instanceof Error ? error.message : String(error)
773
+ errorMessage: readRedactedMessage(error, input.auditRedactValues)
561
774
  })
562
775
  );
563
- throw new NotificationException("EMAIL_SEND_FAILED", { providerName: this.provider.name });
776
+ throw new NotificationException(
777
+ "EMAIL_SEND_FAILED",
778
+ { providerName: this.provider.name },
779
+ { cause: error }
780
+ );
564
781
  }
565
782
  }
566
783
  /**
@@ -586,7 +803,8 @@ var EmailService = class {
586
803
  ...input.from !== void 0 ? { from: input.from } : {},
587
804
  ...input.fromName !== void 0 ? { fromName: input.fromName } : {},
588
805
  ...input.replyTo !== void 0 ? { replyTo: input.replyTo } : {},
589
- ...input.userId !== void 0 ? { userId: input.userId } : {}
806
+ ...input.userId !== void 0 ? { userId: input.userId } : {},
807
+ ...input.auditRedactValues !== void 0 ? { auditRedactValues: input.auditRedactValues } : {}
590
808
  });
591
809
  }
592
810
  /** Returns the resolved email options or throws when the channel is not configured. */
@@ -647,8 +865,8 @@ var EmailService = class {
647
865
  async renderTemplate(template, data, locale) {
648
866
  try {
649
867
  return await this.renderer.render(template, data, locale);
650
- } catch {
651
- throw new NotificationException("TEMPLATE_RENDER_FAILED", { template });
868
+ } catch (error) {
869
+ throw new NotificationException("TEMPLATE_RENDER_FAILED", { template }, { cause: error });
652
870
  }
653
871
  }
654
872
  /** Builds an audit entry with the recipient already masked. */
@@ -671,9 +889,7 @@ var EmailService = class {
671
889
  await this.auditLog.create(entry);
672
890
  } catch (error) {
673
891
  if (!this.options.audit.swallowErrors) {
674
- throw new NotificationException("AUDIT_LOG_FAILED", {
675
- cause: error instanceof Error ? error.message : String(error)
676
- });
892
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
677
893
  }
678
894
  }
679
895
  }
@@ -920,13 +1136,22 @@ var OtpService = class {
920
1136
  });
921
1137
  await this.deliverOtp(input, code, cfg);
922
1138
  } catch (error) {
923
- await this.releaseOtp(input);
1139
+ let failure = error;
1140
+ try {
1141
+ await this.releaseOtp(input);
1142
+ } catch (cleanupError) {
1143
+ attachCauseIfAbsent(cleanupError, error);
1144
+ failure = cleanupError;
1145
+ }
1146
+ const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
924
1147
  await this.audit(
925
1148
  this.otpAuditEntry("failed", input, {
926
- errorMessage: error instanceof Error ? error.message : String(error)
1149
+ // `outgoing` is already fully redacted by the scrub above; this read
1150
+ // only needs the fail-closed guard, not a second redaction pass.
1151
+ errorMessage: readRedactedMessage(outgoing)
927
1152
  })
928
1153
  );
929
- throw error;
1154
+ throw outgoing;
930
1155
  }
931
1156
  }
932
1157
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
@@ -953,6 +1178,9 @@ var OtpService = class {
953
1178
  to: input.recipient,
954
1179
  template: input.emailTemplate ?? DEFAULT_OTP_TEMPLATE,
955
1180
  data: { ...input.emailData, code, expiresInMinutes, purpose: input.purpose },
1181
+ // The provider receives the code inside the rendered body and may echo it
1182
+ // in an error; EmailService must redact it from ITS OWN failed-audit entry.
1183
+ auditRedactValues: [code],
956
1184
  ...input.locale !== void 0 ? { locale: input.locale } : {},
957
1185
  ...input.userId !== void 0 ? { userId: input.userId } : {}
958
1186
  };
@@ -997,9 +1225,7 @@ var OtpService = class {
997
1225
  await this.auditLog.create(entry);
998
1226
  } catch (error) {
999
1227
  if (!this.options.audit.swallowErrors) {
1000
- throw new NotificationException("AUDIT_LOG_FAILED", {
1001
- cause: error instanceof Error ? error.message : String(error)
1002
- });
1228
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1003
1229
  }
1004
1230
  }
1005
1231
  }
@@ -1435,7 +1661,7 @@ var NotificationAuditInterceptor = class {
1435
1661
  await this.auditLog.create(this.buildEntry(input, tenantId, verb, errorMessage));
1436
1662
  } catch (error) {
1437
1663
  if (!this.options.audit.swallowErrors) {
1438
- throw new NotificationException("AUDIT_LOG_FAILED", { cause: toErrorMessage(error) });
1664
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1439
1665
  }
1440
1666
  }
1441
1667
  }
@@ -1584,6 +1810,34 @@ var NoOpEmailProvider = class {
1584
1810
  NoOpEmailProvider = __decorateClass([
1585
1811
  Injectable()
1586
1812
  ], NoOpEmailProvider);
1813
+
1814
+ // src/server/utils/load-optional-peer.ts
1815
+ var MODULE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
1816
+ "ERR_MODULE_NOT_FOUND",
1817
+ "MODULE_NOT_FOUND"
1818
+ ]);
1819
+ function isModuleNotFound(error, moduleName) {
1820
+ const candidate = error;
1821
+ if (typeof candidate?.code !== "string" || !MODULE_NOT_FOUND_CODES.has(candidate.code)) {
1822
+ return false;
1823
+ }
1824
+ return typeof candidate.message === "string" && candidate.message.includes(`'${moduleName}'`);
1825
+ }
1826
+ async function loadOptionalPeer(moduleName) {
1827
+ try {
1828
+ return await import(moduleName);
1829
+ } catch (error) {
1830
+ if (isModuleNotFound(error, moduleName)) {
1831
+ throw new Error(
1832
+ `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`
1833
+ );
1834
+ }
1835
+ const reason = error instanceof Error ? error.message : String(error);
1836
+ throw new Error(`Failed to load \`${moduleName}\`: ${reason}`, { cause: error });
1837
+ }
1838
+ }
1839
+
1840
+ // src/server/providers/resend-email.provider.ts
1587
1841
  var RESEND_MODULE = "resend";
1588
1842
  var _clientPromise, _options;
1589
1843
  var ResendEmailProvider = class {
@@ -1708,17 +1962,12 @@ var ResendEmailProvider = class {
1708
1962
  * Dynamically imports the optional `resend` peer dependency.
1709
1963
  *
1710
1964
  * @returns The SDK's `Resend` constructor.
1711
- * @throws Error When the package is not installed in the consumer app.
1965
+ * @throws Error When the package is not installed, or — reported as itself rather
1966
+ * than as a missing package — when the import fails for any other reason.
1712
1967
  */
1713
1968
  async loadResendConstructor() {
1714
- try {
1715
- const mod = await import(RESEND_MODULE);
1716
- return mod.Resend;
1717
- } catch {
1718
- throw new Error(
1719
- "`resend` package is not installed. Run `pnpm add resend` in the consumer app."
1720
- );
1721
- }
1969
+ const mod = await loadOptionalPeer(RESEND_MODULE);
1970
+ return mod.Resend;
1722
1971
  }
1723
1972
  };
1724
1973
  _clientPromise = new WeakMap();
@@ -2075,17 +2324,11 @@ var SmtpEmailProvider = class {
2075
2324
  * a named export, and one where the CommonJS module lands under `default`.
2076
2325
  *
2077
2326
  * @returns The module's callable surface.
2078
- * @throws Error When the package is not installed in the consumer app.
2327
+ * @throws Error When the package is not installed, or — reported as itself rather
2328
+ * than as a missing package — when the import fails for any other reason.
2079
2329
  */
2080
2330
  async loadNodemailer() {
2081
- let mod;
2082
- try {
2083
- mod = await import(NODEMAILER_MODULE);
2084
- } catch {
2085
- throw new Error(
2086
- "`nodemailer` package is not installed. Run `pnpm add nodemailer` in the consumer app."
2087
- );
2088
- }
2331
+ const mod = await loadOptionalPeer(NODEMAILER_MODULE);
2089
2332
  const candidate = mod.createTransport ? mod : mod.default;
2090
2333
  if (!candidate?.createTransport) {
2091
2334
  throw new Error("`nodemailer` package exposes no createTransport export");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "Multi-channel notification library for NestJS — email, OTP, SMS, push — with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",