@classytic/notifications 2.6.0 → 2.8.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
@@ -2,6 +2,75 @@
2
2
 
3
3
  All notable changes to `@classytic/notifications` will be documented in this file.
4
4
 
5
+ ## [2.8.0] — 2026-11-09
6
+
7
+ ### Added: custom SMTP without authentication, and `requireTLS`
8
+
9
+ An IP-allow-listed relay (an enterprise mail gateway that accepts mail from known addresses and takes
10
+ no SMTP AUTH) could not be configured: `buildEmailTransport` always required `user` and `password`.
11
+
12
+ - `EmailPreset.authOptional` (set on `smtp` only). For such a preset, `user` and `password` both blank
13
+ (absent, empty or whitespace) builds the transport without `auth`. One without the other still
14
+ throws the same "SMTP user is required" / "Password is required" error. Every other preset keeps
15
+ requiring its key.
16
+ - `EmailCredentialData.requireTLS?: string | boolean` (boolean or the form strings `'true'` / `'false'`,
17
+ like `secure`; blank leaves it unset): passed to nodemailer as `requireTLS`, so the transport refuses
18
+ to send unless STARTTLS succeeds. Read only where the host may be overridden (`smtp`, `ses`).
19
+ - `getEmailCredentialSchema()` adds an optional `requireTLS` select; the `user` and `password`
20
+ descriptions say a relay may leave both blank.
21
+
22
+ Additive: a credential that worked before builds the same transport (no `requireTLS` key unless set).
23
+ Pinned by `tests/providers.email.auth-optional.test.ts` (including `testEmailCredential` against a fake
24
+ SMTP server: no `AUTH` command; `requireTLS` with no STARTTLS offered fails verification).
25
+
26
+ FLOW OCC adoption: `@spinekit/integrations`' email provider passes `requireTLS` through and lets the
27
+ administrator leave both fields blank for FLOW ICT's allow-listed relay (gap G-W1-INT-4).
28
+
29
+ ## [2.7.0] — 2026-10-18
30
+
31
+ ### Added — push delivery hints: `collapseKey`, `threadId`, `badge`
32
+
33
+ `PushProvider.send` receives three optional fields, read by `PushChannel` from the payload data
34
+ (`data.collapseKey`, `data.threadId`, `data.badge`): a replace-in-place key (a newer push with the
35
+ same key replaces the older one instead of stacking; FCM `android.collapseKey` + `notification.tag`,
36
+ APNs `apns-collapse-id`), a tray grouping id (APNs `thread-id`), and the app badge count. Only
37
+ well-typed values are forwarded (non-empty strings, a non-negative integer badge). Additive:
38
+ providers that ignore them deliver as before.
39
+
40
+ ### Added — atomic idempotency claims + `RedisIdempotencyStore`
41
+
42
+ `IdempotencyStore` gains an optional `claim(key, leaseMs)` / `release(key)` pair. When the
43
+ store has it, `NotificationService` claims the key before delivery instead of `has()`, so
44
+ concurrent or redelivered sends with the same `idempotencyKey` deliver once, across
45
+ processes. Success upgrades the claim to the full `ttl`; zero sent (or a thrown pipeline
46
+ error) releases it so a retry can deliver. New `idempotency.leaseMs` (default 5 min) bounds
47
+ how long a crashed sender holds a key. `MemoryIdempotencyStore` implements the pair, so
48
+ in-process concurrent duplicates are now also deduplicated. Stores without `claim` keep
49
+ the old `has` / `set` behaviour.
50
+
51
+ `RedisIdempotencyStore({ client, prefix? })` is `SET NX PX` over a structurally typed
52
+ client (`RedisIdempotencyClient`); ioredis fits as is, no Redis dependency.
53
+
54
+ ### Added — `PermanentDeliveryError` for push providers
55
+
56
+ A `PushProvider` can throw `PermanentDeliveryError` (or any error with `retryable: false`) for a
57
+ failure no retry fixes, such as an unregistered device token. `PushChannel` then returns `failed`
58
+ with `retryable: false` instead of throwing a `ChannelError`.
59
+
60
+ ### Fixed — `retryable: false` results were still retried
61
+
62
+ The service turned a non-retryable result into a sentinel error, but `withRetry` retried every
63
+ error, so a hard failure still used all `maxAttempts` (with backoff) before being reported.
64
+ `withRetry` takes an optional `shouldRetry(error)` (additive fourth argument) and the service
65
+ uses it, so non-retryable results stop after the first attempt.
66
+
67
+ ### Fixed — channels assignable to `Channel` under `exactOptionalPropertyTypes`
68
+
69
+ `Channel.rateLimit` / `Channel.retry` are now `?: T | undefined`, matching `BaseChannel`'s
70
+ getters. Strict hosts no longer need `as Channel` on `new PushChannel(...)` (or any built-in
71
+ channel). Guarded by `tests/types/channel-contract.ts`, compiled with
72
+ `exactOptionalPropertyTypes: true` against the built declarations in `npm run typecheck`.
73
+
5
74
  ## [2.6.0] — 2026-10-09
6
75
 
7
76
  ### Added — `TelegramChannel`
package/README.md CHANGED
@@ -183,12 +183,30 @@ const channel = new EmailChannel({
183
183
  | `sendgrid` | `smtp.sendgrid.net:587` | `apiKey` | User is the literal `apikey` |
184
184
  | `mailgun` | `smtp.mailgun.org:465` | `user`, `password` | Per-domain SMTP creds |
185
185
  | `ses` | `email-smtp.us-east-1.amazonaws.com:465` | `user`, `password` | SES IAM SMTP creds. Override `host` for other regions |
186
- | `smtp` | user-supplied | `host`, `port`, `secure`, `user`, `password` | Any auth-SMTP server |
186
+ | `smtp` | user-supplied | `host`, `port`, `secure`, `requireTLS`, `user`, `password` | Any SMTP server. Leave `user` and `password` both blank for a relay without auth (IP allow-listed) |
187
187
 
188
188
  Host override is allowed only for `smtp` and `ses` (regional). Other
189
189
  presets pin the host to prevent footguns like "I changed the host but
190
190
  kept the Resend API key".
191
191
 
192
+ `requireTLS` (boolean or `'true'` / `'false'`, `smtp` and `ses` only)
193
+ makes the transport refuse to send unless STARTTLS succeeds. Custom SMTP
194
+ with `user` and `password` both blank builds a transport without `auth`
195
+ (a relay that allow-lists the sender by address); one without the other
196
+ still throws.
197
+
198
+ ```typescript
199
+ // Enterprise relay, allow-listed by IP, STARTTLS required
200
+ await buildEmailTransport({
201
+ provider: 'smtp',
202
+ fromEmail: 'alerts@corp.example',
203
+ host: 'relay.corp.example',
204
+ port: 25,
205
+ secure: false,
206
+ requireTLS: true,
207
+ });
208
+ ```
209
+
192
210
  ```typescript
193
211
  // SES in eu-west-1
194
212
  await buildEmailTransport({
@@ -609,21 +627,31 @@ await notifications.send({
609
627
  });
610
628
  ```
611
629
 
612
- For distributed systems, implement `IdempotencyStore` with Redis:
630
+ For multiple processes or replicas use the built-in `RedisIdempotencyStore`. It
631
+ claims each key atomically (`SET key 1 PX lease NX`) before delivery, so a redelivered
632
+ event sends once across restarts and replicas. On success the key gets the full `ttl`;
633
+ if nothing was sent (or the pipeline threw) the claim is released so a retry can deliver.
634
+ A crashed sender holds the key only for `leaseMs`. The client is typed structurally
635
+ (no Redis dependency): ioredis fits as is.
613
636
 
614
637
  ```typescript
615
- import type { IdempotencyStore } from '@classytic/notifications/utils';
638
+ import { Redis } from 'ioredis';
639
+ import { NotificationService, RedisIdempotencyStore } from '@classytic/notifications';
616
640
 
617
- class RedisIdempotencyStore implements IdempotencyStore {
618
- async has(key: string): Promise<boolean> {
619
- return !!(await redis.exists(`idemp:${key}`));
620
- }
621
- async set(key: string, ttlMs: number): Promise<void> {
622
- await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
623
- }
624
- }
641
+ const notifications = new NotificationService({
642
+ channels: [...],
643
+ idempotency: {
644
+ store: new RedisIdempotencyStore({ client: new Redis(process.env.REDIS_URL!), prefix: 'notif:idem:' }),
645
+ ttl: 24 * 60 * 60 * 1000, // remembered after a successful send
646
+ leaseMs: 5 * 60 * 1000, // in-flight claim (default)
647
+ },
648
+ });
625
649
  ```
626
650
 
651
+ A custom `IdempotencyStore` gets the same guarantee by implementing the optional
652
+ `claim(key, leaseMs)` / `release(key)` pair; stores with only `has` / `set` keep the
653
+ previous check-then-record behaviour (fine in one process, racy across several).
654
+
627
655
  ## Batch Sending
628
656
 
629
657
  Send thousands of notifications with controlled concurrency:
@@ -709,7 +737,7 @@ emitter.on('user.created', hooks['user.created'][0]);
709
737
  | `RateLimitStore` | Rate limit state | `MemoryRateLimitStore` |
710
738
  | `DeliveryLog` | Audit trail | `MemoryDeliveryLog` |
711
739
  | `QueueAdapter` | Crash-resilient queue | `MemoryQueue` |
712
- | `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` |
740
+ | `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` (`RedisIdempotencyStore` for multi-process) |
713
741
  | `PreferenceResolver` | User preference filtering | — (BYOP) |
714
742
 
715
743
  ### Exports
@@ -1,2 +1,2 @@
1
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-CqFwP-3Y.mjs";
1
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-CzQH7Wa8.mjs";
2
2
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, TelegramChannel, WebhookChannel };
@@ -1,3 +1,3 @@
1
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-B2qKQEkV.mjs";
1
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "../telegram.channel-DnVdyq8_.mjs";
2
2
 
3
3
  export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, TelegramChannel, WebhookChannel };
@@ -25,6 +25,22 @@ var ChannelError = class extends NotificationError {
25
25
  this.name = "ChannelError";
26
26
  }
27
27
  };
28
+ /**
29
+ * Thrown by a provider for a failure no retry can fix (unregistered device token, invalid
30
+ * recipient). Channels that honour it (PushChannel) return `failed` with `retryable: false`, so
31
+ * the service does not retry. Detected structurally (`retryable === false`), so a provider may
32
+ * also throw any error carrying that flag.
33
+ */
34
+ var PermanentDeliveryError = class extends NotificationError {
35
+ retryable = false;
36
+ constructor(message, options) {
37
+ super(message, {
38
+ ...options,
39
+ code: options?.code ?? "PERMANENT_DELIVERY"
40
+ });
41
+ this.name = "PermanentDeliveryError";
42
+ }
43
+ };
28
44
  var ProviderNotInstalledError = class extends NotificationError {
29
45
  constructor(provider, installCmd) {
30
46
  super(`${provider} is required but not installed. Install it: ${installCmd}`, { code: "PROVIDER_NOT_INSTALLED" });
@@ -33,4 +49,4 @@ var ProviderNotInstalledError = class extends NotificationError {
33
49
  };
34
50
 
35
51
  //#endregion
36
- export { NotificationError as n, ProviderNotInstalledError as r, ChannelError as t };
52
+ export { ProviderNotInstalledError as i, NotificationError as n, PermanentDeliveryError as r, ChannelError as t };
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { A as TemplateResolver, B as DeliveryLogEntry, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueEnqueueOptions, G as MemoryIdempotencyStore, H as MemoryDeliveryLog, I as QueueJob, J as RateLimitStore, K as MemoryRateLimitStore, L as QueueJobStatus, M as WebhookChannelConfig, N as MemoryQueue, O as SmtpTransportOptions, P as QueueAdapter, R as QueueProcessor, S as ResolvedRetryConfig, T as ServiceEvent, U as IDEMPOTENCY_DEFAULT_TTL, V as DeliveryLogQuery, W as IdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as TemplateResult, k as TelegramChannelConfig, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitConfig, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLog } from "./types-DsRpYKr-.mjs";
2
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-CqFwP-3Y.mjs";
3
- import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, l as SimpleResolverOptions, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "./status-webhook-C8WnLIMv.mjs";
1
+ import { A as TemplateResolver, B as DeliveryLogEntry, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueEnqueueOptions, G as IdempotencyStore, H as MemoryDeliveryLog, I as QueueJob, J as RedisIdempotencyStore, K as MemoryIdempotencyStore, L as QueueJobStatus, M as WebhookChannelConfig, N as MemoryQueue, O as SmtpTransportOptions, P as QueueAdapter, R as QueueProcessor, S as ResolvedRetryConfig, T as ServiceEvent, U as IDEMPOTENCY_DEFAULT_LEASE, V as DeliveryLogQuery, W as IDEMPOTENCY_DEFAULT_TTL, X as RateLimitConfig, Y as MemoryRateLimitStore, Z as RateLimitStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as TemplateResult, k as TelegramChannelConfig, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RedisIdempotencyClient, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLog } from "./types-DyUMfkyr.mjs";
2
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-CzQH7Wa8.mjs";
3
+ import { C as calculateDelay, E as mergeHooks, S as Emitter, T as withRetry, _ as isQuietHours, a as createStatusHandler, b as PermanentDeliveryError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, l as SimpleResolverOptions, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as resolveRetryConfig, x as ProviderNotInstalledError, y as NotificationError } from "./status-webhook-BlhPvRnD.mjs";
4
4
  //#region src/NotificationService.d.ts
5
- declare class NotificationService {
5
+ export declare class NotificationService {
6
6
  private channels;
7
7
  private templateResolver?;
8
8
  private preferenceResolver?;
@@ -11,6 +11,7 @@ declare class NotificationService {
11
11
  private emitter;
12
12
  private idempotencyStore?;
13
13
  private idempotencyTtl;
14
+ private idempotencyLease;
14
15
  private deliveryLog?;
15
16
  private rateLimitStore?;
16
17
  private queueAdapter?;
@@ -52,6 +53,10 @@ declare class NotificationService {
52
53
  * lifecycle events are always emitted.
53
54
  */
54
55
  private sendDirect;
56
+ /** Drop a claimed idempotency key so a later retry can deliver. Never throws. */
57
+ private releaseIdempotency;
58
+ /** Steps 2-5 of the send pipeline: template, channel filter, preferences, delivery. */
59
+ private deliver;
55
60
  /**
56
61
  * Single exit path for all send outcomes.
57
62
  * Records to delivery log and emits lifecycle events regardless of
@@ -133,4 +138,4 @@ declare class NotificationService {
133
138
  off(event: ServiceEvent, handler: EventHandler): this;
134
139
  }
135
140
  //#endregion
136
- export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, TelegramChannel, type TelegramChannelConfig, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
141
+ export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, type NotificationServiceConfig, type PMapOptions, PermanentDeliveryError, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type RedisIdempotencyClient, RedisIdempotencyStore, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SimpleResolverOptions, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, TelegramChannel, type TelegramChannelConfig, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { a as MemoryQueue, c as pMap, d as MemoryIdempotencyStore, f as isQuietHours, g as Emitter, h as withRetry, i as interpolateHtml, l as MemoryRateLimitStore, m as resolveRetryConfig, n as withFallback, o as MemoryDeliveryLog, p as calculateDelay, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_TTL } from "./status-webhook-B4Sv8X_G.mjs";
2
- import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
3
- import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-B2qKQEkV.mjs";
1
+ import { _ as withRetry, a as MemoryQueue, c as pMap, d as IDEMPOTENCY_DEFAULT_TTL, f as MemoryIdempotencyStore, g as resolveRetryConfig, h as calculateDelay, i as interpolateHtml, l as MemoryRateLimitStore, m as isQuietHours, n as withFallback, o as MemoryDeliveryLog, p as RedisIdempotencyStore, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_LEASE, v as Emitter } from "./status-webhook-D7Hrr71A.mjs";
2
+ import { i as ProviderNotInstalledError, n as NotificationError, r as PermanentDeliveryError, t as ChannelError } from "./errors-CsQZKfec.mjs";
3
+ import { a as WebhookChannel, i as ConsoleChannel, n as PushChannel, o as EmailChannel, r as SmsChannel, s as BaseChannel, t as TelegramChannel } from "./telegram.channel-DnVdyq8_.mjs";
4
4
 
5
5
  //#region src/NotificationService.ts
6
6
  /**
@@ -66,6 +66,7 @@ var NotificationService = class {
66
66
  emitter = new Emitter();
67
67
  idempotencyStore;
68
68
  idempotencyTtl;
69
+ idempotencyLease;
69
70
  deliveryLog;
70
71
  rateLimitStore;
71
72
  queueAdapter;
@@ -80,6 +81,7 @@ var NotificationService = class {
80
81
  this.idempotencyStore = config.idempotency.store ?? new MemoryIdempotencyStore();
81
82
  this.idempotencyTtl = config.idempotency.ttl ?? 864e5;
82
83
  } else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
84
+ this.idempotencyLease = config.idempotency?.leaseMs ?? 3e5;
83
85
  this.deliveryLog = config.deliveryLog;
84
86
  if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
85
87
  else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
@@ -169,8 +171,10 @@ var NotificationService = class {
169
171
  async sendDirect(payload) {
170
172
  const start = Date.now();
171
173
  await this.emitter.emit("before:send", payload);
174
+ let claimed = false;
172
175
  if (payload.idempotencyKey && this.idempotencyStore) {
173
- if (await this.idempotencyStore.has(payload.idempotencyKey)) {
176
+ const store = this.idempotencyStore;
177
+ if (store.claim ? !(claimed = await store.claim(payload.idempotencyKey, this.idempotencyLease)) : await store.has(payload.idempotencyKey)) {
174
178
  this.logger.debug?.(`Duplicate notification skipped (key: ${payload.idempotencyKey})`);
175
179
  return this.finalize(payload, {
176
180
  event: payload.event,
@@ -182,6 +186,25 @@ var NotificationService = class {
182
186
  });
183
187
  }
184
188
  }
189
+ if (!claimed) return this.deliver(payload, start);
190
+ let delivered;
191
+ try {
192
+ delivered = await this.deliver(payload, start);
193
+ return delivered;
194
+ } finally {
195
+ if (!delivered || delivered.sent === 0) await this.releaseIdempotency(payload.idempotencyKey);
196
+ }
197
+ }
198
+ /** Drop a claimed idempotency key so a later retry can deliver. Never throws. */
199
+ async releaseIdempotency(key) {
200
+ try {
201
+ await this.idempotencyStore?.release?.(key);
202
+ } catch (err) {
203
+ this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
204
+ }
205
+ }
206
+ /** Steps 2-5 of the send pipeline: template, channel filter, preferences, delivery. */
207
+ async deliver(payload, start) {
185
208
  let enrichedPayload = payload;
186
209
  if (payload.template && this.templateResolver) try {
187
210
  const rendered = await this.templateResolver(payload.template, payload.data);
@@ -315,7 +338,7 @@ var NotificationService = class {
315
338
  }).catch((emitErr) => {
316
339
  this.logger.error(`[${channel.name}] send:retry listener error: ${emitErr instanceof Error ? emitErr.message : emitErr}`);
317
340
  });
318
- }),
341
+ }, (error) => !(NON_RETRYABLE in error)),
319
342
  duration: Date.now() - start
320
343
  };
321
344
  } catch (err) {
@@ -552,4 +575,4 @@ var NotificationService = class {
552
575
  */
553
576
 
554
577
  //#endregion
555
- export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, ProviderNotInstalledError, PushChannel, SmsChannel, TelegramChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
578
+ export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, PermanentDeliveryError, ProviderNotInstalledError, PushChannel, RedisIdempotencyStore, SmsChannel, TelegramChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
@@ -45,12 +45,19 @@ interface EmailPreset {
45
45
  * — prevents "changed host, kept the Resend key" footguns.
46
46
  */
47
47
  allowHostOverride?: boolean;
48
+ /**
49
+ * `true` when the relay may take no SMTP AUTH: with BOTH `user` and
50
+ * `password` blank the transport is built without `auth` (an
51
+ * IP-allow-listed relay). One without the other is still an error.
52
+ * Only custom SMTP sets it; every preset keeps requiring its key.
53
+ */
54
+ authOptional?: boolean;
48
55
  /** Setup instructions surfaced in the Integrations UI. */
49
56
  setupHint: string;
50
57
  }
51
- declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
58
+ export declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
52
59
  /** Convenience dropdown options for the credential UI. */
53
- declare const EMAIL_PROVIDER_OPTIONS: {
60
+ export declare const EMAIL_PROVIDER_OPTIONS: {
54
61
  value: EmailProviderName;
55
62
  label: string;
56
63
  }[];
@@ -74,6 +81,12 @@ interface EmailCredentialData {
74
81
  host?: string;
75
82
  port?: string | number;
76
83
  secure?: string | boolean;
84
+ /**
85
+ * Refuse to send unless STARTTLS succeeds (nodemailer `requireTLS`).
86
+ * Boolean or the form strings `'true'` / `'false'`; blank leaves it
87
+ * unset. Read only where the host may be overridden (`smtp`, `ses`).
88
+ */
89
+ requireTLS?: string | boolean;
77
90
  }
78
91
  /**
79
92
  * Build a `nodemailer` `Transporter` from the credential blob.
@@ -81,13 +94,13 @@ interface EmailCredentialData {
81
94
  * @throws `Error` when required fields are missing for the chosen provider.
82
95
  * @throws `Error` when `nodemailer` is not installed (optional peer).
83
96
  */
84
- declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
97
+ export declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
85
98
  /**
86
99
  * Compose the RFC-5322 `From` header value from the credential blob.
87
100
  * Returns `"Display Name" <email@example.com>` when `fromName` is set,
88
101
  * otherwise just `email@example.com`.
89
102
  */
90
- declare function buildFromHeader(data: EmailCredentialData): string;
103
+ export declare function buildFromHeader(data: EmailCredentialData): string;
91
104
  //#endregion
92
105
  //#region src/providers/email/schema.d.ts
93
106
  /**
@@ -117,7 +130,7 @@ interface EmailCredentialField {
117
130
  }
118
131
  /** Union-of-fields schema — every field appears; the UI hides what's
119
132
  * not relevant for the chosen `provider`. */
120
- declare function getEmailCredentialSchema(): EmailCredentialField[];
133
+ export declare function getEmailCredentialSchema(): EmailCredentialField[];
121
134
  //#endregion
122
135
  //#region src/providers/email/test.d.ts
123
136
  type EmailTestStatus = 'OK' | 'Error';
@@ -130,6 +143,6 @@ interface EmailTestResult {
130
143
  fromEmail: string;
131
144
  };
132
145
  }
133
- declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
146
+ export declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
134
147
  //#endregion
135
- export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, type EmailCredentialData, type EmailCredentialField, type EmailCredentialFieldType, type EmailPreset, type EmailProviderName, type EmailTestResult, type EmailTestStatus, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
148
+ export type { EmailCredentialData, EmailCredentialField, EmailCredentialFieldType, EmailPreset, EmailProviderName, EmailTestResult, EmailTestStatus };
@@ -59,7 +59,8 @@ const EMAIL_PRESETS = {
59
59
  secure: false,
60
60
  userSource: "user",
61
61
  passSource: "password",
62
- setupHint: "Use for SMTP servers without a preset. Standard auth-SMTP only — no OAuth-XOAUTH2."
62
+ authOptional: true,
63
+ setupHint: "Use for SMTP servers without a preset. Standard auth-SMTP only — no OAuth-XOAUTH2. For a relay that accepts mail from allow-listed addresses without authentication, leave user and password both blank."
63
64
  }
64
65
  };
65
66
  /** Convenience dropdown options for the credential UI. */
@@ -70,6 +71,14 @@ const EMAIL_PROVIDER_OPTIONS = Object.keys(EMAIL_PRESETS).map((name) => ({
70
71
 
71
72
  //#endregion
72
73
  //#region src/providers/email/transport.ts
74
+ function isBlank(value) {
75
+ return value === void 0 || value === null || String(value).trim() === "";
76
+ }
77
+ /** Boolean, or the form strings `'true'` / `'false'`; blank is `undefined`. */
78
+ function readFlag(value) {
79
+ if (typeof value === "boolean") return value;
80
+ if (typeof value === "string" && value.trim() !== "") return value.trim() === "true";
81
+ }
73
82
  function resolveUser(data, userSource) {
74
83
  if (userSource.startsWith("literal:")) return userSource.slice(8);
75
84
  if (userSource === "user") {
@@ -102,6 +111,11 @@ async function buildEmailTransport(data) {
102
111
  if (typeof data.secure === "boolean") secure = data.secure;
103
112
  else if (typeof data.secure === "string") secure = data.secure === "true";
104
113
  }
114
+ const requireTLS = allowOverride ? readFlag(data.requireTLS) : void 0;
115
+ const auth = preset.authOptional === true && preset.userSource === "user" && isBlank(data.user) && isBlank(preset.passSource === "apiKey" ? data.apiKey : data.password) ? void 0 : {
116
+ user: resolveUser(data, preset.userSource),
117
+ pass: resolvePass(data, preset.passSource)
118
+ };
105
119
  let nodemailer;
106
120
  try {
107
121
  nodemailer = await import("nodemailer");
@@ -112,10 +126,8 @@ async function buildEmailTransport(data) {
112
126
  host,
113
127
  port,
114
128
  secure,
115
- auth: {
116
- user: resolveUser(data, preset.userSource),
117
- pass: resolvePass(data, preset.passSource)
118
- }
129
+ ...requireTLS !== void 0 ? { requireTLS } : {},
130
+ ...auth ? { auth } : {}
119
131
  });
120
132
  }
121
133
  /**
@@ -182,14 +194,14 @@ function getEmailCredentialSchema() {
182
194
  displayName: "SMTP Username",
183
195
  type: "text",
184
196
  required: false,
185
- description: "Gmail address, Mailgun SMTP user, or custom SMTP user."
197
+ description: "Gmail address, Mailgun SMTP user, or custom SMTP user. Custom SMTP: leave user and password both blank for a relay that accepts mail without authentication."
186
198
  },
187
199
  {
188
200
  name: "password",
189
201
  displayName: "SMTP Password",
190
202
  type: "password",
191
203
  required: false,
192
- description: "Gmail app password, Mailgun SMTP password, or custom SMTP password."
204
+ description: "Gmail app password, Mailgun SMTP password, or custom SMTP password. Custom SMTP: leave both blank for a relay without authentication."
193
205
  },
194
206
  {
195
207
  name: "host",
@@ -220,6 +232,20 @@ function getEmailCredentialSchema() {
220
232
  label: "false (port 587 / STARTTLS)"
221
233
  }],
222
234
  description: "Custom SMTP only."
235
+ },
236
+ {
237
+ name: "requireTLS",
238
+ displayName: "Require STARTTLS",
239
+ type: "select",
240
+ required: false,
241
+ options: [{
242
+ value: "true",
243
+ label: "true (refuse to send without STARTTLS)"
244
+ }, {
245
+ value: "false",
246
+ label: "false (use STARTTLS when offered)"
247
+ }],
248
+ description: "Custom SMTP only. With Secure false, refuse to send unless the relay upgrades to TLS."
223
249
  }
224
250
  ];
225
251
  }
@@ -1,4 +1,4 @@
1
- import { A as TemplateResolver, C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, o as DispatchResult, u as HookHandler } from "./types-DsRpYKr-.mjs";
1
+ import { A as TemplateResolver, C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, o as DispatchResult, u as HookHandler } from "./types-DyUMfkyr.mjs";
2
2
  //#region src/utils/merge-hooks.d.ts
3
3
  type HookInput = Record<string, HookHandler | HookHandler[]>;
4
4
  declare function mergeHooks(...hookConfigs: (HookInput | null | undefined)[]): HookMap;
@@ -17,7 +17,9 @@ declare function calculateDelay(attempt: number, config: ResolvedRetryConfig): n
17
17
  * @returns Result of fn
18
18
  * @throws Last error after all attempts exhausted
19
19
  */
20
- declare function withRetry<T>(fn: () => Promise<T>, config: ResolvedRetryConfig, onRetry?: (attempt: number, error: Error) => void): Promise<T>;
20
+ declare function withRetry<T>(fn: () => Promise<T>, config: ResolvedRetryConfig, onRetry?: (attempt: number, error: Error) => void,
21
+ /** Return `false` to stop retrying and rethrow this error at once. Default: retry everything. */
22
+ shouldRetry?: (error: Error) => boolean): Promise<T>;
21
23
  //#endregion
22
24
  //#region src/utils/emitter.d.ts
23
25
  /**
@@ -58,6 +60,20 @@ declare class NotificationError extends Error {
58
60
  declare class ChannelError extends NotificationError {
59
61
  constructor(channel: string, message: string, cause?: Error);
60
62
  }
63
+ /**
64
+ * Thrown by a provider for a failure no retry can fix (unregistered device token, invalid
65
+ * recipient). Channels that honour it (PushChannel) return `failed` with `retryable: false`, so
66
+ * the service does not retry. Detected structurally (`retryable === false`), so a provider may
67
+ * also throw any error carrying that flag.
68
+ */
69
+ declare class PermanentDeliveryError extends NotificationError {
70
+ readonly retryable: false;
71
+ constructor(message: string, options?: {
72
+ code?: string;
73
+ channel?: string;
74
+ cause?: Error;
75
+ });
76
+ }
61
77
  declare class ProviderNotInstalledError extends NotificationError {
62
78
  constructor(provider: string, installCmd: string);
63
79
  }
@@ -334,4 +350,4 @@ interface StatusHandler {
334
350
  */
335
351
  declare function createStatusHandler(config?: StatusHandlerConfig): StatusHandler;
336
352
  //#endregion
337
- export { resolveRetryConfig as C, calculateDelay as S, mergeHooks as T, isQuietHours as _, createStatusHandler as a, ProviderNotInstalledError as b, InterpolateOptions as c, TemplateMap as d, createSimpleResolver as f, QuietHoursConfig as g, pMap as h, StatusUpdate as i, SimpleResolverOptions as l, PMapOptions as m, StatusHandler as n, FallbackOptions as o, interpolateHtml as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, TemplateDefinition as u, ChannelError as v, withRetry as w, Emitter as x, NotificationError as y };
353
+ export { calculateDelay as C, mergeHooks as E, Emitter as S, withRetry as T, isQuietHours as _, createStatusHandler as a, PermanentDeliveryError as b, InterpolateOptions as c, TemplateMap as d, createSimpleResolver as f, QuietHoursConfig as g, pMap as h, StatusUpdate as i, SimpleResolverOptions as l, PMapOptions as m, StatusHandler as n, FallbackOptions as o, interpolateHtml as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, TemplateDefinition as u, ChannelError as v, resolveRetryConfig as w, ProviderNotInstalledError as x, NotificationError as y };
@@ -70,13 +70,13 @@ function sleep(ms) {
70
70
  * @returns Result of fn
71
71
  * @throws Last error after all attempts exhausted
72
72
  */
73
- async function withRetry(fn, config, onRetry) {
73
+ async function withRetry(fn, config, onRetry, shouldRetry) {
74
74
  let lastError;
75
75
  for (let attempt = 1; attempt <= config.maxAttempts; attempt++) try {
76
76
  return await fn();
77
77
  } catch (err) {
78
78
  lastError = err instanceof Error ? err : new Error(String(err));
79
- if (attempt === config.maxAttempts) break;
79
+ if (attempt === config.maxAttempts || shouldRetry?.(lastError) === false) break;
80
80
  const delay = calculateDelay(attempt, config);
81
81
  onRetry?.(attempt, lastError);
82
82
  await sleep(delay);
@@ -194,6 +194,14 @@ var MemoryIdempotencyStore = class {
194
194
  this.cleanup();
195
195
  }
196
196
  }
197
+ claim(key, leaseMs) {
198
+ if (this.has(key)) return false;
199
+ this.set(key, leaseMs);
200
+ return true;
201
+ }
202
+ release(key) {
203
+ this.store.delete(key);
204
+ }
197
205
  /** Remove all expired entries. Safe to call at any time. */
198
206
  cleanup() {
199
207
  const now = Date.now();
@@ -218,6 +226,32 @@ var MemoryIdempotencyStore = class {
218
226
  };
219
227
  /** Default TTL for idempotency keys (24 hours) */
220
228
  const IDEMPOTENCY_DEFAULT_TTL = DEFAULT_TTL;
229
+ /** Default in-flight lease for `claim()` (5 minutes): covers a send with its retries. */
230
+ const IDEMPOTENCY_DEFAULT_LEASE = 3e5;
231
+ /**
232
+ * Distributed idempotency store on Redis: `claim()` is one `SET key 1 PX lease NX`,
233
+ * so exactly one process delivers a given key across restarts and replicas.
234
+ */
235
+ var RedisIdempotencyStore = class {
236
+ client;
237
+ prefix;
238
+ constructor(options) {
239
+ this.client = options.client;
240
+ this.prefix = options.prefix ?? "notif:idem:";
241
+ }
242
+ async has(key) {
243
+ return await this.client.exists(this.prefix + key) > 0;
244
+ }
245
+ async set(key, ttlMs) {
246
+ await this.client.set(this.prefix + key, "1", "PX", Math.max(1, Math.ceil(ttlMs)));
247
+ }
248
+ async claim(key, leaseMs) {
249
+ return await this.client.set(this.prefix + key, "1", "PX", Math.max(1, Math.ceil(leaseMs)), "NX") === "OK";
250
+ }
251
+ async release(key) {
252
+ await this.client.del(this.prefix + key);
253
+ }
254
+ };
221
255
 
222
256
  //#endregion
223
257
  //#region src/utils/rate-limiter.ts
@@ -745,4 +779,4 @@ function createStatusHandler(config = {}) {
745
779
  }
746
780
 
747
781
  //#endregion
748
- export { MemoryQueue as a, pMap as c, MemoryIdempotencyStore as d, isQuietHours as f, Emitter as g, withRetry as h, interpolateHtml as i, MemoryRateLimitStore as l, resolveRetryConfig as m, withFallback as n, MemoryDeliveryLog as o, calculateDelay as p, createSimpleResolver as r, mergeHooks as s, createStatusHandler as t, IDEMPOTENCY_DEFAULT_TTL as u };
782
+ export { withRetry as _, MemoryQueue as a, pMap as c, IDEMPOTENCY_DEFAULT_TTL as d, MemoryIdempotencyStore as f, resolveRetryConfig as g, calculateDelay as h, interpolateHtml as i, MemoryRateLimitStore as l, isQuietHours as m, withFallback as n, MemoryDeliveryLog as o, RedisIdempotencyStore as p, createSimpleResolver as r, mergeHooks as s, createStatusHandler as t, IDEMPOTENCY_DEFAULT_LEASE as u, Emitter as v };
@@ -1,4 +1,4 @@
1
- import { C as RetryConfig, E as SmsChannelConfig, M as WebhookChannelConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, k as TelegramChannelConfig, q as RateLimitConfig, w as SendResult, y as PushChannelConfig } from "./types-DsRpYKr-.mjs";
1
+ import { C as RetryConfig, E as SmsChannelConfig, M as WebhookChannelConfig, X as RateLimitConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, k as TelegramChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-DyUMfkyr.mjs";
2
2
  //#region src/channels/BaseChannel.d.ts
3
3
  declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
4
4
  readonly name: string;
@@ -1,4 +1,4 @@
1
- import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-BxRjct-E.mjs";
1
+ import { i as ProviderNotInstalledError, t as ChannelError } from "./errors-CsQZKfec.mjs";
2
2
  import { createHmac } from "node:crypto";
3
3
 
4
4
  //#region src/channels/BaseChannel.ts
@@ -554,13 +554,19 @@ var PushChannel = class extends BaseChannel {
554
554
  channel: this.name,
555
555
  error: "No title or body (data.title, data.body)"
556
556
  };
557
+ const collapseKey = typeof data.collapseKey === "string" && data.collapseKey ? data.collapseKey : void 0;
558
+ const threadId = typeof data.threadId === "string" && data.threadId ? data.threadId : void 0;
559
+ const badge = typeof data.badge === "number" && Number.isInteger(data.badge) && data.badge >= 0 ? data.badge : void 0;
557
560
  try {
558
561
  const result = await this.provider.send({
559
562
  token: recipient.deviceToken,
560
563
  title,
561
564
  body,
562
565
  data: data.pushData,
563
- imageUrl: data.imageUrl
566
+ imageUrl: data.imageUrl,
567
+ ...collapseKey !== void 0 ? { collapseKey } : {},
568
+ ...threadId !== void 0 ? { threadId } : {},
569
+ ...badge !== void 0 ? { badge } : {}
564
570
  });
565
571
  return {
566
572
  status: "sent",
@@ -585,6 +591,12 @@ var PushChannel = class extends BaseChannel {
585
591
  };
586
592
  } catch (err) {
587
593
  const message = err instanceof Error ? err.message : String(err);
594
+ if (err?.retryable === false) return {
595
+ status: "failed",
596
+ channel: this.name,
597
+ error: message,
598
+ retryable: false
599
+ };
588
600
  throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
589
601
  }
590
602
  }
@@ -88,6 +88,17 @@ interface IdempotencyStore {
88
88
  has(key: string): boolean | Promise<boolean>;
89
89
  /** Record a key with TTL in milliseconds */
90
90
  set(key: string, ttlMs: number): void | Promise<void>;
91
+ /**
92
+ * Atomically take the key for an in-flight send (`SET key NX PX leaseMs`).
93
+ * Resolves `true` only for the one caller that took it; every concurrent or
94
+ * later duplicate (any process) gets `false` and is skipped. When present the
95
+ * service uses it instead of `has()`: it claims before delivery, then `set()`s
96
+ * the full TTL on success or `release()`s on failure so a retry can deliver.
97
+ * The lease bounds how long a crashed sender holds the key.
98
+ */
99
+ claim?(key: string, leaseMs: number): boolean | Promise<boolean>;
100
+ /** Drop a claimed key (delivery failed or never started). */
101
+ release?(key: string): void | Promise<void>;
91
102
  }
92
103
  /**
93
104
  * In-memory idempotency store with TTL-based expiry.
@@ -120,6 +131,8 @@ declare class MemoryIdempotencyStore implements IdempotencyStore {
120
131
  });
121
132
  has(key: string): boolean;
122
133
  set(key: string, ttlMs: number): void;
134
+ claim(key: string, leaseMs: number): boolean;
135
+ release(key: string): void;
123
136
  /** Remove all expired entries. Safe to call at any time. */
124
137
  cleanup(): void;
125
138
  /** Number of entries (including possibly expired). */
@@ -134,6 +147,36 @@ declare class MemoryIdempotencyStore implements IdempotencyStore {
134
147
  }
135
148
  /** Default TTL for idempotency keys (24 hours) */
136
149
  declare const IDEMPOTENCY_DEFAULT_TTL: number;
150
+ /** Default in-flight lease for `claim()` (5 minutes): covers a send with its retries. */
151
+ declare const IDEMPOTENCY_DEFAULT_LEASE: number;
152
+ /**
153
+ * The subset of a Redis client the store needs, typed structurally so the
154
+ * package has no Redis dependency. ioredis (`Redis`, `Cluster`) matches as is;
155
+ * for node-redis pass `{ set: (k, v, _px, ms, nx) => client.set(k, v, nx ? { PX: ms, NX: true } : { PX: ms }), del: (k) => client.del(k), exists: (k) => client.exists(k) }`.
156
+ */
157
+ interface RedisIdempotencyClient {
158
+ set(key: string, value: string, px: 'PX', ttlMs: number): Promise<unknown>;
159
+ set(key: string, value: string, px: 'PX', ttlMs: number, nx: 'NX'): Promise<unknown>;
160
+ del(key: string): Promise<unknown>;
161
+ exists(key: string): Promise<number>;
162
+ }
163
+ /**
164
+ * Distributed idempotency store on Redis: `claim()` is one `SET key 1 PX lease NX`,
165
+ * so exactly one process delivers a given key across restarts and replicas.
166
+ */
167
+ declare class RedisIdempotencyStore implements IdempotencyStore {
168
+ private readonly client;
169
+ private readonly prefix;
170
+ constructor(options: {
171
+ client: RedisIdempotencyClient;
172
+ /** Key prefix. Default: `notif:idem:`. */
173
+ prefix?: string;
174
+ });
175
+ has(key: string): Promise<boolean>;
176
+ set(key: string, ttlMs: number): Promise<void>;
177
+ claim(key: string, leaseMs: number): Promise<boolean>;
178
+ release(key: string): Promise<void>;
179
+ }
137
180
  //#endregion
138
181
  //#region src/utils/delivery-log.d.ts
139
182
  /** A single delivery log entry */
@@ -470,13 +513,13 @@ interface Channel {
470
513
  * implement `Channel` directly should surface it here so the service
471
514
  * applies the limit (otherwise the channel is treated as unlimited).
472
515
  */
473
- readonly rateLimit?: RateLimitConfig;
516
+ readonly rateLimit?: RateLimitConfig | undefined;
474
517
  /**
475
518
  * Optional per-channel retry override, read by the service. When unset the
476
519
  * service's global retry config applies. `BaseChannel` exposes this from
477
520
  * `config.retry`.
478
521
  */
479
- readonly retry?: RetryConfig;
522
+ readonly retry?: RetryConfig | undefined;
480
523
  shouldHandle(event: string): boolean;
481
524
  send(payload: NotificationPayload): Promise<SendResult>;
482
525
  /**
@@ -608,7 +651,11 @@ interface SmsChannelConfig extends ChannelConfig {
608
651
  /** SMS provider implementation (Twilio, SNS, Vonage, etc.) */
609
652
  provider: SmsProvider;
610
653
  }
611
- /** Push notification provider interface (FCM or custom) */
654
+ /**
655
+ * Push notification provider interface (FCM or custom). Throw to fail the send (retried per
656
+ * the retry config); throw a `PermanentDeliveryError` (or any error with `retryable: false`)
657
+ * for a failure no retry can fix, such as an unregistered device token.
658
+ */
612
659
  interface PushProvider {
613
660
  send(message: {
614
661
  token: string;
@@ -616,6 +663,16 @@ interface PushProvider {
616
663
  body: string;
617
664
  data?: Record<string, string>;
618
665
  imageUrl?: string;
666
+ /**
667
+ * Replace-in-place key: a newer push with the same key replaces the older one on the device
668
+ * instead of stacking (FCM `android.collapseKey` + `notification.tag`, APNs `apns-collapse-id`,
669
+ * at most 64 bytes). From `data.collapseKey`. Absent = every push shows on its own.
670
+ */
671
+ collapseKey?: string;
672
+ /** Groups notifications in the tray (APNs `aps.thread-id`, Android group). From `data.threadId`. */
673
+ threadId?: string;
674
+ /** App icon badge count (APNs `aps.badge`, Android `notificationCount`). From `data.badge`. */
675
+ badge?: number;
619
676
  }): Promise<{
620
677
  messageId: string;
621
678
  }>;
@@ -698,6 +755,8 @@ interface NotificationServiceConfig {
698
755
  store?: IdempotencyStore;
699
756
  /** TTL in milliseconds (default: 86400000 = 24h) */
700
757
  ttl?: number;
758
+ /** In-flight lease for stores with an atomic `claim()` (default: 300000 = 5 min) */
759
+ leaseMs?: number;
701
760
  };
702
761
  /** Delivery log for audit trail — records every send attempt */
703
762
  deliveryLog?: DeliveryLog;
@@ -775,4 +834,4 @@ interface BatchResult {
775
834
  results: DispatchResult[];
776
835
  }
777
836
  //#endregion
778
- export { TemplateResolver as A, DeliveryLogEntry as B, RetryConfig as C, SmsProvider as D, SmsChannelConfig as E, QueueEnqueueOptions as F, MemoryIdempotencyStore as G, MemoryDeliveryLog as H, QueueJob as I, RateLimitStore as J, MemoryRateLimitStore as K, QueueJobStatus as L, WebhookChannelConfig as M, MemoryQueue as N, SmtpTransportOptions as O, QueueAdapter as P, QueueProcessor as R, ResolvedRetryConfig as S, ServiceEvent as T, IDEMPOTENCY_DEFAULT_TTL as U, DeliveryLogQuery as V, IdempotencyStore as W, NotificationServiceConfig as _, ChannelConfig as a, PushProvider as b, EmailChannelConfig as c, HookMap as d, Logger as f, NotificationPreferences as g, NotificationPayload as h, Channel as i, TemplateResult as j, TelegramChannelConfig as k, EventHandler as l, NotificationHookConfig as m, BatchProgress as n, DispatchResult as o, NodemailerTransporter as p, RateLimitConfig as q, BatchResult as r, EmailAttachment as s, BatchOptions as t, HookHandler as u, PreferenceResolver as v, SendResult as w, Recipient as x, PushChannelConfig as y, DeliveryLog as z };
837
+ export { TemplateResolver as A, DeliveryLogEntry as B, RetryConfig as C, SmsProvider as D, SmsChannelConfig as E, QueueEnqueueOptions as F, IdempotencyStore as G, MemoryDeliveryLog as H, QueueJob as I, RedisIdempotencyStore as J, MemoryIdempotencyStore as K, QueueJobStatus as L, WebhookChannelConfig as M, MemoryQueue as N, SmtpTransportOptions as O, QueueAdapter as P, QueueProcessor as R, ResolvedRetryConfig as S, ServiceEvent as T, IDEMPOTENCY_DEFAULT_LEASE as U, DeliveryLogQuery as V, IDEMPOTENCY_DEFAULT_TTL as W, RateLimitConfig as X, MemoryRateLimitStore as Y, RateLimitStore as Z, NotificationServiceConfig as _, ChannelConfig as a, PushProvider as b, EmailChannelConfig as c, HookMap as d, Logger as f, NotificationPreferences as g, NotificationPayload as h, Channel as i, TemplateResult as j, TelegramChannelConfig as k, EventHandler as l, NotificationHookConfig as m, BatchProgress as n, DispatchResult as o, NodemailerTransporter as p, RedisIdempotencyClient as q, BatchResult as r, EmailAttachment as s, BatchOptions as t, HookHandler as u, PreferenceResolver as v, SendResult as w, Recipient as x, PushChannelConfig as y, DeliveryLog as z };
@@ -1,3 +1,3 @@
1
- import { B as DeliveryLogEntry, F as QueueEnqueueOptions, G as MemoryIdempotencyStore, H as MemoryDeliveryLog, I as QueueJob, J as RateLimitStore, K as MemoryRateLimitStore, L as QueueJobStatus, N as MemoryQueue, P as QueueAdapter, R as QueueProcessor, U as IDEMPOTENCY_DEFAULT_TTL, V as DeliveryLogQuery, W as IdempotencyStore, q as RateLimitConfig, z as DeliveryLog } from "../types-DsRpYKr-.mjs";
2
- import { C as resolveRetryConfig, S as calculateDelay, T as mergeHooks, _ as isQuietHours, a as createStatusHandler, b as ProviderNotInstalledError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as withRetry, x as Emitter, y as NotificationError } from "../status-webhook-C8WnLIMv.mjs";
3
- export { ChannelError, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, Emitter, type FallbackOptions, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, type PMapOptions, ProviderNotInstalledError, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
1
+ import { B as DeliveryLogEntry, F as QueueEnqueueOptions, G as IdempotencyStore, H as MemoryDeliveryLog, I as QueueJob, J as RedisIdempotencyStore, K as MemoryIdempotencyStore, L as QueueJobStatus, N as MemoryQueue, P as QueueAdapter, R as QueueProcessor, U as IDEMPOTENCY_DEFAULT_LEASE, V as DeliveryLogQuery, W as IDEMPOTENCY_DEFAULT_TTL, X as RateLimitConfig, Y as MemoryRateLimitStore, Z as RateLimitStore, q as RedisIdempotencyClient, z as DeliveryLog } from "../types-DyUMfkyr.mjs";
2
+ import { C as calculateDelay, E as mergeHooks, S as Emitter, T as withRetry, _ as isQuietHours, a as createStatusHandler, b as PermanentDeliveryError, c as InterpolateOptions, d as TemplateMap, f as createSimpleResolver, g as QuietHoursConfig, h as pMap, i as StatusUpdate, m as PMapOptions, n as StatusHandler, o as FallbackOptions, p as interpolateHtml, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as TemplateDefinition, v as ChannelError, w as resolveRetryConfig, x as ProviderNotInstalledError, y as NotificationError } from "../status-webhook-BlhPvRnD.mjs";
3
+ export { ChannelError, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, Emitter, type FallbackOptions, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type InterpolateOptions, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, type PMapOptions, PermanentDeliveryError, ProviderNotInstalledError, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type RedisIdempotencyClient, RedisIdempotencyStore, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
@@ -1,4 +1,4 @@
1
- import { a as MemoryQueue, c as pMap, d as MemoryIdempotencyStore, f as isQuietHours, g as Emitter, h as withRetry, i as interpolateHtml, l as MemoryRateLimitStore, m as resolveRetryConfig, n as withFallback, o as MemoryDeliveryLog, p as calculateDelay, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_TTL } from "../status-webhook-B4Sv8X_G.mjs";
2
- import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "../errors-BxRjct-E.mjs";
1
+ import { _ as withRetry, a as MemoryQueue, c as pMap, d as IDEMPOTENCY_DEFAULT_TTL, f as MemoryIdempotencyStore, g as resolveRetryConfig, h as calculateDelay, i as interpolateHtml, l as MemoryRateLimitStore, m as isQuietHours, n as withFallback, o as MemoryDeliveryLog, p as RedisIdempotencyStore, r as createSimpleResolver, s as mergeHooks, t as createStatusHandler, u as IDEMPOTENCY_DEFAULT_LEASE, v as Emitter } from "../status-webhook-D7Hrr71A.mjs";
2
+ import { i as ProviderNotInstalledError, n as NotificationError, r as PermanentDeliveryError, t as ChannelError } from "../errors-CsQZKfec.mjs";
3
3
 
4
- export { ChannelError, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, ProviderNotInstalledError, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
4
+ export { ChannelError, Emitter, IDEMPOTENCY_DEFAULT_LEASE, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, PermanentDeliveryError, ProviderNotInstalledError, RedisIdempotencyStore, calculateDelay, createSimpleResolver, createStatusHandler, interpolateHtml, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/notifications",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "Multi-channel notifications (Email, SMS, Push, Webhook, Telegram) with rate limiting, delivery tracking, queue adapters, channel fallback, templates, retry — zero required dependencies",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -92,11 +92,13 @@
92
92
  "build": "tsdown",
93
93
  "dev": "tsdown --watch",
94
94
  "test": "vitest run",
95
+ "check:skills": "node scripts/check-skills.mjs",
95
96
  "test:watch": "vitest",
96
97
  "test:coverage": "vitest run --coverage",
97
98
  "test:live": "vitest run --config vitest.live.config.ts",
98
- "typecheck": "tsc --noEmit",
99
- "prepublishOnly": "npm run build && npm run typecheck && npm test",
99
+ "typecheck": "tsc --noEmit && npm run typecheck:consumer",
100
+ "typecheck:consumer": "tsdown --logLevel warn && tsc --noEmit -p tsconfig.types.json",
101
+ "prepublishOnly": "npm run build && npm run check:skills && npm run typecheck && npm test",
100
102
  "push": "classytic-push",
101
103
  "publish:dry": "npm publish --dry-run --access public",
102
104
  "publish:npm": "npm publish --access public",
@@ -106,13 +108,13 @@
106
108
  "release:major": "npm version major && npm run release"
107
109
  },
108
110
  "devDependencies": {
109
- "@classytic/dev-tools": "^0.2.0",
110
- "@types/node": "^22.0.0",
111
- "@types/nodemailer": "^8.0.0",
112
- "@vitest/coverage-v8": "4.1.8",
113
- "nodemailer": "^8.0.10",
114
- "tsdown": "^0.22.14",
115
- "typescript": "^6.0.3",
116
- "vitest": "^4.1.8"
111
+ "@classytic/dev-tools": "^0.2.1",
112
+ "@types/node": "^26.6.5",
113
+ "@types/nodemailer": "^8.0.2",
114
+ "@vitest/coverage-v8": "5.0.5",
115
+ "nodemailer": "^10.1.2",
116
+ "tsdown": "^0.23.1",
117
+ "typescript": "^7.0.2",
118
+ "vitest": "^5.0.5"
117
119
  }
118
120
  }